code
stringlengths 1
2.08M
| language
stringclasses 1
value |
|---|---|
for(var i = 0; i < 69; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u11');
}
});
function rdo491(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo492(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo493(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo494(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo495(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_加班时间管理.html'), "");
}
}
function rdo496(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo497(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo498(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置.html'), "");
}
}
function rdo499(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo4999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_考勤系统.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1工资系统.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo491(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u55'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo496(e);
}
});
gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u32'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo492(e);
}
});
gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u30'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u64'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u49'] = 'top';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u66'] = 'top';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo499(e);
}
});
gv_vAlignTable['u2'] = 'top';gv_vAlignTable['u22'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo325(e);
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo494(e);
}
});
gv_vAlignTable['u47'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo493(e);
}
});
document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u24'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u39_img').tabIndex = 0;
HookHover('u39', false);
u39.style.cursor = 'pointer';
$axure.eventManager.click('u39', function(e) {
if (true) {
rdo4999(e);
}
});
document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo498(e);
}
});
gv_vAlignTable['u26'] = 'top';HookHover('u65', false);
document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u12'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo497(e);
}
});
HookHover('u63', false);
document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u40'] = 'top';gv_vAlignTable['u14'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo321(e);
}
});
document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo495(e);
}
});
gv_vAlignTable['u59'] = 'top';
|
JavaScript
|
for(var i = 0; i < 479; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u11');
SetWidgetSelected('u75');
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u465'] = 'top';gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u194'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u152'] = 'top';gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u298'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u1'] = 'center';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u126'] = 'top';gv_vAlignTable['u332'] = 'top';document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u346'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u378'] = 'center';gv_vAlignTable['u463'] = 'top';gv_vAlignTable['u138'] = 'top';gv_vAlignTable['u425'] = 'center';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u302'] = 'top';gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u192'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u150'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u400'] = 'center';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u80'] = 'top';
u476.style.cursor = 'pointer';
$axure.eventManager.click('u476', function(e) {
if (true) {
NewWindow($axure.globalVariableProvider.getLinkUrl('排班方案年度明细内容.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
gv_vAlignTable['u318'] = 'top';gv_vAlignTable['u449'] = 'top';gv_vAlignTable['u268'] = 'top';gv_vAlignTable['u330'] = 'top';gv_vAlignTable['u274'] = 'top';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u344'] = 'top';document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u326'] = 'top';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u410'] = 'top';gv_vAlignTable['u419'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u162'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u447'] = 'center';gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u55'] = 'top';HookHover('u111', false);
gv_vAlignTable['u306'] = 'top';gv_vAlignTable['u284'] = 'top';gv_vAlignTable['u342'] = 'top';gv_vAlignTable['u437'] = 'center';gv_vAlignTable['u356'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u461'] = 'top';gv_vAlignTable['u160'] = 'center';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u49'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u304'] = 'top';gv_vAlignTable['u282'] = 'top';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u240'] = 'top';gv_vAlignTable['u296'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u254'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u12'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u358'] = 'center';gv_vAlignTable['u51'] = 'top';HookHover('u109', false);
gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u359'] = 'top';gv_vAlignTable['u134'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
gv_vAlignTable['u280'] = 'top';gv_vAlignTable['u316'] = 'top';gv_vAlignTable['u294'] = 'top';gv_vAlignTable['u433'] = 'top';gv_vAlignTable['u252'] = 'top';gv_vAlignTable['u386'] = 'center';gv_vAlignTable['u266'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u82'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u314'] = 'top';gv_vAlignTable['u292'] = 'top';document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u369'] = 'top';gv_vAlignTable['u431'] = 'center';gv_vAlignTable['u250'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u445'] = 'center';gv_vAlignTable['u34'] = 'top';document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u146'] = 'top';document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u459'] = 'top';gv_vAlignTable['u388'] = 'center';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u190'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u443'] = 'center';gv_vAlignTable['u118'] = 'top';gv_vAlignTable['u262'] = 'top';gv_vAlignTable['u457'] = 'top';gv_vAlignTable['u276'] = 'top';document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u130'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u406'] = 'center';gv_vAlignTable['u384'] = 'center';gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u43'] = 'top';
u456.style.cursor = 'pointer';
$axure.eventManager.click('u456', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("这个与添加按钮有区别,这个是插入按钮<BR><BR>例如当前作息时间为<BR><BR>13.1.1 正常打卡时间(下午12:30上班)<BR><BR>现在需要增加一个夏季作息时间,下午13:30上班,但在10月1号之后又要恢复回正常打卡时间,这时就用插入方式。<BR>界面会显示开始时间,作息方案,同时会有方案结束时间,系统会自动把当前该 方案之前的方案作为下一方案再增加一行开始时间,变成如下效果。<BR><BR>13.1.1 正常打卡时间(下午12:30上班)<BR>13.5.1 夏季作息打卡时间(下午13:30上班)<BR>13.10.1 正常打卡时间(下午12:30上班)<BR><BR>这个可以省去两次添加的麻烦(此功能可后增加)<BR>"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u210'] = 'top';document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u260'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u455'] = 'center';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u328'] = 'top';gv_vAlignTable['u435'] = 'center';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u404'] = 'center';gv_vAlignTable['u382'] = 'center';gv_vAlignTable['u142'] = 'top';gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u340'] = 'top';gv_vAlignTable['u396'] = 'center';gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u354'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u105'] = 'top';gv_vAlignTable['u222'] = 'top';
u372.style.cursor = 'pointer';
$axure.eventManager.click('u372', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("点击后可以选择一个新的作息时间方案如夏令时方案等,该 方案会以指定开始时间,如当前开始时间为13.5.1,则会增加一行记录是13.5.1开始的作息时间。"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u36'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u272'] = 'top';gv_vAlignTable['u402'] = 'center';gv_vAlignTable['u336'] = 'top';gv_vAlignTable['u367'] = 'top';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u308'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u380'] = 'center';gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u394'] = 'center';gv_vAlignTable['u477'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u352'] = 'top';gv_vAlignTable['u312'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u158'] = 'center';gv_vAlignTable['u220'] = 'top';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u234'] = 'top';gv_vAlignTable['u408'] = 'top';gv_vAlignTable['u270'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u365'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u338'] = 'top';gv_vAlignTable['u300'] = 'top';gv_vAlignTable['u471'] = 'top';gv_vAlignTable['u417'] = 'top';gv_vAlignTable['u414'] = 'top';gv_vAlignTable['u392'] = 'center';gv_vAlignTable['u469'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u350'] = 'top';gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u115'] = 'top';gv_vAlignTable['u232'] = 'top';gv_vAlignTable['u427'] = 'center';document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u246'] = 'top';gv_vAlignTable['u363'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u290'] = 'top';gv_vAlignTable['u278'] = 'top';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u218'] = 'top';gv_vAlignTable['u376'] = 'center';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u286'] = 'top';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u412'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u244'] = 'top';gv_vAlignTable['u390'] = 'center';gv_vAlignTable['u361'] = 'top';gv_vAlignTable['u124'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
gv_vAlignTable['u348'] = 'top';gv_vAlignTable['u310'] = 'top';gv_vAlignTable['u324'] = 'top';gv_vAlignTable['u441'] = 'top';document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u242'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u439'] = 'center';gv_vAlignTable['u256'] = 'top';gv_vAlignTable['u288'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u322'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u453'] = 'center';gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u467'] = 'top';gv_vAlignTable['u398'] = 'center';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u140'] = 'top';gv_vAlignTable['u196'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u264'] = 'top';gv_vAlignTable['u429'] = 'center';gv_vAlignTable['u84'] = 'top';gv_vAlignTable['u258'] = 'top';gv_vAlignTable['u320'] = 'top';gv_vAlignTable['u334'] = 'top';gv_vAlignTable['u451'] = 'center';
|
JavaScript
|
for(var i = 0; i < 69; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u13');
}
});
function rdo491(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo492(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo493(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo494(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo495(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_加班时间管理.html'), "");
}
}
function rdo496(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo497(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo498(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置.html'), "");
}
}
function rdo499(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo4999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_考勤系统.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1工资系统.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo491(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u55'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo496(e);
}
});
gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u32'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo492(e);
}
});
gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u30'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u64'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u49'] = 'top';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u66'] = 'top';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo499(e);
}
});
gv_vAlignTable['u2'] = 'top';gv_vAlignTable['u22'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo325(e);
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo494(e);
}
});
gv_vAlignTable['u47'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo493(e);
}
});
document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u24'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u39_img').tabIndex = 0;
HookHover('u39', false);
u39.style.cursor = 'pointer';
$axure.eventManager.click('u39', function(e) {
if (true) {
rdo4999(e);
}
});
document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo498(e);
}
});
gv_vAlignTable['u26'] = 'top';HookHover('u65', false);
document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u12'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo497(e);
}
});
HookHover('u63', false);
document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u40'] = 'top';gv_vAlignTable['u14'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo321(e);
}
});
document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo495(e);
}
});
gv_vAlignTable['u59'] = 'top';
|
JavaScript
|
for(var i = 0; i < 40; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetPanelState('u37', 'pd0u37','none','',500,'none','',500);
}
});
gv_vAlignTable['u31'] = 'top';HookHover('u16', false);
gv_vAlignTable['u17'] = 'top';document.getElementById('u28_img').tabIndex = 0;
HookHover('u28', false);
u28.style.cursor = 'pointer';
$axure.eventManager.click('u28', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
NewWindow("resources/Other.html#other=" + encodeURI("打开人事系统界面,选择基本员工档案功能"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
SetWidgetSelected('u28');
SetWidgetNotSelected('u26');
SetWidgetNotSelected('u30');
SetWidgetNotSelected('u32');
SetWidgetNotSelected('u34');
}
});
gv_vAlignTable['u29'] = 'top';HookHover('u8', false);
document.getElementById('u30_img').tabIndex = 0;
HookHover('u30', false);
u30.style.cursor = 'pointer';
$axure.eventManager.click('u30', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u30');
SetWidgetNotSelected('u28');
SetWidgetNotSelected('u26');
SetWidgetNotSelected('u32');
SetWidgetNotSelected('u34');
}
});
gv_vAlignTable['u21'] = 'top';HookHover('u6', false);
document.getElementById('u32_img').tabIndex = 0;
HookHover('u32', false);
u32.style.cursor = 'pointer';
$axure.eventManager.click('u32', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u32');
SetWidgetNotSelected('u26');
SetWidgetNotSelected('u28');
SetWidgetNotSelected('u30');
SetWidgetNotSelected('u34');
}
});
gv_vAlignTable['u3'] = 'top';gv_vAlignTable['u13'] = 'top';HookHover('u14', false);
gv_vAlignTable['u15'] = 'top';document.getElementById('u26_img').tabIndex = 0;
HookHover('u26', false);
u26.style.cursor = 'pointer';
$axure.eventManager.click('u26', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
NewWindow("resources/Other.html#other=" + encodeURI("打开基本页面,"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
SetWidgetSelected('u26');
SetWidgetNotSelected('u34');
SetWidgetNotSelected('u32');
SetWidgetNotSelected('u30');
SetWidgetNotSelected('u28');
}
});
HookHover('u10', false);
gv_vAlignTable['u11'] = 'top';HookHover('u12', false);
gv_vAlignTable['u9'] = 'top';gv_vAlignTable['u35'] = 'top';gv_vAlignTable['u27'] = 'top';gv_vAlignTable['u7'] = 'top';HookHover('u4', false);
HookHover('u2', false);
gv_vAlignTable['u20'] = 'center';gv_vAlignTable['u5'] = 'top';gv_vAlignTable['u33'] = 'top';document.getElementById('u34_img').tabIndex = 0;
HookHover('u34', false);
u34.style.cursor = 'pointer';
$axure.eventManager.click('u34', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u34');
SetWidgetNotSelected('u32');
SetWidgetNotSelected('u30');
SetWidgetNotSelected('u28');
SetWidgetNotSelected('u26');
}
});
|
JavaScript
|
|
JavaScript
|
for(var i = 0; i < 407; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u289');
SetWidgetSelected('u372');
SetPanelState('u298', 'pd1u298','none','',500,'none','',500);
SetPanelState('u0', 'pd0u0','none','',500,'none','',500);
}
if (true) {
SetWidgetSelected('u271');
}
if (true) {
SetPanelVisibility('u25','hidden','none',500);
}
});
function rdo1121(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo1122(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo1123(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo1124(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo1125(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo1126(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo1127(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo1128(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo91(e) {
if (true) {
SetPanelState('u298', 'pd0u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo92(e) {
if (true) {
SetPanelState('u298', 'pd1u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo93(e) {
if (true) {
SetPanelState('u298', 'pd2u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo94(e) {
if (true) {
SetPanelState('u298', 'pd3u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo95(e) {
}
function rdo99(e) {
if (true) {
SetPanelState('u298', 'pd4u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo1341(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo1342(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo1343(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo1344(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo1345(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo1346(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo1347(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo1348(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo1349(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
function rdo1491(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo1492(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo1493(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo1494(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo1495(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo1496(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo1497(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo1498(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo1499(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo14999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo15new(e) {
}
function rdo15edit(e) {
}
function rdo15delete(e) {
}
function rdo15print(e) {
}
function rdo1231(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo1232(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo1233(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo1234(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo1235(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo1236(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo1237(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo1238(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo1239(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo12310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo12311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo12312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo12313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
document.getElementById('u370_img').tabIndex = 0;
HookHover('u370', false);
u370.style.cursor = 'pointer';
$axure.eventManager.click('u370', function(e) {
if (true) {
rdo1121(e);
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u319', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
gv_vAlignTable['u400'] = 'center';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u333'] = 'top';document.getElementById('u347_img').tabIndex = 0;
HookHover('u347', false);
u347.style.cursor = 'pointer';
$axure.eventManager.click('u347', function(e) {
if (true) {
rdo1233(e);
}
});
gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u139'] = 'top';gv_vAlignTable['u201'] = 'top';gv_vAlignTable['u1'] = 'top';gv_vAlignTable['u193'] = 'top';gv_vAlignTable['u11'] = 'top';HookHover('u391', false);
gv_vAlignTable['u151'] = 'top';gv_vAlignTable['u71'] = 'top';gv_vAlignTable['u346'] = 'top';document.getElementById('u378_img').tabIndex = 0;
HookHover('u378', false);
u378.style.cursor = 'pointer';
$axure.eventManager.click('u378', function(e) {
if (true) {
rdo1125(e);
}
});
gv_vAlignTable['u100'] = 'top';gv_vAlignTable['u302'] = 'top';gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u192'] = 'top';gv_vAlignTable['u67'] = 'top';gv_vAlignTable['u390'] = 'top';gv_vAlignTable['u150'] = 'top';document.getElementById('u287_img').tabIndex = 0;
HookHover('u287', false);
u287.style.cursor = 'pointer';
$axure.eventManager.click('u287', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u287');
SetWidgetNotSelected('u295');
SetWidgetNotSelected('u293');
SetWidgetNotSelected('u291');
SetWidgetNotSelected('u289');
rdo91(e);
}
});
gv_vAlignTable['u48'] = 'top';document.getElementById('u345_img').tabIndex = 0;
HookHover('u345', false);
u345.style.cursor = 'pointer';
$axure.eventManager.click('u345', function(e) {
if (true) {
rdo1232(e);
}
});
gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u318'] = 'top';gv_vAlignTable['u113'] = 'top';document.getElementById('u330_img').tabIndex = 0;
HookHover('u330', false);
u330.style.cursor = 'pointer';
$axure.eventManager.click('u330', function(e) {
if (true) {
rdo1345(e);
}
});
gv_vAlignTable['u4'] = 'top';
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
SetPanelVisibility('u25','hidden','none',500);
}
});
document.getElementById('u326_img').tabIndex = 0;
HookHover('u326', false);
u326.style.cursor = 'pointer';
$axure.eventManager.click('u326', function(e) {
if (true) {
rdo1343(e);
}
});
gv_vAlignTable['u177'] = 'top';gv_vAlignTable['u37'] = 'top';gv_vAlignTable['u112'] = 'top';document.getElementById('u307_img').tabIndex = 0;
HookHover('u307', false);
u307.style.cursor = 'pointer';
$axure.eventManager.click('u307', function(e) {
if (true) {
rdo1494(e);
}
});
gv_vAlignTable['u50'] = 'top';document.getElementById('u343_img').tabIndex = 0;
HookHover('u343', false);
u343.style.cursor = 'pointer';
$axure.eventManager.click('u343', function(e) {
if (true) {
rdo1231(e);
}
});
document.getElementById('u357_img').tabIndex = 0;
HookHover('u357', false);
u357.style.cursor = 'pointer';
$axure.eventManager.click('u357', function(e) {
if (true) {
rdo1237(e);
}
});
HookHover('u389', false);
gv_vAlignTable['u55'] = 'top';document.getElementById('u332_img').tabIndex = 0;
HookHover('u332', false);
u332.style.cursor = 'pointer';
$axure.eventManager.click('u332', function(e) {
if (true) {
rdo1346(e);
}
});
gv_vAlignTable['u306'] = 'top';gv_vAlignTable['u125'] = 'top';gv_vAlignTable['u161'] = 'top';gv_vAlignTable['u329'] = 'top';gv_vAlignTable['u356'] = 'top';gv_vAlignTable['u229'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u348'] = 'top';document.getElementById('u305_img').tabIndex = 0;
HookHover('u305', false);
u305.style.cursor = 'pointer';
$axure.eventManager.click('u305', function(e) {
if (true) {
rdo1493(e);
}
});
gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u160'] = 'top';
$axure.eventManager.click('u297', function(e) {
if (true) {
SetPanelState('u298', 'pd0u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u297', function(e) {
if (true) {
SetPanelState('u298', 'pd0u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u297', function(e) {
if (true) {
SetPanelState('u298', 'pd0u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u297', function(e) {
if (true) {
SetPanelState('u298', 'pd0u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u297', function(e) {
if (true) {
SetPanelState('u298', 'pd0u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u297', function(e) {
if (true) {
SetPanelState('u298', 'pd0u298','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u8'] = 'top';document.getElementById('u355_img').tabIndex = 0;
HookHover('u355', false);
u355.style.cursor = 'pointer';
$axure.eventManager.click('u355', function(e) {
if (true) {
rdo1236(e);
}
});
gv_vAlignTable['u81'] = 'top';gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u304'] = 'top';gv_vAlignTable['u282'] = 'top';gv_vAlignTable['u278'] = 'center';gv_vAlignTable['u240'] = 'center';gv_vAlignTable['u296'] = 'top';gv_vAlignTable['u137'] = 'top';gv_vAlignTable['u254'] = 'top';gv_vAlignTable['u173'] = 'top';gv_vAlignTable['u213'] = 'top';document.getElementById('u303_img').tabIndex = 0;
HookHover('u303', false);
u303.style.cursor = 'pointer';
$axure.eventManager.click('u303', function(e) {
if (true) {
rdo1492(e);
}
});
gv_vAlignTable['u281'] = 'center';gv_vAlignTable['u94'] = 'top';gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u358'] = 'top';document.getElementById('u317_img').tabIndex = 0;
HookHover('u317', false);
u317.style.cursor = 'pointer';
$axure.eventManager.click('u317', function(e) {
if (true) {
rdo14999(e);
}
});
document.getElementById('u295_img').tabIndex = 0;
HookHover('u295', false);
u295.style.cursor = 'pointer';
$axure.eventManager.click('u295', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u295');
SetWidgetNotSelected('u293');
SetWidgetNotSelected('u291');
SetWidgetNotSelected('u289');
SetWidgetNotSelected('u287');
rdo99(e);
}
});
gv_vAlignTable['u51'] = 'top';document.getElementById('u359_img').tabIndex = 0;
HookHover('u359', false);
u359.style.cursor = 'pointer';
$axure.eventManager.click('u359', function(e) {
if (true) {
rdo1238(e);
}
});
gv_vAlignTable['u267'] = 'top';document.getElementById('u399_img').tabIndex = 0;
HookHover('u399', false);
u399.style.cursor = 'pointer';
$axure.eventManager.click('u399', function(e) {
if (true) {
rdo15edit(e);
}
});
gv_vAlignTable['u46'] = 'top';gv_vAlignTable['u316'] = 'top';gv_vAlignTable['u294'] = 'top';gv_vAlignTable['u135'] = 'top';gv_vAlignTable['u108'] = 'top';gv_vAlignTable['u252'] = 'top';gv_vAlignTable['u171'] = 'top';gv_vAlignTable['u266'] = 'top';gv_vAlignTable['u64'] = 'top';HookHover('u239', false);
gv_vAlignTable['u263'] = 'top';gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u315_img').tabIndex = 0;
HookHover('u315', false);
u315.style.cursor = 'pointer';
$axure.eventManager.click('u315', function(e) {
if (true) {
rdo1499(e);
}
});
document.getElementById('u293_img').tabIndex = 0;
HookHover('u293', false);
u293.style.cursor = 'pointer';
$axure.eventManager.click('u293', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u293');
SetWidgetNotSelected('u287');
SetWidgetNotSelected('u289');
SetWidgetNotSelected('u291');
SetWidgetNotSelected('u295');
rdo94(e);
}
});
gv_vAlignTable['u21'] = 'top';gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u373'] = 'top';gv_vAlignTable['u265'] = 'top';gv_vAlignTable['u238'] = 'center';gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u314'] = 'top';gv_vAlignTable['u292'] = 'top';gv_vAlignTable['u77'] = 'top';gv_vAlignTable['u250'] = 'top';
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
});
gv_vAlignTable['u327'] = 'top';gv_vAlignTable['u164'] = 'top';
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u386', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u146'] = 'top';gv_vAlignTable['u274'] = 'center';document.getElementById('u277_img').tabIndex = 0;
HookHover('u277', false);
u277.style.cursor = 'pointer';
$axure.eventManager.click('u277', function(e) {
if (true) {
SetPanelState('u0', 'pd3u0','none','',500,'none','',500);
SetWidgetNotSelected('u271');
SetWidgetNotSelected('u273');
SetWidgetNotSelected('u275');
SetWidgetSelected('u277');
}
});
gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u190'] = 'top';gv_vAlignTable['u385'] = 'top';gv_vAlignTable['u60'] = 'top';gv_vAlignTable['u118'] = 'top';gv_vAlignTable['u262'] = 'top';gv_vAlignTable['u89'] = 'top';gv_vAlignTable['u131'] = 'top';gv_vAlignTable['u276'] = 'center';gv_vAlignTable['u65'] = 'top';gv_vAlignTable['u211'] = 'top';gv_vAlignTable['u85'] = 'top';
u406.style.cursor = 'pointer';
$axure.eventManager.click('u406', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("1、弹出文件选择窗口,按固定格式导入表格数据到当前花名册信息。<BR>2、导入如果部门为空或岗位为空,没有找到,提醒无法完成导入,有一个验证数据的功能,通过验证才能实现导入。<BR>3、例如200条批量数据,有一条不能导入,则会有错误 提示,然后200条均没有导入。用户要修改好之后才能进行导入。"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
document.getElementById('u384_img').tabIndex = 0;
HookHover('u384', false);
u384.style.cursor = 'pointer';
$axure.eventManager.click('u384', function(e) {
if (true) {
rdo1128(e);
}
});
u22.style.cursor = 'pointer';
$axure.eventManager.click('u22', function(e) {
if (true) {
MoveWidgetTo('u25', GetNum('10'), GetNum('40'),'none',500);
SetPanelVisibility('u25','','none',500);
}
});
gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u261'] = 'top';gv_vAlignTable['u175'] = 'top';document.getElementById('u275_img').tabIndex = 0;
HookHover('u275', false);
u275.style.cursor = 'pointer';
$axure.eventManager.click('u275', function(e) {
if (true) {
SetPanelState('u0', 'pd2u0','none','',500,'none','',500);
SetWidgetNotSelected('u271');
SetWidgetNotSelected('u273');
SetWidgetSelected('u275');
SetWidgetNotSelected('u277');
}
});
gv_vAlignTable['u17'] = 'top';gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u325'] = 'top';gv_vAlignTable['u383'] = 'top';gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u379'] = 'top';gv_vAlignTable['u260'] = 'top';document.getElementById('u397_img').tabIndex = 0;
HookHover('u397', false);
u397.style.cursor = 'pointer';
$axure.eventManager.click('u397', function(e) {
if (true) {
rdo15new(e);
}
});
gv_vAlignTable['u9'] = 'top';document.getElementById('u309_img').tabIndex = 0;
HookHover('u309', false);
u309.style.cursor = 'pointer';
$axure.eventManager.click('u309', function(e) {
if (true) {
rdo1496(e);
}
});
document.getElementById('u328_img').tabIndex = 0;
HookHover('u328', false);
u328.style.cursor = 'pointer';
$axure.eventManager.click('u328', function(e) {
if (true) {
rdo1344(e);
}
});
gv_vAlignTable['u106'] = 'top';gv_vAlignTable['u404'] = 'center';document.getElementById('u382_img').tabIndex = 0;
HookHover('u382', false);
u382.style.cursor = 'pointer';
$axure.eventManager.click('u382', function(e) {
if (true) {
rdo1127(e);
}
});
gv_vAlignTable['u223'] = 'top';gv_vAlignTable['u331'] = 'top';
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u340', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
HookHover('u237', false);
gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u354'] = 'top';document.getElementById('u273_img').tabIndex = 0;
HookHover('u273', false);
u273.style.cursor = 'pointer';
$axure.eventManager.click('u273', function(e) {
if (true) {
SetPanelState('u0', 'pd1u0','none','',500,'none','',500);
SetWidgetNotSelected('u271');
SetWidgetSelected('u273');
SetWidgetNotSelected('u277');
SetWidgetNotSelected('u275');
}
});
document.getElementById('u301_img').tabIndex = 0;
HookHover('u301', false);
u301.style.cursor = 'pointer';
$axure.eventManager.click('u301', function(e) {
if (true) {
rdo1491(e);
}
});
document.getElementById('u403_img').tabIndex = 0;
HookHover('u403', false);
u403.style.cursor = 'pointer';
$axure.eventManager.click('u403', function(e) {
if (true) {
rdo15print(e);
}
});
gv_vAlignTable['u381'] = 'top';document.getElementById('u311_img').tabIndex = 0;
HookHover('u311', false);
u311.style.cursor = 'pointer';
$axure.eventManager.click('u311', function(e) {
if (true) {
rdo1497(e);
}
});
gv_vAlignTable['u6'] = 'top';gv_vAlignTable['u29'] = 'center';gv_vAlignTable['u209'] = 'top';document.getElementById('u353_img').tabIndex = 0;
HookHover('u353', false);
u353.style.cursor = 'pointer';
$axure.eventManager.click('u353', function(e) {
if (true) {
rdo12313(e);
}
});
gv_vAlignTable['u272'] = 'center';gv_vAlignTable['u402'] = 'center';document.getElementById('u336_img').tabIndex = 0;
HookHover('u336', false);
u336.style.cursor = 'pointer';
$axure.eventManager.click('u336', function(e) {
if (true) {
rdo1348(e);
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u367', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u104'] = 'top';gv_vAlignTable['u308'] = 'top';gv_vAlignTable['u259'] = 'top';document.getElementById('u380_img').tabIndex = 0;
HookHover('u380', false);
u380.style.cursor = 'pointer';
$axure.eventManager.click('u380', function(e) {
if (true) {
rdo1126(e);
}
});
gv_vAlignTable['u221'] = 'top';gv_vAlignTable['u232'] = 'top';gv_vAlignTable['u13'] = 'top';gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u352'] = 'top';document.getElementById('u271_img').tabIndex = 0;
HookHover('u271', false);
u271.style.cursor = 'pointer';
$axure.eventManager.click('u271', function(e) {
if (true) {
SetPanelState('u0', 'pd0u0','none','',500,'none','',500);
SetWidgetSelected('u271');
SetWidgetNotSelected('u273');
SetWidgetNotSelected('u277');
SetWidgetNotSelected('u275');
}
});
gv_vAlignTable['u312'] = 'top';gv_vAlignTable['u366'] = 'top';gv_vAlignTable['u339'] = 'top';document.getElementById('u401_img').tabIndex = 0;
HookHover('u401', false);
u401.style.cursor = 'pointer';
$axure.eventManager.click('u401', function(e) {
if (true) {
rdo15delete(e);
}
});
gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u31'] = 'top';gv_vAlignTable['u234'] = 'top';gv_vAlignTable['u73'] = 'top';document.getElementById('u351_img').tabIndex = 0;
HookHover('u351', false);
u351.style.cursor = 'pointer';
$axure.eventManager.click('u351', function(e) {
if (true) {
rdo1235(e);
}
});
document.getElementById('u365_img').tabIndex = 0;
HookHover('u365', false);
u365.style.cursor = 'pointer';
$axure.eventManager.click('u365', function(e) {
if (true) {
rdo12311(e);
}
});
gv_vAlignTable['u92'] = 'top';gv_vAlignTable['u56'] = 'top';document.getElementById('u322_img').tabIndex = 0;
HookHover('u322', false);
u322.style.cursor = 'pointer';
$axure.eventManager.click('u322', function(e) {
if (true) {
rdo1342(e);
}
});
gv_vAlignTable['u116'] = 'top';gv_vAlignTable['u392'] = 'top';gv_vAlignTable['u87'] = 'top';gv_vAlignTable['u350'] = 'top';
u68.style.cursor = 'pointer';
$axure.eventManager.click('u68', function(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('合同签定.html'), "");
}
});
gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u364'] = 'top';gv_vAlignTable['u101'] = 'top';document.getElementById('u338_img').tabIndex = 0;
HookHover('u338', false);
u338.style.cursor = 'pointer';
$axure.eventManager.click('u338', function(e) {
if (true) {
rdo1349(e);
}
});
document.getElementById('u313_img').tabIndex = 0;
HookHover('u313', false);
u313.style.cursor = 'pointer';
$axure.eventManager.click('u313', function(e) {
if (true) {
rdo1495(e);
}
});
document.getElementById('u291_img').tabIndex = 0;
HookHover('u291', false);
u291.style.cursor = 'pointer';
$axure.eventManager.click('u291', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u291');
SetWidgetNotSelected('u289');
SetWidgetNotSelected('u287');
SetWidgetNotSelected('u293');
SetWidgetNotSelected('u295');
rdo93(e);
}
});
gv_vAlignTable['u62'] = 'top';gv_vAlignTable['u219'] = 'top';document.getElementById('u363_img').tabIndex = 0;
HookHover('u363', false);
u363.style.cursor = 'pointer';
$axure.eventManager.click('u363', function(e) {
if (true) {
rdo12310(e);
}
});
gv_vAlignTable['u377'] = 'top';document.getElementById('u372_img').tabIndex = 0;
HookHover('u372', false);
u372.style.cursor = 'pointer';
$axure.eventManager.click('u372', function(e) {
if (true) {
rdo1122(e);
}
});
gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u290'] = 'top';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u218'] = 'top';gv_vAlignTable['u362'] = 'top';gv_vAlignTable['u98'] = 'top';document.getElementById('u376_img').tabIndex = 0;
HookHover('u376', false);
u376.style.cursor = 'pointer';
$axure.eventManager.click('u376', function(e) {
if (true) {
rdo1124(e);
}
});
gv_vAlignTable['u75'] = 'top';document.getElementById('u349_img').tabIndex = 0;
HookHover('u349', false);
u349.style.cursor = 'pointer';
$axure.eventManager.click('u349', function(e) {
if (true) {
rdo1234(e);
}
});
gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u127'] = 'top';gv_vAlignTable['u244'] = 'top';document.getElementById('u361_img').tabIndex = 0;
HookHover('u361', false);
u361.style.cursor = 'pointer';
$axure.eventManager.click('u361', function(e) {
if (true) {
rdo1239(e);
}
});
gv_vAlignTable['u375'] = 'top';gv_vAlignTable['u27'] = 'center';gv_vAlignTable['u83'] = 'top';gv_vAlignTable['u310'] = 'top';gv_vAlignTable['u185'] = 'top';gv_vAlignTable['u40'] = 'top';document.getElementById('u324_img').tabIndex = 0;
HookHover('u324', false);
u324.style.cursor = 'pointer';
$axure.eventManager.click('u324', function(e) {
if (true) {
rdo1341(e);
}
});
gv_vAlignTable['u360'] = 'top';gv_vAlignTable['u69'] = 'top';document.getElementById('u289_img').tabIndex = 0;
HookHover('u289', false);
u289.style.cursor = 'pointer';
$axure.eventManager.click('u289', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u289');
SetWidgetNotSelected('u287');
SetWidgetNotSelected('u291');
SetWidgetNotSelected('u293');
SetWidgetNotSelected('u295');
rdo92(e);
}
});
gv_vAlignTable['u45'] = 'top';document.getElementById('u374_img').tabIndex = 0;
HookHover('u374', false);
u374.style.cursor = 'pointer';
$axure.eventManager.click('u374', function(e) {
if (true) {
rdo1123(e);
}
});
gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u323'] = 'top';gv_vAlignTable['u242'] = 'top';gv_vAlignTable['u96'] = 'top';gv_vAlignTable['u344'] = 'top';gv_vAlignTable['u337'] = 'top';gv_vAlignTable['u256'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u129'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u183'] = 'top';gv_vAlignTable['u288'] = 'top';gv_vAlignTable['u141'] = 'top';gv_vAlignTable['u39'] = 'top';gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u398'] = 'center';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u196'] = 'top';gv_vAlignTable['u335'] = 'top';gv_vAlignTable['u23'] = 'top';gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u264'] = 'top';gv_vAlignTable['u371'] = 'top';gv_vAlignTable['u181'] = 'top';gv_vAlignTable['u258'] = 'top';gv_vAlignTable['u41'] = 'top';document.getElementById('u334_img').tabIndex = 0;
HookHover('u334', false);
u334.style.cursor = 'pointer';
$axure.eventManager.click('u334', function(e) {
if (true) {
rdo1347(e);
}
});
|
JavaScript
|
for(var i = 0; i < 115; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u15');
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u95'] = 'top';document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u55'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u38'] = 'top';document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u1'] = 'center';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u84'] = 'top';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u8'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u34'] = 'top';HookHover('u111', false);
gv_vAlignTable['u64'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u49'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u51'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u36'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u66'] = 'top';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u2'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u22'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u43'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
HookHover('u109', false);
document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u101'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u14'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u103'] = 'top';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u26'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u105'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u82'] = 'top';document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u112'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u72'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u99'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u74'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u91'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
|
JavaScript
|
for(var i = 0; i < 583; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u77');
SetWidgetSelected('u11');
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo8week12345(e) {
if (true) {
SetPanelState('u325', 'pd0u325','none','',500,'none','',500);
}
}
function rdo8week67(e) {
if (true) {
SetPanelState('u325', 'pd1u325','none','',500,'none','',500);
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u370'] = 'center';gv_vAlignTable['u465'] = 'top';gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u400'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u194'] = 'top';gv_vAlignTable['u514'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u152'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u166'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u1'] = 'center';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u126'] = 'top';gv_vAlignTable['u413'] = 'center';gv_vAlignTable['u332'] = 'center';gv_vAlignTable['u568'] = 'top';gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u378'] = 'top';gv_vAlignTable['u463'] = 'top';gv_vAlignTable['u138'] = 'top';gv_vAlignTable['u425'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
gv_vAlignTable['u302'] = 'center';gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u192'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u150'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u340'] = 'top';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u346'] = 'center';gv_vAlignTable['u318'] = 'center';gv_vAlignTable['u431'] = 'center';gv_vAlignTable['u268'] = 'top';gv_vAlignTable['u330'] = 'center';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u501'] = 'top';document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u475'] = 'top';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u410'] = 'top';gv_vAlignTable['u419'] = 'center';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u579'] = 'center';gv_vAlignTable['u162'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u55'] = 'top';gv_vAlignTable['u528'] = 'center';HookHover('u111', false);
gv_vAlignTable['u540'] = 'top';gv_vAlignTable['u306'] = 'center';gv_vAlignTable['u423'] = 'center';gv_vAlignTable['u342'] = 'top';
$axure.eventManager.click('u512', function(e) {
if (true) {
SetPanelState('u325', 'pd0u325','none','',500,'none','',500);
}
});
$axure.eventManager.click('u512', function(e) {
if (true) {
SetPanelState('u325', 'pd0u325','none','',500,'none','',500);
}
});
gv_vAlignTable['u437'] = 'top';gv_vAlignTable['u356'] = 'top';gv_vAlignTable['u554'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u348'] = 'top';gv_vAlignTable['u461'] = 'top';gv_vAlignTable['u283'] = 'top';gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u526'] = 'center';gv_vAlignTable['u279'] = 'top';gv_vAlignTable['u160'] = 'top';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u49'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u511'] = 'top';gv_vAlignTable['u304'] = 'center';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u240'] = 'top';gv_vAlignTable['u296'] = 'center';gv_vAlignTable['u435'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u254'] = 'top';gv_vAlignTable['u552'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u495'] = 'top';gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u281'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u358'] = 'center';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u51'] = 'top';HookHover('u109', false);
gv_vAlignTable['u548'] = 'top';gv_vAlignTable['u172'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
gv_vAlignTable['u538'] = 'top';document.getElementById('u500_img').tabIndex = 0;
HookHover('u500', false);
u500.style.cursor = 'pointer';
$axure.eventManager.click('u500', function(e) {
if (true) {
rdo8week12345(e);
SetWidgetNotSelected('u498');
SetWidgetSelected('u500');
SetWidgetNotSelected('u502');
SetWidgetNotSelected('u504');
SetWidgetNotSelected('u510');
SetWidgetNotSelected('u508');
SetWidgetNotSelected('u506');
}
});
gv_vAlignTable['u509'] = 'top';gv_vAlignTable['u316'] = 'center';gv_vAlignTable['u294'] = 'center';gv_vAlignTable['u433'] = 'top';gv_vAlignTable['u252'] = 'top';gv_vAlignTable['u550'] = 'top';gv_vAlignTable['u447'] = 'top';gv_vAlignTable['u266'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u564'] = 'top';gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u134'] = 'top';gv_vAlignTable['u491'] = 'center';gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u82'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u200'] = 'top';document.getElementById('u502_img').tabIndex = 0;
HookHover('u502', false);
u502.style.cursor = 'pointer';
$axure.eventManager.click('u502', function(e) {
if (true) {
rdo8week12345(e);
SetWidgetNotSelected('u498');
SetWidgetNotSelected('u500');
SetWidgetSelected('u502');
SetWidgetNotSelected('u504');
SetWidgetNotSelected('u510');
SetWidgetNotSelected('u508');
SetWidgetNotSelected('u506');
}
});
gv_vAlignTable['u577'] = 'top';gv_vAlignTable['u314'] = 'center';gv_vAlignTable['u292'] = 'center';document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u250'] = 'top';gv_vAlignTable['u429'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u445'] = 'top';gv_vAlignTable['u34'] = 'top';document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u562'] = 'top';gv_vAlignTable['u164'] = 'top';
u576.style.cursor = 'pointer';
$axure.eventManager.click('u576', function(e) {
if (true) {
NewWindow($axure.globalVariableProvider.getLinkUrl('打卡时间方案管理.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u146'] = 'top';document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u277'] = 'top';gv_vAlignTable['u572'] = 'top';gv_vAlignTable['u388'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u190'] = 'top';document.getElementById('u510_img').tabIndex = 0;
HookHover('u510', false);
u510.style.cursor = 'pointer';
$axure.eventManager.click('u510', function(e) {
if (true) {
rdo8week67(e);
SetWidgetNotSelected('u498');
SetWidgetNotSelected('u500');
SetWidgetNotSelected('u502');
SetWidgetNotSelected('u504');
SetWidgetSelected('u510');
SetWidgetNotSelected('u508');
SetWidgetNotSelected('u506');
}
});
gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u524'] = 'center';gv_vAlignTable['u443'] = 'center';gv_vAlignTable['u118'] = 'top';gv_vAlignTable['u262'] = 'top';gv_vAlignTable['u560'] = 'top';gv_vAlignTable['u322'] = 'top';gv_vAlignTable['u457'] = 'top';document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u130'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u406'] = 'center';gv_vAlignTable['u384'] = 'top';gv_vAlignTable['u503'] = 'top';gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u43'] = 'top';gv_vAlignTable['u275'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u210'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u581'] = 'center';gv_vAlignTable['u260'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u455'] = 'center';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
gv_vAlignTable['u328'] = 'center';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u404'] = 'top';gv_vAlignTable['u382'] = 'center';gv_vAlignTable['u142'] = 'top';gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u396'] = 'top';gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u354'] = 'top';gv_vAlignTable['u273'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u105'] = 'top';gv_vAlignTable['u222'] = 'top';gv_vAlignTable['u372'] = 'top';gv_vAlignTable['u417'] = 'center';gv_vAlignTable['u489'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u534'] = 'top';gv_vAlignTable['u272'] = 'center';gv_vAlignTable['u570'] = 'top';gv_vAlignTable['u402'] = 'top';gv_vAlignTable['u336'] = 'center';gv_vAlignTable['u449'] = 'top';gv_vAlignTable['u499'] = 'top';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u308'] = 'center';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u421'] = 'center';gv_vAlignTable['u232'] = 'top';gv_vAlignTable['u394'] = 'center';gv_vAlignTable['u477'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u459'] = 'top';gv_vAlignTable['u366'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u220'] = 'top';gv_vAlignTable['u415'] = 'center';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u234'] = 'top';document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u270'] = 'top';gv_vAlignTable['u380'] = 'top';gv_vAlignTable['u546'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u338'] = 'center';gv_vAlignTable['u300'] = 'center';gv_vAlignTable['u471'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u392'] = 'top';gv_vAlignTable['u469'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u350'] = 'top';gv_vAlignTable['u487'] = 'top';document.getElementById('u508_img').tabIndex = 0;
HookHover('u508', false);
u508.style.cursor = 'pointer';
$axure.eventManager.click('u508', function(e) {
if (true) {
rdo8week67(e);
SetWidgetNotSelected('u498');
SetWidgetNotSelected('u500');
SetWidgetNotSelected('u502');
SetWidgetNotSelected('u504');
SetWidgetNotSelected('u510');
SetWidgetSelected('u508');
SetWidgetNotSelected('u506');
}
});
gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u364'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u115'] = 'top';gv_vAlignTable['u530'] = 'top';gv_vAlignTable['u427'] = 'top';document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u246'] = 'top';gv_vAlignTable['u544'] = 'top';gv_vAlignTable['u298'] = 'center';gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u312'] = 'center';gv_vAlignTable['u290'] = 'center';gv_vAlignTable['u408'] = 'top';gv_vAlignTable['u507'] = 'top';gv_vAlignTable['u485'] = 'top';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u218'] = 'top';gv_vAlignTable['u362'] = 'top';gv_vAlignTable['u439'] = 'top';gv_vAlignTable['u376'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u519'] = 'top';document.getElementById('u506_img').tabIndex = 0;
HookHover('u506', false);
u506.style.cursor = 'pointer';
$axure.eventManager.click('u506', function(e) {
if (true) {
rdo8week12345(e);
SetWidgetNotSelected('u498');
SetWidgetNotSelected('u500');
SetWidgetNotSelected('u502');
SetWidgetNotSelected('u504');
SetWidgetNotSelected('u510');
SetWidgetNotSelected('u508');
SetWidgetSelected('u506');
}
});
gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u244'] = 'top';gv_vAlignTable['u542'] = 'top';gv_vAlignTable['u390'] = 'top';gv_vAlignTable['u575'] = 'center';gv_vAlignTable['u556'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u368'] = 'top';gv_vAlignTable['u310'] = 'center';gv_vAlignTable['u505'] = 'top';gv_vAlignTable['u483'] = 'top';gv_vAlignTable['u324'] = 'top';gv_vAlignTable['u479'] = 'center';gv_vAlignTable['u441'] = 'top';gv_vAlignTable['u360'] = 'top';gv_vAlignTable['u532'] = 'top';document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u374'] = 'top';gv_vAlignTable['u352'] = 'top';gv_vAlignTable['u536'] = 'top';gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u184'] = 'top';document.getElementById('u504_img').tabIndex = 0;
HookHover('u504', false);
u504.style.cursor = 'pointer';
$axure.eventManager.click('u504', function(e) {
if (true) {
rdo8week12345(e);
SetWidgetNotSelected('u498');
SetWidgetNotSelected('u500');
SetWidgetNotSelected('u502');
SetWidgetSelected('u504');
SetWidgetNotSelected('u510');
SetWidgetNotSelected('u508');
SetWidgetNotSelected('u506');
}
});
gv_vAlignTable['u242'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u344'] = 'top';gv_vAlignTable['u386'] = 'top';gv_vAlignTable['u256'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u481'] = 'top';gv_vAlignTable['u558'] = 'top';gv_vAlignTable['u473'] = 'top';gv_vAlignTable['u566'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u453'] = 'top';gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u467'] = 'center';gv_vAlignTable['u398'] = 'top';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u140'] = 'top';document.getElementById('u498_img').tabIndex = 0;
HookHover('u498', false);
u498.style.cursor = 'pointer';
$axure.eventManager.click('u498', function(e) {
if (true) {
rdo8week12345(e);
SetWidgetSelected('u498');
SetWidgetNotSelected('u500');
SetWidgetNotSelected('u502');
SetWidgetNotSelected('u504');
SetWidgetNotSelected('u510');
SetWidgetNotSelected('u508');
SetWidgetNotSelected('u506');
}
});
gv_vAlignTable['u196'] = 'top';gv_vAlignTable['u516'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u264'] = 'top';gv_vAlignTable['u84'] = 'top';gv_vAlignTable['u258'] = 'top';gv_vAlignTable['u320'] = 'center';gv_vAlignTable['u493'] = 'top';gv_vAlignTable['u334'] = 'center';gv_vAlignTable['u451'] = 'top';
|
JavaScript
|
for(var i = 0; i < 23; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
});
gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u4'] = 'top';gv_vAlignTable['u0'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u20'] = 'top';gv_vAlignTable['u6'] = 'center';gv_vAlignTable['u2'] = 'top';gv_vAlignTable['u18'] = 'top';
|
JavaScript
|
for(var i = 0; i < 69; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u15');
SetWidgetSelected('u35');
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
}
});
function rdo491(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo492(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo493(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo494(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo495(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_加班时间管理.html'), "");
}
}
function rdo496(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo497(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo498(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置.html'), "");
}
}
function rdo499(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo4999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_考勤系统.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1工资系统.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo491(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u55'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo496(e);
}
});
gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u32'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo492(e);
}
});
gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u30'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u64'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u49'] = 'top';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u41', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u66'] = 'top';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo499(e);
}
});
gv_vAlignTable['u2'] = 'top';gv_vAlignTable['u22'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo325(e);
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo494(e);
}
});
gv_vAlignTable['u47'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo493(e);
}
});
document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u24'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u39_img').tabIndex = 0;
HookHover('u39', false);
u39.style.cursor = 'pointer';
$axure.eventManager.click('u39', function(e) {
if (true) {
rdo4999(e);
}
});
document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo498(e);
}
});
gv_vAlignTable['u26'] = 'top';HookHover('u65', false);
document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u12'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo497(e);
}
});
HookHover('u63', false);
document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u40'] = 'top';gv_vAlignTable['u14'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo321(e);
}
});
document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo495(e);
}
});
gv_vAlignTable['u59'] = 'top';
|
JavaScript
|
for(var i = 0; i < 315; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u13');
SetWidgetSelected('u58');
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u194'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u152'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u298'] = 'top';gv_vAlignTable['u1'] = 'center';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u126'] = 'top';document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u138'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u192'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u150'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u268'] = 'center';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u112'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u162'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u55'] = 'top';HookHover('u111', false);
gv_vAlignTable['u306'] = 'top';gv_vAlignTable['u284'] = 'center';gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u110'] = 'top';
u279.style.cursor = 'pointer';
$axure.eventManager.click('u279', function(e) {
if (true) {
NewWindow($axure.globalVariableProvider.getLinkUrl('保险明细方案.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
gv_vAlignTable['u274'] = 'center';gv_vAlignTable['u160'] = 'top';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u49'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u304'] = 'center';gv_vAlignTable['u282'] = 'center';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u278'] = 'top';gv_vAlignTable['u240'] = 'top';gv_vAlignTable['u296'] = 'center';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u290'] = 'top';gv_vAlignTable['u99'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u51'] = 'top';HookHover('u109', false);
gv_vAlignTable['u253'] = 'top';gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u302'] = 'center';gv_vAlignTable['u294'] = 'center';gv_vAlignTable['u266'] = 'center';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u134'] = 'top';gv_vAlignTable['u251'] = 'top';gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u82'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u292'] = 'center';document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u34'] = 'top';document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u146'] = 'top';document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u190'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u118'] = 'top';gv_vAlignTable['u262'] = 'center';gv_vAlignTable['u276'] = 'center';document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u249'] = 'top';gv_vAlignTable['u130'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u43'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u210'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u224'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
gv_vAlignTable['u59'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
gv_vAlignTable['u91'] = 'top';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u142'] = 'top';gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u105'] = 'top';gv_vAlignTable['u222'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u272'] = 'center';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u308'] = 'center';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u232'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u208'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u220'] = 'top';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u234'] = 'top';document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u270'] = 'center';gv_vAlignTable['u28'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u300'] = 'center';gv_vAlignTable['u186'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u247'] = 'top';gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u115'] = 'top';
u313.style.cursor = 'pointer';
$axure.eventManager.click('u313', function(e) {
if (true) {
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u312'] = 'center';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u245'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u218'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u286'] = 'center';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u244'] = 'center';gv_vAlignTable['u124'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u310'] = 'center';document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u242'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u288'] = 'center';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u10'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
gv_vAlignTable['u255'] = 'top';document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u140'] = 'top';gv_vAlignTable['u196'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u264'] = 'center';gv_vAlignTable['u84'] = 'top';
|
JavaScript
|
|
JavaScript
|
for(var i = 0; i < 342; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u11');
SetWidgetSelected('u63');
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u194'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u333'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u152'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u298'] = 'center';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u1'] = 'center';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u126'] = 'top';gv_vAlignTable['u332'] = 'center';document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u138'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u192'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u150'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u318'] = 'center';gv_vAlignTable['u268'] = 'top';gv_vAlignTable['u330'] = 'center';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u326'] = 'center';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u112'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u162'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u55'] = 'top';HookHover('u111', false);
gv_vAlignTable['u306'] = 'center';gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u283'] = 'top';gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u279'] = 'top';gv_vAlignTable['u160'] = 'top';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u49'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u304'] = 'center';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u240'] = 'top';gv_vAlignTable['u296'] = 'center';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u254'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u281'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u51'] = 'top';HookHover('u109', false);
gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u302'] = 'center';gv_vAlignTable['u316'] = 'center';gv_vAlignTable['u294'] = 'center';gv_vAlignTable['u252'] = 'top';gv_vAlignTable['u266'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u134'] = 'top';gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u82'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u314'] = 'center';gv_vAlignTable['u292'] = 'center';document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u250'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u34'] = 'top';document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u146'] = 'top';document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u277'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u190'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u118'] = 'top';gv_vAlignTable['u262'] = 'top';gv_vAlignTable['u322'] = 'center';document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u130'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u43'] = 'top';gv_vAlignTable['u275'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u210'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u260'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
gv_vAlignTable['u59'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u328'] = 'center';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u142'] = 'top';gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u156'] = 'top';document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u273'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u105'] = 'top';gv_vAlignTable['u222'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u272'] = 'center';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u308'] = 'center';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u232'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u312'] = 'center';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u220'] = 'top';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u234'] = 'top';document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u270'] = 'top';gv_vAlignTable['u28'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u300'] = 'center';gv_vAlignTable['u186'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u246'] = 'top';gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u290'] = 'center';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u218'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u244'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u310'] = 'center';gv_vAlignTable['u324'] = 'center';document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u115'] = 'top';gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u242'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u337'] = 'top';gv_vAlignTable['u256'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u10'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u140'] = 'top';gv_vAlignTable['u196'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u264'] = 'top';gv_vAlignTable['u84'] = 'top';gv_vAlignTable['u258'] = 'top';gv_vAlignTable['u320'] = 'center';gv_vAlignTable['u334'] = 'top';
|
JavaScript
|
for(var i = 0; i < 311; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u13');
SetWidgetSelected('u100');
SetPanelState('u22', 'pd1u22','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo9new(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新增一个组织"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
}
function rdo9update(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("保存当前组织信息"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
}
function rdo9delete(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("删除当前组织,当前组织如果有下级,无法删除"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u22', 'pd0u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u22', 'pd1u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u22', 'pd2u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u22', 'pd3u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u22', 'pd4u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u299'] = 'top';gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u194'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u152'] = 'center';document.getElementById('u60_img').tabIndex = 0;
HookHover('u60', false);
u60.style.cursor = 'pointer';
$axure.eventManager.click('u60', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u298'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u1'] = 'center';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u11');
SetWidgetNotSelected('u19');
SetWidgetNotSelected('u17');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
rdo11(e);
}
});
gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u165'] = 'center';gv_vAlignTable['u138'] = 'center';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo324(e);
}
});
document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u192'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo431(e);
}
});
document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u80'] = 'top';HookHover('u113', false);
gv_vAlignTable['u268'] = 'top';gv_vAlignTable['u42'] = 'top';gv_vAlignTable['u163'] = 'center';gv_vAlignTable['u63'] = 'top';gv_vAlignTable['u177'] = 'center';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo695(e);
}
});
document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo542(e);
}
});
u307.style.cursor = 'pointer';
$axure.eventManager.click('u307', function(e) {
if (true) {
rdo9new(e);
}
});
gv_vAlignTable['u18'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo543(e);
}
});
document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u55'] = 'top';gv_vAlignTable['u149'] = 'center';gv_vAlignTable['u306'] = 'top';gv_vAlignTable['u284'] = 'top';gv_vAlignTable['u12'] = 'top';
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u110', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u20'] = 'top';gv_vAlignTable['u124'] = 'center';gv_vAlignTable['u160'] = 'center';gv_vAlignTable['u49'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo691(e);
}
});
document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u88'] = 'top';gv_vAlignTable['u304'] = 'top';gv_vAlignTable['u282'] = 'top';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u278'] = 'top';gv_vAlignTable['u240'] = 'top';gv_vAlignTable['u296'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u254'] = 'top';gv_vAlignTable['u99'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u122'] = 'center';gv_vAlignTable['u5'] = 'center';gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u109'] = 'top';
u302.style.cursor = 'pointer';
$axure.eventManager.click('u302', function(e) {
if (true) {
NewWindow($axure.globalVariableProvider.getLinkUrl('组织与岗位关联.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
gv_vAlignTable['u280'] = 'top';gv_vAlignTable['u294'] = 'top';gv_vAlignTable['u135'] = 'center';document.getElementById('u108_img').tabIndex = 0;
HookHover('u108', false);
u108.style.cursor = 'pointer';
$axure.eventManager.click('u108', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u252'] = 'top';gv_vAlignTable['u171'] = 'center';gv_vAlignTable['u266'] = 'top';
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u64', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u21', function(e) {
if (true) {
SetPanelState('u22', 'pd0u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u21', function(e) {
if (true) {
SetPanelState('u22', 'pd0u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u21', function(e) {
if (true) {
SetPanelState('u22', 'pd0u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u21', function(e) {
if (true) {
SetPanelState('u22', 'pd0u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u21', function(e) {
if (true) {
SetPanelState('u22', 'pd0u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u21', function(e) {
if (true) {
SetPanelState('u22', 'pd0u22','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u82'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u292'] = 'top';document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u250'] = 'top';gv_vAlignTable['u147'] = 'center';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u90'] = 'top';gv_vAlignTable['u61'] = 'top';gv_vAlignTable['u132'] = 'center';document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u274'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u262'] = 'top';gv_vAlignTable['u276'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u144'] = 'center';
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u43', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u17_img').tabIndex = 0;
HookHover('u17', false);
u17.style.cursor = 'pointer';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u17');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u19');
rdo14(e);
}
});
gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u210'] = 'top';gv_vAlignTable['u107'] = 'top';gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u260'] = 'top';gv_vAlignTable['u157'] = 'center';gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u189'] = 'center';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo697(e);
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u91', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
u309.style.cursor = 'pointer';
$axure.eventManager.click('u309', function(e) {
if (true) {
rdo9delete(e);
}
});
document.getElementById('u106_img').tabIndex = 0;
HookHover('u106', false);
u106.style.cursor = 'pointer';
$axure.eventManager.click('u106', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u105'] = 'top';gv_vAlignTable['u222'] = 'top';gv_vAlignTable['u6'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo693(e);
}
});
gv_vAlignTable['u272'] = 'top';gv_vAlignTable['u141'] = 'center';document.getElementById('u19_img').tabIndex = 0;
HookHover('u19', false);
u19.style.cursor = 'pointer';
$axure.eventManager.click('u19', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u19');
SetWidgetNotSelected('u17');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
rdo19(e);
}
});
document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo326(e);
}
});
u308.style.cursor = 'pointer';
$axure.eventManager.click('u308', function(e) {
if (true) {
rdo9update(e);
}
});
gv_vAlignTable['u232'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u17');
SetWidgetNotSelected('u19');
rdo12(e);
}
});
gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u220'] = 'top';gv_vAlignTable['u3'] = 'center';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo694(e);
}
});
gv_vAlignTable['u234'] = 'top';document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u270'] = 'top';document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo325(e);
}
});
document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u300'] = 'top';gv_vAlignTable['u116'] = 'top';document.getElementById('u87_img').tabIndex = 0;
HookHover('u87', false);
u87.style.cursor = 'pointer';
$axure.eventManager.click('u87', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u101'] = 'top';document.getElementById('u89_img').tabIndex = 0;
HookHover('u89', false);
u89.style.cursor = 'pointer';
$axure.eventManager.click('u89', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u246'] = 'top';document.getElementById('u62_img').tabIndex = 0;
HookHover('u62', false);
u62.style.cursor = 'pointer';
$axure.eventManager.click('u62', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u114'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u290'] = 'top';gv_vAlignTable['u187'] = 'top';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u218'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo323(e);
}
});
document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u286'] = 'top';gv_vAlignTable['u168'] = 'center';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u127'] = 'center';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u244'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo692(e);
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo438(e);
}
});
$axure.eventManager.click('u310', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新增一个组织"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
$axure.eventManager.click('u310', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新增一个组织"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
$axure.eventManager.click('u310', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新增一个组织"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u185'] = 'center';gv_vAlignTable['u40'] = 'top';document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo432(e);
}
});
HookHover('u115', false);
gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u242'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo322(e);
}
});
gv_vAlignTable['u256'] = 'top';gv_vAlignTable['u288'] = 'top';gv_vAlignTable['u129'] = 'center';gv_vAlignTable['u174'] = 'center';gv_vAlignTable['u179'] = 'center';document.getElementById('u39_img').tabIndex = 0;
HookHover('u39', false);
u39.style.cursor = 'pointer';
$axure.eventManager.click('u39', function(e) {
if (true) {
rdo699(e);
}
});
document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo433(e);
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u17');
SetWidgetNotSelected('u19');
rdo13(e);
}
});
gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u182'] = 'center';gv_vAlignTable['u196'] = 'top';gv_vAlignTable['u154'] = 'center';gv_vAlignTable['u264'] = 'top';gv_vAlignTable['u84'] = 'top';gv_vAlignTable['u258'] = 'top';document.getElementById('u41_img').tabIndex = 0;
HookHover('u41', false);
u41.style.cursor = 'pointer';
$axure.eventManager.click('u41', function(e) {
if (true) {
rdo6999(e);
}
});
|
JavaScript
|
for(var i = 0; i < 1069; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u81');
SetWidgetSelected('u11');
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u602'] = 'top';gv_vAlignTable['u892'] = 'top';gv_vAlignTable['u990'] = 'top';gv_vAlignTable['u712'] = 'top';gv_vAlignTable['u684'] = 'top';gv_vAlignTable['u852'] = 'top';gv_vAlignTable['u688'] = 'top';gv_vAlignTable['u820'] = 'top';gv_vAlignTable['u400'] = 'top';gv_vAlignTable['u680'] = 'top';gv_vAlignTable['u612'] = 'top';gv_vAlignTable['u266'] = 'top';gv_vAlignTable['u234'] = 'top';gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u49'] = 'top';gv_vAlignTable['u446'] = 'top';gv_vAlignTable['u228'] = 'top';document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u414'] = 'top';gv_vAlignTable['u484'] = 'top';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u474'] = 'top';gv_vAlignTable['u408'] = 'top';gv_vAlignTable['u968'] = 'top';gv_vAlignTable['u768'] = 'top';gv_vAlignTable['u442'] = 'top';gv_vAlignTable['u800'] = 'top';gv_vAlignTable['u700'] = 'top';gv_vAlignTable['u468'] = 'top';gv_vAlignTable['u542'] = 'top';gv_vAlignTable['u396'] = 'top';document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u470'] = 'top';gv_vAlignTable['u648'] = 'top';gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u774'] = 'top';gv_vAlignTable['u826'] = 'top';gv_vAlignTable['u838'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u936'] = 'top';gv_vAlignTable['u584'] = 'top';gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u998'] = 'top';gv_vAlignTable['u796'] = 'top';gv_vAlignTable['u300'] = 'top';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u818'] = 'top';gv_vAlignTable['u932'] = 'top';gv_vAlignTable['u580'] = 'top';gv_vAlignTable['u512'] = 'top';gv_vAlignTable['u350'] = 'top';gv_vAlignTable['u792'] = 'top';gv_vAlignTable['u134'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u960'] = 'top';document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
gv_vAlignTable['u346'] = 'top';gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u162'] = 'top';gv_vAlignTable['u752'] = 'top';gv_vAlignTable['u130'] = 'top';gv_vAlignTable['u720'] = 'top';gv_vAlignTable['u374'] = 'top';gv_vAlignTable['u308'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u342'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u964'] = 'top';gv_vAlignTable['u548'] = 'top';gv_vAlignTable['u890'] = 'top';gv_vAlignTable['u12'] = 'top';document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u156'] = 'top';document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u606'] = 'top';gv_vAlignTable['u938'] = 'top';gv_vAlignTable['u994'] = 'top';gv_vAlignTable['u836'] = 'top';gv_vAlignTable['u804'] = 'top';gv_vAlignTable['u898'] = 'top';document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u864'] = 'top';gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u832'] = 'top';gv_vAlignTable['u480'] = 'top';gv_vAlignTable['u412'] = 'top';gv_vAlignTable['u858'] = 'top';gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u692'] = 'top';gv_vAlignTable['u624'] = 'top';gv_vAlignTable['u860'] = 'top';gv_vAlignTable['u896'] = 'top';gv_vAlignTable['u514'] = 'top';gv_vAlignTable['u440'] = 'top';gv_vAlignTable['u246'] = 'top';gv_vAlignTable['u82'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u652'] = 'top';gv_vAlignTable['u996'] = 'top';gv_vAlignTable['u620'] = 'top';gv_vAlignTable['u274'] = 'top';gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u242'] = 'top';gv_vAlignTable['u268'] = 'top';gv_vAlignTable['u43'] = 'top';gv_vAlignTable['u270'] = 'top';gv_vAlignTable['u448'] = 'top';gv_vAlignTable['u886'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u140'] = 'top';gv_vAlignTable['u640'] = 'top';gv_vAlignTable['u402'] = 'top';gv_vAlignTable['u384'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u146'] = 'top';gv_vAlignTable['u790'] = 'top';gv_vAlignTable['u916'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
gv_vAlignTable['u976'] = 'top';gv_vAlignTable['u550'] = 'top';gv_vAlignTable['u314'] = 'top';gv_vAlignTable['u944'] = 'top';gv_vAlignTable['u592'] = 'top';gv_vAlignTable['u524'] = 'top';gv_vAlignTable['u340'] = 'top';gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u736'] = 'top';gv_vAlignTable['u972'] = 'top';gv_vAlignTable['u552'] = 'top';gv_vAlignTable['u798'] = 'top';gv_vAlignTable['u520'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u380'] = 'top';gv_vAlignTable['u142'] = 'top';gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u758'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u760'] = 'top';gv_vAlignTable['u348'] = 'top';gv_vAlignTable['u986'] = 'top';gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u1027'] = 'center';gv_vAlignTable['u1025'] = 'center';gv_vAlignTable['u1021'] = 'center';gv_vAlignTable['u1057'] = 'top';gv_vAlignTable['u284'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u690'] = 'top';gv_vAlignTable['u496'] = 'top';gv_vAlignTable['u816'] = 'top';gv_vAlignTable['u866'] = 'top';gv_vAlignTable['u280'] = 'top';gv_vAlignTable['u876'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u286'] = 'top';gv_vAlignTable['u844'] = 'top';gv_vAlignTable['u492'] = 'top';gv_vAlignTable['u424'] = 'top';gv_vAlignTable['u240'] = 'top';gv_vAlignTable['u636'] = 'top';gv_vAlignTable['u872'] = 'top';gv_vAlignTable['u452'] = 'top';gv_vAlignTable['u698'] = 'top';gv_vAlignTable['u420'] = 'top';gv_vAlignTable['u664'] = 'top';gv_vAlignTable['u978'] = 'top';gv_vAlignTable['u1047'] = 'center';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u632'] = 'top';gv_vAlignTable['u658'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
gv_vAlignTable['u988'] = 'top';gv_vAlignTable['u660'] = 'top';gv_vAlignTable['u966'] = 'top';gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u382'] = 'top';gv_vAlignTable['u868'] = 'top';gv_vAlignTable['u908'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u716'] = 'top';gv_vAlignTable['u982'] = 'top';document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u588'] = 'top';gv_vAlignTable['u590'] = 'top';gv_vAlignTable['u910'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u1023'] = 'center';gv_vAlignTable['u392'] = 'top';gv_vAlignTable['u105'] = 'top';gv_vAlignTable['u324'] = 'top';gv_vAlignTable['u954'] = 'top';gv_vAlignTable['u1029'] = 'center';gv_vAlignTable['u956'] = 'top';gv_vAlignTable['u536'] = 'top';gv_vAlignTable['u86'] = 'top';document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u504'] = 'top';gv_vAlignTable['u598'] = 'top';gv_vAlignTable['u101'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u918'] = 'top';gv_vAlignTable['u564'] = 'top';gv_vAlignTable['u532'] = 'top';gv_vAlignTable['u776'] = 'top';gv_vAlignTable['u558'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u744'] = 'top';gv_vAlignTable['u560'] = 'top';gv_vAlignTable['u148'] = 'top';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u882'] = 'top';gv_vAlignTable['u55'] = 'top';gv_vAlignTable['u930'] = 'top';gv_vAlignTable['u904'] = 'top';gv_vAlignTable['u704'] = 'top';gv_vAlignTable['u490'] = 'top';gv_vAlignTable['u540'] = 'top';gv_vAlignTable['u810'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u856'] = 'top';gv_vAlignTable['u436'] = 'top';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u404'] = 'top';gv_vAlignTable['u498'] = 'top';gv_vAlignTable['u220'] = 'top';gv_vAlignTable['u706'] = 'top';gv_vAlignTable['u616'] = 'top';gv_vAlignTable['u740'] = 'top';gv_vAlignTable['u432'] = 'top';gv_vAlignTable['u878'] = 'top';gv_vAlignTable['u676'] = 'top';gv_vAlignTable['u458'] = 'top';gv_vAlignTable['u644'] = 'top';gv_vAlignTable['u460'] = 'top';gv_vAlignTable['u638'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u672'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u117'] = 'top';gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u596'] = 'top';gv_vAlignTable['u926'] = 'top';gv_vAlignTable['u546'] = 'top';gv_vAlignTable['u390'] = 'top';gv_vAlignTable['u2'] = 'top';gv_vAlignTable['u786'] = 'top';gv_vAlignTable['u848'] = 'top';gv_vAlignTable['u922'] = 'top';gv_vAlignTable['u714'] = 'top';gv_vAlignTable['u782'] = 'top';gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u196'] = 'top';gv_vAlignTable['u950'] = 'top';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u336'] = 'top';gv_vAlignTable['u304'] = 'top';gv_vAlignTable['u398'] = 'top';gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u710'] = 'top';gv_vAlignTable['u516'] = 'top';gv_vAlignTable['u604'] = 'top';gv_vAlignTable['u332'] = 'top';gv_vAlignTable['u576'] = 'top';gv_vAlignTable['u358'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u544'] = 'top';gv_vAlignTable['u360'] = 'top';gv_vAlignTable['u756'] = 'top';gv_vAlignTable['u538'] = 'top';gv_vAlignTable['u656'] = 'top';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u572'] = 'top';gv_vAlignTable['u70'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u718'] = 'top';gv_vAlignTable['u778'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
u1017.style.cursor = 'pointer';
$axure.eventManager.click('u1017', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("点击时将进行提示,同意后将指定范围内的员工考勤记录标识为需要重算。有重算标识的记录每天自动运算的作业会启动重算程序。"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u1015'] = 'top';gv_vAlignTable['u1014'] = 'top';gv_vAlignTable['u1012'] = 'top';gv_vAlignTable['u1010'] = 'top';gv_vAlignTable['u290'] = 'top';gv_vAlignTable['u888'] = 'top';gv_vAlignTable['u686'] = 'top';gv_vAlignTable['u822'] = 'top';gv_vAlignTable['u1043'] = 'center';gv_vAlignTable['u682'] = 'top';gv_vAlignTable['u850'] = 'top';gv_vAlignTable['u370'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u928'] = 'top';gv_vAlignTable['u152'] = 'top';gv_vAlignTable['u204'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u610'] = 'top';gv_vAlignTable['u416'] = 'top';gv_vAlignTable['u232'] = 'top';gv_vAlignTable['u476'] = 'top';gv_vAlignTable['u258'] = 'top';gv_vAlignTable['u84'] = 'top';gv_vAlignTable['u444'] = 'top';gv_vAlignTable['u260'] = 'top';gv_vAlignTable['u438'] = 'top';gv_vAlignTable['u472'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u222'] = 'top';gv_vAlignTable['u830'] = 'top';gv_vAlignTable['u906'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u618'] = 'top';gv_vAlignTable['u678'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
gv_vAlignTable['u732'] = 'top';gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u190'] = 'top';gv_vAlignTable['u586'] = 'top';gv_vAlignTable['u1052'] = 'top';gv_vAlignTable['u1051'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u934'] = 'top';gv_vAlignTable['u582'] = 'top';gv_vAlignTable['u902'] = 'top';HookHover('u111', false);
gv_vAlignTable['u794'] = 'top';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u726'] = 'top';gv_vAlignTable['u962'] = 'top';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u788'] = 'top';gv_vAlignTable['u510'] = 'top';gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u754'] = 'top';gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u376'] = 'top';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u320'] = 'top';gv_vAlignTable['u344'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u160'] = 'top';gv_vAlignTable['u750'] = 'top';gv_vAlignTable['u556'] = 'top';gv_vAlignTable['u338'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
gv_vAlignTable['u372'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u518'] = 'top';gv_vAlignTable['u578'] = 'top';document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u958'] = 'top';gv_vAlignTable['u486'] = 'top';gv_vAlignTable['u1066'] = 'top';gv_vAlignTable['u1064'] = 'top';gv_vAlignTable['u1063'] = 'top';gv_vAlignTable['u806'] = 'top';gv_vAlignTable['u1060'] = 'top';gv_vAlignTable['u834'] = 'top';gv_vAlignTable['u482'] = 'top';gv_vAlignTable['u802'] = 'top';gv_vAlignTable['u694'] = 'top';gv_vAlignTable['u828'] = 'top';gv_vAlignTable['u626'] = 'top';gv_vAlignTable['u862'] = 'top';gv_vAlignTable['u410'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u654'] = 'top';gv_vAlignTable['u622'] = 'top';gv_vAlignTable['u276'] = 'top';gv_vAlignTable['u244'] = 'top';gv_vAlignTable['u650'] = 'top';gv_vAlignTable['u456'] = 'top';gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u272'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
gv_vAlignTable['u418'] = 'top';gv_vAlignTable['u738'] = 'top';gv_vAlignTable['u292'] = 'top';gv_vAlignTable['u478'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u386'] = 'top';gv_vAlignTable['u900'] = 'top';gv_vAlignTable['u264'] = 'top';gv_vAlignTable['u946'] = 'top';gv_vAlignTable['u594'] = 'top';gv_vAlignTable['u526'] = 'top';gv_vAlignTable['u914'] = 'top';gv_vAlignTable['u296'] = 'top';gv_vAlignTable['u974'] = 'top';gv_vAlignTable['u310'] = 'top';gv_vAlignTable['u116'] = 'center';gv_vAlignTable['u554'] = 'top';gv_vAlignTable['u942'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u522'] = 'top';gv_vAlignTable['u766'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u734'] = 'top';gv_vAlignTable['u970'] = 'top';gv_vAlignTable['u702'] = 'top';gv_vAlignTable['u356'] = 'top';gv_vAlignTable['u138'] = 'top';gv_vAlignTable['u728'] = 'top';gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u762'] = 'top';gv_vAlignTable['u730'] = 'top';gv_vAlignTable['u772'] = 'top';gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u318'] = 'top';gv_vAlignTable['u378'] = 'top';gv_vAlignTable['u1045'] = 'center';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u1041'] = 'center';gv_vAlignTable['u434'] = 'top';gv_vAlignTable['u1049'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u1006'] = 'top';gv_vAlignTable['u1004'] = 'top';gv_vAlignTable['u1002'] = 'top';gv_vAlignTable['u1000'] = 'top';gv_vAlignTable['u364'] = 'top';gv_vAlignTable['u1008'] = 'top';gv_vAlignTable['u846'] = 'top';gv_vAlignTable['u494'] = 'top';gv_vAlignTable['u426'] = 'top';gv_vAlignTable['u814'] = 'top';gv_vAlignTable['u488'] = 'top';gv_vAlignTable['u874'] = 'top';gv_vAlignTable['u254'] = 'top';gv_vAlignTable['u808'] = 'top';gv_vAlignTable['u454'] = 'top';gv_vAlignTable['u842'] = 'top';gv_vAlignTable['u422'] = 'top';gv_vAlignTable['u666'] = 'top';gv_vAlignTable['u634'] = 'top';gv_vAlignTable['u870'] = 'top';gv_vAlignTable['u450'] = 'top';gv_vAlignTable['u256'] = 'top';gv_vAlignTable['u628'] = 'top';gv_vAlignTable['u662'] = 'top';gv_vAlignTable['u298'] = 'top';gv_vAlignTable['u630'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u218'] = 'top';gv_vAlignTable['u278'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u312'] = 'top';gv_vAlignTable['u984'] = 'top';gv_vAlignTable['u824'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u980'] = 'top';gv_vAlignTable['u464'] = 'top';gv_vAlignTable['u912'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u210'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u770'] = 'top';gv_vAlignTable['u940'] = 'top';gv_vAlignTable['u326'] = 'top';gv_vAlignTable['u316'] = 'top';gv_vAlignTable['u388'] = 'top';gv_vAlignTable['u354'] = 'top';gv_vAlignTable['u506'] = 'top';gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u322'] = 'top';gv_vAlignTable['u566'] = 'top';gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u534'] = 'top';gv_vAlignTable['u502'] = 'top';gv_vAlignTable['u948'] = 'top';gv_vAlignTable['u746'] = 'top';gv_vAlignTable['u528'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u562'] = 'top';gv_vAlignTable['u1033'] = 'center';gv_vAlignTable['u530'] = 'top';gv_vAlignTable['u708'] = 'top';gv_vAlignTable['u742'] = 'top';gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u894'] = 'top';gv_vAlignTable['u394'] = 'top';gv_vAlignTable['u696'] = 'top';gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u884'] = 'top';document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u880'] = 'top';gv_vAlignTable['u812'] = 'top';gv_vAlignTable['u428'] = 'top';
u1054.style.cursor = 'pointer';
$axure.eventManager.click('u1054', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("弹出窗口选择新的打卡方案,更新后返回。"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
u1053.style.cursor = 'pointer';
$axure.eventManager.click('u1053', function(e) {
if (true) {
NewWindow($axure.globalVariableProvider.getLinkUrl('员工考勤生成流程说明.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
gv_vAlignTable['u840'] = 'top';gv_vAlignTable['u294'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u288'] = 'top';gv_vAlignTable['u600'] = 'top';gv_vAlignTable['u406'] = 'top';gv_vAlignTable['u252'] = 'top';gv_vAlignTable['u192'] = 'top';gv_vAlignTable['u282'] = 'top';gv_vAlignTable['u466'] = 'top';document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u250'] = 'top';document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u646'] = 'top';gv_vAlignTable['u368'] = 'top';gv_vAlignTable['u614'] = 'top';gv_vAlignTable['u430'] = 'top';gv_vAlignTable['u674'] = 'top';gv_vAlignTable['u608'] = 'top';gv_vAlignTable['u642'] = 'top';gv_vAlignTable['u668'] = 'top';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u262'] = 'top';gv_vAlignTable['u462'] = 'top';gv_vAlignTable['u670'] = 'top';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u992'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u924'] = 'top';gv_vAlignTable['u194'] = 'top';gv_vAlignTable['u784'] = 'top';gv_vAlignTable['u126'] = 'top';gv_vAlignTable['u150'] = 'top';gv_vAlignTable['u952'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u920'] = 'top';gv_vAlignTable['u500'] = 'top';gv_vAlignTable['u306'] = 'top';gv_vAlignTable['u352'] = 'top';gv_vAlignTable['u780'] = 'top';gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u366'] = 'top';gv_vAlignTable['u334'] = 'top';gv_vAlignTable['u724'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u302'] = 'top';gv_vAlignTable['u722'] = 'top';HookHover('u109', false);
gv_vAlignTable['u328'] = 'top';gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u362'] = 'top';gv_vAlignTable['u330'] = 'top';gv_vAlignTable['u574'] = 'top';gv_vAlignTable['u508'] = 'top';
u1018.style.cursor = 'pointer';
$axure.eventManager.click('u1018', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("对查询条件内容的记录进行立即后台重算,直接调用重算语句。一般用于小范围(时间比较 短,并且涉及人员少)"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u568'] = 'top';gv_vAlignTable['u14'] = 'top';document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u854'] = 'top';gv_vAlignTable['u570'] = 'top';gv_vAlignTable['u1037'] = 'center';gv_vAlignTable['u748'] = 'top';gv_vAlignTable['u1035'] = 'center';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
gv_vAlignTable['u1031'] = 'center';gv_vAlignTable['u1039'] = 'center';gv_vAlignTable['u764'] = 'top';
|
JavaScript
|
for(var i = 0; i < 391; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u9');
SetWidgetSelected('u94');
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u299'] = 'top';gv_vAlignTable['u319'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u36'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u194'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u333'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u152'] = 'top';gv_vAlignTable['u347'] = 'top';gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u166'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u1'] = 'center';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u126'] = 'top';gv_vAlignTable['u275'] = 'top';gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u138'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u192'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u269'] = 'top';gv_vAlignTable['u331'] = 'top';gv_vAlignTable['u321'] = 'top';gv_vAlignTable['u150'] = 'top';gv_vAlignTable['u287'] = 'top';gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u345'] = 'top';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u80'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u307'] = 'top';gv_vAlignTable['u285'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u162'] = 'top';gv_vAlignTable['u357'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u55'] = 'top';HookHover('u111', false);
gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u305'] = 'top';gv_vAlignTable['u283'] = 'top';gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u279'] = 'top';gv_vAlignTable['u160'] = 'top';gv_vAlignTable['u297'] = 'top';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u49'] = 'top';gv_vAlignTable['u355'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u240'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u343'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u303'] = 'top';gv_vAlignTable['u281'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u317'] = 'top';gv_vAlignTable['u295'] = 'top';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u51'] = 'top';HookHover('u109', false);
gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u359'] = 'top';gv_vAlignTable['u267'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
gv_vAlignTable['u252'] = 'top';
u386.style.cursor = 'pointer';
$axure.eventManager.click('u386', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("执行取消备案标识"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u301'] = 'top';gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u2'] = 'top';gv_vAlignTable['u315'] = 'top';gv_vAlignTable['u293'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u134'] = 'top';gv_vAlignTable['u251'] = 'center';gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u373'] = 'top';gv_vAlignTable['u265'] = 'top';gv_vAlignTable['u82'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u200'] = 'top';document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u369'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u34'] = 'top';document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u327'] = 'top';gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u255'] = 'top';gv_vAlignTable['u146'] = 'top';document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u263'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u277'] = 'top';gv_vAlignTable['u388'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u190'] = 'top';
u385.style.cursor = 'pointer';
$axure.eventManager.click('u385', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("对选中的内容进行批量完成备案标识"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u28'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u249'] = 'top';gv_vAlignTable['u130'] = 'top';
u384.style.cursor = 'pointer';
$axure.eventManager.click('u384', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("导入当前显示未备案的明细到文件中"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u261'] = 'top';gv_vAlignTable['u43'] = 'top';document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u329'] = 'top';gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u210'] = 'top';gv_vAlignTable['u325'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u383'] = 'top';gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u379'] = 'top';gv_vAlignTable['u341'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
gv_vAlignTable['u59'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u309'] = 'top';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u142'] = 'top';gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u273'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u105'] = 'top';gv_vAlignTable['u381'] = 'top';gv_vAlignTable['u222'] = 'top';gv_vAlignTable['u311'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u353'] = 'top';gv_vAlignTable['u367'] = 'top';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u232'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u271'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u339'] = 'top';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u220'] = 'top';gv_vAlignTable['u117'] = 'top';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u234'] = 'top';gv_vAlignTable['u351'] = 'top';gv_vAlignTable['u365'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u116'] = 'center';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u198'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u313'] = 'top';gv_vAlignTable['u291'] = 'top';document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u246'] = 'top';gv_vAlignTable['u363'] = 'top';gv_vAlignTable['u377'] = 'top';gv_vAlignTable['u259'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u218'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u349'] = 'top';gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u244'] = 'top';gv_vAlignTable['u390'] = 'top';gv_vAlignTable['u361'] = 'top';gv_vAlignTable['u375'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u257'] = 'top';document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u289'] = 'top';gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u206'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u323'] = 'top';gv_vAlignTable['u242'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u337'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u10'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u140'] = 'top';gv_vAlignTable['u196'] = 'top';gv_vAlignTable['u335'] = 'top';document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u371'] = 'top';gv_vAlignTable['u84'] = 'top';
|
JavaScript
|
for(var i = 0; i < 9; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
});
gv_vAlignTable['u4'] = 'top';gv_vAlignTable['u5'] = 'top';gv_vAlignTable['u7'] = 'center';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u3'] = 'center';
|
JavaScript
|
for(var i = 0; i < 115; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u13');
SetWidgetSelected('u56');
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3自定义列取数设置.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单生成.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u95'] = 'top';document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u86'] = 'top';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u55'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u38'] = 'top';document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u97'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u1'] = 'center';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u84'] = 'top';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u8'] = 'top';
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1员工工资方案管理.html'), "");
}
});
gv_vAlignTable['u34'] = 'top';HookHover('u111', false);
gv_vAlignTable['u64'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u49'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
gv_vAlignTable['u51'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u36'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u66'] = 'top';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u2'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u22'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u43'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
HookHover('u109', false);
document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u101'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u14'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u103'] = 'top';document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u26'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u105'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u82'] = 'top';document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u112'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u72'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u10'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u99'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u74'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u91'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
|
JavaScript
|
for(var i = 0; i < 128; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u15');
SetWidgetSelected('u27');
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
}
});
function rdo491(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo492(e) {
}
function rdo493(e) {
}
function rdo494(e) {
}
function rdo495(e) {
}
function rdo496(e) {
}
function rdo499(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统参数设置.html'), "");
}
}
function rdo6new(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新建一个参数字段"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
}
function rdo6edit(e) {
}
function rdo6delete(e) {
}
function rdo6print(e) {
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_考勤系统.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1工资系统.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo491(e);
}
});
gv_vAlignTable['u86'] = 'center';HookHover('u51', false);
document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo493(e);
}
});
gv_vAlignTable['u16'] = 'top';document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo328(e);
}
});
document.getElementById('u38_img').tabIndex = 0;
HookHover('u38', false);
u38.style.cursor = 'pointer';
$axure.eventManager.click('u38', function(e) {
if (true) {
rdo324(e);
}
});
document.getElementById('u32_img').tabIndex = 0;
HookHover('u32', false);
u32.style.cursor = 'pointer';
$axure.eventManager.click('u32', function(e) {
if (true) {
rdo321(e);
}
});
document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo492(e);
}
});
gv_vAlignTable['u62'] = 'center';HookHover('u53', false);
gv_vAlignTable['u1'] = 'center';document.getElementById('u119_img').tabIndex = 0;
HookHover('u119', false);
u119.style.cursor = 'pointer';
$axure.eventManager.click('u119', function(e) {
if (true) {
rdo6new(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
gv_vAlignTable['u115'] = 'top';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u89'] = 'center';gv_vAlignTable['u122'] = 'center';document.getElementById('u34_img').tabIndex = 0;
HookHover('u34', false);
u34.style.cursor = 'pointer';
$axure.eventManager.click('u34', function(e) {
if (true) {
rdo322(e);
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u64'] = 'center';gv_vAlignTable['u100'] = 'center';gv_vAlignTable['u103'] = 'center';gv_vAlignTable['u81'] = 'center';gv_vAlignTable['u97'] = 'center';gv_vAlignTable['u124'] = 'center';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u41'] = 'top';gv_vAlignTable['u108'] = 'center';document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u45'] = 'top';document.getElementById('u36_img').tabIndex = 0;
HookHover('u36', false);
u36.style.cursor = 'pointer';
$axure.eventManager.click('u36', function(e) {
if (true) {
rdo323(e);
}
});
gv_vAlignTable['u75'] = 'center';gv_vAlignTable['u58'] = 'center';gv_vAlignTable['u37'] = 'top';gv_vAlignTable['u126'] = 'center';gv_vAlignTable['u2'] = 'top';gv_vAlignTable['u22'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u52'] = 'top';gv_vAlignTable['u43'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo499(e);
}
});
gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u84'] = 'center';gv_vAlignTable['u28'] = 'top';gv_vAlignTable['u24'] = 'top';gv_vAlignTable['u54'] = 'top';gv_vAlignTable['u39'] = 'top';gv_vAlignTable['u111'] = 'center';gv_vAlignTable['u69'] = 'center';gv_vAlignTable['u78'] = 'center';gv_vAlignTable['u120'] = 'center';gv_vAlignTable['u114'] = 'center';gv_vAlignTable['u94'] = 'center';gv_vAlignTable['u91'] = 'center';gv_vAlignTable['u35'] = 'top';gv_vAlignTable['u26'] = 'top';
$axure.eventManager.click('u127', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新建一个参数字段"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
$axure.eventManager.click('u127', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新建一个参数字段"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
$axure.eventManager.click('u127', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新建一个参数字段"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
$axure.eventManager.click('u127', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("新建一个参数字段"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u105'] = 'center';document.getElementById('u123_img').tabIndex = 0;
HookHover('u123', false);
u123.style.cursor = 'pointer';
$axure.eventManager.click('u123', function(e) {
if (true) {
rdo6delete(e);
}
});
gv_vAlignTable['u12'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo326(e);
}
});
gv_vAlignTable['u33'] = 'top';gv_vAlignTable['u72'] = 'center';
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u48', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u67'] = 'center';document.getElementById('u125_img').tabIndex = 0;
HookHover('u125', false);
u125.style.cursor = 'pointer';
$axure.eventManager.click('u125', function(e) {
if (true) {
rdo6print(e);
}
});
gv_vAlignTable['u10'] = 'top';document.getElementById('u40_img').tabIndex = 0;
HookHover('u40', false);
u40.style.cursor = 'pointer';
$axure.eventManager.click('u40', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u14'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo327(e);
}
});
$axure.eventManager.click('u29', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u29', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u29', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u29', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u29', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u29', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u29', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u121_img').tabIndex = 0;
HookHover('u121', false);
u121.style.cursor = 'pointer';
$axure.eventManager.click('u121', function(e) {
if (true) {
rdo6edit(e);
}
});
|
JavaScript
|
for(var i = 0; i < 253; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u9');
SetWidgetSelected('u102');
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo8new(e) {
if (true) {
parent.window.close();
NewWindow($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
}
function rdo8edit(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
}
}
function rdo8delete(e) {
}
function rdo8print(e) {
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u32'] = 'top';
$axure.eventManager.click('u252', function(e) {
if (true) {
parent.window.close();
NewWindow($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
$axure.eventManager.click('u252', function(e) {
if (true) {
parent.window.close();
NewWindow($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
$axure.eventManager.click('u252', function(e) {
if (true) {
parent.window.close();
NewWindow($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
$axure.eventManager.click('u252', function(e) {
if (true) {
parent.window.close();
NewWindow($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "", "directories=1, height=500, location=1, menubar=1, resizable=1, scrollbars=1, status=1, toolbar=1, width=500", true, 500, 500);
}
});
gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u130'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u140'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u222'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u55'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u105'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u24'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
gv_vAlignTable['u247'] = 'center';document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u238'] = 'top';gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u239'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u146'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u116'] = 'center';gv_vAlignTable['u172'] = 'top';document.getElementById('u246_img').tabIndex = 0;
HookHover('u246', false);
u246.style.cursor = 'pointer';
$axure.eventManager.click('u246', function(e) {
if (true) {
rdo8edit(e);
}
});
document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u249'] = 'center';gv_vAlignTable['u10'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u82'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u74'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u160'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
gv_vAlignTable['u126'] = 'top';document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u251'] = 'center';gv_vAlignTable['u198'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u214'] = 'top';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u43'] = 'top';gv_vAlignTable['u240'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u150'] = 'top';gv_vAlignTable['u28'] = 'top';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u142'] = 'top';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u154'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
document.getElementById('u250_img').tabIndex = 0;
HookHover('u250', false);
u250.style.cursor = 'pointer';
$axure.eventManager.click('u250', function(e) {
if (true) {
rdo8print(e);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u206'] = 'top';HookHover('u109', false);
gv_vAlignTable['u84'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u97'] = 'top';document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u134'] = 'top';document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u128'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u190'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u234'] = 'top';gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u162'] = 'top';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u117'] = 'top';gv_vAlignTable['u210'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u152'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
HookHover('u111', false);
document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u245'] = 'center';gv_vAlignTable['u86'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u36'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u232'] = 'top';document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u192'] = 'top';gv_vAlignTable['u196'] = 'top';document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u49'] = 'top';gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u138'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u93'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u12'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
gv_vAlignTable['u59'] = 'top';document.getElementById('u244_img').tabIndex = 0;
HookHover('u244', false);
u244.style.cursor = 'pointer';
$axure.eventManager.click('u244', function(e) {
if (true) {
rdo8new(e);
}
});
gv_vAlignTable['u110'] = 'top';document.getElementById('u248_img').tabIndex = 0;
HookHover('u248', false);
u248.style.cursor = 'pointer';
$axure.eventManager.click('u248', function(e) {
if (true) {
rdo8delete(e);
}
});
gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u220'] = 'top';gv_vAlignTable['u182'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u218'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u194'] = 'top';
|
JavaScript
|
for(var i = 0; i < 264; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u15');
SetWidgetSelected('u27');
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u122'] = 'center';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u130'] = 'center';gv_vAlignTable['u2'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u140'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u222'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u55'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u105'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
gv_vAlignTable['u259'] = 'top';document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u120'] = 'center';gv_vAlignTable['u24'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u238'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u133'] = 'top';gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u214'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u253'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u246'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u174'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u249'] = 'top';gv_vAlignTable['u10'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u82'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u74'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u160'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u126'] = 'center';document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u251'] = 'top';gv_vAlignTable['u198'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u43'] = 'top';gv_vAlignTable['u257'] = 'top';gv_vAlignTable['u240'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u150'] = 'top';gv_vAlignTable['u28'] = 'top';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u142'] = 'top';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u68'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u192'] = 'top';document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u206'] = 'top';HookHover('u109', false);
gv_vAlignTable['u84'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u97'] = 'top';document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u148'] = 'top';document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u138'] = 'top';gv_vAlignTable['u255'] = 'top';gv_vAlignTable['u128'] = 'center';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u190'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u234'] = 'top';gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u242'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u162'] = 'top';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u210'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
gv_vAlignTable['u152'] = 'top';document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
HookHover('u111', false);
document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u132'] = 'center';gv_vAlignTable['u86'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u36'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
gv_vAlignTable['u154'] = 'top';gv_vAlignTable['u232'] = 'top';document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u8'] = 'top';gv_vAlignTable['u188'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u146'] = 'top';gv_vAlignTable['u196'] = 'top';document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u49'] = 'top';gv_vAlignTable['u124'] = 'center';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u136'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u118'] = 'center';gv_vAlignTable['u244'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u248'] = 'center';gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u220'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u218'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u194'] = 'top';
|
JavaScript
|
for(var i = 0; i < 202; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u15');
SetWidgetSelected('u31');
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u115'] = 'top';gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u130'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u140'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u55'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u105'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u152'] = 'top';gv_vAlignTable['u24'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u146'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u191'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u158'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
gv_vAlignTable['u197'] = 'top';document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u174'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u182'] = 'top';gv_vAlignTable['u10'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u82'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u195'] = 'top';gv_vAlignTable['u74'] = 'top';gv_vAlignTable['u156'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u160'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
gv_vAlignTable['u126'] = 'top';document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u43'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u150'] = 'top';gv_vAlignTable['u28'] = 'top';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
gv_vAlignTable['u142'] = 'top';
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u154'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
gv_vAlignTable['u193'] = 'top';document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
HookHover('u109', false);
gv_vAlignTable['u84'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u97'] = 'top';document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u134'] = 'top';document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
gv_vAlignTable['u128'] = 'top';document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u190'] = 'center';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u162'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
HookHover('u111', false);
document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u86'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u36'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u8'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u49'] = 'top';gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u138'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u93'] = 'top';gv_vAlignTable['u12'] = 'top';gv_vAlignTable['u201'] = 'top';gv_vAlignTable['u199'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u118'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u22'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u180'] = 'top';
|
JavaScript
|
|
JavaScript
|
for(var i = 0; i < 0; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
});
|
JavaScript
|
for(var i = 0; i < 251; i++) { var scriptId = 'u' + i; window[scriptId] = document.getElementById(scriptId); }
$axure.eventManager.pageLoad(
function (e) {
if (true) {
SetWidgetSelected('u9');
SetWidgetSelected('u100');
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
}
});
function rdo431(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo432(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_2请假管理.html'), "");
}
}
function rdo433(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_3产假管理.html'), "");
}
}
function rdo434(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_4停工待料管理.html'), "");
}
}
function rdo435(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_5因工外出管理.html'), "");
}
}
function rdo436(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_6排班方案管理.html'), "");
}
}
function rdo437(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_7打卡时间管理.html'), "");
}
}
function rdo438(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_8倒班管理.html'), "");
}
}
function rdo439(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_9员工考勤生成.html'), "");
}
}
function rdo4310(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_10员工考勤查询.html'), "");
}
}
function rdo4311(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_11考勤自定义编辑.html'), "");
}
}
function rdo4312(e) {
if (true) {
parent.window.close();
NewTab('#', "");
}
}
function rdo4313(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_13忘打卡管理.html'), "");
}
}
function rdo691(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo692(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_2_会计期间管理.html'), "");
}
}
function rdo693(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_3_DAY全年初始化.html'), "");
}
}
function rdo694(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_4_连续工作时间管理.html'), "");
}
}
function rdo695(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_5_法定假日设置.html'), "");
}
}
function rdo696(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_6_全年总工时控制.html'), "");
}
}
function rdo697(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_7_公司年假方式设置.html'), "");
}
}
function rdo698(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_8_工资表结构设置-重复了.html'), "");
}
}
function rdo699(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_9_系统权限设置.html'), "");
}
}
function rdo6999(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_99_系统参数设置.html'), "");
}
}
function rdo11(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
}
function rdo12(e) {
if (true) {
SetPanelState('u18', 'pd1u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo13(e) {
if (true) {
SetPanelState('u18', 'pd2u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
}
function rdo14(e) {
if (true) {
SetPanelState('u18', 'pd3u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo15(e) {
}
function rdo19(e) {
if (true) {
SetPanelState('u18', 'pd4u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
}
function rdo321(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
}
function rdo322(e) {
if (true) {
NewTab($axure.globalVariableProvider.getLinkUrl('2_2_新增员工档案.html'), "");
parent.window.close();
}
}
function rdo323(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_3_未成年工档案管理.html'), "");
}
}
function rdo324(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_4_公司组织结构管理.html'), "");
}
}
function rdo325(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_5_岗位工种管理.html'), "");
}
}
function rdo326(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_6_员工离职管理.html'), "");
}
}
function rdo327(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_7_体检记录管理.html'), "");
}
}
function rdo328(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_8_员工合同管理.html'), "");
}
}
function rdo541(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
}
function rdo542(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_2工资表结构设置.html'), "");
}
}
function rdo543(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_3动态数据源管理.html'), "");
}
}
function rdo544(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_4每月工资运算管理.html'), "");
}
}
function rdo545(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_5每月工资表查询.html'), "");
}
}
function rdo546(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_6离职工资管理.html'), "");
}
}
function rdo547(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_7银行对帐单格式定义.html'), "");
}
}
function rdo548(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_8银行对帐单查询.html'), "");
}
}
function rdo549(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_9保险种类管理.html'), "");
}
}
gv_vAlignTable['u122'] = 'top';gv_vAlignTable['u53'] = 'top';gv_vAlignTable['u32'] = 'top';gv_vAlignTable['u156'] = 'top';gv_vAlignTable['u130'] = 'top';gv_vAlignTable['u2'] = 'top';document.getElementById('u79_img').tabIndex = 0;
HookHover('u79', false);
u79.style.cursor = 'pointer';
$axure.eventManager.click('u79', function(e) {
if (true) {
rdo438(e);
}
});
gv_vAlignTable['u236'] = 'top';gv_vAlignTable['u150'] = 'top';gv_vAlignTable['u226'] = 'top';gv_vAlignTable['u140'] = 'top';
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
$axure.eventManager.click('u17', function(e) {
if (true) {
SetPanelState('u18', 'pd0u18','none','',500,'none','',500);
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('1_1首页.html'), "");
}
});
gv_vAlignTable['u222'] = 'top';gv_vAlignTable['u212'] = 'top';gv_vAlignTable['u103'] = 'top';gv_vAlignTable['u55'] = 'top';gv_vAlignTable['u101'] = 'top';gv_vAlignTable['u186'] = 'top';gv_vAlignTable['u126'] = 'top';gv_vAlignTable['u105'] = 'top';document.getElementById('u27_img').tabIndex = 0;
HookHover('u27', false);
u27.style.cursor = 'pointer';
$axure.eventManager.click('u27', function(e) {
if (true) {
rdo694(e);
}
});
document.getElementById('u7_img').tabIndex = 0;
HookHover('u7', false);
u7.style.cursor = 'pointer';
$axure.eventManager.click('u7', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '1');
SetWidgetSelected('u7');
SetWidgetNotSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
rdo11(e);
}
});
document.getElementById('u52_img').tabIndex = 0;
HookHover('u52', false);
u52.style.cursor = 'pointer';
$axure.eventManager.click('u52', function(e) {
if (true) {
rdo546(e);
}
});
document.getElementById('u11_img').tabIndex = 0;
HookHover('u11', false);
u11.style.cursor = 'pointer';
$axure.eventManager.click('u11', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '3');
SetWidgetSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo13(e);
}
});
gv_vAlignTable['u120'] = 'top';gv_vAlignTable['u24'] = 'top';document.getElementById('u48_img').tabIndex = 0;
HookHover('u48', false);
u48.style.cursor = 'pointer';
$axure.eventManager.click('u48', function(e) {
if (true) {
rdo544(e);
}
});
document.getElementById('u37_img').tabIndex = 0;
HookHover('u37', false);
u37.style.cursor = 'pointer';
$axure.eventManager.click('u37', function(e) {
if (true) {
rdo6999(e);
}
});
gv_vAlignTable['u238'] = 'top';document.getElementById('u21_img').tabIndex = 0;
HookHover('u21', false);
u21.style.cursor = 'pointer';
$axure.eventManager.click('u21', function(e) {
if (true) {
rdo691(e);
}
});
gv_vAlignTable['u200'] = 'top';gv_vAlignTable['u34'] = 'top';gv_vAlignTable['u68'] = 'top';gv_vAlignTable['u208'] = 'top';gv_vAlignTable['u47'] = 'top';gv_vAlignTable['u184'] = 'top';gv_vAlignTable['u228'] = 'top';gv_vAlignTable['u72'] = 'top';gv_vAlignTable['u112'] = 'top';gv_vAlignTable['u216'] = 'top';gv_vAlignTable['u164'] = 'top';gv_vAlignTable['u99'] = 'top';gv_vAlignTable['u146'] = 'top';gv_vAlignTable['u214'] = 'top';document.getElementById('u44_img').tabIndex = 0;
HookHover('u44', false);
u44.style.cursor = 'pointer';
$axure.eventManager.click('u44', function(e) {
if (true) {
rdo541(e);
}
});
gv_vAlignTable['u78'] = 'top';gv_vAlignTable['u57'] = 'top';gv_vAlignTable['u16'] = 'top';gv_vAlignTable['u172'] = 'top';gv_vAlignTable['u246'] = 'top';document.getElementById('u54_img').tabIndex = 0;
HookHover('u54', false);
u54.style.cursor = 'pointer';
$axure.eventManager.click('u54', function(e) {
if (true) {
rdo547(e);
}
});
document.getElementById('u67_img').tabIndex = 0;
HookHover('u67', false);
u67.style.cursor = 'pointer';
$axure.eventManager.click('u67', function(e) {
if (true) {
rdo433(e);
}
});
gv_vAlignTable['u38'] = 'top';gv_vAlignTable['u176'] = 'top';gv_vAlignTable['u26'] = 'top';gv_vAlignTable['u174'] = 'top';gv_vAlignTable['u128'] = 'top';gv_vAlignTable['u51'] = 'top';gv_vAlignTable['u182'] = 'top';
u249.style.cursor = 'pointer';
$axure.eventManager.click('u249', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("弹出窗口选择员工之后点离职操作,有离职相关信息(离职时间、原因、离职方式<自动离职、常规离职>,还有其他信息备注)"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
gv_vAlignTable['u10'] = 'top';document.getElementById('u100_img').tabIndex = 0;
HookHover('u100', false);
u100.style.cursor = 'pointer';
$axure.eventManager.click('u100', function(e) {
if (true) {
rdo326(e);
}
});
document.getElementById('u77_img').tabIndex = 0;
HookHover('u77', false);
u77.style.cursor = 'pointer';
$axure.eventManager.click('u77', function(e) {
if (true) {
rdo437(e);
}
});
gv_vAlignTable['u202'] = 'top';gv_vAlignTable['u166'] = 'top';gv_vAlignTable['u82'] = 'top';document.getElementById('u75_img').tabIndex = 0;
HookHover('u75', false);
u75.style.cursor = 'pointer';
$axure.eventManager.click('u75', function(e) {
if (true) {
rdo436(e);
}
});
gv_vAlignTable['u30'] = 'top';gv_vAlignTable['u95'] = 'top';gv_vAlignTable['u116'] = 'center';gv_vAlignTable['u158'] = 'top';gv_vAlignTable['u74'] = 'top';document.getElementById('u33_img').tabIndex = 0;
HookHover('u33', false);
u33.style.cursor = 'pointer';
$axure.eventManager.click('u33', function(e) {
if (true) {
rdo695(e);
}
});
gv_vAlignTable['u160'] = 'top';document.getElementById('u92_img').tabIndex = 0;
HookHover('u92', false);
u92.style.cursor = 'pointer';
$axure.eventManager.click('u92', function(e) {
if (true) {
rdo322(e);
}
});
document.getElementById('u46_img').tabIndex = 0;
HookHover('u46', false);
u46.style.cursor = 'pointer';
$axure.eventManager.click('u46', function(e) {
if (true) {
rdo543(e);
}
});
document.getElementById('u71_img').tabIndex = 0;
HookHover('u71', false);
u71.style.cursor = 'pointer';
$axure.eventManager.click('u71', function(e) {
if (true) {
rdo435(e);
}
});
gv_vAlignTable['u198'] = 'top';document.getElementById('u98_img').tabIndex = 0;
HookHover('u98', false);
u98.style.cursor = 'pointer';
$axure.eventManager.click('u98', function(e) {
if (true) {
rdo325(e);
}
});
gv_vAlignTable['u43'] = 'top';gv_vAlignTable['u240'] = 'top';document.getElementById('u56_img').tabIndex = 0;
HookHover('u56', false);
u56.style.cursor = 'pointer';
$axure.eventManager.click('u56', function(e) {
if (true) {
rdo548(e);
}
});
gv_vAlignTable['u28'] = 'top';document.getElementById('u42_img').tabIndex = 0;
HookHover('u42', false);
u42.style.cursor = 'pointer';
$axure.eventManager.click('u42', function(e) {
if (true) {
rdo542(e);
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
$axure.eventManager.click('u106', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('2_1_基本员工档案管理.html'), "");
}
});
gv_vAlignTable['u168'] = 'top';gv_vAlignTable['u154'] = 'top';
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
$axure.eventManager.click('u87', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('3_1_员工年假表管理.html'), "");
}
});
document.getElementById('u23_img').tabIndex = 0;
HookHover('u23', false);
u23.style.cursor = 'pointer';
$axure.eventManager.click('u23', function(e) {
if (true) {
rdo692(e);
}
});
document.getElementById('u104_img').tabIndex = 0;
HookHover('u104', false);
u104.style.cursor = 'pointer';
$axure.eventManager.click('u104', function(e) {
if (true) {
rdo328(e);
}
});
gv_vAlignTable['u192'] = 'top';
u250.style.cursor = 'pointer';
$axure.eventManager.click('u250', function(e) {
if (true) {
NewWindow("resources/Other.html#other=" + encodeURI("选中离职信息可以进行删除操作,(后续还要加上会计期间的控制,也就是会计期间已经结帐的情况 不能删除对应离职时间,也就是删除不了之前的离职信息)"), "", "directories=0, height=300, location=0, menubar=0, resizable=1, scrollbars=1, status=0, toolbar=0, width=300", true, 300, 300);
}
});
document.getElementById('u102_img').tabIndex = 0;
HookHover('u102', false);
u102.style.cursor = 'pointer';
$axure.eventManager.click('u102', function(e) {
if (true) {
rdo327(e);
}
});
document.getElementById('u65_img').tabIndex = 0;
HookHover('u65', false);
u65.style.cursor = 'pointer';
$axure.eventManager.click('u65', function(e) {
if (true) {
rdo432(e);
}
});
gv_vAlignTable['u206'] = 'top';HookHover('u109', false);
gv_vAlignTable['u84'] = 'top';document.getElementById('u50_img').tabIndex = 0;
HookHover('u50', false);
u50.style.cursor = 'pointer';
$axure.eventManager.click('u50', function(e) {
if (true) {
rdo545(e);
}
});
gv_vAlignTable['u97'] = 'top';document.getElementById('u63_img').tabIndex = 0;
HookHover('u63', false);
u63.style.cursor = 'pointer';
$axure.eventManager.click('u63', function(e) {
if (true) {
rdo431(e);
}
});
gv_vAlignTable['u14'] = 'top';gv_vAlignTable['u170'] = 'top';gv_vAlignTable['u76'] = 'top';gv_vAlignTable['u134'] = 'top';document.getElementById('u81_img').tabIndex = 0;
HookHover('u81', false);
u81.style.cursor = 'pointer';
$axure.eventManager.click('u81', function(e) {
if (true) {
rdo439(e);
}
});
document.getElementById('u94_img').tabIndex = 0;
HookHover('u94', false);
u94.style.cursor = 'pointer';
$axure.eventManager.click('u94', function(e) {
if (true) {
rdo323(e);
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
$axure.eventManager.click('u60', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('4_1静态数据源管理.html'), "");
}
});
gv_vAlignTable['u190'] = 'top';document.getElementById('u9_img').tabIndex = 0;
HookHover('u9', false);
u9.style.cursor = 'pointer';
$axure.eventManager.click('u9', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '2');
SetWidgetSelected('u9');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u15');
rdo12(e);
}
});
document.getElementById('u73_img').tabIndex = 0;
HookHover('u73', false);
u73.style.cursor = 'pointer';
$axure.eventManager.click('u73', function(e) {
if (true) {
rdo4313(e);
}
});
gv_vAlignTable['u234'] = 'top';gv_vAlignTable['u91'] = 'top';gv_vAlignTable['u242'] = 'top';gv_vAlignTable['u64'] = 'top';gv_vAlignTable['u70'] = 'top';gv_vAlignTable['u188'] = 'top';gv_vAlignTable['u230'] = 'top';gv_vAlignTable['u162'] = 'top';gv_vAlignTable['u204'] = 'top';gv_vAlignTable['u117'] = 'top';gv_vAlignTable['u210'] = 'top';document.getElementById('u13_img').tabIndex = 0;
HookHover('u13', false);
u13.style.cursor = 'pointer';
$axure.eventManager.click('u13', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '4');
SetWidgetSelected('u13');
SetWidgetNotSelected('u7');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u15');
rdo14(e);
}
});
document.getElementById('u29_img').tabIndex = 0;
HookHover('u29', false);
u29.style.cursor = 'pointer';
$axure.eventManager.click('u29', function(e) {
if (true) {
rdo696(e);
}
});
HookHover('u111', false);
document.getElementById('u90_img').tabIndex = 0;
HookHover('u90', false);
u90.style.cursor = 'pointer';
$axure.eventManager.click('u90', function(e) {
if (true) {
rdo321(e);
}
});
gv_vAlignTable['u132'] = 'top';gv_vAlignTable['u86'] = 'top';document.getElementById('u58_img').tabIndex = 0;
HookHover('u58', false);
u58.style.cursor = 'pointer';
$axure.eventManager.click('u58', function(e) {
if (true) {
rdo549(e);
}
});
gv_vAlignTable['u36'] = 'top';
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
$axure.eventManager.click('u39', function(e) {
if (true) {
parent.window.close();
NewTab($axure.globalVariableProvider.getLinkUrl('9_1_员工档案格式设置.html'), "");
}
});
document.getElementById('u31_img').tabIndex = 0;
HookHover('u31', false);
u31.style.cursor = 'pointer';
$axure.eventManager.click('u31', function(e) {
if (true) {
rdo697(e);
}
});
gv_vAlignTable['u232'] = 'top';document.getElementById('u83_img').tabIndex = 0;
HookHover('u83', false);
u83.style.cursor = 'pointer';
$axure.eventManager.click('u83', function(e) {
if (true) {
rdo4310(e);
}
});
gv_vAlignTable['u178'] = 'top';gv_vAlignTable['u8'] = 'top';document.getElementById('u96_img').tabIndex = 0;
HookHover('u96', false);
u96.style.cursor = 'pointer';
$axure.eventManager.click('u96', function(e) {
if (true) {
rdo324(e);
}
});
gv_vAlignTable['u59'] = 'top';gv_vAlignTable['u196'] = 'top';document.getElementById('u15_img').tabIndex = 0;
HookHover('u15', false);
u15.style.cursor = 'pointer';
$axure.eventManager.click('u15', function(e) {
if (true) {
SetGlobalVariableValue('CurrentType', '9');
SetWidgetSelected('u15');
SetWidgetNotSelected('u13');
SetWidgetNotSelected('u11');
SetWidgetNotSelected('u9');
SetWidgetNotSelected('u7');
rdo19(e);
}
});
gv_vAlignTable['u49'] = 'top';gv_vAlignTable['u124'] = 'top';gv_vAlignTable['u144'] = 'top';gv_vAlignTable['u136'] = 'top';gv_vAlignTable['u80'] = 'top';gv_vAlignTable['u1'] = 'center';gv_vAlignTable['u138'] = 'top';gv_vAlignTable['u148'] = 'top';gv_vAlignTable['u142'] = 'top';gv_vAlignTable['u93'] = 'top';document.getElementById('u85_img').tabIndex = 0;
HookHover('u85', false);
u85.style.cursor = 'pointer';
$axure.eventManager.click('u85', function(e) {
if (true) {
rdo4311(e);
}
});
gv_vAlignTable['u12'] = 'top';document.getElementById('u25_img').tabIndex = 0;
HookHover('u25', false);
u25.style.cursor = 'pointer';
$axure.eventManager.click('u25', function(e) {
if (true) {
rdo693(e);
}
});
gv_vAlignTable['u224'] = 'top';gv_vAlignTable['u244'] = 'top';gv_vAlignTable['u110'] = 'top';gv_vAlignTable['u248'] = 'top';gv_vAlignTable['u66'] = 'top';gv_vAlignTable['u45'] = 'top';gv_vAlignTable['u22'] = 'top';gv_vAlignTable['u152'] = 'top';gv_vAlignTable['u220'] = 'top';document.getElementById('u35_img').tabIndex = 0;
HookHover('u35', false);
u35.style.cursor = 'pointer';
$axure.eventManager.click('u35', function(e) {
if (true) {
rdo699(e);
}
});
document.getElementById('u69_img').tabIndex = 0;
HookHover('u69', false);
u69.style.cursor = 'pointer';
$axure.eventManager.click('u69', function(e) {
if (true) {
rdo434(e);
}
});
gv_vAlignTable['u218'] = 'top';gv_vAlignTable['u180'] = 'top';gv_vAlignTable['u194'] = 'top';
|
JavaScript
|
var tmp_evt;
var andy_element;
var TOUCH_START = generateTouchEvent('touchstart');
var TOUCH_END = generateTouchEvent('touchend');
var CLICK = generateHTMLEvent('click');
function dispatchTouchOn(element, eventName){
var coords = getElementCenter(element);
var evt = document.createEvent('TouchEvent');
var touches = [];
var t = document.createTouch(window, element, 12341, coords[0], coords[1], coords[0], coords[1]);
var t2 = document.createTouch(window, element, 12342, coords[0], coords[1], coords[0], coords[1]);
touches.push(t);
touches.push(t2);
var tl = document.createTouchList(touches);
evt.initTouchEvent(tl, tl, tl, eventName, window,
coords[0], coords[1], coords[0],coords[1],
false, false, false, false);
element.dispatchEvent(evt);
}
function generateHTMLEvent(eventName) {
var evt = document.createEvent('HTMLEvents');
evt.initEvent(eventName, false, false);
}
function generateMouseEvent(eventName) {
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent (eventName, true, true, window, 0,
0, 0 ,0 , 0,
false, false, false, false,
0, null);
return evt;
}
function generateTouchEvent(eventName) {
var evt = document.createEvent('TouchEvent');
evt.initTouchEvent(null, null, null, eventName, window,
0, 0, 0, 0,
false, false, false, false);
return evt;
}
function getText(element) {
if (element == null)
return null;
if (element.textContent)
return element.textContent;
else if (element.innerText)
return element.innerText;
else
return null;
}
function getClassName(elem) {
if (! elem) return null;
if (elem.className) return elem.className;
else if (elem.getAttribute) return elem.getAttribute("class");
return null;
}
function getElementCSSValue (element, attr) {
try{
if(element.currentStyle)
return element.currentStyle[attr];
else
return document.defaultView.getComputedStyle(element, false).getPropertyValue(attr);
}
catch(e){
return null;
}
}
function getElementByText(text){
var nodes = document.getElementsByTagName('*');
var node;
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
var nodeInnerText = getText(node) ? getText(node).format() : null;
if (nodeInnerText && nodeInnerText == text){
return node;
}
}
return null;
}
function getElementByTagAndText(tag, text, isInclude){
var nodes = document.getElementsByTagName(tag);
var node;
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
var nodeInnerText = getText(node) ? getText(node).format() : null;
if (nodeInnerText) {
if (isInclude == 'true'){
if (nodeInnerText.indexOf(text) != -1)
return node;
}
else{
if (nodeInnerText == text)
return node;
}
}
}
return null;
}
function getElementByXPath(xpath) {
var result = parseOrdinal(xpath);
var ordinal = Number(result.ordinal);
var content, tagName;
if (!isNaN(ordinal)) {
content = result.content;
result = parseTagAndAttr(content);
tagName = result.content;
content = result.attr;
}
else {
ordinal = 0;
result = parseTagAndAttr(xpath);
tagName = result.content;
content = result.attr;
}
var conditions = content.split(" and ");
var names = [];
var values = [];
var functions = [];
for (var i = 0; i < conditions.length; i++){
var cond = conditions[i];
var at, equals, comma, name, value;
if (cond.indexOf('contains')>=0) {
at = cond.indexOf("@");
comma = cond.indexOf(",");
if (at<0 || comma<0)
return null;
name = cond.substring(at+1, comma).trim();
value = cond.substring(comma+1, cond.length);
functions.push("contains");
}
else if (cond.indexOf('=')>=0){
at = cond.indexOf("@");
equals = cond.indexOf("=");
if (at<0 || equals<0)
return null;
name = cond.substring(at+1, equals).trim();
value = cond.substring(equals+1, cond.length);
functions.push("=");
}
values.push(value.substring(value.indexOf("\'")+1, value.lastIndexOf("\'")).trim());
names.push(name);
}
var nodes = document.getElementsByTagName(tagName);
var count = 0;
for (var i = 0; i < nodes.length; i++) {
var element = nodes[i];
var conditionSatisfied = true;
for (var j = 0; j < names.length; j++){
var attrValue;
if (names[j] == "class") attrValue = getClassName(element);
else if (names[j] == "text") attrValue = getText(element);
else attrValue = element.getAttribute(names[j]);
if (attrValue == null) {
conditionSatisfied = false;
break;
}
else
attrValue = attrValue.trim();
if (functions[j] == "=") {
if (values[j] != attrValue) {
conditionSatisfied = false;
break;
}
}
else if (functions[j] == "contains") {
if (attrValue.indexOf(values[j]) < 0) {
conditionSatisfied = false;
break;
}
}
}
if (conditionSatisfied == true) {
if (count++ == ordinal)
return element;
}
}
return null;
}
function getElementByTagAndCondition(tag, condition){
var nodes = document.getElementsByTagName(tag);
var node;
for (var i = 0; i < nodes.length; i++) {
node = nodes[i];
if (eval(condition)) {
return node;
}
}
return null;
}
function parseOrdinal(text) {
var leftPos = text.lastIndexOf("[");
var rightPos = text.lastIndexOf("]");
var content = text;
var ordinal = 0;
if (leftPos >= 0 && rightPos >= 0 && leftPos < rightPos) {
ordinal = text.substring(leftPos+1, rightPos);
content = text.substring(0, leftPos);
}
var retval = {content: content, ordinal: ordinal};
return retval;
}
function parseTagAndAttr(text) {
var leftPos = text.indexOf("[");
var rightPos = text.lastIndexOf("]");
var content = text;
var attr = null;
if (leftPos >= 0 && rightPos >= 0 && leftPos < rightPos) {
attr = text.substring(leftPos+1, rightPos);
content = text.substring(0, leftPos);
}
var retval = {content: content, attr: attr};
return retval;
}
function getElementCenter(element) {
var width = element.clientWidth;
var height = element.clientHeight;
var result = [element.offsetLeft, element.offsetTop];
element = element.offsetParent;
while (element) {
result[0] += element.offsetLeft;
result[1] += element.offsetTop;
element = element.offsetParent;
}
return [result[0]+width/2, result[1]+height/2];
}
function getElementPosition(element) {
var width = element.clientWidth;
var height = element.clientHeight;
var result = [element.offsetLeft, element.offsetTop];
element = element.parentNode;
var flag = false;
while (element) {
var webkit_transform_str = getElementCSSValue(element, '-webkit-transform');
if (webkit_transform_str && webkit_transform_str != 'none'){
try {
var pos_left_brace = webkit_transform_str.indexOf('(');
var pos_right_brace = webkit_transform_str.indexOf(')');
var matrix_str = webkit_transform_str.substring(pos_left_brace+1, pos_right_brace);
var matrix_cells = matrix_str.split(',');
var matrix = [];
for (var i in matrix_cells) {
matrix.push(parseFloat(matrix_cells[i].trim().replace('px', '')));
}
result[0] = matrix[0] * result[0] + matrix[1] * result[1] + matrix[4];
result[1] = matrix[2] * result[0] + matrix[3] * result[1] + matrix[5];
}
catch(e){
alert('error: ' + matrix_str);
}
}
if (element.offsetLeft != null && element.offsetTop != null) {
result[0] += element.offsetLeft;
result[1] += element.offsetTop;
}
element = element.parentNode;
}
return result[0]+','+result[1]+','+width+','+height;
}
function isElementPresent(){
if (andy_element) return true;
else return false;
}
function displayProperties(obj){
var str = '--- '+typeof(obj) +' | '+obj + ' ---\n';
var count = 0;
for (var i in obj)
str += '('+(++count)+'): '+ i +' | '+typeof(i)+' | '+obj[i] + '\n';
alert(str);
}
function initHTMLViewer(){
window.addEventListener('touchmove', function(ev){
alert(ev.target.outerHTML);
}, false)
}
function initDebugger(){
window.addEventListener('touchmove', function(ev){
alert(getDocumentData());
}, false)
}
function init(){
}
init();
String.prototype.format = function(){
var s = this;
s = s.replace(/\u00a0/g, " ");
return s;
}
|
JavaScript
|
// Copyright 2012 Google Inc.
/**
* @name Store Locator for Google Maps API V3
* @version 0.1
* @author Chris Broadfoot (Google)
* @fileoverview
* This library makes it easy to create a fully-featured Store Locator for
* your business's website.
*/
/**
* @license
*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Namespace for Store Locator.
* @constructor
*/
var storeLocator = function() {};
window['storeLocator'] = storeLocator;
/**
* Convert from degrees to radians.
* @private
* @param {number} degrees the number in degrees.
* @return {number} the number in radians.
*/
storeLocator.toRad_ = function(degrees) {
return degrees * Math.PI / 180;
};
|
JavaScript
|
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* Allows developers to specify a static set of stores to be used in the
* storelocator.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A DataFeed with a static set of stores. Provides sorting of stores by
* proximity and feature filtering (store must have <em>all</em> features from
* the filter).
* @example <pre>
* var dataFeed = new storeLocator.StaticDataFeed();
* jQuery.getJSON('stores.json', function(json) {
* var stores = parseStores(json);
* dataFeed.setStores(stores);
* });
* new storeLocator.View(map, dataFeed);
* </pre>
* @implements {storeLocator.DataFeed}
* @constructor
* @implements storeLocator_StaticDataFeed
*/
storeLocator.StaticDataFeed = function() {
/**
* The static list of stores.
* @private
* @type {Array.<storeLocator.Store>}
*/
this.stores_ = [];
};
storeLocator['StaticDataFeed'] = storeLocator.StaticDataFeed;
/**
* This will contain a callback to be called if getStores was called before
* setStores (i.e. if the map is waiting for data from the data source).
* @private
* @type {Function}
*/
storeLocator.StaticDataFeed.prototype.firstCallback_;
/**
* Set the stores for this data feed.
* @param {!Array.<!storeLocator.Store>} stores the stores for this data feed.
*/
storeLocator.StaticDataFeed.prototype.setStores = function(stores) {
this.stores_ = stores;
if (this.firstCallback_) {
this.firstCallback_();
} else {
delete this.firstCallback_;
}
};
/**
* @inheritDoc
*/
storeLocator.StaticDataFeed.prototype.getStores = function(bounds, features,
callback) {
// Prevent race condition - if getStores is called before stores are loaded.
if (!this.stores_.length) {
var that = this;
this.firstCallback_ = function() {
that.getStores(bounds, features, callback);
};
return;
}
// Filter stores for features.
var stores = [];
for (var i = 0, store; store = this.stores_[i]; i++) {
if (store.hasAllFeatures(features)) {
stores.push(store);
}
}
this.sortByDistance_(bounds.getCenter(), stores);
callback(stores);
};
/**
* Sorts a list of given stores by distance from a point in ascending order.
* Directly manipulates the given array (has side effects).
* @private
* @param {google.maps.LatLng} latLng the point to sort from.
* @param {!Array.<!storeLocator.Store>} stores the stores to sort.
*/
storeLocator.StaticDataFeed.prototype.sortByDistance_ = function(latLng,
stores) {
stores.sort(function(a, b) {
return a.distanceTo(latLng) - b.distanceTo(latLng);
});
};
|
JavaScript
|
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* Feature model class for Store Locator library.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Representation of a feature of a store. (e.g. 24 hours, BYO, etc).
* @example <pre>
* var feature = new storeLocator.Feature('24hour', 'Open 24 Hours');
* </pre>
* @param {string} id unique identifier for this feature.
* @param {string} name display name of this feature.
* @constructor
* @implements storeLocator_Feature
*/
storeLocator.Feature = function(id, name) {
this.id_ = id;
this.name_ = name;
};
storeLocator['Feature'] = storeLocator.Feature;
/**
* Gets this Feature's ID.
* @return {string} this feature's ID.
*/
storeLocator.Feature.prototype.getId = function() {
return this.id_;
};
/**
* Gets this Feature's display name.
* @return {string} this feature's display name.
*/
storeLocator.Feature.prototype.getDisplayName = function() {
return this.name_;
};
storeLocator.Feature.prototype.toString = function() {
return this.getDisplayName();
};
|
JavaScript
|
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* An info panel, which complements the map view of the Store Locator.
* Provides a list of stores, location search, feature filter, and directions.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* An info panel, to complement the map view.
* Provides a list of stores, location search, feature filter, and directions.
* @example <pre>
* var container = document.getElementById('panel');
* var panel = new storeLocator.Panel(container, {
* view: view,
* locationSearchLabel: 'Location:'
* });
* google.maps.event.addListener(panel, 'geocode', function(result) {
* geocodeMarker.setPosition(result.geometry.location);
* });
* </pre>
* @extends {google.maps.MVCObject}
* @param {!Node} el the element to contain this panel.
* @param {storeLocator.PanelOptions} opt_options
* @constructor
* @implements storeLocator_Panel
*/
storeLocator.Panel = function(el, opt_options) {
this.el_ = $(el);
this.el_.addClass('storelocator-panel');
this.settings_ = $.extend({
'locationSearch': true,
'locationSearchLabel': 'Where are you?',
'featureFilter': true,
'directions': true,
'view': null
}, opt_options);
this.directionsRenderer_ = new google.maps.DirectionsRenderer({
draggable: true
});
this.directionsService_ = new google.maps.DirectionsService;
this.init_();
};
storeLocator['Panel'] = storeLocator.Panel;
storeLocator.Panel.prototype = new google.maps.MVCObject;
/**
* Initialise the info panel
* @private
*/
storeLocator.Panel.prototype.init_ = function() {
var that = this;
this.itemCache_ = {};
if (this.settings_['view']) {
this.set('view', this.settings_['view']);
}
this.filter_ = $('<form class="storelocator-filter"/>');
this.el_.append(this.filter_);
if (this.settings_['locationSearch']) {
this.locationSearch_ = $('<div class="location-search"><h4>' +
this.settings_['locationSearchLabel'] + '</h4><input></div>');
this.filter_.append(this.locationSearch_);
if (typeof google.maps.places != 'undefined') {
this.initAutocomplete_();
} else {
this.filter_.submit(function() {
var search = $('input', that.locationSearch_).val();
that.searchPosition(/** @type {string} */(search));
});
}
this.filter_.submit(function() {
return false;
});
google.maps.event.addListener(this, 'geocode', function(place) {
if (!place.geometry) {
that.searchPosition(place.name);
return;
}
this.directionsFrom_ = place.geometry.location;
if (that.directionsVisible_) {
that.renderDirections_();
}
var sl = that.get('view');
sl.highlight(null);
var map = sl.getMap();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(13);
}
sl.refreshView();
that.listenForStoresUpdate_();
});
}
if (this.settings_['featureFilter']) {
// TODO(cbro): update this on view_changed
this.featureFilter_ = $('<div class="feature-filter"/>');
var allFeatures = this.get('view').getFeatures().asList();
for (var i = 0, ii = allFeatures.length; i < ii; i++) {
var feature = allFeatures[i];
var checkbox = $('<input type="checkbox"/>');
checkbox.data('feature', feature);
$('<label/>').append(checkbox).append(feature.getDisplayName())
.appendTo(this.featureFilter_);
}
this.filter_.append(this.featureFilter_);
this.featureFilter_.find('input').change(function() {
var feature = $(this).data('feature');
that.toggleFeatureFilter_(/** @type {storeLocator.Feature} */(feature));
that.get('view').refreshView();
});
}
this.storeList_ = $('<ul class="store-list"/>');
this.el_.append(this.storeList_);
if (this.settings_['directions']) {
this.directionsPanel_ = $('<div class="directions-panel"><form>' +
'<input class="directions-to"/>' +
'<input type="submit" value="Find directions"/>' +
'<a href="#" class="close-directions">Close</a>' +
'</form><div class="rendered-directions"></div></div>');
this.directionsPanel_.find('.directions-to').attr('readonly', 'readonly');
this.directionsPanel_.hide();
this.directionsVisible_ = false;
this.directionsPanel_.find('form').submit(function() {
that.renderDirections_();
return false;
});
this.directionsPanel_.find('.close-directions').click(function() {
that.hideDirections();
});
this.el_.append(this.directionsPanel_);
}
};
/**
* Toggles a particular feature on/off in the feature filter.
* @param {storeLocator.Feature} feature The feature to toggle.
* @private
*/
storeLocator.Panel.prototype.toggleFeatureFilter_ = function(feature) {
var featureFilter = this.get('featureFilter');
featureFilter.toggle(feature);
this.set('featureFilter', featureFilter);
};
/**
* Global Geocoder instance, for convenience.
* @type {google.maps.Geocoder}
* @private
*/
storeLocator.geocoder_ = new google.maps.Geocoder;
/**
* Triggers an update for the store list in the Panel. Will wait for stores
* to load asynchronously from the data source.
* @private
*/
storeLocator.Panel.prototype.listenForStoresUpdate_ = function() {
var that = this;
var view = /** @type storeLocator.View */(this.get('view'));
if (this.storesChangedListener_) {
google.maps.event.removeListener(this.storesChangedListener_);
}
this.storesChangedListener_ = google.maps.event.addListenerOnce(view,
'stores_changed', function() {
that.set('stores', view.get('stores'));
});
};
/**
* Search and pan to the specified address.
* @param {string} searchText the address to pan to.
*/
storeLocator.Panel.prototype.searchPosition = function(searchText) {
var that = this;
var request = {
address: searchText,
bounds: this.get('view').getMap().getBounds()
};
storeLocator.geocoder_.geocode(request, function(result, status) {
if (status != google.maps.GeocoderStatus.OK) {
//TODO(cbro): proper error handling
return;
}
google.maps.event.trigger(that, 'geocode', result[0]);
});
};
/**
* Sets the associated View.
* @param {storeLocator.View} view the view to set.
*/
storeLocator.Panel.prototype.setView = function(view) {
this.set('view', view);
};
/**
* view_changed handler.
* Sets up additional bindings between the info panel and the map view.
*/
storeLocator.Panel.prototype.view_changed = function() {
var sl = /** @type {google.maps.MVCObject} */ (this.get('view'));
this.bindTo('selectedStore', sl);
var that = this;
if (this.geolocationListener_) {
google.maps.event.removeListener(this.geolocationListener_);
}
if (this.zoomListener_) {
google.maps.event.removeListener(this.zoomListener_);
}
if (this.idleListener_) {
google.maps.event.removeListener(this.idleListener_);
}
var center = sl.getMap().getCenter();
var updateList = function() {
sl.clearMarkers();
that.listenForStoresUpdate_();
};
//TODO(cbro): somehow get the geolocated position and populate the 'from' box.
this.geolocationListener_ = google.maps.event.addListener(sl, 'load',
updateList);
this.zoomListener_ = google.maps.event.addListener(sl.getMap(),
'zoom_changed', updateList);
this.idleListener_ = google.maps.event.addListener(sl.getMap(),
'idle', function() {
return that.idle_(sl.getMap());
});
updateList();
this.bindTo('featureFilter', sl);
if (this.autoComplete_) {
this.autoComplete_.bindTo('bounds', sl.getMap());
}
};
/**
* Adds autocomplete to the input box.
* @private
*/
storeLocator.Panel.prototype.initAutocomplete_ = function() {
var that = this;
var input = $('input', this.locationSearch_)[0];
this.autoComplete_ = new google.maps.places.Autocomplete(input);
if (this.get('view')) {
this.autoComplete_.bindTo('bounds', this.get('view').getMap());
}
google.maps.event.addListener(this.autoComplete_, 'place_changed',
function() {
google.maps.event.trigger(that, 'geocode', this.getPlace());
});
};
/**
* Called on the view's map idle event. Refreshes the store list if the
* user has navigated far away enough.
* @param {google.maps.Map} map the current view's map.
* @private
*/
storeLocator.Panel.prototype.idle_ = function(map) {
if (!this.center_) {
this.center_ = map.getCenter();
} else if (!map.getBounds().contains(this.center_)) {
this.center_ = map.getCenter();
this.listenForStoresUpdate_();
}
};
/**
* @const
* @type {string}
* @private
*/
storeLocator.Panel.NO_STORES_HTML_ = '<li class="no-stores">There are no' +
' stores in this area.</li>';
/**
* @const
* @type {string}
* @private
*/
storeLocator.Panel.NO_STORES_IN_VIEW_HTML_ = '<li class="no-stores">There are' +
' no stores in this area. However, stores closest to you are' +
' listed below.</li>';
/**
* Handler for stores_changed. Updates the list of stores.
* @this storeLocator.Panel
*/
storeLocator.Panel.prototype.stores_changed = function() {
if (!this.get('stores')) {
return;
}
var view = this.get('view');
var bounds = view && view.getMap().getBounds();
var that = this;
var stores = this.get('stores');
var selectedStore = this.get('selectedStore');
this.storeList_.empty();
if (!stores.length) {
this.storeList_.append(storeLocator.Panel.NO_STORES_HTML_);
} else if (bounds && !bounds.contains(stores[0].getLocation())) {
this.storeList_.append(storeLocator.Panel.NO_STORES_IN_VIEW_HTML_);
}
var clickHandler = function() {
view.highlight(this['store'], true);
};
// TODO(cbro): change 10 to a setting/option
for (var i = 0, ii = Math.min(10, stores.length); i < ii; i++) {
var storeLi = stores[i].getInfoPanelItem();
storeLi['store'] = stores[i];
if (selectedStore && stores[i].getId() == selectedStore.getId()) {
$(storeLi).addClass('highlighted');
}
if (!storeLi.clickHandler_) {
storeLi.clickHandler_ = google.maps.event.addDomListener(
storeLi, 'click', clickHandler);
}
that.storeList_.append(storeLi);
}
};
/**
* Handler for selectedStore_changed. Highlights the selected store in the
* store list.
* @this storeLocator.Panel
*/
storeLocator.Panel.prototype.selectedStore_changed = function() {
$('.highlighted', this.storeList_).removeClass('highlighted');
var that = this;
var store = this.get('selectedStore');
if (!store) {
return;
}
this.directionsTo_ = store;
this.storeList_.find('#store-' + store.getId()).addClass('highlighted');
if (this.settings_['directions']) {
this.directionsPanel_.find('.directions-to')
.val(store.getDetails().title);
}
var node = that.get('view').getInfoWindow().getContent();
var directionsLink = $('<a/>')
.text('Directions')
.attr('href', '#')
.addClass('action')
.addClass('directions');
// TODO(cbro): Make these two permanent fixtures in InfoWindow.
// Move out of Panel.
var zoomLink = $('<a/>')
.text('Zoom here')
.attr('href', '#')
.addClass('action')
.addClass('zoomhere');
var streetViewLink = $('<a/>')
.text('Street view')
.attr('href', '#')
.addClass('action')
.addClass('streetview');
directionsLink.click(function() {
that.showDirections();
return false;
});
zoomLink.click(function() {
that.get('view').getMap().setOptions({
center: store.getLocation(),
zoom: 16
});
});
streetViewLink.click(function() {
var streetView = that.get('view').getMap().getStreetView();
streetView.setPosition(store.getLocation());
streetView.setVisible(true);
});
$(node).append(directionsLink).append(zoomLink).append(streetViewLink);
};
/**
* Hides the directions panel.
*/
storeLocator.Panel.prototype.hideDirections = function() {
this.directionsVisible_ = false;
this.directionsPanel_.fadeOut();
this.featureFilter_.fadeIn();
this.storeList_.fadeIn();
this.directionsRenderer_.setMap(null);
};
/**
* Shows directions to the selected store.
*/
storeLocator.Panel.prototype.showDirections = function() {
var store = this.get('selectedStore');
this.featureFilter_.fadeOut();
this.storeList_.fadeOut();
this.directionsPanel_.find('.directions-to').val(store.getDetails().title);
this.directionsPanel_.fadeIn();
this.renderDirections_();
this.directionsVisible_ = true;
};
/**
* Renders directions from the location in the input box, to the store that is
* pre-filled in the 'to' box.
* @private
*/
storeLocator.Panel.prototype.renderDirections_ = function() {
var that = this;
if (!this.directionsFrom_ || !this.directionsTo_) {
return;
}
var rendered = this.directionsPanel_.find('.rendered-directions').empty();
this.directionsService_.route({
origin: this.directionsFrom_,
destination: this.directionsTo_.getLocation(),
travelMode: google.maps['DirectionsTravelMode'].DRIVING
//TODO(cbro): region biasing, waypoints, travelmode
}, function(result, status) {
if (status != google.maps.DirectionsStatus.OK) {
// TODO(cbro): better error handling
return;
}
var renderer = that.directionsRenderer_;
renderer.setPanel(rendered[0]);
renderer.setMap(that.get('view').getMap());
renderer.setDirections(result);
});
};
/**
* featureFilter_changed event handler.
*/
storeLocator.Panel.prototype.featureFilter_changed = function() {
this.listenForStoresUpdate_();
};
/**
* Fired when searchPosition has been called. This happens when the user has
* searched for a location from the location search box and/or autocomplete.
* @name storeLocator.Panel#event:geocode
* @param {google.maps.PlaceResult|google.maps.GeocoderResult} result
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>view</code> property changes.
* @name storeLocator.Panel#event:view_changed
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>featureFilter</code> property
* changes.
* @name storeLocator.Panel#event:featureFilter_changed
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>stores</code> property changes.
* @name storeLocator.Panel#event:stores_changed
* @event
*/
/**
* Fired when the <code>Panel</code>'s <code>selectedStore</code> property
* changes.
* @name storeLocator.Panel#event:selectedStore_changed
* @event
*/
/**
* @example see storeLocator.Panel
* @interface
*/
storeLocator.PanelOptions = function() {};
/**
* Whether to show the location search box. Default is true.
* @type boolean
*/
storeLocator.prototype.locationSearch;
/**
* The label to show above the location search box. Default is "Where are you
* now?".
* @type string
*/
storeLocator.PanelOptions.prototype.locationSearchLabel;
/**
* Whether to show the feature filter picker. Default is true.
* @type boolean
*/
storeLocator.PanelOptions.prototype.featureFilter;
/**
* Whether to provide directions. Deafult is true.
* @type boolean
*/
storeLocator.PanelOptions.prototype.directions;
/**
* The store locator model to bind to.
* @type storeLocator.View
*/
storeLocator.PanelOptions.prototype.view;
|
JavaScript
|
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* This library makes it easy to create a fully-featured Store Locator for
* your business's website.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Data feed that returns stores based on a given bounds and a set of features.
* @example <pre>
* // always returns the same stores
* function SimpleStaticFeed(stores) {
* this.stores = stores;
* }
* SimpleStaticFeed.prototype.getStores = function(bounds, features, callback) {
* callback(this.stores);
* };
* new storeLocator.View(map, new SimpleStaticFeed());
* </pre>
* @interface
*/
storeLocator.DataFeed = function() {};
storeLocator['DataFeed'] = storeLocator.DataFeed;
/**
* Fetch stores, based on bounds to search within, and features to filter on.
* @param {google.maps.LatLngBounds} bounds the bounds to search within.
* @param {storeLocator.FeatureSet} features the features to filter on.
* @param {function(Array.<!storeLocator.Store>)} callback the callback
* function.
*/
storeLocator.DataFeed.prototype.getStores =
function(bounds, features, callback) {};
/**
* The main store locator object.
* @example <pre>
* new storeLocator.View(map, dataFeed);
* </pre>
* <pre>
* var features = new storeLocator.FeatureSet(feature1, feature2, feature3);
* new storeLocator.View(map, dataFeed, {
* markerIcon: 'icon.png',
* features: features,
* geolocation: false
* });
* </pre>
* <pre>
* // refresh stores every 10 seconds, regardless of interaction on the map.
* var view = new storeLocator.View(map, dataFeed, {
* updateOnPan: false
* });
* setTimeout(function() {
* view.refreshView();
* }, 10000);
* </pre>
* <pre>
* // custom MarkerOptions, by overriding the createMarker method.
* view.createMarker = function(store) {
* return new google.maps.Marker({
* position: store.getLocation(),
* icon: store.getDetails().icon,
* title: store.getDetails().title
* });
* };
* </pre>
* @extends {google.maps.MVCObject}
* @param {google.maps.Map} map the map to operate upon.
* @param {storeLocator.DataFeed} data the data feed to fetch stores from.
* @param {storeLocator.ViewOptions} opt_options
* @constructor
* @implements storeLocator_View
*/
storeLocator.View = function(map, data, opt_options) {
this.map_ = map;
this.data_ = data;
this.settings_ = $.extend({
'updateOnPan': true,
'geolocation': true,
'features': new storeLocator.FeatureSet
}, opt_options);
this.init_();
google.maps.event.trigger(this, 'load');
this.set('featureFilter', new storeLocator.FeatureSet);
};
storeLocator['View'] = storeLocator.View;
storeLocator.View.prototype = new google.maps.MVCObject;
/**
* Attempt to perform geolocation and pan to the given location
* @private
*/
storeLocator.View.prototype.geolocate_ = function() {
var that = this;
if (window.navigator && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
var loc = new google.maps.LatLng(
pos.coords.latitude, pos.coords.longitude);
that.getMap().setCenter(loc);
that.getMap().setZoom(11);
google.maps.event.trigger(that, 'load');
}, undefined, /** @type GeolocationPositionOptions */({
maximumAge: 60 * 1000,
timeout: 10 * 1000
}));
}
};
/**
* Initialise the View object
* @private
*/
storeLocator.View.prototype.init_ = function() {
if (this.settings_['geolocation']) {
this.geolocate_();
}
this.markerCache_ = {};
this.infoWindow_ = new google.maps.InfoWindow;
var that = this;
var map = this.getMap();
this.set('updateOnPan', this.settings_['updateOnPan']);
google.maps.event.addListener(this.infoWindow_, 'closeclick', function() {
that.highlight(null);
});
google.maps.event.addListener(map, 'click', function() {
that.highlight(null);
that.infoWindow_.close();
});
};
/**
* Adds/remove hooks as appropriate.
*/
storeLocator.View.prototype.updateOnPan_changed = function() {
if (this.updateOnPanListener_) {
google.maps.event.removeListener(this.updateOnPanListener_);
}
if (this.get('updateOnPan') && this.getMap()) {
var that = this;
var map = this.getMap();
this.updateOnPanListener_ = google.maps.event.addListener(map, 'idle',
function() {
that.refreshView();
});
}
};
/**
* Add a store to the map.
* @param {storeLocator.Store} store the store to add.
*/
storeLocator.View.prototype.addStoreToMap = function(store) {
var marker = this.getMarker(store);
store.setMarker(marker);
var that = this;
marker.clickListener_ = google.maps.event.addListener(marker, 'click',
function() {
that.highlight(store, false);
});
if (marker.getMap() != this.getMap()) {
marker.setMap(this.getMap());
}
};
/**
* Create a marker for a store.
* @param {storeLocator.Store} store the store to produce a marker for.
* @this storeLocator.View
* @return {google.maps.Marker} a new marker.
* @export
*/
storeLocator.View.prototype.createMarker = function(store) {
var markerOptions = {
position: store.getLocation()
};
var opt_icon = this.settings_['markerIcon'];
if (opt_icon) {
markerOptions.icon = opt_icon;
}
return new google.maps.Marker(markerOptions);
};
/**
* Get a marker for a store. By default, this caches the value from
* createMarker(store)
* @param {storeLocator.Store} store the store to get the marker from.
* @return {google.maps.Marker} the marker.
*/
storeLocator.View.prototype.getMarker = function(store) {
var cache = this.markerCache_;
var key = store.getId();
if (!cache[key]) {
cache[key] = this['createMarker'](store);
}
return cache[key];
};
/**
* Get a InfoWindow for a particular store.
* @param {storeLocator.Store} store the store.
* @return {google.maps.InfoWindow} the store's InfoWindow.
*/
storeLocator.View.prototype.getInfoWindow = function(store) {
if (!store) {
return this.infoWindow_;
}
var div = $(store.getInfoWindowContent());
this.infoWindow_.setContent(div[0]);
return this.infoWindow_;
};
/**
* Gets all possible features for this View.
* @return {storeLocator.FeatureSet} All possible features.
*/
storeLocator.View.prototype.getFeatures = function() {
return this.settings_['features'];
};
/**
* Gets a feature by its id. Convenience method.
* @param {string} id the feature's id.
* @return {storeLocator.Feature|undefined} The feature, if the id is valid.
* undefined if not.
*/
storeLocator.View.prototype.getFeatureById = function(id) {
if (!this.featureById_) {
this.featureById_ = {};
for (var i = 0, feature; feature = this.settings_['features'][i]; i++) {
this.featureById_[feature.getId()] = feature;
}
}
return this.featureById_[id];
};
/**
* featureFilter_changed event handler.
*/
storeLocator.View.prototype.featureFilter_changed = function() {
google.maps.event.trigger(this, 'featureFilter_changed',
this.get('featureFilter'));
if (this.get('stores')) {
this.clearMarkers();
}
};
/**
* Clears the visible markers on the map.
*/
storeLocator.View.prototype.clearMarkers = function() {
for (var marker in this.markerCache_) {
this.markerCache_[marker].setMap(null);
var listener = this.markerCache_[marker].clickListener_;
if (listener) {
google.maps.event.removeListener(listener);
}
}
};
/**
* Refresh the map's view. This will fetch new data based on the map's bounds.
*/
storeLocator.View.prototype.refreshView = function() {
var that = this;
this.data_.getStores(this.getMap().getBounds(),
/** @type {storeLocator.FeatureSet} */ (this.get('featureFilter')),
function(stores) {
var oldStores = that.get('stores');
if (oldStores) {
for (var i = 0, ii = oldStores.length; i < ii; i++) {
google.maps.event.removeListener(
oldStores[i].getMarker().clickListener_);
}
}
that.set('stores', stores);
});
};
/**
* stores_changed event handler.
* This will display all new stores on the map.
* @this storeLocator.View
*/
storeLocator.View.prototype.stores_changed = function() {
var stores = this.get('stores');
for (var i = 0, store; store = stores[i]; i++) {
this.addStoreToMap(store);
}
};
/**
* Gets the view's Map.
* @return {google.maps.Map} the view's Map.
*/
storeLocator.View.prototype.getMap = function() {
return this.map_;
};
/**
* Select a particular store.
* @param {storeLocator.Store} store the store to highlight.
* @param {boolean=} opt_pan if panning to the store on the map is desired.
*/
storeLocator.View.prototype.highlight = function(store, opt_pan) {
var infoWindow = this.getInfoWindow(store);
if (store) {
var infoWindow = this.getInfoWindow(store);
if (store.getMarker()) {
infoWindow.open(this.getMap(), store.getMarker());
} else {
infoWindow.setPosition(store.getLocation());
infoWindow.open(this.getMap());
}
if (opt_pan) {
this.getMap().panTo(store.getLocation());
}
if (this.getMap().getStreetView().getVisible()) {
this.getMap().getStreetView().setPosition(store.getLocation());
}
} else {
infoWindow.close();
}
this.set('selectedStore', store);
};
/**
* Re-triggers the selectedStore_changed event with the store as a parameter.
* @this storeLocator.View
*/
storeLocator.View.prototype.selectedStore_changed = function() {
google.maps.event.trigger(this, 'selectedStore_changed',
this.get('selectedStore'));
};
/**
* Fired when the <code>View</code> is loaded. This happens once immediately,
* then once more if geolocation is successful.
* @name storeLocator.View#event:load
* @event
*/
/**
* Fired when the <code>View</code>'s <code>featureFilter</code> property
* changes.
* @name storeLocator.View#event:featureFilter_changed
* @event
*/
/**
* Fired when the <code>View</code>'s <code>updateOnPan</code> property changes.
* @name storeLocator.View#event:updateOnPan_changed
* @event
*/
/**
* Fired when the <code>View</code>'s <code>stores</code> property changes.
* @name storeLocator.View#event:stores_changed
* @event
*/
/**
* Fired when the <code>View</code>'s <code>selectedStore</code> property
* changes. This happens after <code>highlight()</code> is called.
* @name storeLocator.View#event:selectedStore_changed
* @param {storeLocator.Store} store
* @event
*/
/**
* @example see storeLocator.View
* @interface
*/
storeLocator.ViewOptions = function() {};
/**
* Whether the map should update stores in the visible area when the visible
* area changes. <code>refreshView()</code> will need to be called
* programatically. Defaults to true.
* @type boolean
*/
storeLocator.ViewOptions.prototype.updateOnPan;
/**
* Whether the store locator should attempt to determine the user's location
* for the initial view. Defaults to true.
* @type boolean
*/
storeLocator.ViewOptions.prototype.geolocation;
/**
* All available store features. Defaults to empty FeatureSet.
* @type storeLocator.FeatureSet
*/
storeLocator.ViewOptions.prototype.features;
/**
* The icon to use for markers representing stores.
* @type string|google.maps.MarkerImage
*/
storeLocator.ViewOptions.prototype.markerIcon;
|
JavaScript
|
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* Store model class for Store Locator library.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Represents a store.
* @example <pre>
* var latLng = new google.maps.LatLng(40.7585, -73.9861);
* var store = new storeLocator.Store('times_square', latLng, null);
* </pre>
* <pre>
* var features = new storeLocator.FeatureSet(
* view.getFeatureById('24hour'),
* view.getFeatureById('express'),
* view.getFeatureById('wheelchair_access'));
*
* var store = new storeLocator.Store('times_square', latLng, features, {
* title: 'Times Square',
* address: '1 Times Square<br>Manhattan, NY 10036'
* });
* </pre>
* <pre>
* store.distanceTo(map.getCenter());
*
* // override default info window
* store.getInfoWindowContent = function() {
* var details = this.getDetails();
* return '<h1>' + details.title + '<h1>' + details.address;
* };
* </pre>
* @param {string} id globally unique id of the store - should be suitable to
* use as a HTML id.
* @param {!google.maps.LatLng} location location of the store.
* @param {storeLocator.FeatureSet} features the features of this store.
* @param {Object.<string, *>=} props any additional properties.
* <p> Recommended fields are:
* 'title', 'address', 'phone', 'misc', 'web'. </p>
* @constructor
* @implements storeLocator_Store
*/
storeLocator.Store = function(id, location, features, props) {
this.id_ = id;
this.location_ = location;
this.features_ = features || storeLocator.FeatureSet.NONE;
this.props_ = props || {};
};
storeLocator['Store'] = storeLocator.Store;
/**
* Sets this store's Marker.
* @param {google.maps.Marker} marker the marker to set on this store.
*/
storeLocator.Store.prototype.setMarker = function(marker) {
this.marker_ = marker;
google.maps.event.trigger(this, 'marker_changed', marker);
};
/**
* Gets this store's Marker
* @return {google.maps.Marker} the store's marker.
*/
storeLocator.Store.prototype.getMarker = function() {
return this.marker_;
};
/**
* Gets this store's ID.
* @return {string} this store's ID.
*/
storeLocator.Store.prototype.getId = function() {
return this.id_;
};
/**
* Gets this store's location.
* @return {google.maps.LatLng} this store's location.
*/
storeLocator.Store.prototype.getLocation = function() {
return this.location_;
};
/**
* Gets this store's features.
* @return {storeLocator.FeatureSet} this store's features.
*/
storeLocator.Store.prototype.getFeatures = function() {
return this.features_;
};
/**
* Checks whether this store has a particular feature.
* @param {!storeLocator.Feature} feature the feature to check for.
* @return {boolean} true if the store has the feature, false otherwise.
*/
storeLocator.Store.prototype.hasFeature = function(feature) {
return this.features_.contains(feature);
};
/**
* Checks whether this store has all the given features.
* @param {storeLocator.FeatureSet} features the features to check for.
* @return {boolean} true if the store has all features, false otherwise.
*/
storeLocator.Store.prototype.hasAllFeatures = function(features) {
if (!features) {
return true;
}
var featureList = features.asList();
for (var i = 0, ii = featureList.length; i < ii; i++) {
if (!this.hasFeature(featureList[i])) {
return false;
}
}
return true;
};
/**
* Gets additional details about this store.
* @return {Object} additional properties of this store.
*/
storeLocator.Store.prototype.getDetails = function() {
return this.props_;
};
/**
* Generates HTML for additional details about this store.
* @private
* @param {Array.<string>} fields the optional fields of this store to output.
* @return {string} html version of additional fields of this store.
*/
storeLocator.Store.prototype.generateFieldsHTML_ = function(fields) {
var html = [];
for (var i = 0, ii = fields.length; i < ii; i++) {
var prop = fields[i];
if (this.props_[prop]) {
html.push('<div class="');
html.push(prop);
html.push('">');
html.push(this.props_[prop]);
html.push('</div>');
}
}
return html.join('');
};
/**
* Generates a HTML list of this store's features.
* @private
* @return {string} html list of this store's features.
*/
storeLocator.Store.prototype.generateFeaturesHTML_ = function() {
var html = [];
html.push('<ul class="features">');
var featureList = this.features_.asList();
for (var i = 0, feature; feature = featureList[i]; i++) {
html.push('<li>');
html.push(feature.getDisplayName());
html.push('</li>');
}
html.push('</ul>');
return html.join('');
};
/**
* Gets the HTML content for this Store, suitable for use in an InfoWindow.
* @return {string} a HTML version of this store.
*/
storeLocator.Store.prototype.getInfoWindowContent = function() {
if (!this.content_) {
// TODO(cbro): make this a setting?
var fields = ['title', 'address', 'phone', 'misc', 'web'];
var html = ['<div class="store">'];
html.push(this.generateFieldsHTML_(fields));
html.push(this.generateFeaturesHTML_());
html.push('</div>');
this.content_ = html.join('');
}
return this.content_;
};
/**
* Gets the HTML content for this Store, suitable for use in suitable for use
* in the sidebar info panel.
* @this storeLocator.Store
* @return {string} a HTML version of this store.
*/
storeLocator.Store.prototype.getInfoPanelContent = function() {
return this.getInfoWindowContent();
};
/**
* Keep a cache of InfoPanel items (DOM Node), keyed by the store ID.
* @private
* @type {Object}
*/
storeLocator.Store.infoPanelCache_ = {};
/**
* Gets a HTML element suitable for use in the InfoPanel.
* @return {Node} a HTML element.
*/
storeLocator.Store.prototype.getInfoPanelItem = function() {
var cache = storeLocator.Store.infoPanelCache_;
var store = this;
var key = store.getId();
if (!cache[key]) {
var content = store.getInfoPanelContent();
cache[key] = $('<li class="store" id="store-' + store.getId() +
'">' + content + '</li>')[0];
}
return cache[key];
};
/**
* Gets the distance between this Store and a certain location.
* @param {google.maps.LatLng} point the point to calculate distance to/from.
* @return {number} the distance from this store to a given point.
* @license
* Latitude/longitude spherical geodesy formulae & scripts
* (c) Chris Veness 2002-2010
* www.movable-type.co.uk/scripts/latlong.html
*/
storeLocator.Store.prototype.distanceTo = function(point) {
var R = 6371; // mean radius of earth
var location = this.getLocation();
var lat1 = storeLocator.toRad_(location.lat());
var lon1 = storeLocator.toRad_(location.lng());
var lat2 = storeLocator.toRad_(point.lat());
var lon2 = storeLocator.toRad_(point.lng());
var dLat = lat2 - lat1;
var dLon = lon2 - lon1;
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1) * Math.cos(lat2) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
};
/**
* Fired when the <code>Store</code>'s <code>marker</code> property changes.
* @name storeLocator.Store#event:marker_changed
* @param {google.maps.Marker} marker
* @event
*/
|
JavaScript
|
// Copyright 2013 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* Provides access to store data through Google Maps Engine.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A DataFeed where stores are provided by Google Maps Engine.
* <p>
* Note: the table that contains the stores needs to be publicly accessible.
* @example <pre>
* var dataFeed = new storeLocator.GMEDataFeed({
* tableId: '12421761926155747447-06672618218968397709',
* apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM',
* propertiesModifier: function(props) {
* return {
* id: transformId(props.store_id),
* title: props.store_title
* };
* }
* });
* new storeLocator.View(map, dataFeed);
* </pre>
* @implements storeLocator.DataFeed
* @param {!storeLocator.GMEDataFeedOptions} opts the table ID, API key and
* a transformation function for feature/store properties.
* @constructor
* @implements storeLocator_GMEDataFeed
*/
storeLocator.GMEDataFeed = function(opts) {
this.tableId_ = opts['tableId'];
this.apiKey_ = opts['apiKey'];
if (opts['propertiesModifier']) {
this.propertiesModifier_ = opts['propertiesModifier'];
}
};
storeLocator['GMEDataFeed'] = storeLocator.GMEDataFeed;
storeLocator.GMEDataFeed.prototype.getStores =
function(bounds, features, callback) {
// TODO: use features.
var that = this;
var center = bounds.getCenter();
var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' +
' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)';
var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + this.tableId_ +
'/features?callback=?';
$.getJSON(url, {
'key': this.apiKey_,
'where': where,
'version': 'published',
'maxResults': 300
}, function(resp) {
var stores = that.parse_(resp);
that.sortByDistance_(center, stores);
callback(stores);
});
};
/**
* @private
* @param {!google.maps.LatLng} point
* @return {string}
*/
storeLocator.GMEDataFeed.prototype.latLngToWkt_ = function(point) {
return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')';
};
/**
* @private
* @param {!google.maps.LatLngBounds} bounds
* @return {string}
*/
storeLocator.GMEDataFeed.prototype.boundsToWkt_ = function(bounds) {
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
return [
"ST_GEOMFROMTEXT('POLYGON ((",
sw.lng(), ' ', sw.lat(), ', ',
ne.lng(), ' ', sw.lat(), ', ',
ne.lng(), ' ', ne.lat(), ', ',
sw.lng(), ' ', ne.lat(), ', ',
sw.lng(), ' ', sw.lat(),
"))')"
].join('');
};
/**
* @private
* @param {*} data GeoJSON feature set.
* @return {!Array.<!storeLocator.Store>}
*/
storeLocator.GMEDataFeed.prototype.parse_ = function(data) {
if (data['error']) {
window.alert(data['error']['message']);
return [];
}
var features = data['features'];
if (!features) {
return [];
}
var stores = [];
for (var i = 0, row; row = features[i]; i++) {
var coordinates = row['geometry']['coordinates'];
var position = new google.maps.LatLng(coordinates[1], coordinates[0]);
var props = this.propertiesModifier_(row['properties']);
var store = new storeLocator.Store(props['id'], position, null, props);
stores.push(store);
}
return stores;
};
/**
* Default properties modifier. Just returns the same properties passed into
* it. Useful if the columns in the GME table are already appropriate.
* @private
* @param {Object} props
* @return {Object} an Object to be passed into the "props" argument in the
* Store constructor.
*/
storeLocator.GMEDataFeed.prototype.propertiesModifier_ = function(props) {
return props;
};
/**
* Sorts a list of given stores by distance from a point in ascending order.
* Directly manipulates the given array (has side effects).
* @private
* @param {google.maps.LatLng} latLng the point to sort from.
* @param {!Array.<!storeLocator.Store>} stores the stores to sort.
*/
storeLocator.GMEDataFeed.prototype.sortByDistance_ =
function(latLng, stores) {
stores.sort(function(a, b) {
return a.distanceTo(latLng) - b.distanceTo(latLng);
});
};
/**
* @example see storeLocator.GMEDataFeed
* @interface
*/
storeLocator.GMEDataFeedOptions = function() {};
/**
* The table's asset ID.
* @type string
*/
storeLocator.GMEDataFeedOptions.prototype.tableId;
/**
* The API key to use for all requests.
* @type string
*/
storeLocator.GMEDataFeedOptions.prototype.apiKey;
/**
* A transformation function. The first argument is the feature's properties.
* Return an object useful for the <code>"props"</code> argument in the
* storeLocator.Store constructor. The default properties modifier
* function passes the feature straight through.
* <p>
* Note: storeLocator.GMEDataFeed expects an <code>"id"</code> property.
* @type ?(function(Object): Object)
*/
storeLocator.GMEDataFeedOptions.prototype.propertiesModifier;
|
JavaScript
|
// Copyright 2012 Google Inc.
/**
* @author Chris Broadfoot (Google)
* @fileoverview
* FeatureSet class for Store Locator library. A mutable, ordered set of
* storeLocator.Features.
*/
/**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A mutable, ordered set of <code>storeLocator.Feature</code>s.
* @example <pre>
* var feature1 = new storeLocator.Feature('1', 'Feature One');
* var feature2 = new storeLocator.Feature('2', 'Feature Two');
* var feature3 = new storeLocator.Feature('3', 'Feature Three');
*
* var featureSet = new storeLocator.FeatureSet(feature1, feature2, feature3);
* </pre>
* @param {...storeLocator.Feature} var_args the initial features to add to
* the set.
* @constructor
* @implements storeLocator_FeatureSet
*/
storeLocator.FeatureSet = function(var_args) {
/**
* Stores references to the actual Feature.
* @private
* @type {!Array.<storeLocator.Feature>}
*/
this.array_ = [];
/**
* Maps from a Feature's id to its array index.
* @private
* @type {Object.<string, number>}
*/
this.hash_ = {};
for (var i = 0, feature; feature = arguments[i]; i++) {
this.add(feature);
}
};
storeLocator['FeatureSet'] = storeLocator.FeatureSet;
/**
* Adds the given feature to the set, if it doesn't exist in the set already.
* Else, removes the feature from the set.
* @param {!storeLocator.Feature} feature the feature to toggle.
*/
storeLocator.FeatureSet.prototype.toggle = function(feature) {
if (this.contains(feature)) {
this.remove(feature);
} else {
this.add(feature);
}
};
/**
* Check if a feature exists within this set.
* @param {!storeLocator.Feature} feature the feature.
* @return {boolean} true if the set contains the given feature.
*/
storeLocator.FeatureSet.prototype.contains = function(feature) {
return feature.getId() in this.hash_;
};
/**
* Gets a Feature object from the set, by the feature id.
* @param {string} featureId the feature's id.
* @return {storeLocator.Feature} the feature, if the set contains it.
*/
storeLocator.FeatureSet.prototype.getById = function(featureId) {
if (featureId in this.hash_) {
return this.array_[this.hash_[featureId]];
}
return null;
};
/**
* Adds a feature to the set.
* @param {storeLocator.Feature} feature the feature to add.
*/
storeLocator.FeatureSet.prototype.add = function(feature) {
if (!feature) {
return;
}
this.array_.push(feature);
this.hash_[feature.getId()] = this.array_.length - 1;
};
/**
* Removes a feature from the set, if it already exists in the set. If it does
* not already exist in the set, this function is a no op.
* @param {!storeLocator.Feature} feature the feature to remove.
*/
storeLocator.FeatureSet.prototype.remove = function(feature) {
if (!this.contains(feature)) {
return;
}
this.array_[this.hash_[feature.getId()]] = null;
delete this.hash_[feature.getId()];
};
/**
* Get the contents of this set as an Array.
* @return {Array.<!storeLocator.Feature>} the features in the set, in the order
* they were inserted.
*/
storeLocator.FeatureSet.prototype.asList = function() {
var filtered = [];
for (var i = 0, ii = this.array_.length; i < ii; i++) {
var elem = this.array_[i];
if (elem !== null) {
filtered.push(elem);
}
}
return filtered;
};
/**
* Empty feature set.
* @type storeLocator.FeatureSet
* @const
*/
storeLocator.FeatureSet.NONE = new storeLocator.FeatureSet;
|
JavaScript
|
/** @interface */
function storeLocator_Feature() {};
storeLocator_Feature.prototype.getId = function(var_args) {};
storeLocator_Feature.prototype.getDisplayName = function(var_args) {};
/** @interface */
function storeLocator_FeatureSet() {};
storeLocator_FeatureSet.prototype.toggle = function(var_args) {};
storeLocator_FeatureSet.prototype.contains = function(var_args) {};
storeLocator_FeatureSet.prototype.getById = function(var_args) {};
storeLocator_FeatureSet.prototype.add = function(var_args) {};
storeLocator_FeatureSet.prototype.remove = function(var_args) {};
storeLocator_FeatureSet.prototype.asList = function(var_args) {};
/** @interface */
function storeLocator_GMEDataFeed() {};
/** @interface */
function storeLocator_Panel() {};
storeLocator_Panel.prototype.searchPosition = function(var_args) {};
storeLocator_Panel.prototype.setView = function(var_args) {};
storeLocator_Panel.prototype.view_changed = function(var_args) {};
storeLocator_Panel.prototype.stores_changed = function(var_args) {};
storeLocator_Panel.prototype.selectedStore_changed = function(var_args) {};
storeLocator_Panel.prototype.hideDirections = function(var_args) {};
storeLocator_Panel.prototype.showDirections = function(var_args) {};
storeLocator_Panel.prototype.featureFilter_changed = function(var_args) {};
/** @interface */
function storeLocator_StaticDataFeed() {};
storeLocator_StaticDataFeed.prototype.setStores = function(var_args) {};
storeLocator_StaticDataFeed.prototype.getStores = function(var_args) {};
/** @interface */
function storeLocator_Store() {};
storeLocator_Store.prototype.setMarker = function(var_args) {};
storeLocator_Store.prototype.getMarker = function(var_args) {};
storeLocator_Store.prototype.getId = function(var_args) {};
storeLocator_Store.prototype.getLocation = function(var_args) {};
storeLocator_Store.prototype.getFeatures = function(var_args) {};
storeLocator_Store.prototype.hasFeature = function(var_args) {};
storeLocator_Store.prototype.hasAllFeatures = function(var_args) {};
storeLocator_Store.prototype.getDetails = function(var_args) {};
storeLocator_Store.prototype.getInfoWindowContent = function(var_args) {};
storeLocator_Store.prototype.getInfoPanelContent = function(var_args) {};
storeLocator_Store.prototype.getInfoPanelItem = function(var_args) {};
storeLocator_Store.prototype.distanceTo = function(var_args) {};
/** @interface */
function storeLocator_View() {};
storeLocator_View.prototype.updateOnPan_changed = function(var_args) {};
storeLocator_View.prototype.addStoreToMap = function(var_args) {};
storeLocator_View.prototype.createMarker = function(var_args) {};
storeLocator_View.prototype.getMarker = function(var_args) {};
storeLocator_View.prototype.getInfoWindow = function(var_args) {};
storeLocator_View.prototype.getFeatures = function(var_args) {};
storeLocator_View.prototype.getFeatureById = function(var_args) {};
storeLocator_View.prototype.featureFilter_changed = function(var_args) {};
storeLocator_View.prototype.clearMarkers = function(var_args) {};
storeLocator_View.prototype.refreshView = function(var_args) {};
storeLocator_View.prototype.stores_changed = function(var_args) {};
storeLocator_View.prototype.getMap = function(var_args) {};
storeLocator_View.prototype.highlight = function(var_args) {};
storeLocator_View.prototype.selectedStore_changed = function(var_args) {};
|
JavaScript
|
// A simple demo showing how to grab places using the Maps API Places Library.
// Useful extensions may include using "name" filtering or "keyword" search.
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = document.getElementById('panel');
var data = new PlacesDataSource(map);
var view = new storeLocator.View(map, data);
var markerSize = new google.maps.Size(24, 24);
view.createMarker = function(store) {
return new google.maps.Marker({
position: store.getLocation(),
icon: new google.maps.MarkerImage(store.getDetails().icon, null, null,
null, markerSize)
});
};
new storeLocator.Panel(panelDiv, {
view: view
});
});
/**
* Creates a new PlacesDataSource.
* @param {google.maps.Map} map
* @constructor
*/
function PlacesDataSource(map) {
this.service_ = new google.maps.places.PlacesService(map);
}
/**
* @inheritDoc
*/
PlacesDataSource.prototype.getStores = function(bounds, features, callback) {
this.service_.search({
bounds: bounds
}, function(results, status) {
var stores = [];
for (var i = 0, result; result = results[i]; i++) {
var latLng = result.geometry.location;
var store = new storeLocator.Store(result.id, latLng, null, {
title: result.name,
address: result.types.join(', '),
icon: result.icon
});
stores.push(store);
}
callback(stores);
});
};
|
JavaScript
|
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = document.getElementById('panel');
var data = new storeLocator.GMEDataFeed({
tableId: '12421761926155747447-06672618218968397709',
apiKey: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM',
propertiesModifier: function(props) {
var shop = join([props.Shp_num_an, props.Shp_centre], ', ');
var locality = join([props.Locality, props.Postcode], ', ');
return {
id: props.uuid,
title: props.Fcilty_nam,
address: join([shop, props.Street_add, locality], '<br>'),
hours: props.Hrs_of_bus
};
}
});
var view = new storeLocator.View(map, data, {
geolocation: false
});
new storeLocator.Panel(panelDiv, {
view: view
});
});
/**
* Joins elements of an array that are non-empty and non-null.
* @private
* @param {!Array} arr array of elements to join.
* @param {string} sep the separator.
* @return {string}
*/
function join(arr, sep) {
var parts = [];
for (var i = 0, ii = arr.length; i < ii; i++) {
arr[i] && parts.push(arr[i]);
}
return parts.join(sep);
}
|
JavaScript
|
/**
* @implements storeLocator.DataFeed
* @constructor
*/
function MedicareDataSource() {
}
MedicareDataSource.prototype.getStores = function(bounds, features, callback) {
var that = this;
var center = bounds.getCenter();
var audioFeature = this.FEATURES_.getById('Audio-YES');
var wheelchairFeature = this.FEATURES_.getById('Wheelchair-YES');
var where = '(ST_INTERSECTS(geometry, ' + this.boundsToWkt_(bounds) + ')' +
' OR ST_DISTANCE(geometry, ' + this.latLngToWkt_(center) + ') < 20000)';
if (features.contains(audioFeature)) {
where += " AND Audio='YES'";
}
if (features.contains(wheelchairFeature)) {
where += " AND Wheelchair='YES'";
}
var tableId = '12421761926155747447-06672618218968397709';
var url = 'https://www.googleapis.com/mapsengine/v1/tables/' + tableId +
'/features?callback=?';
$.getJSON(url, {
key: 'AIzaSyAtunhRg0VTElV-P7n4Agpm9tYlABQDCAM',
where: where,
version: 'published',
maxResults: 300
}, function(resp) {
var stores = that.parse_(resp);
that.sortByDistance_(center, stores);
callback(stores);
});
};
MedicareDataSource.prototype.latLngToWkt_ = function(point) {
return 'ST_POINT(' + point.lng() + ', ' + point.lat() + ')';
};
MedicareDataSource.prototype.boundsToWkt_ = function(bounds) {
var ne = bounds.getNorthEast();
var sw = bounds.getSouthWest();
return [
"ST_GEOMFROMTEXT('POLYGON ((",
sw.lng(), ' ', sw.lat(), ', ',
ne.lng(), ' ', sw.lat(), ', ',
ne.lng(), ' ', ne.lat(), ', ',
sw.lng(), ' ', ne.lat(), ', ',
sw.lng(), ' ', sw.lat(),
"))')"
].join('');
};
MedicareDataSource.prototype.parse_ = function(data) {
var stores = [];
for (var i = 0, row; row = data.features[i]; i++) {
var props = row.properties;
var features = new storeLocator.FeatureSet;
features.add(this.FEATURES_.getById('Wheelchair-' + props.Wheelchair));
features.add(this.FEATURES_.getById('Audio-' + props.Audio));
var position = new google.maps.LatLng(row.geometry.coordinates[1],
row.geometry.coordinates[0]);
var shop = this.join_([props.Shp_num_an, props.Shp_centre], ', ');
var locality = this.join_([props.Locality, props.Postcode], ', ');
var store = new storeLocator.Store(props.uuid, position, features, {
title: props.Fcilty_nam,
address: this.join_([shop, props.Street_add, locality], '<br>'),
hours: props.Hrs_of_bus
});
stores.push(store);
}
return stores;
};
/**
* @const
* @type {!storeLocator.FeatureSet}
* @private
*/
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'),
new storeLocator.Feature('Audio-YES', 'Audio')
);
/**
* @return {!storeLocator.FeatureSet}
*/
MedicareDataSource.prototype.getFeatures = function() {
return this.FEATURES_;
};
/**
* Joins elements of an array that are non-empty and non-null.
* @private
* @param {!Array} arr array of elements to join.
* @param {string} sep the separator.
* @return {string}
*/
MedicareDataSource.prototype.join_ = function(arr, sep) {
var parts = [];
for (var i = 0, ii = arr.length; i < ii; i++) {
arr[i] && parts.push(arr[i]);
}
return parts.join(sep);
};
/**
* Sorts a list of given stores by distance from a point in ascending order.
* Directly manipulates the given array (has side effects).
* @private
* @param {google.maps.LatLng} latLng the point to sort from.
* @param {!Array.<!storeLocator.Store>} stores the stores to sort.
*/
MedicareDataSource.prototype.sortByDistance_ = function(latLng, stores) {
stores.sort(function(a, b) {
return a.distanceTo(latLng) - b.distanceTo(latLng);
});
};
|
JavaScript
|
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = document.getElementById('panel');
var data = new MedicareDataSource;
var view = new storeLocator.View(map, data, {
geolocation: false,
features: data.getFeatures()
});
new storeLocator.Panel(panelDiv, {
view: view
});
});
|
JavaScript
|
/**
* @extends storeLocator.StaticDataFeed
* @constructor
*/
function MedicareDataSource() {
$.extend(this, new storeLocator.StaticDataFeed);
var that = this;
$.get('medicare.csv', function(data) {
that.setStores(that.parse_(data));
});
}
/**
* @const
* @type {!storeLocator.FeatureSet}
* @private
*/
MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'),
new storeLocator.Feature('Audio-YES', 'Audio')
);
/**
* @return {!storeLocator.FeatureSet}
*/
MedicareDataSource.prototype.getFeatures = function() {
return this.FEATURES_;
};
/**
* @private
* @param {string} csv
* @return {!Array.<!storeLocator.Store>}
*/
MedicareDataSource.prototype.parse_ = function(csv) {
var stores = [];
var rows = csv.split('\n');
var headings = this.parseRow_(rows[0]);
for (var i = 1, row; row = rows[i]; i++) {
row = this.toObject_(headings, this.parseRow_(row));
var features = new storeLocator.FeatureSet;
features.add(this.FEATURES_.getById('Wheelchair-' + row.Wheelchair));
features.add(this.FEATURES_.getById('Audio-' + row.Audio));
var position = new google.maps.LatLng(row.Ycoord, row.Xcoord);
var shop = this.join_([row.Shp_num_an, row.Shp_centre], ', ');
var locality = this.join_([row.Locality, row.Postcode], ', ');
var store = new storeLocator.Store(row.uuid, position, features, {
title: row.Fcilty_nam,
address: this.join_([shop, row.Street_add, locality], '<br>'),
hours: row.Hrs_of_bus
});
stores.push(store);
}
return stores;
};
/**
* Joins elements of an array that are non-empty and non-null.
* @private
* @param {!Array} arr array of elements to join.
* @param {string} sep the separator.
* @return {string}
*/
MedicareDataSource.prototype.join_ = function(arr, sep) {
var parts = [];
for (var i = 0, ii = arr.length; i < ii; i++) {
arr[i] && parts.push(arr[i]);
}
return parts.join(sep);
};
/**
* Very rudimentary CSV parsing - we know how this particular CSV is formatted.
* IMPORTANT: Don't use this for general CSV parsing!
* @private
* @param {string} row
* @return {Array.<string>}
*/
MedicareDataSource.prototype.parseRow_ = function(row) {
// Strip leading quote.
if (row.charAt(0) == '"') {
row = row.substring(1);
}
// Strip trailing quote. There seems to be a character between the last quote
// and the line ending, hence 2 instead of 1.
if (row.charAt(row.length - 2) == '"') {
row = row.substring(0, row.length - 2);
}
row = row.split('","');
return row;
};
/**
* Creates an object mapping headings to row elements.
* @private
* @param {Array.<string>} headings
* @param {Array.<string>} row
* @return {Object}
*/
MedicareDataSource.prototype.toObject_ = function(headings, row) {
var result = {};
for (var i = 0, ii = row.length; i < ii; i++) {
result[headings[i]] = row[i];
}
return result;
};
|
JavaScript
|
// Store locator with customisations
// - custom marker
// - custom info window (using Info Bubble)
// - custom info window content (+ store hours)
var ICON = new google.maps.MarkerImage('medicare.png', null, null,
new google.maps.Point(14, 13));
var SHADOW = new google.maps.MarkerImage('medicare-shadow.png', null, null,
new google.maps.Point(14, 13));
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(-28, 135),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var panelDiv = document.getElementById('panel');
var data = new MedicareDataSource;
var view = new storeLocator.View(map, data, {
geolocation: false,
features: data.getFeatures()
});
view.createMarker = function(store) {
var markerOptions = {
position: store.getLocation(),
icon: ICON,
shadow: SHADOW,
title: store.getDetails().title
};
return new google.maps.Marker(markerOptions);
}
var infoBubble = new InfoBubble;
view.getInfoWindow = function(store) {
if (!store) {
return infoBubble;
}
var details = store.getDetails();
var html = ['<div class="store"><div class="title">', details.title,
'</div><div class="address">', details.address, '</div>',
'<div class="hours misc">', details.hours, '</div></div>'].join('');
infoBubble.setContent($(html)[0]);
return infoBubble;
};
new storeLocator.Panel(panelDiv, {
view: view
});
});
|
JavaScript
|
//=============================================================================
// System : Color Syntax Highlighter
// File : Highlight.js
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 11/13/2007
// Note : Copyright 2006, Eric Woodruff, All rights reserved
//
// This contains the script to expand and collapse the regions in the
// syntax highlighted code.
//
//=============================================================================
// Expand/collapse a region
function HighlightExpandCollapse(showId, hideId)
{
var showSpan = document.getElementById(showId),
hideSpan = document.getElementById(hideId);
showSpan.style.display = "inline";
hideSpan.style.display = "none";
}
// Copy the code if Enter or Space is hit with the image focused
function CopyColorizedCodeCheckKey(titleDiv, eventObj)
{
if(eventObj != undefined && (eventObj.keyCode == 13 ||
eventObj.keyCode == 32))
CopyColorizedCode(titleDiv);
}
// Change the icon as the mouse moves in and out of the Copy Code link
// There should be an image with the same name but an "_h" suffix just
// before the extension.
function CopyCodeChangeIcon(linkSpan)
{
var image = linkSpan.firstChild.src;
var pos = image.lastIndexOf(".");
if(linkSpan.className == "highlight-copycode")
{
linkSpan.className = "highlight-copycode_h";
linkSpan.firstChild.src = image.substr(0, pos) + "_h" +
image.substr(pos);
}
else
{
linkSpan.className = "highlight-copycode";
linkSpan.firstChild.src = image.substr(0, pos - 2) + image.substr(pos);
}
}
// Copy the code from a colorized code block to the clipboard.
function CopyColorizedCode(titleDiv)
{
var preTag, idx, line, block, htmlLines, lines, codeText, hasLineNos,
hasRegions, clip, trans, copyObject, clipID;
var reLineNo = /^\s*\d{1,4}/;
var reRegion = /^\s*\d{1,4}\+.*?\d{1,4}-/;
var reRegionText = /^\+.*?\-/;
// Find the <pre> tag containing the code. It should be in the next
// element or one of its children.
block = titleDiv.nextSibling;
while(block.nodeName == "#text")
block = block.nextSibling;
while(block.tagName != "PRE")
{
block = block.firstChild;
while(block.nodeName == "#text")
block = block.nextSibling;
}
if(block.innerText != undefined)
codeText = block.innerText;
else
codeText = block.textContent;
hasLineNos = block.innerHTML.indexOf("highlight-lineno");
hasRegions = block.innerHTML.indexOf("highlight-collapsebox");
htmlLines = block.innerHTML.split("\n");
lines = codeText.split("\n");
// Remove the line numbering and collapsible regions if present
if(hasLineNos != -1 || hasRegions != -1)
{
codeText = "";
for(idx = 0; idx < lines.length; idx++)
{
line = lines[idx];
if(hasRegions && reRegion.test(line))
line = line.replace(reRegion, "");
else
{
line = line.replace(reLineNo, "");
// Lines in expanded blocks have an extra space
if(htmlLines[idx].indexOf("highlight-expanded") != -1 ||
htmlLines[idx].indexOf("highlight-endblock") != -1)
line = line.substr(1);
}
if(hasRegions && reRegionText.test(line))
line = line.replace(reRegionText, "");
codeText += line;
// Not all browsers keep the line feed when split
if(line[line.length - 1] != "\n")
codeText += "\n";
}
}
// IE or FireFox/Netscape?
if(window.clipboardData)
window.clipboardData.setData("Text", codeText);
else
if(window.netscape)
{
// Give unrestricted access to browser APIs using XPConnect
try
{
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalXPConnect");
}
catch(e)
{
alert("Universal Connect was refused, cannot copy to " +
"clipboard. Go to about:config and set " +
"signed.applets.codebase_principal_support to true to " +
"enable clipboard support.");
return;
}
// Creates an instance of nsIClipboard
clip = Components.classes[
"@mozilla.org/widget/clipboard;1"].createInstance(
Components.interfaces.nsIClipboard);
// Creates an instance of nsITransferable
if(clip)
trans = Components.classes[
"@mozilla.org/widget/transferable;1"].createInstance(
Components.interfaces.nsITransferable);
if(!trans)
{
alert("Copy to Clipboard is not supported by this browser");
return;
}
// Register the data flavor
trans.addDataFlavor("text/unicode");
// Create object to hold the data
copyObject = new Object();
// Creates an instance of nsISupportsString
copyObject = Components.classes[
"@mozilla.org/supports-string;1"].createInstance(
Components.interfaces.nsISupportsString);
// Assign the data to be copied
copyObject.data = codeText;
// Add data objects to transferable
trans.setTransferData("text/unicode", copyObject,
codeText.length * 2);
clipID = Components.interfaces.nsIClipboard;
if(!clipID)
{
alert("Copy to Clipboard is not supported by this browser");
return;
}
// Transfer the data to the clipboard
clip.setData(trans, null, clipID.kGlobalClipboard);
}
else
alert("Copy to Clipboard is not supported by this browser");
}
|
JavaScript
|
//=============================================================================
// System : Sandcastle Help File Builder
// File : TOC.js
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 04/11/2008
// Note : Copyright 2006-2008, Eric Woodruff, All rights reserved
// Compiler: JavaScript
//
// This file contains the methods necessary to implement a simple tree view
// for the table of content with a resizable splitter and Ajax support to
// load tree nodes on demand. It also contains the script necessary to do
// full-text searches.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://www.CodePlex.com/SHFB. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.3.0.0 09/12/2006 EFW Created the code
// 1.4.0.2 06/15/2007 EFW Reworked to get rid of frame set and to add
// support for Ajax to load tree nodes on demand.
// 1.5.0.0 06/24/2007 EFW Added full-text search capabilities
// 1.6.0.7 04/01/2008 EFW Merged changes from Ferdinand Prantl to add a
// website keyword index. Added support for "topic"
// query string option.
//=============================================================================
// IE flag
var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
// Minimum width of the TOC div
var minWidth = 100;
// Elements and sizing info
var divTOC, divSizer, topicContent, divNavOpts, divSearchOpts, divSearchResults,
divIndexOpts, divIndexResults, divTree, docBody, maxWidth, offset,
txtSearchText, chkSortByTitle;
// Last node selected
var lastNode, lastSearchNode, lastIndexNode;
// Last page with keyword index
var currentIndexPage = 0;
//============================================================================
// Initialize the tree view and resize the content
function Initialize()
{
docBody = document.getElementsByTagName("body")[0];
divTOC = document.getElementById("TOCDiv");
divSizer = document.getElementById("TOCSizer");
topicContent = document.getElementById("TopicContent");
divNavOpts = document.getElementById("divNavOpts");
divSearchOpts = document.getElementById("divSearchOpts");
divSearchResults = document.getElementById("divSearchResults");
divIndexOpts = document.getElementById("divIndexOpts");
divIndexResults = document.getElementById("divIndexResults");
divTree = document.getElementById("divTree");
txtSearchText = document.getElementById("txtSearchText");
chkSortByTitle = document.getElementById("chkSortByTitle");
// The sizes are bit off in FireFox
if(!isIE)
divNavOpts.style.width = divSearchOpts.style.width =
divIndexOpts.style.width = 292;
ResizeTree();
SyncTOC();
// Use an alternate default page if a topic is specified in
// the query string.
var queryString = document.location.search;
if(queryString != "")
{
var idx, options = queryString.split(/[\?\=\&]/);
for(idx = 0; idx < options.length; idx++)
if(options[idx] == "topic" && idx + 1 < options.length)
{
topicContent.src = options[idx + 1];
break;
}
}
}
//============================================================================
// Navigation and expand/collaps code
// Synchronize the table of content with the selected page if possible
function SyncTOC()
{
var idx, anchor, base, href, url, anchors, treeNode, saveNode;
base = window.location.href;
base = base.substr(0, base.lastIndexOf("/") + 1);
if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///")
base = base.replace("file://", "file:///");
url = GetCurrentUrl();
if(url == "")
return false;
if(url.substr(0, 5) == "file:" && url.substr(0, 8) != "file:///")
url = url.replace("file://", "file:///");
while(true)
{
anchors = divTree.getElementsByTagName("A");
anchor = null;
for(idx = 0; idx < anchors.length; idx++)
{
href = anchors[idx].href;
if(href.substring(0, 7) != 'http://' &&
href.substring(0, 8) != 'https://' &&
href.substring(0, 7) != 'file://')
href = base + href;
if(href == url)
{
anchor = anchors[idx];
break;
}
}
if(anchor == null)
{
// If it contains a "#", strip anything after that and try again
if(url.indexOf("#") != -1)
{
url = url.substr(0, url.indexOf("#"));
continue;
}
return;
}
break;
}
// If found, select it and find the parent tree node
SelectNode(anchor);
saveNode = anchor;
lastNode = null;
while(anchor != null)
{
if(anchor.className == "TreeNode")
{
treeNode = anchor;
break;
}
anchor = anchor.parentNode;
}
// Expand it and all of its parents
while(anchor != null)
{
Expand(anchor);
anchor = anchor.parentNode;
while(anchor != null)
{
if(anchor.className == "TreeNode")
break;
anchor = anchor.parentNode;
}
}
lastNode = saveNode;
// Scroll the node into view
var windowTop = lastNode.offsetTop - divTree.offsetTop - divTree.scrollTop;
var windowBottom = divTree.clientHeight - windowTop - lastNode.offsetHeight;
if(windowTop < 0)
divTree.scrollTop += windowTop - 30;
else
if(windowBottom < 0)
divTree.scrollTop -= windowBottom - 30;
}
// Get the currently loaded URL from the IFRAME
function GetCurrentUrl()
{
var base, url = "";
try
{
url = window.frames["TopicContent"].document.URL.replace(/\\/g, "/");
}
catch(e)
{
// If this happens the user probably navigated to another frameset
// that didn't make itself the topmost frameset and we don't have
// control of the other frame anymore. In that case, just reload
// our index page.
base = window.location.href;
base = base.substr(0, base.lastIndexOf("/") + 1);
if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///")
base = base.replace("file://", "file:///");
if(base.substr(0, 5) == "file:")
top.location.href = base + "Index.html";
else
top.location.href = base + "Index.aspx";
}
return url;
}
// Expand or collapse all nodes
function ExpandOrCollapseAll(expandNodes)
{
var divIdx, childIdx, img, divs = document.getElementsByTagName("DIV");
var childNodes, child, div, link, img;
for(divIdx = 0; divIdx < divs.length; divIdx++)
if(divs[divIdx].className == "Hidden" ||
divs[divIdx].className == "Visible")
{
childNodes = divs[divIdx].parentNode.childNodes;
for(childIdx = 0; childIdx < childNodes.length; childIdx++)
{
child = childNodes[childIdx];
if(child.className == "TreeNodeImg")
img = child;
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(div.className == "Visible" && !expandNodes)
{
div.className = "Hidden";
img.src = "Collapsed.gif";
}
else
if(div.className == "Hidden" && expandNodes)
{
div.className = "Visible";
img.src = "Expanded.gif";
if(div.innerHTML == "")
FillNode(div, true)
}
}
}
// Toggle the state of the specified node
function Toggle(node)
{
var i, childNodes, child, div, link;
childNodes = node.parentNode.childNodes;
for(i = 0; i < childNodes.length; i++)
{
child = childNodes[i];
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(div.className == "Visible")
{
div.className = "Hidden";
node.src = "Collapsed.gif";
}
else
{
div.className = "Visible";
node.src = "Expanded.gif";
if(div.innerHTML == "")
FillNode(div, false)
}
}
// Expand the selected node
function Expand(node)
{
var i, childNodes, child, div, img;
// If not valid, don't bother
if(GetCurrentUrl() == "")
return false;
if(node.tagName == "A")
childNodes = node.parentNode.childNodes;
else
childNodes = node.childNodes;
for(i = 0; i < childNodes.length; i++)
{
child = childNodes[i];
if(child.className == "TreeNodeImg")
img = child;
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(lastNode != null)
lastNode.className = "UnselectedNode";
div.className = "Visible";
img.src = "Expanded.gif";
if(node.tagName == "A")
{
node.className = "SelectedNode";
lastNode = node;
}
if(div.innerHTML == "")
FillNode(div, false)
return true;
}
// Set the style of the specified node to "selected"
function SelectNode(node)
{
// If not valid, don't bother
if(GetCurrentUrl() == "")
return false;
if(lastNode != null)
lastNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastNode = node;
return true;
}
//============================================================================
// Ajax-related code used to fill the tree nodes on demand
function GetXmlHttpRequest()
{
var xmlHttp = null;
// If IE7, Mozilla, Safari, etc., use the native object.
// Otherwise, use the ActiveX control for IE5.x and IE6.
if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
else
if(window.ActiveXObject)
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
return xmlHttp;
}
// Perform an AJAX-style request for the contents of a node and put the
// contents into the empty div.
function FillNode(div, expandChildren)
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
if(xmlHttp == null)
{
div.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
div.innerHTML = "Loading...";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "FillNode.aspx?Id=" + div.id + "&hash=" +
now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
div.innerHTML = xmlHttp.responseText;
if(expandChildren)
ExpandOrCollapseAll(true);
}
}
xmlHttp.send(null)
}
//============================================================================
// Resizing code
// Resize the tree div so that it fills the document body
function ResizeTree()
{
var y, newHeight;
if(self.innerHeight) // All but IE
y = self.innerHeight;
else // IE - Strict
if(document.documentElement && document.documentElement.clientHeight)
y = document.documentElement.clientHeight;
else // Everything else
if(document.body)
y = document.body.clientHeight;
newHeight = y - parseInt(divNavOpts.style.height, 10) - 6;
if(newHeight < 50)
newHeight = 50;
divTree.style.height = newHeight;
newHeight = y - parseInt(divSearchOpts.style.height, 10) - 6;
if(newHeight < 100)
newHeight = 100;
divSearchResults.style.height = newHeight;
newHeight = y - parseInt(divIndexOpts.style.height, 10) - 6;
if(newHeight < 25)
newHeight = 25;
divIndexResults.style.height = newHeight;
// Resize the content div
ResizeContent();
}
// Resize the content div
function ResizeContent()
{
if(isIE)
maxWidth = docBody.clientWidth;
else
maxWidth = docBody.clientWidth - 4;
topicContent.style.width = maxWidth - (divSizer.offsetLeft +
divSizer.offsetWidth);
maxWidth -= minWidth;
}
// This is called to prepare for dragging the sizer div
function OnMouseDown(event)
{
var x;
// Make sure the splitter is at the top of the z-index
divSizer.style.zIndex = 5000;
// The content is in an IFRAME which steals mouse events so
// hide it while resizing.
topicContent.style.display = "none";
if(isIE)
x = window.event.clientX + document.documentElement.scrollLeft +
document.body.scrollLeft;
else
x = event.clientX + window.scrollX;
// Save starting offset
offset = parseInt(divSizer.style.left, 10);
if(isNaN(offset))
offset = 0;
offset -= x;
if(isIE)
{
document.attachEvent("onmousemove", OnMouseMove);
document.attachEvent("onmouseup", OnMouseUp);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
else
{
document.addEventListener("mousemove", OnMouseMove, true);
document.addEventListener("mouseup", OnMouseUp, true);
event.preventDefault();
}
}
// Resize the TOC and content divs as the sizer is dragged
function OnMouseMove(event)
{
var x, pos;
// Get cursor position with respect to the page
if(isIE)
x = window.event.clientX + document.documentElement.scrollLeft +
document.body.scrollLeft;
else
x = event.clientX + window.scrollX;
left = offset + x;
// Adjusts the width of the TOC divs
pos = (event.clientX > maxWidth) ? maxWidth :
(event.clientX < minWidth) ? minWidth : event.clientX;
divTOC.style.width = divSearchResults.style.width =
divIndexResults.style.width = divTree.style.width = pos;
if(!isIE)
pos -= 8;
divNavOpts.style.width = divSearchOpts.style.width =
divIndexOpts.style.width = pos;
// Resize the content div to fit in the remaining space
ResizeContent();
}
// Finish the drag operation when the mouse button is released
function OnMouseUp(event)
{
if(isIE)
{
document.detachEvent("onmousemove", OnMouseMove);
document.detachEvent("onmouseup", OnMouseUp);
}
else
{
document.removeEventListener("mousemove", OnMouseMove, true);
document.removeEventListener("mouseup", OnMouseUp, true);
}
// Show the content div again
topicContent.style.display = "inline";
}
//============================================================================
// Search code
function ShowHideSearch(show)
{
if(show)
{
divNavOpts.style.display = divTree.style.display = "none";
divSearchOpts.style.display = divSearchResults.style.display = "";
}
else
{
divSearchOpts.style.display = divSearchResults.style.display = "none";
divNavOpts.style.display = divTree.style.display = "";
}
}
// When enter is hit in the search text box, do the search
function OnSearchTextKeyPress(evt)
{
if(evt.keyCode == 13)
{
PerformSearch();
return false;
}
return true;
}
// Perform a keyword search
function PerformSearch()
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
if(xmlHttp == null)
{
divSearchResults.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
divSearchResults.innerHTML = "<span class=\"PaddedText\">Searching...</span>";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "SearchHelp.aspx?Keywords=" + txtSearchText.value +
"&SortByTitle=" + (chkSortByTitle.checked ? "true" : "false") +
"&hash=" + now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
divSearchResults.innerHTML = xmlHttp.responseText;
lastSearchNode = divSearchResults.childNodes[0].childNodes[1];
if(lastSearchNode != null)
{
if(lastSearchNode.tagName != "A")
lastSearchNode = lastSearchNode.nextSibling;
SelectSearchNode(lastSearchNode);
topicContent.src = lastSearchNode.href;
}
}
}
xmlHttp.send(null)
}
// Set the style of the specified search result node to "selected"
function SelectSearchNode(node)
{
if(lastSearchNode != null)
lastSearchNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastSearchNode = node;
return true;
}
//============================================================================
// KeyWordIndex code
function ShowHideIndex(show)
{
if(show)
{
PopulateIndex(currentIndexPage);
divNavOpts.style.display = divTree.style.display = "none";
divIndexOpts.style.display = divIndexResults.style.display = "";
}
else
{
divIndexOpts.style.display = divIndexResults.style.display = "none";
divNavOpts.style.display = divTree.style.display = "";
}
}
// Populate keyword index
function PopulateIndex(startIndex)
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
var firstNode;
if(xmlHttp == null)
{
divIndexResults.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
divIndexResults.innerHTML = "<span class=\"PaddedText\">Loading " +
"keyword index...</span>";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "LoadIndexKeywords.aspx?StartIndex=" + startIndex +
"&hash=" + now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
divIndexResults.innerHTML = xmlHttp.responseText;
if(startIndex > 0)
{
firstNode = divIndexResults.childNodes[1];
if(firstNode != null && !firstNode.innerHTML)
firstNode = divIndexResults.childNodes[2];
}
else
firstNode = divIndexResults.childNodes[0];
if(firstNode != null)
lastIndexNode = firstNode.childNodes[0];
if(lastIndexNode != null)
{
if(lastIndexNode.tagName != "A")
lastIndexNode = lastIndexNode.nextSibling;
SelectIndexNode(lastIndexNode);
topicContent.src = lastIndexNode.href;
}
currentIndexPage = startIndex;
}
}
xmlHttp.send(null)
}
// Set the style of the specified keyword index node to "selected"
function SelectIndexNode(node)
{
if(lastIndexNode != null)
lastIndexNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastIndexNode = node;
return true;
}
// Changes the current page with keyword index forward or backward
function ChangeIndexPage(direction)
{
PopulateIndex(currentIndexPage + direction);
return false;
}
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A clickable overlay covering the entire doodle area.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.Overlay');
goog.require('turing.sprites');
goog.require('turing.util');
/**
* The z-index for the overlay div. Should be on top of everything else.
* @type {number}
* @const
*/
turing.OVERLAY_ZINDEX = 500;
/**
* An invisible div on top of the doodle in its passive mode.
* @constructor
*/
turing.Overlay = function() {
/**
* An empty div element which fills its parent.
* @type {Element}
* @private
*/
this.div_;
/**
* Event listener for clicks.
* @type {?function()}
* @private
*/
this.clickHandler_;
/**
* Called to report a click to an observer.
* @type {function()}
* @private
*/
this.callback_;
};
/**
* Creates overlay div and registers a click event listener on it.
* @param {Element} logoContainer Element to overlay; used for sizing.
*/
turing.Overlay.prototype.create = function(logoContainer) {
this.div_ = turing.sprites.getEmptyDiv();
this.div_.style.width = logoContainer.offsetWidth + 'px';
this.div_.style.height = logoContainer.offsetHeight + 'px';
this.div_.style.cursor = 'pointer';
this.div_.style.zIndex = turing.OVERLAY_ZINDEX;
this.clickHandler_ = goog.bind(this.onClick, this);
turing.util.listen(this.div_, 'click', this.clickHandler_);
};
/**
* Destroys dom elements and cleans up event listeners.
*/
turing.Overlay.prototype.destroy = function() {
turing.util.unlisten(this.div_, 'click', this.clickHandler_);
turing.util.removeNode(this.div_);
this.clickHandler_ = null;
this.div_ = null;
};
/**
* Attaches to dom and sets click action.
* @param {Element} elem Parent.
* @param {function()} callback Called on a click.
*/
turing.Overlay.prototype.attachTo = function(elem, callback) {
elem.appendChild(this.div_);
this.callback_ = callback;
};
/**
* Event listener for clicks on the overlay.
*/
turing.Overlay.prototype.onClick = function() {
this.destroy();
this.callback_();
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Simulates a Turing machine program running.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.Simulator');
goog.require('turing.Program');
goog.require('turing.Tape');
goog.require('turing.anim');
/**
* Speed settings the simulator can run at.
* @enum {number}
*/
turing.SpeedSetting = {
SLOW: 0,
TUTORIAL: 1,
NORMAL: 2,
FAST: 3,
LUDICROUS: 4
};
/**
* Configuration for a simulator speed setting.
* - stepTime: ms between simulation steps that do something.
* - emptyStepTime: ms between no-op steps.
* - tapeTime: ms for a tape operation.
* - branchTime: ms for a branch operation.
* @typedef {{stepTime: number, tapeTime: number, emptyStepTime: number,
* branchTime: number}}
* @private
*/
turing.Speeds;
/**
* The definitions for speed settings.
* @type {Object.<turing.SpeedSetting, turing.Speeds>}
* @const
*/
turing.SPEED_CONFIG = {
0 /* SLOW */: {
stepTime: 750,
tapeTime: 600,
emptyStepTime: 400,
branchTime: 850
},
1 /* TUTORIAL */: {
stepTime: 650,
tapeTime: 500,
emptyStepTime: 200,
branchTime: 750
},
2 /* NORMAL */: {
stepTime: 450,
tapeTime: 300,
emptyStepTime: 200,
branchTime: 550
},
3 /* FAST */: {
stepTime: 250,
tapeTime: 200,
emptyStepTime: 100,
branchTime: 250
},
4 /* LUDICROUS */: {
stepTime: 100,
tapeTime: 50,
emptyStepTime: 100,
branchTime: 100
}
};
/**
* How many times an operation can be repeated before it gets somewhat boring.
* @type {number}
* @const
*/
turing.SOMEWHAT_BORING_REPEAT_COUNT = 4;
/**
* How many times an operation can be repeated before it gets very boring.
* @type {number}
* @const
*/
turing.VERY_BORING_REPEAT_COUNT = 6;
/**
* Simulates programs.
* @constructor
*/
turing.Simulator = function() {
/**
* The currently running program.
* @type {turing.Program}
* @private
*/
this.program_ = null;
/**
* The currently simulating tape.
* @type {turing.Tape}
* @private
*/
this.tape_ = null;
/**
* The id of the timeout which will step the program forward one step.
* @type {number}
* @private
*/
this.stepTimerId_ = -1;
/**
* Function to call when the program is done.
* @type {?function()}
* @private
*/
this.doneCallback_ = null;
/**
* Steps this program has run.
* @type {number}
* @private
*/
this.stepCount_ = 0;
/**
* Steps the program may run before we terminate it.
* @type {number}
* @private
*/
this.stepLimit_ = 0;
/**
* Maps from program locations to how many time operations at that location
* have been run.
* @type {Object.<string, number>}
* @private
*/
this.runCount_ = {};
/**
* How fast the simulation is going.
* @type {turing.Speeds}
* @private
*/
this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.NORMAL];
/**
* True iff simulation is currently paused.
* @type {boolean}
* @private
*/
this.paused_ = false;
};
/**
* Returns whether the simulator is stepping the program.
* @return {boolean} True iff the program is currently running.
*/
turing.Simulator.prototype.isRunning = function() {
return this.stepTimerId_ != -1;
};
/**
* Sets a limit for the number of steps a program may execute.
* @param {number} limit The number of steps, or 0 for no limit.
*/
turing.Simulator.prototype.setStepLimit = function(limit) {
this.stepLimit_ = limit;
};
/**
* Used to check if the simulator will run until explicitly stopped, which is
* the case in demo mode and when showing the bonus program.
* @return {boolean} True iff the simulator has a step limit, false if it may
* run forever.
*/
turing.Simulator.prototype.hasStepLimit = function() {
return this.stepLimit_ != 0;
};
/**
* Starts running a program.
* @param {turing.Program} program Program to run.
* @param {turing.Tape} tape Tape for I/O.
* @param {turing.SpeedSetting} speed How fast to run.
* @param {function()=} opt_doneCallback Function to call when program halts or
* times out.
*/
turing.Simulator.prototype.run = function(program, tape, speed,
opt_doneCallback) {
if (this.isRunning()) {
return;
}
// Start at the first instruction.
program.setNextPos(0, 0);
this.speeds_ = turing.SPEED_CONFIG[speed];
this.stepCount_ = 0;
this.runCount_ = {};
this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), 0);
this.program_ = program;
this.tape_ = tape;
this.doneCallback_ = opt_doneCallback || null;
};
/**
* Immediately stops running the current program, if running.
*/
turing.Simulator.prototype.stop = function() {
if (this.stepTimerId_ != -1) {
turing.anim.cancel(this.stepTimerId_);
}
this.stepTimerId_ = -1;
this.program_ = null;
this.tape_ = null;
if (this.doneCallback_) {
this.doneCallback_();
this.doneCallback_ = null;
}
};
/**
* Pauses simulation: cancels the next step call, but does not reset any state.
*/
turing.Simulator.prototype.pause = function() {
if (this.stepTimerId_ != -1) {
turing.anim.cancel(this.stepTimerId_);
}
this.stepTimerId_ = -1;
this.paused_ = true;
};
/**
* Resumes simulation at the next step.
*/
turing.Simulator.prototype.resumeIfPaused = function() {
if (this.paused_) {
this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), 0);
}
this.paused_ = false;
};
/**
* Advances program simulation by one step.
*/
turing.Simulator.prototype.step = function() {
if (!this.tape_ || !this.program_ || this.stepTimerId_ == -1) {
return;
}
this.stepTimerId_ = -1;
// Dim the current instruction and highlight the next (if not at end). Note
// that this only changes the value of the current pos, not the next pos;
// the next pos here is set by setNextPos from the previous call.
this.program_.goToNextPos();
if (this.program_.isNextPosEnd() ||
(this.stepLimit_ > 0 && this.stepCount_ > this.stepLimit_)) {
// Simulation stops when we try to move to an invalid position or run for
// more than a maximum number of steps.
// We must explicitly dim the current lit up op in case we exceeded the step
// count (the Program object doesn't know this, so it will still be lit
// after the goToNextPos call above.)
this.program_.dimCurOp();
this.stop();
return;
}
if (this.stepLimit_ > 0) {
// Only accelerate boring loops when they might be unintentional infinite
// loops (i.e., when a step limit is set).
this.speedUpBoringLoops_();
}
this.stepCount_++;
var op = this.program_.getCurOp();
if (op && op.charAt(0) == '*') {
op = op.substr(1);
}
var implicitStep = true; // Most ops implicitly step one position.
// Tape ops update tape state immediately, but take speeds_.tapeTime ms
// to animate. Spend half the total animation time setting up (erasing before
// printing or delaying before moving) and the other half animating, so that
// there's a delay between when the op is lit and when it seems to happen.
var tapeWaitTime = this.speeds_.tapeTime / 2;
var tapeExecuteTime = this.speeds_.tapeTime / 2;
if (op == '0' || op == '1' || op == '_') {
this.tape_.print(op, tapeWaitTime, tapeExecuteTime);
} else if (op == 'L') {
this.tape_.scanLeft(tapeWaitTime, tapeExecuteTime);
} else if (op == 'R') {
this.tape_.scanRight(tapeWaitTime, tapeExecuteTime);
} else if (/B[2-9]/.test(op)) {
// Regexp matches a B followed by a digit from 2 to 9, which are allowable
// branch offsets. Normal game programs only use B2-4, but our bonus program
// needs longer branch offsets.
this.program_.setNextPos(this.program_.getCurTrack(),
this.program_.getCurTrackPos() - parseInt(op.charAt(1), 10));
implicitStep = false;
} else if (/^D/.test(op)) {
// 'Dx' jumps down one track if the current symbol is 'x'. 'D' by itself
// jumps down unconditionally.
if (op.length == 1 || this.tape_.getCurSymbol() == op.charAt(1)) {
this.program_.setNextPos(this.program_.getCurTrack() + 1,
this.program_.getCurTrackPos());
implicitStep = false;
}
} else if (/^U/.test(op)) {
// 'Ux' jumps up one track if the current symbol is 'x'. 'U' by itself jumps
// up unconditionally.
if (op.length == 1 || this.tape_.getCurSymbol() == op.charAt(1)) {
this.program_.setNextPos(this.program_.getCurTrack() - 1,
this.program_.getCurTrackPos());
implicitStep = false;
}
}
if (implicitStep) {
this.program_.setNextPos(this.program_.getCurTrack(),
this.program_.getCurTrackPos() + 1);
}
var stepTime = this.speeds_.stepTime;
if (!op) {
stepTime = this.speeds_.emptyStepTime;
} else if (/^[UDB]/.test(op)) {
// /^[UDB]/ matches a U, D or B at the start of op, which are branch
// operations.
stepTime = this.speeds_.branchTime;
}
this.stepTimerId_ = turing.anim.delay(goog.bind(this.step, this), stepTime);
};
/**
* Detects if the program has gotten stuck in a boring loop, and speeds up if
* so. A loop is "somewhat boring" when the same operation has been repeated
* more than 4 times (since game programs are only supposed to change 5 squares
* on the tape, this is about right), and "very boring" when it has been
* repeated more than 6 times. This speed boost only applies to the current
* run() call, and speeds and operation run counts are reset at the beginning of
* the next run.
* @private
*/
turing.Simulator.prototype.speedUpBoringLoops_ = function() {
var pc = this.program_.getCurTrack() + ',' + this.program_.getCurTrackPos();
var count = this.runCount_[pc] || 0;
this.runCount_[pc] = count + 1;
if (count > turing.VERY_BORING_REPEAT_COUNT) {
// We have to go straight to ludicrous speed.
this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.LUDICROUS];
} else if (count > turing.SOMEWHAT_BORING_REPEAT_COUNT) {
// This is getting boring, speed it up.
this.speeds_ = turing.SPEED_CONFIG[turing.SpeedSetting.FAST];
}
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Samples points on cubic Bézier curves.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.CubicBezier');
/**
* How many points to pre-compute for evaluating curves.
* This can be a fairly low number, since a 1 second animation at 60Hz will
* update only about 60 times, and most of our animations are short.
* @type {number}
* @const
*/
turing.BEZIER_SAMPLES = 120;
/**
* The resolution for numerically solving the "x" polynomial when sampling.
* I picked this value by staring at curves until they looked smooth.
* @type {number}
* @const
*/
turing.BEZIER_EPSILON = 0.0001;
/**
* How to evaluate curves. Different platforms have widely varying floating
* point and Javascript performance. Here are times (in us) for some different
* platforms for each of these methods:
* Platform Solve Linear Nearest
* MacBook Pro 150 88 18
* iPad1 3939 1258 692
* Nexus S 1074 616 252
* @enum {number}
*/
turing.BezierEvaluation = {
SOLVE: 0,
NEAREST_INTERP: 1,
LINEAR_INTERP: 2
};
/**
* Evaluates a cubic Bézier curve,
* B(t) = (1-t)^3 P0 + 3(1-t)^2 t P1 + 3(1-t) t^2 P2 + t^3 P3, t in [0,1],
* at positions x in [0,1] given P0=(0,0), P3=(1,1), and P1 and P2 specified.
* Used for animation timing in browsers that do not support CSS transitions.
* Based on WebKit:
* trac.webkit.org/browser/trunk/Source/WebCore/platform/graphics/UnitBezier.h
* @param {number} p1x x-coordinate of P1.
* @param {number} p1y y-coordinate of P1.
* @param {number} p2x x-coordinate of P2.
* @param {number} p2y y-coordinate of P2.
* @param {turing.BezierEvaluation} evalMode How to evaluate.
* @constructor
*/
turing.CubicBezier = function(p1x, p1y, p2x, p2y, evalMode) {
/**
* Coefficients of the x polynomial.
* @type {Array.<number>}
* @private
*/
this.xCoefs_ = this.getCoefs_(p1x, p2x);
/**
* Coefficients of the y polynomial.
* @type {Array.<number>}
* @private
*/
this.yCoefs_ = this.getCoefs_(p1y, p2y);
/**
* How to evaluate the curve.
* @type {turing.BezierEvaluation}
* @private
*/
this.evalMode_ = evalMode;
/**
* Sampled points on the curve.
* @type {Array.<number>}
* @private
*/
this.samples_ = this.evalMode_ != turing.BezierEvaluation.SOLVE ?
this.precompute_() : [];
};
/**
* Converts parametric form to an explicit polynomial.
* @param {number} p1 The first parameteric point.
* @param {number} p2 The second parameteric point.
* @return {Array.<number>} Coefficients for an explicit polynomial.
* @private
*/
turing.CubicBezier.prototype.getCoefs_ = function(p1, p2) {
var c = 3 * p1;
var b = 3 * (p2 - p1) - c;
var a = 1 - c - b;
return [a, b, c];
};
/**
* Precomputes a table of (x, y) positions on the curve.
* @return {Array.<number>} y coordinates on the curve for x positions in [0,1],
* with indices of x * BEZIER_SAMPLES.
* @private
*/
turing.CubicBezier.prototype.precompute_ = function() {
var samples = [];
for (var i = 0; i < turing.BEZIER_SAMPLES; i++) {
var x = i / turing.BEZIER_SAMPLES;
samples[i] = this.evaluate_(this.yCoefs_, this.solve_(x));
}
return samples;
};
/**
* Samples the curve.
* @param {number} x The x value to evaluate.
* @return {number} The y value near there.
*/
turing.CubicBezier.prototype.sample = function(x) {
if (this.evalMode_ == turing.BezierEvaluation.NEAREST_INTERP) {
return this.sampleNearest_(x);
} else if (this.evalMode_ == turing.BezierEvaluation.LINEAR_INTERP) {
return this.sampleLinear_(x);
} else {
return this.evaluate_(this.yCoefs_, this.solve_(x));
}
};
/**
* Picks the nearest precomputed sample to get the y value of the curve near x
* in [0,1].
* @param {number} x The x value to evaluate.
* @return {number} The y value near there.
* @private
*/
turing.CubicBezier.prototype.sampleNearest_ = function(x) {
var s = Math.floor(x * turing.BEZIER_SAMPLES);
return s < 0 ? 0 : (s >= turing.BEZIER_SAMPLES ? 1 : this.samples_[s]);
};
/**
* Uses linear interpolation between precomputed samples to get the y value of
* the curve near x in [0,1].
* @param {number} x The x value to evaluate.
* @return {number} The y value near there.
* @private
*/
turing.CubicBezier.prototype.sampleLinear_ = function(x) {
var s = x * turing.BEZIER_SAMPLES; // The sample number.
var sLeft = Math.floor(s);
var sRight = Math.ceil(s);
if (sLeft < 0) {
// x < 0: The leftmost point is fixed at (0,0).
return 0;
} else if (sLeft >= turing.BEZIER_SAMPLES) {
// x >= 1: The rightmost point is fixed at (1,1).
return 1;
} else if (sLeft == sRight) {
// x is exactly on a sample.
return this.samples_[sLeft];
} else {
// Linearly interpolate between the nearest samples to x.
return ((sRight - s) * this.samples_[sLeft] +
(s - sLeft) * this.samples_[sRight]);
}
};
/**
* Evaluates a t^3 + b t^2 + c t expanded using Horner's rule.
* @param {Array.<number>} coefs Coefficients [a, b, c].
* @param {number} t Input for polynmoial.
* @return {number} The value of the polynomial.
* @private
*/
turing.CubicBezier.prototype.evaluate_ = function(coefs, t) {
return ((coefs[0] * t + coefs[1]) * t + coefs[2]) * t;
};
/**
* Evaluates the derivative of a t^3 + b t^2 + c t.
* @param {Array.<number>} coefs Coefficients [a, b, c].
* @param {number} t Input for polynmoial.
* @return {number} The value of the derivative polynomial.
* @private
*/
turing.CubicBezier.prototype.evaluateDerivative_ = function(coefs, t) {
return (3 * coefs[0] * t + 2 * coefs[1]) * t + coefs[2];
};
/**
* Solves a t^3 + b t^2 + c t = x for t.
* @param {number} x x position to solve for.
* @return {number} The t (parameter) value corresponding to a given x.
* @private
*/
turing.CubicBezier.prototype.solve_ = function(x) {
var t0;
var t1;
var t2;
var x2;
var d2;
var i;
// First try a few iterations of Newton's method -- normally very fast.
for (t2 = x, i = 0; i < 8; i++) {
x2 = this.evaluate_(this.xCoefs_, t2) - x;
if (Math.abs(x2) < turing.BEZIER_EPSILON) {
return t2;
}
d2 = this.evaluateDerivative_(this.xCoefs_, t2);
if (Math.abs(d2) < 1e-6) {
break;
}
t2 = t2 - x2 / d2;
}
// Fall back to the bisection method for reliability.
t0 = 0.0;
t1 = 1.0;
t2 = x;
if (t2 < t0) {
return t0;
}
if (t2 > t1) {
return t1;
}
while (t0 < t1) {
x2 = this.evaluate_(this.xCoefs_, t2);
if (Math.abs(x2 - x) < turing.BEZIER_EPSILON) {
return t2;
}
if (x > x2) {
t0 = t2;
} else {
t1 = t2;
}
t2 = (t1 - t0) * .5 + t0;
}
// Failure.
return t2;
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview A small collection of helpers.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.util');
/**
* Browser vendor name prefixes, used for looking up vendor-specific properties.
* Other known vendor prefixes include 'Khtml' and 'Icab', but I'm excluding
* these because I don't have them available to test.
* @type {Array.<string>}
* @const
*/
turing.VENDOR_PREFIXES = ['Moz', 'Webkit', 'O', 'ms'];
/**
* Removes an element from its dom parent.
* @param {Element} elem The element to remove.
*/
turing.util.removeNode = function(elem) {
if (elem && elem.parentNode) {
elem.parentNode.removeChild(elem);
}
};
/**
* Chooses the value after value in arr, or null if not in arr.
* @param {Array} arr An array to search in.
* @param {*} value The value to search for.
* @return {*} The value after the searched one, or null if none.
*/
turing.util.getNextValue = function(arr, value) {
for (var i = 0, arrValue; arrValue = arr[i]; i++) {
if (arrValue == value) {
break;
}
}
var nextValue = i == arr.length - 1 ? arr[0] : arr[i + 1];
return i == arr.length ? null : nextValue;
};
/**
* Gets the vendor-specific name of a CSS property.
* Adapted from https://gist.github.com/556448
* @param {string} property The standard name of a CSS property.
* @return {string|undefined} The name of this property as implemented in the
* current browser, or undefined if not implemented.
*/
turing.util.getVendorCssPropertyName = function(property) {
var body = document.body || document.documentElement;
var style = body.style;
if (typeof style == 'undefined') {
// No CSS support. Something is badly wrong.
return undefined;
}
if (typeof style[property] == 'string') {
// The standard name is supported.
return property;
}
// Test for vendor specific names.
var capitalizedProperty = property.charAt(0).toUpperCase() +
property.substr(1);
for (var i = 0, prefix; prefix = turing.VENDOR_PREFIXES[i++]; ) {
if (typeof style[prefix + capitalizedProperty] == 'string') {
return prefix + capitalizedProperty;
}
}
};
/**
* Calls either addEventListener or attachEvent depending on what's
* available.
* @param {(Document|Element|Window)} element The object to listen on.
* @param {string} eventName The event to listen to, such as 'click'.
* @param {Function} listener The listener function to trigger.
*/
turing.util.listen = function(element, eventName, listener) {
if (element.addEventListener) {
element.addEventListener(eventName, listener, false);
} else {
element.attachEvent('on' + eventName, listener);
}
};
/**
* Stops listening to the specified event on the given target.
* @param {(Document|Element|Window)} element The object that we were listening
* on.
* @param {string} eventName The event we were listening to, such as 'click'.
* @param {Function} listener The listener function to remove.
*/
turing.util.unlisten = function(element, eventName, listener) {
if (!element || !listener) {
return;
}
if (element.removeEventListener) {
element.removeEventListener(eventName, listener, false);
} else if (element.detachEvent) {
element.detachEvent('on' + eventName, listener);
}
};
/**
* Sets the opacity of a node (x-browser).
* @param {Element} el Elements whose opacity has to be set.
* @param {number|string} alpha Opacity between 0 and 1 or an empty string
* {@code ''} to clear the opacity.
*/
turing.util.setOpacity = function(el, alpha) {
var style = el.style;
if ('opacity' in style) {
style.opacity = alpha;
} else if ('MozOpacity' in style) {
style.MozOpacity = alpha;
} else if ('filter' in style) {
if (alpha === '') {
style.filter = '';
} else {
style.filter = 'alpha(opacity=' + alpha * 100 + ')';
}
}
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Offsets for the number plate sprite.
* @author corrieann@google.com (Corrie Scalisi)
*/
goog.provide('turing.sprites.numberplate');
goog.require('turing.sprites');
goog.require('turing.sprites.offsets');
/**
* The width of the number plate.
* @type {number}
* @const
* @private
*/
turing.sprites.numberplate.WIDTH_ = 129;
/**
* Gets the CSS background for the given unlit number plate.
* @param {string} target The target.
* @return {string} The CSS background string.
*/
turing.sprites.numberplate.getUnlitNumberPlate = function(target) {
return turing.sprites.getBackground('light-' + target + '-0');
};
/**
* Return the background for the given number target and digit combination.
* If the length of the target (5) is passed in, then the sprite representing
* the entire string will be returned.
* @param {string} target The target.
* @param {number} digit The digit we care about right now.
* @param {boolean} fullyLit Whether the digit should be fully lit.
* @return {string} The CSS background string.
*/
turing.sprites.numberplate.getLitTargetForDigit = function(
target, digit, fullyLit) {
// The column number of the unlit version of that digit.
// We always add at least 1 because the first column has no digits lit.
var digitXOffset = digit * 2 + (fullyLit ? 2 : 1);
return turing.sprites.getBackground('light-' + target + '-' + digitXOffset);
};
/**
* Get an array of backgrounds used to animate scrolling of the given target.
* Grabs the first one from the main sprite and triggers a load of the sprites
* with the other number plates.
* @param {string} target The target.
* @param {boolean} scrollIn Whether the target should scroll in, scrolls out if
* false.
* @return {Array.<string>} The CSS backgrounds.
*/
turing.sprites.numberplate.getScrollingTarget = function(target, scrollIn) {
var backgrounds = [];
for (var i = 0;
i <= turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME; i++) {
var col =
scrollIn ? i : turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME + i;
backgrounds.push(turing.sprites.getBackground(
'scroll-' + target + '-' + col));
}
return backgrounds;
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Offsets for sprites. Auto-generated; do not edit.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.deferredsprites.offsets');
goog.require('turing.sprites.offsets');
/**
* Bounding boxes of sprites in combined image.
* @type {Object.<string, turing.sprites.offsets.Rect>}
*/
turing.deferredsprites.offsets.RECTS = {
'light-00011-0': {x: 2454, y: 0, width: 129, height: 47},
'light-00011-1': {x: 2583, y: 0, width: 129, height: 47},
'light-00011-10': {x: 3744, y: 0, width: 129, height: 47},
'light-00011-11': {x: 3873, y: 0, width: 129, height: 47},
'light-00011-12': {x: 4002, y: 0, width: 129, height: 47},
'light-00011-2': {x: 2712, y: 0, width: 129, height: 47},
'light-00011-3': {x: 2841, y: 0, width: 129, height: 47},
'light-00011-4': {x: 2970, y: 0, width: 129, height: 47},
'light-00011-5': {x: 3099, y: 0, width: 129, height: 47},
'light-00011-6': {x: 3228, y: 0, width: 129, height: 47},
'light-00011-7': {x: 3357, y: 0, width: 129, height: 47},
'light-00011-8': {x: 3486, y: 0, width: 129, height: 47},
'light-00011-9': {x: 3615, y: 0, width: 129, height: 47},
'light-01001-0': {x: 2454, y: 47, width: 129, height: 47},
'light-01001-1': {x: 2583, y: 47, width: 129, height: 47},
'light-01001-10': {x: 3744, y: 47, width: 129, height: 47},
'light-01001-11': {x: 3873, y: 47, width: 129, height: 47},
'light-01001-12': {x: 4002, y: 47, width: 129, height: 47},
'light-01001-2': {x: 2712, y: 47, width: 129, height: 47},
'light-01001-3': {x: 2841, y: 47, width: 129, height: 47},
'light-01001-4': {x: 2970, y: 47, width: 129, height: 47},
'light-01001-5': {x: 3099, y: 47, width: 129, height: 47},
'light-01001-6': {x: 3228, y: 47, width: 129, height: 47},
'light-01001-7': {x: 3357, y: 47, width: 129, height: 47},
'light-01001-8': {x: 3486, y: 47, width: 129, height: 47},
'light-01001-9': {x: 3615, y: 47, width: 129, height: 47},
'light-01011-0': {x: 2454, y: 94, width: 129, height: 47},
'light-01011-1': {x: 2583, y: 94, width: 129, height: 47},
'light-01011-10': {x: 3744, y: 94, width: 129, height: 47},
'light-01011-11': {x: 3873, y: 94, width: 129, height: 47},
'light-01011-12': {x: 4002, y: 94, width: 129, height: 47},
'light-01011-2': {x: 2712, y: 94, width: 129, height: 47},
'light-01011-3': {x: 2841, y: 94, width: 129, height: 47},
'light-01011-4': {x: 2970, y: 94, width: 129, height: 47},
'light-01011-5': {x: 3099, y: 94, width: 129, height: 47},
'light-01011-6': {x: 3228, y: 94, width: 129, height: 47},
'light-01011-7': {x: 3357, y: 94, width: 129, height: 47},
'light-01011-8': {x: 3486, y: 94, width: 129, height: 47},
'light-01011-9': {x: 3615, y: 94, width: 129, height: 47},
'light-10000-0': {x: 2454, y: 141, width: 129, height: 47},
'light-10000-1': {x: 2583, y: 141, width: 129, height: 47},
'light-10000-10': {x: 3744, y: 141, width: 129, height: 47},
'light-10000-11': {x: 3873, y: 141, width: 129, height: 47},
'light-10000-12': {x: 4002, y: 141, width: 129, height: 47},
'light-10000-2': {x: 2712, y: 141, width: 129, height: 47},
'light-10000-3': {x: 2841, y: 141, width: 129, height: 47},
'light-10000-4': {x: 2970, y: 141, width: 129, height: 47},
'light-10000-5': {x: 3099, y: 141, width: 129, height: 47},
'light-10000-6': {x: 3228, y: 141, width: 129, height: 47},
'light-10000-7': {x: 3357, y: 141, width: 129, height: 47},
'light-10000-8': {x: 3486, y: 141, width: 129, height: 47},
'light-10000-9': {x: 3615, y: 141, width: 129, height: 47},
'scroll-00011-0': {x: 0, y: 47, width: 129, height: 47},
'scroll-00011-1': {x: 129, y: 47, width: 129, height: 47},
'scroll-00011-10': {x: 1290, y: 47, width: 129, height: 47},
'scroll-00011-11': {x: 1419, y: 47, width: 129, height: 47},
'scroll-00011-12': {x: 1548, y: 47, width: 129, height: 47},
'scroll-00011-13': {x: 1677, y: 47, width: 129, height: 47},
'scroll-00011-14': {x: 1806, y: 47, width: 129, height: 47},
'scroll-00011-15': {x: 1935, y: 47, width: 129, height: 47},
'scroll-00011-16': {x: 2064, y: 47, width: 129, height: 47},
'scroll-00011-17': {x: 2193, y: 47, width: 129, height: 47},
'scroll-00011-18': {x: 2322, y: 47, width: 129, height: 47},
'scroll-00011-2': {x: 258, y: 47, width: 129, height: 47},
'scroll-00011-3': {x: 387, y: 47, width: 129, height: 47},
'scroll-00011-4': {x: 516, y: 47, width: 129, height: 47},
'scroll-00011-5': {x: 645, y: 47, width: 129, height: 47},
'scroll-00011-6': {x: 774, y: 47, width: 129, height: 47},
'scroll-00011-7': {x: 903, y: 47, width: 129, height: 47},
'scroll-00011-8': {x: 1032, y: 47, width: 129, height: 47},
'scroll-00011-9': {x: 1161, y: 47, width: 129, height: 47},
'scroll-01001-0': {x: 0, y: 94, width: 129, height: 47},
'scroll-01001-1': {x: 129, y: 94, width: 129, height: 47},
'scroll-01001-10': {x: 1290, y: 94, width: 129, height: 47},
'scroll-01001-11': {x: 1419, y: 94, width: 129, height: 47},
'scroll-01001-12': {x: 1548, y: 94, width: 129, height: 47},
'scroll-01001-13': {x: 1677, y: 94, width: 129, height: 47},
'scroll-01001-14': {x: 1806, y: 94, width: 129, height: 47},
'scroll-01001-15': {x: 1935, y: 94, width: 129, height: 47},
'scroll-01001-16': {x: 2064, y: 94, width: 129, height: 47},
'scroll-01001-17': {x: 2193, y: 94, width: 129, height: 47},
'scroll-01001-18': {x: 2322, y: 94, width: 129, height: 47},
'scroll-01001-2': {x: 258, y: 94, width: 129, height: 47},
'scroll-01001-3': {x: 387, y: 94, width: 129, height: 47},
'scroll-01001-4': {x: 516, y: 94, width: 129, height: 47},
'scroll-01001-5': {x: 645, y: 94, width: 129, height: 47},
'scroll-01001-6': {x: 774, y: 94, width: 129, height: 47},
'scroll-01001-7': {x: 903, y: 94, width: 129, height: 47},
'scroll-01001-8': {x: 1032, y: 94, width: 129, height: 47},
'scroll-01001-9': {x: 1161, y: 94, width: 129, height: 47},
'scroll-01011-0': {x: 0, y: 0, width: 129, height: 47},
'scroll-01011-1': {x: 129, y: 0, width: 129, height: 47},
'scroll-01011-10': {x: 1290, y: 0, width: 129, height: 47},
'scroll-01011-11': {x: 1419, y: 0, width: 129, height: 47},
'scroll-01011-12': {x: 1548, y: 0, width: 129, height: 47},
'scroll-01011-13': {x: 1677, y: 0, width: 129, height: 47},
'scroll-01011-14': {x: 1806, y: 0, width: 129, height: 47},
'scroll-01011-15': {x: 1935, y: 0, width: 129, height: 47},
'scroll-01011-16': {x: 2064, y: 0, width: 129, height: 47},
'scroll-01011-17': {x: 2193, y: 0, width: 129, height: 47},
'scroll-01011-18': {x: 2322, y: 0, width: 129, height: 47},
'scroll-01011-2': {x: 258, y: 0, width: 129, height: 47},
'scroll-01011-3': {x: 387, y: 0, width: 129, height: 47},
'scroll-01011-4': {x: 516, y: 0, width: 129, height: 47},
'scroll-01011-5': {x: 645, y: 0, width: 129, height: 47},
'scroll-01011-6': {x: 774, y: 0, width: 129, height: 47},
'scroll-01011-7': {x: 903, y: 0, width: 129, height: 47},
'scroll-01011-8': {x: 1032, y: 0, width: 129, height: 47},
'scroll-01011-9': {x: 1161, y: 0, width: 129, height: 47},
'scroll-10000-0': {x: 0, y: 141, width: 129, height: 47},
'scroll-10000-1': {x: 129, y: 141, width: 129, height: 47},
'scroll-10000-10': {x: 1290, y: 141, width: 129, height: 47},
'scroll-10000-11': {x: 1419, y: 141, width: 129, height: 47},
'scroll-10000-12': {x: 1548, y: 141, width: 129, height: 47},
'scroll-10000-13': {x: 1677, y: 141, width: 129, height: 47},
'scroll-10000-14': {x: 1806, y: 141, width: 129, height: 47},
'scroll-10000-15': {x: 1935, y: 141, width: 129, height: 47},
'scroll-10000-16': {x: 2064, y: 141, width: 129, height: 47},
'scroll-10000-17': {x: 2193, y: 141, width: 129, height: 47},
'scroll-10000-18': {x: 2322, y: 141, width: 129, height: 47},
'scroll-10000-2': {x: 258, y: 141, width: 129, height: 47},
'scroll-10000-3': {x: 387, y: 141, width: 129, height: 47},
'scroll-10000-4': {x: 516, y: 141, width: 129, height: 47},
'scroll-10000-5': {x: 645, y: 141, width: 129, height: 47},
'scroll-10000-6': {x: 774, y: 141, width: 129, height: 47},
'scroll-10000-7': {x: 903, y: 141, width: 129, height: 47},
'scroll-10000-8': {x: 1032, y: 141, width: 129, height: 47},
'scroll-10000-9': {x: 1161, y: 141, width: 129, height: 47}
};
/**
* @type {number}
* @const
*/
turing.deferredsprites.offsets.NUM_SCROLL_FRAMES = 19;
/**
* @type {number}
* @const
*/
turing.deferredsprites.offsets.MIDDLE_SCROLL_FRAME = 9;
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Shows the desired contents of the tape.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.Target');
goog.require('turing.anim');
goog.require('turing.sprites');
goog.require('turing.sprites.numberplate');
goog.require('turing.util');
/**
* The left offset of the target number plate.
* @type {string}
* @const
*/
turing.NUMBER_PLATE_LEFT = '280px';
/**
* The top offset of the target number plate.
* @type {string}
* @const
*/
turing.NUMBER_PLATE_TOP = '21px';
/**
* The top offset of the track from the tape to the target number plate.
* @type {string}
* @const
*/
turing.TRACK_TO_NUMBER_PLATE_TOP = '40px';
/**
* The left offset of the track from the tape to the target number plate.
* @type {string}
* @const
*/
turing.TRACK_TO_NUMBER_PLATE_LEFT = '383px';
/**
* The top offset of the equal indicator.
* @type {string}
* @const
*/
turing.EQUAL_INDICATOR_TOP = '25px';
/**
* The left offset of the equal indicator.
* @type {string}
* @const
*/
turing.EQUAL_INDICATOR_LEFT = '411px';
/**
* The amount of time it takes to blink the equal sign once.
* @type {number}
* @const
*/
turing.EQUAL_BLINK_DURATION = 400;
/**
* A plate showing the desired state of the tape.
* @constructor
*/
turing.Target = function() {
/**
* Div for the plate with numbers the user is trying to match.
* @type {Element}
* @private
*/
this.numberPlate_;
/**
* The current value of the target number plate.
* @type {string}
* @private
*/
this.curValue_ = '';
/**
* A track segment leading from the tape to the target number plate.
* @type {Element}
* @private
*/
this.trackToNumberPlate_;
/**
* The equivalence indicator shown on the track segment that leads to the
* number plate.
* @type {Element}
* @private
*/
this.equalIndicator_;
/**
* A click event listener bound on the equals indicator.
* @type {Function}
* @private
*/
this.equalClickListener_;
/**
* A callback called when the equals indicator is clicked.
* @type {?function()}
* @private
*/
this.equalClickCallback_;
};
/**
* Creates dom nodes.
*/
turing.Target.prototype.create = function() {
this.numberPlate_ = turing.sprites.getDiv('target-blank');
this.numberPlate_.style.top = turing.NUMBER_PLATE_TOP;
this.numberPlate_.style.zIndex = 400;
this.numberPlate_.style.left = turing.NUMBER_PLATE_LEFT;
this.trackToNumberPlate_ = turing.sprites.getDiv('track');
var trackToNumberPlateStyle = this.trackToNumberPlate_.style;
trackToNumberPlateStyle.top = turing.TRACK_TO_NUMBER_PLATE_TOP;
trackToNumberPlateStyle.left = turing.TRACK_TO_NUMBER_PLATE_LEFT;
// We're repurposing the track icon but only showing a small part of it.
trackToNumberPlateStyle.height = '9px';
trackToNumberPlateStyle.width = '40px';
trackToNumberPlateStyle.zIndex = 398; // Behind tape and number plate.
this.equalIndicator_ = turing.sprites.getDiv('eq-dim');
this.equalIndicator_.style.top = turing.EQUAL_INDICATOR_TOP;
this.equalIndicator_.style.left = turing.EQUAL_INDICATOR_LEFT;
this.equalIndicator_.style.zIndex = 399; // Above trackToNumberPlate.
this.equalClickListener_ = goog.bind(this.onClickEqual_, this);
turing.util.listen(this.equalIndicator_, 'click', this.equalClickListener_);
};
/**
* Cleans up dom nodes.
*/
turing.Target.prototype.destroy = function() {
turing.util.removeNode(this.numberPlate_);
this.numberPlate_ = null;
turing.util.removeNode(this.trackToNumberPlate_);
this.trackToNumberPlate_ = null;
turing.util.unlisten(this.equalIndicator_, 'click', this.equalClickListener_);
this.equalClickListener_ = null;
turing.util.removeNode(this.equalIndicator_);
this.equalIndicator_ = null;
this.curValue_ = '';
};
/**
* Attaches dom nodes.
* @param {Element} elem Where to attach.
*/
turing.Target.prototype.attachTo = function(elem) {
elem.appendChild(this.numberPlate_);
elem.appendChild(this.trackToNumberPlate_);
elem.appendChild(this.equalIndicator_);
};
/**
* Sets the value on the target number plate.
* @param {string} str The desired bit string, or the empty string for a blank
* target.
* @param {number} duration The amount of time to animate for.
*/
turing.Target.prototype.setValue = function(str, duration) {
if (!str && !this.curValue_) {
// Don't switch sheets! It causes flashing! So just pick the first
// blank target in the deferred sheet.
this.numberPlate_.style.background = turing.sprites.getBackground(
'scroll-01011-18');
return;
}
var backgrounds;
if (!str) {
// We're switching to blank so animate the current value scrolling away.
backgrounds = turing.sprites.numberplate.getScrollingTarget(
this.curValue_, false);
} else {
// We're switching to the given string, so animate it scrolling in.
backgrounds = turing.sprites.numberplate.getScrollingTarget(str, true);
}
if (!duration) {
this.numberPlate_.style.background = backgrounds[backgrounds.length - 1];
} else {
turing.anim.animateThroughBackgrounds(
this.numberPlate_, backgrounds, duration);
}
this.curValue_ = str;
};
/**
* Sets the equal indicator.
* @param {string} str One of 'dim', 'eq', or 'neq'.
* @param {number=} opt_blinkDelay If specified, the amount of time to blink
* the equal display.
*/
turing.Target.prototype.setEqual = function(str, opt_blinkDelay) {
if (!opt_blinkDelay || opt_blinkDelay < turing.EQUAL_BLINK_DURATION) {
this.equalIndicator_.style.background = turing.sprites.getBackground(
'eq-' + str);
} else {
var backgrounds = [];
var remainingDelay = opt_blinkDelay;
while (remainingDelay > turing.EQUAL_BLINK_DURATION) {
backgrounds.push('eq-dim');
backgrounds.push('eq-' + str);
remainingDelay = remainingDelay - turing.EQUAL_BLINK_DURATION;
}
backgrounds.push('eq-dim');
turing.anim.animateFromSprites(
this.equalIndicator_, backgrounds, opt_blinkDelay);
}
};
/**
* Highlights the given space on the number plate.
* @param {string} str The desired bit string.
* @param {number} index The index of the number to highlight, or 5 which is
* the length of the target, to highlight the entire number plate.
* @param {number} duration The amount of time to highlight for.
*/
turing.Target.prototype.highlightAt = function(str, index, duration) {
if (index > str.length) {
return;
}
var lowlit = turing.sprites.numberplate.getLitTargetForDigit(
str, index, false);
var lit = turing.sprites.numberplate.getLitTargetForDigit(
str, index, true);
var unlit = turing.sprites.numberplate.getUnlitNumberPlate(str);
turing.anim.animateThroughBackgrounds(this.numberPlate_,
[unlit, lowlit, lit, lit, lit, lit, lowlit, unlit], duration);
};
/**
* Pops up a bunny in the equals indicator and makes it clickable.
* @param {function()} onClick Callback to call when clicked.
* @param {string} color The color for the bunny background.
*/
turing.Target.prototype.showBonusBunny = function(onClick, color) {
this.setEqual('bunny-' + color);
this.equalIndicator_.style.cursor = 'pointer';
this.equalClickCallback_ = onClick;
};
/**
* Click handler for the equal indicator.
* @private
*/
turing.Target.prototype.onClickEqual_ = function() {
if (this.equalClickCallback_) {
this.equalClickCallback_();
}
};
/**
* Hides the bunny in the equals indicator and makes it non-clickable.
*/
turing.Target.prototype.hideBonusBunny = function() {
this.equalClickCallback_ = null;
this.equalIndicator_.style.cursor = 'default';
this.setEqual('dim');
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview An interactive doodle for Alan Turing's 100th birthday.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing');
goog.require('turing.Controls');
goog.require('turing.GameState');
goog.require('turing.Logo');
goog.require('turing.Program');
goog.require('turing.Simulator');
goog.require('turing.Tape');
goog.require('turing.Target');
goog.require('turing.anim');
goog.require('turing.sprites');
goog.require('turing.util');
/**
* The container where our dom modifications will be contained.
* @type {string}
* @const
*/
turing.LOGO_CONTAINER_ID = 'logo';
/**
* The maximum number of steps a game program can run. This should be just high
* enough so that all halting programs can run fully, and all cyclic programs do
* something that checks wrong before we kill them; but low enough so that users
* don't get bored if they make a trivial infinite loop.
* @type {number}
* @const
*/
turing.GAME_PROGRAM_STEP_LIMIT = 40;
/**
* How many failed attempts at current puzzle before we slow down execution.
* @type {number}
* @const
*/
turing.FAILURES_BEFORE_SLOWING = 2;
/**
* Assembles a program from strings.
* @param {...string} var_args One string for each program track.
* @return {Object.<string, Array.<Array.<string>>>} An object with correct and
* incorrect array of op arrays for each track.
* @private
*/
turing.assemble_ = function(var_args) {
var ops = {};
for (var pass = 0; pass <= 1; pass++) {
// Make two passes through each program to save incorrect and correct
// copies. We need correct copies to animate stepping through solved puzzles
// when the game is over.
var tracks = [];
for (var i = 0; i < arguments.length; i++) {
// Split on whitespace and copy the resulting array (/ +/ matches one or
// more spaces.)
var trackOps = arguments[i].split(/ +/).slice(0);
for (var j = 0; j < trackOps.length; j++) {
if (trackOps[j] == '.') {
// No-ops are represented internally with the empty string.
trackOps[j] = '';
} else if (/\(.*\)/.test(trackOps[j])) {
// /\(.*\)/ matches a parenthesized expression inside the op
// description. These are corrections for ops initially set to a wrong
// value for the game.
if (pass == 0) {
// Keep only the correction. (The re below matches the whole op
// string, but captures only the part in parentheses.)
trackOps[j] = trackOps[j].replace(/.*\((.*)\).*/, '$1');
} else {
// Eliminate the correction.
trackOps[j] = '*' + trackOps[j].replace(/\(.*\)/, '');
}
} else if (pass == 0 && trackOps[j] && trackOps[j][0] == '*') {
// Some buttons are clickable but do not have explicit corrections
// since they are not needed to solve the program. These are just
// marked with a *. Remove it if present so they are not clickable
// when playing through the solved program on game over.
trackOps[j] = trackOps[j].substr(1);
}
}
tracks.push(trackOps);
}
if (pass == 0) {
ops.correct = tracks;
} else {
ops.incorrect = tracks;
}
}
return ops;
};
/**
* One of the doodle's programs.
* @typedef {{tape: string, goal: string, ops: Object.<string, Array>}}
*/
turing.ProgramDef;
/**
* The set of programs which the user must complete in order to relight the
* Google logo, along with an initial demo/demos to show off the machine.
* @type {Array.<turing.ProgramDef>}
* @const
*/
turing.PROGRAMS = [
// Demo program shown when the doodle loads.
{
// This program counts forever in binary starting at 1.
tape: '',
goal: '',
ops: turing.assemble_('D0 D_ 0 L B4',
'. 1 R U_ B2')
},
// First quest: The following six programs are four basic tutorial programs
// and two interesting but not especially challenging programs. We hope most
// people can get through these with no trouble.
{
tape: '00010',
goal: '01011',
// A really gentle intro to the basic operations: just moves and prints.
// - Tried L L *0, but most users clicked through without understanding.
// - Tried L L 1(0) R R R R 0(1) with the tape 11010. Needing to click two
// things reduced random click throughs, but some users were stuck here
// when buttons cycled L/R/0/1 (so now they cycle 0/1).
// - Considered the above program with the tape _101_ to make printing more
// obvious, but decided the first program needs to start with a five bit
// string on the tape for clear correspondence with the number plate.
// - Revised to this program because we want the leftmost bit to be correct
// so at first the user sees one bit check correct and then one wrong.
ops: turing.assemble_('L 0(1) R R R 0(1)'),
tutorial: true,
logoLetterIndex: 0,
highlight: 'b'
},
{
tape: '0_011',
goal: '00011',
// Introduces conditional branching between tracks, the down-if operation
// and the notation we use to mean a blank square.
// - The extra L is supposed to give users time to notice the program is
// running.
// - We tried 0 *D0 followed by some Ls and Rs on each track. Users clicked
// through but were generally confused about our notation, so we didn't
// learn much. Also we had aesthetic complaints about branching on
// something just written.
ops: turing.assemble_('L D0(D_) 1',
'. 0'),
tutorial: true,
logoLetterIndex: 1,
highlight: 'r'
},
{
tape: '01011',
goal: '00011',
// Introduces backwards branches. The goal is to line up with the correct
// conditional. The extra Rs are supposed to show there is an incorrect
// alternative path; hopefully this is not confusing.
// - We tried a more elaborate program with a loop where one had to pick the
// correct exit. This was too complex. Users had trouble noticing the
// backwards arcing tracks, which this program really emphasizes visually
// since it lines up with the descending track from the D1 ops.
ops: turing.assemble_('D1 D1 D1 L B2(B4)',
'0 R R R'),
tutorial: true,
logoLetterIndex: 2,
highlight: 'y'
},
{
tape: '11011',
goal: '01011',
// Introduces loops. Finds the first bit and changes it.
ops: turing.assemble_('L D1(D_) B2',
'. R 0'),
tutorial: true,
logoLetterIndex: 3,
highlight: 'b'
},
{
tape: '0_001',
goal: '01001',
// Replaces a single blank with 1s.
// This would be more challenging if the D1 exit were changeable.
ops: turing.assemble_('L L D0(D_) R D1 B3',
'. . 1 U1'),
logoLetterIndex: 4,
highlight: 'g'
},
{
tape: '01111',
goal: '10000',
// Inverts the string on the tape.
// This is an actual interesting program with a clear task. Two different
// solutions work to make the program do inverting; on track 2, 0 -> 1,
// U0 -> U1; or on track 1, D0 -> D1, 0 -> 1.
ops: turing.assemble_('L L D0(D1) 0(1) R D_ B4',
'. . *0 . *U0'),
logoLetterIndex: 5,
highlight: 'r'
},
// Second quest: These more interesting programs are here for users who
// really like this sort of thing and want more challenge/interest.
{
tape: '11010',
goal: '01011',
// Uses loops to find the first and last bits and change them.
ops: turing.assemble_('L D_ B2 . R(L) 1',
'. R 0 R U0(U_) B2'),
logoLetterIndex: 0,
highlight: 'b'
},
{
tape: '01_01',
goal: '00011',
// Adds two base one numbers, sort of, not really.
ops: turing.assemble_('L D_(D1) B2 . L 1 L 0',
'. . 0 R U_(U1) B2 . .'),
logoLetterIndex: 1,
highlight: 'r'
},
{
tape: '00111',
goal: '00011',
// A maze of conditionals. This is maybe sort of insane.
ops: turing.assemble_('D_(D1) 1 L D_(D1) 1 L D_(D0) 1',
'1 R U_(U1) 0 R U_(U1) 0 *U_'),
logoLetterIndex: 2,
highlight: 'y'
},
{
tape: '01011',
goal: '01011',
// A goofy easy one to break up the tension. So easy it actually does
// nothing. This is an homage to the Konami code.
ops: turing.assemble_('. . D_ D_ L R L R',
'U_ U_ . . . . 1 0'),
tutorial: true,
logoLetterIndex: 3,
highlight: 'b'
},
{
tape: '0_00_',
goal: '01001',
// Replaces zeroes followed by blanks with 1s.
// This is meant to be sort of challenging. The main challenge is to avoid
// infinite loops and reason about what makes the program terminate
// properly.
ops: turing.assemble_('L L D_(D0) 1 R D1(D_) B4',
'. R U0(U_) B2'),
logoLetterIndex: 4,
highlight: 'g'
},
{
tape: '00001',
goal: '10000',
// Shifts the one to left.
ops: turing.assemble_('D0(D1) R . D0(D_) B4',
'0 L 1 L U_(U0)'),
stepLimit: 80,
logoLetterIndex: 5,
highlight: 'r'
}
];
/**
* A bonus program displayed only in a special mode which the user can trigger
* after winning the game. This program prints the rabbit sequence, which is a
* bitstring with many beautiful relationships to Fibonacci numbers and the
* golden ratio. More immediately, it implements the substitution system with
* rules 1 -> 10, 0 -> 1.
* @type {Array.<Array.<string>>}
* @const
*/
turing.BONUS_PROGRAM = turing.assemble_(
'1 . D1 . . . . _ R D_ B2',
'R U _ R D_ B2 . 1 B8 1 D_ L B2',
'U . B2 . 1 R 0 U_ L B2 0 B9').correct;
/**
* Current game state.
* @type {turing.GameState}
* @private
*/
turing.state_ = new turing.GameState();
/**
* True iff the game has ended.
* @type {boolean}
* @private
*/
turing.gameOver_ = false;
/**
* How many times has the user failed to solve the current puzzle?
* @type {number}
* @private
*/
turing.numFailures_ = 0;
/**
* The time when the current program was first set up.
* @type {number}
* @private
*/
turing.startProgramTime_ = 0;
/**
* The tape.
* @type {turing.Tape}
* @private
*/
turing.tape_;
/**
* The letters of the Google logo.
* @type {turing.Logo}
* @private
*/
turing.logo_ = new turing.Logo();
/**
* The program display.
* @type {turing.Program}
* @private
*/
turing.program_;
/**
* An overlay which covers the doodle initially.
* @type {turing.Overlay}
* @private
*/
turing.overlay_ = new turing.Overlay();
/**
* Helper to simulate programs.
* @type {turing.Simulator}
* @private
*/
turing.simulator_ = new turing.Simulator();
/**
* Controls to start and stop program execution.
* @type {turing.Controls}
* @private
*/
turing.controls_ = new turing.Controls();
/**
* A board to display the desired target for the current game program.
* @type {turing.Target}
* @private
*/
turing.target_ = new turing.Target();
/**
* The main container for the doodle.
* @type {Element}
* @private
*/
turing.logoContainer_ = null;
/**
* @return {boolean} True iff current program is a tutorial.
* @private
*/
turing.inTutorial_ = function() {
return turing.PROGRAMS[turing.state_.getCurProgram()].tutorial;
};
/**
* @param {Element} img An img element.
* @return {boolean} True iff an image is already loaded.
* @private
*/
turing.isImageReady_ = function(img) {
return img['complete'] || img['readyState'] == 'complete';
};
/**
* Starts up demo mode.
* @private
*/
turing.startDemo_ = function() {
turing.logo_.attachTo(turing.logoContainer_);
turing.tape_.attachTo(turing.logoContainer_);
turing.program_.attachTo(turing.logoContainer_);
turing.overlay_.attachTo(turing.logoContainer_, turing.startGame_);
turing.controls_.attachTo(turing.logoContainer_);
turing.target_.attachTo(turing.logoContainer_);
// Remove the base overlay image which we show while our sprite preloads.
turing.logoContainer_.style.background = '';
turing.startSleepTimer_();
turing.program_.setInteractive(false);
turing.program_.change(turing.PROGRAMS[0].ops.correct, true /* Hidden. */);
turing.simulator_.run(turing.program_, turing.tape_,
turing.SpeedSetting.FAST);
};
/**
* Changes into game mode.
* @private
*/
turing.startGame_ = function() {
// Begin loading the deferred sprite sheet.
var deferredSprite = turing.sprites.preload(
turing.sprites.DEFERRED_SPRITE_PATH);
turing.simulator_.stop();
turing.simulator_.setStepLimit(turing.GAME_PROGRAM_STEP_LIMIT);
if (turing.PROGRAMS[turing.state_.getCurProgram()].logoLetterIndex == 0) {
// Only dim the logo if the user hasn't solved any programs yet, i.e., they
// are on the 'G' program; otherwise we'll pick up where they left off.
turing.logo_.dim(500);
}
if (turing.isImageReady_(deferredSprite)) {
// If the deferred sprite was cached or loaded very fast, go right to the
// game.
turing.destroySleepTimer_();
turing.anim.delay(function() {
turing.setupProgram_(turing.state_.getCurProgram());
}, 500);
} else {
// Otherwise, if we're waiting for the deferred sprite, treat the tape as a
// progress bar and sit scrolling it until the sprite loads.
var loaded = false;
turing.anim.delay(function() {
if (!loaded) {
turing.tape_.scanRight(100, 100);
turing.anim.delay(/** @type {function()} */(arguments.callee), 300);
}
}, 300);
deferredSprite.onload = function() {
loaded = true;
turing.destroySleepTimer_();
turing.setupProgram_(turing.state_.getCurProgram());
};
}
};
/**
* Sets up the game for a given program.
* Things change in the order: Target, tape, program (top to bottom).
* @param {number} index The program to enter.
* @private
*/
turing.setupProgram_ = function(index) {
var program = turing.PROGRAMS[index];
turing.startProgramTime_ = new Date().getTime();
if (program.stepLimit) {
turing.simulator_.setStepLimit(program.stepLimit);
}
// Make the program vanish and the target scroll away.
turing.program_.change([[], []]);
turing.target_.setValue('', 800);
turing.target_.setEqual('dim');
turing.anim.delay(turing.callIfNotInBonusMode_(function() {
turing.tape_.setString(program.tape);
}), 800);
turing.anim.delay(turing.callIfNotInBonusMode_(function() {
turing.target_.setValue(program.goal, 800);
}), 2200);
turing.anim.delay(turing.callIfNotInBonusMode_(function() {
if (!turing.gameOver_) {
turing.program_.change(program.ops.incorrect);
turing.makeInteractive_(0, 500);
} else {
turing.program_.change(program.ops.correct);
// The bunny takes you to bonus mode!
turing.target_.showBonusBunny(turing.enterBonusMode_,
program.highlight);
turing.setOpHighlightColor(program.highlight);
turing.simulator_.run(turing.program_, turing.tape_,
turing.SpeedSetting.FAST,
turing.callIfNotInBonusMode_(function() {
turing.winLevel_(index);
}));
}
}), 3200);
};
/**
* Changes program and makes the play button pressable after the tape is set up.
* @param {number} popOutPlayDelay ms to delay before popping button out.
* @param {number} lightOpsDelay ms to delay before lighting clickable buttons.
* @private
*/
turing.makeInteractive_ = function(popOutPlayDelay, lightOpsDelay) {
turing.target_.setEqual('dim');
turing.anim.delay(function() {
turing.controls_.popOutPlayButton(function() {
turing.program_.setInteractive(false);
turing.controls_.pushInPlayButton();
// Pause between lighting the play button and lighting the first
// operation to make it clear these are two separate things happening.
turing.anim.delay(function() {
// Speed picks up a little after the initial programs, but slows back
// down if the user has trouble.
var speed = turing.inTutorial_() ? turing.SpeedSetting.TUTORIAL :
turing.SpeedSetting.NORMAL;
if (turing.numFailures_ >= turing.FAILURES_BEFORE_SLOWING) {
// Having a hard time.
speed = turing.inTutorial_() ? turing.SpeedSetting.SLOW :
turing.SpeedSetting.TUTORIAL;
}
// Note: I tried dropping back down to SLOW if there are twice as many
// failures, but this is just too slow for looping programs.
turing.simulator_.run(turing.program_, turing.tape_, speed,
turing.finishProgramRun_);
}, 600);
});
// Light up clickable ops a little after the play button pops out so that
// people will first notice the play button, then things to click.
turing.anim.delay(function() {
turing.program_.setInteractive(true);
}, lightOpsDelay);
}, popOutPlayDelay);
};
/**
* Ends the game after the user has won.
* This method is called twice:
* - once to signal that the user has finished the game and start an
* animation of the play-through.
* - then, it is called again but instead navigates to serp.
* @private
*/
turing.endGame_ = function() {
turing.tape_.setString('');
turing.program_.change([[], []]);
turing.program_.reset();
turing.target_.setValue('', 800);
if (!turing.gameOver_) {
if (turing.state_.getCurProgram() == turing.PROGRAMS.length - 1) {
// Reset current program so the next playthrough will start over.
turing.state_.setCurProgram(1);
} else {
// On next playthrough, begin at a new set of programs.
turing.state_.setCurProgram(turing.state_.getCurProgram() + 1);
}
turing.gameOver_ = true;
turing.anim.delay(
goog.bind(turing.logo_.deluminate, turing.logo_,
turing.replaySolutionsInSequence_),
1000);
} else {
window.location.href = '/search?q=Alan+Turing';
}
turing.target_.setEqual('dim');
};
/**
* Plays through solved programs in sequence.
* @private
*/
turing.replaySolutionsInSequence_ = function() {
// Because gameOver is now set, setupProgram_ will just step through programs
// until the last.
// We have already set up the new value of curProgram for the next game. Count
// back six programs, wrapping, to figure out which program began this game,
// so we can replay from the correct place.
var firstProgramInNextGame = turing.state_.getCurProgram();
var firstProgramInThisGame = firstProgramInNextGame == 1 ?
turing.PROGRAMS.length - 6 : firstProgramInNextGame - 6;
turing.setupProgram_(firstProgramInThisGame);
};
/**
* Sets up a more complicated, interesting program after the game is done.
* @private
*/
turing.enterBonusMode_ = function() {
turing.simulator_.stop();
turing.logo_.destroy();
turing.controls_.destroy();
turing.target_.destroy();
turing.program_.destroy();
turing.switchProgramsToBonusMode();
turing.setOpHighlightColor('y');
turing.startSleepTimer_();
turing.tape_.slideUp();
turing.anim.delay(function() {
// There may be another setString queued, so wait a while and then clear
// the tape to be sure it starts out blank.
turing.tape_.setString('');
turing.anim.delay(function() {
turing.program_ = new turing.Program();
turing.program_.create();
turing.program_.attachTo(turing.logoContainer_);
turing.program_.change(turing.BONUS_PROGRAM);
turing.simulator_.setStepLimit(0);
turing.simulator_.run(turing.program_, turing.tape_,
turing.SpeedSetting.FAST);
}, 2000);
}, 2000);
};
/**
* Wraps a function with a test to check for bonus mode prior to calling.
* @param {function()} func The function to call.
* @return {function()} A function which first tests for bonus mode.
* @private
*/
turing.callIfNotInBonusMode_ = function(func) {
return function() {
if (!turing.isInBonusMode()) {
func();
}
}
};
/**
* Called when a program is finished running.
* @private
*/
turing.finishProgramRun_ = function() {
// Let the last operation light remain off for a while to make it clear the
// program is done.
turing.anim.delay(function() {
// First dim, but do not pop out the play button.
turing.controls_.dimPlayButton();
// Give the user just long enough to notice the play button before starting
// to check the tape.
turing.anim.delay(turing.checkTape_, 1000);
}, 700);
};
/**
* Checks to see whether the tape is correct
* @private
*/
turing.checkTape_ = function() {
// -1 seeks one position left of the first square to attract attention to
// checking before it starts.
turing.checkNextSquare_(-1, turing.winLevel_, turing.failLevel_);
};
/**
* Called when the user wins a level (the tape checks correct).
* @param {number=} opt_index Iff present, use this as the index of the program
* just completed.
* @private
*/
turing.winLevel_ = function(opt_index) {
turing.numFailures_ = 0;
var index = opt_index || turing.state_.getCurProgram();
var letterIndex = turing.PROGRAMS[index].logoLetterIndex;
// Change the current letter to be lit up.
turing.logo_.lightLetterAtPosition(letterIndex, 500);
if (!turing.isInBonusMode() && letterIndex == 5 /* 'e'. */) {
// End the game when the 'e' program is solved.
turing.anim.delay(turing.endGame_, 500);
} else if (opt_index) {
// Run new program but don't update state; used for end-game animation.
turing.anim.delay(turing.callIfNotInBonusMode_(function() {
turing.setupProgram_(/** @type {number} */(opt_index) + 1);
}), 500);
} else {
// Update state.
turing.anim.delay(turing.callIfNotInBonusMode_(function() {
turing.state_.setCurProgram(index + 1);
turing.setupProgram_(turing.state_.getCurProgram());
}), 500);
}
};
/**
* Called when the user fails the level (tape doesn't check.)
* @private
*/
turing.failLevel_ = function() {
// Reset the tape and try again.
turing.numFailures_++;
var program = turing.PROGRAMS[turing.state_.getCurProgram()];
turing.anim.delay(function() {
turing.tape_.resetString(program.tape);
turing.anim.delay(function() {
turing.makeInteractive_(0, 100);
turing.program_.reset();
}, 400);
}, 300);
};
/**
* Check the square in the tape pointed to by the index arg.
* If it's past the last symbol on the tape and in the target, then
* trigger success.
* If it doesn't match the target's symbol at index, then trigger failure.
* Otherwise wait a bit and check the next square.
* @param {number} index The index to check.
* @param {function()} successCallback What to do if all squares match
* the target.
* @param {function()} failureCallback What to do if there is a mismatch.
* @private
*/
turing.checkNextSquare_ =
function(index, successCallback, failureCallback) {
var symbol = turing.tape_.scanToAndGetSymbol(index);
var program = turing.PROGRAMS[turing.state_.getCurProgram()];
if (index == -1) {
// First scan one square to the left of the solution to get people to
// look up to the tape.
turing.anim.delay(
goog.partial(turing.checkNextSquare_, index + 1,
successCallback, failureCallback), 600);
return;
}
if (!symbol && !program.goal[index]) {
turing.target_.highlightAt(program.goal, index, 1600);
turing.target_.setEqual('eq', 1600);
// Success. We've gone off the end of both strings.
turing.anim.delay(successCallback, 2000);
} else if (symbol != program.goal[index]) {
turing.target_.highlightAt(program.goal, index, 1600);
turing.target_.setEqual('neq', 1600);
// Fail!
turing.anim.delay(failureCallback, 2000);
} else {
// Speed up checking after we've passed the intro programs.
var duration = turing.inTutorial_() ? 1000 : 500;
turing.target_.highlightAt(program.goal, index, duration);
turing.target_.setEqual('eq', duration - 200);
turing.anim.delay(
goog.partial(turing.checkNextSquare_, index + 1,
successCallback, failureCallback), duration);
}
};
/**
* Id for a timer which puts the doodle to sleep due to inactivity.
* @type {?number}
* @private
*/
turing.sleepTimerId_ = null;
/**
* True iff we saw the mouse move since the last sleep timer callback.
* @type {boolean}
* @private
*/
turing.sawMouseMove_ = false;
/**
* Period in ms of a timer which checks if it should put the doodle to sleep.
* Note this means the doodle must be inactive for [t, 2*t] before going to
* sleep.
* @type {number}
* @const
*/
turing.SLEEP_TIMEOUT = 20000;
/**
* Sets up a timer to put the doodle to sleep after a period of inactivity.
* @private
*/
turing.startSleepTimer_ = function() {
// Inactivity is defined as no mouse movement for a period of the sleep timer.
turing.sawMouseMove_ = false;
turing.util.listen(document, 'mousemove', turing.mouseMoveListener_);
turing.util.listen(document, 'touchstart', turing.touchStartListener_);
// Put the doodle to sleep when simulator is running with no user activity.
turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_,
turing.SLEEP_TIMEOUT);
};
/**
* Event listener for mouse movements on the document element. Used to detect
* long periods of inactivity and put the doodle to sleep.
* @private
*/
turing.mouseMoveListener_ = function() {
turing.sawMouseMove_ = true;
if (turing.anim.isStopped()) {
// Wake the doodle up immediately so the user doesn't see it paused.
turing.anim.start();
turing.simulator_.resumeIfPaused();
turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_,
turing.SLEEP_TIMEOUT);
}
};
/**
* Event listener for touchstart events.
* @private
*/
turing.touchStartListener_ = function() {
turing.program_.setTouchDevice();
turing.mouseMoveListener_();
};
/**
* Called periodically to put the doodle to sleep if it is inactive.
* @private
*/
turing.sleepIfInactive_ = function() {
if (turing.simulator_.isRunning() && !turing.simulator_.hasStepLimit() &&
!turing.sawMouseMove_) {
// Only sleep if the simulator is running forever; the game settles down to
// an idle steady state when playing.
turing.simulator_.pause();
turing.anim.stop();
} else {
turing.sleepTimerId_ = window.setTimeout(turing.sleepIfInactive_,
turing.SLEEP_TIMEOUT);
}
// This will be reset in onmousemove if the user is mousing.
turing.sawMouseMove_ = false;
};
/**
* Tears down the sleep timeout timer.
* @private
*/
turing.destroySleepTimer_ = function() {
turing.util.unlisten(document, 'mousemove', turing.mouseMoveListener_);
turing.util.unlisten(document, 'touchstart', turing.touchStartListener_);
if (turing.sleepTimerId_ != null) {
window.clearTimeout(turing.sleepTimerId_);
turing.sleepTimerId_ = null;
}
};
/**
* Preloads sprite, creates dom elements and binds event listeners.
*/
turing.init = function() {
turing.logoContainer_ = document.getElementById(turing.LOGO_CONTAINER_ID);
if (!turing.logoContainer_) {
// Do not show if the logo container is missing.
return;
}
var mainSprite = turing.sprites.preload(turing.sprites.PATH);
turing.state_.restore();
turing.anim.reset();
turing.anim.start();
// In case we were previously in bonus mode.
turing.switchProgramsToNormalMode();
turing.setOpHighlightColor('y');
turing.program_ = new turing.Program();
turing.gameOver_ = false;
turing.numFailures_ = 0;
turing.overlay_.create(turing.logoContainer_);
// If the user has not solved the 'G' program, light the entire logo
// initially, else light as many letters as they have solved.
var curProgram = turing.state_.getCurProgram();
var letterIndex = turing.PROGRAMS[curProgram].logoLetterIndex;
turing.logo_.create(letterIndex == 0 ? 6 : letterIndex);
turing.tape_ = new turing.Tape();
turing.tape_.create();
turing.program_.create();
turing.controls_.create();
turing.target_.create();
// Start the demo when we have the image for the main sprite.
// Set up the handlers after we've initialized everything above as
// the handler does use some of those objects.
if (turing.isImageReady_(mainSprite)) {
turing.startDemo_();
} else {
mainSprite.onload = turing.startDemo_;
}
};
/**
* Cleans up dom elements and listeners.
*/
turing.destroy = function() {
turing.state_.save();
turing.destroySleepTimer_();
turing.anim.reset();
turing.simulator_.stop();
turing.target_.destroy();
turing.overlay_.destroy();
if (turing.program_) {
turing.program_.destroy();
turing.program_ = null;
}
if (turing.tape_) {
turing.tape_.destroy();
turing.tape_ = null;
}
turing.logo_.destroy();
turing.controls_.destroy();
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Lightweight helper library for animation.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.anim');
goog.require('turing.sprites');
goog.require('turing.util');
/**
* Iff true, do not schedule any more animations.
* @type {boolean}
* @private
*/
turing.anim.stopped_ = true;
/**
* A list of pending animation frames.
* @type {Array.<Object>}
* @private
*/
turing.anim.queue_ = [];
/**
* True iff there were more frames queued this tick and the queue needs to be
* resorted.
* @type {boolean}
* @private
*/
turing.anim.queueDirty_ = false;
/**
* The current animation tick.
* @type {number}
* @private
*/
turing.anim.curTick_ = 0;
/**
* The next event id.
* @private
* @type {number}
*/
turing.anim.eventId_ = 1;
/**
* The time when the last animation tick started.
* @type {number}
* @private
*/
turing.anim.lastTickStartTime_ = 0;
/**
* A count of recent ticks which were were longer than the current target.
* @type {number}
* @private
*/
turing.anim.tooSlowTicks_ = 0;
/**
* Inverse of the maximum frame rate (60 Hz).
* @type {number}
* @private
* @const
*/
turing.anim.MAX_FPS_MS_ = 1000 / 60;
/**
* Inverse of the minimum frame rate (20 Hz).
* The game is functional, but really laggy to play below this frame rate. We'll
* never schedule animations slower than this.
* @type {number}
* @private
* @const
*/
turing.anim.MIN_FPS_MS_ = 1000 / 20;
/**
* The interval at which the next frame will be rescheduled. This is controlled
* by throttleFrameRate_.
* @type {number}
* @private
*/
turing.anim.msPerFrame_ = turing.anim.MAX_FPS_MS_;
/**
* The name of the CSS3 transition property, or undefined if transitions are
* unsupported.
* @type {string|undefined}
* @private
*/
turing.anim.transitionPropertyName_ = turing.util.getVendorCssPropertyName(
'transition');
/**
* Map from CSS properties we know how to animate to the units we expect will be
* attached. Used to trim units off and add them back when interpolating values.
* @type {Object.<string, string>}
*/
turing.anim.UNITS = {
'top': 'px',
'left': 'px'
};
/**
* How to schedule the next animation frame.
* @type {function(function())}
*/
window['requestAnimationFrame'] = (function() {
return window['requestAnimationFrame'] ||
window['webkitRequestAnimationFrame'] ||
window['mozRequestAnimationFrame'] ||
window['oRequestAnimationFrame'] ||
window['msRequestAnimationFrame'] ||
function(callback) {
// Binding this on window because Chrome gets cross if we do not.
// If we have nothing better, just do a setTimeout; the caller should be
// careful to check turing.anim.stopped_. It is not checked here because
// it'd be weird to export that behavior.
window.setTimeout(callback, turing.anim.msPerFrame_);
};
})();
/**
* @param {number} duration A duration in ms.
* @return {number} The corresponding number of ticks at the current frame rate.
* @private
*/
turing.anim.getNumTicks_ = function(duration) {
return Math.ceil(duration / turing.anim.msPerFrame_);
};
/**
* Schedules callback to be run after a duration in ms.
* @param {function()} callback The function to call when delay is elapsed.
* @param {number} duration How long to wait in ms.
* @return {number} An id for the event to be delayed.
*/
turing.anim.delay = function(callback, duration) {
// Count ticks to wait based on the current frame rate.
return turing.anim.delayTicks(callback,
turing.anim.getNumTicks_(duration));
};
/**
* Schedules callback to be run after a duration in animation ticks.
* @param {function()} callback The function to call when delay is elapsed.
* @param {number} ticksToWait How long to wait in animation loop ticks.
* @return {number} An id for the event to be delayed.
*/
turing.anim.delayTicks = function(callback, ticksToWait) {
var eventId = turing.anim.eventId_++;
turing.anim.queue_.push({
ticks: turing.anim.curTick_ + ticksToWait,
call: callback,
eventId: eventId
});
turing.anim.queueDirty_ = true;
return eventId;
};
/**
* Cancels a pending event previously scheduled with some delay.
* @param {number} eventId The id of the event in the animation queue.
*/
turing.anim.cancel = function(eventId) {
for (var i = 0; i < turing.anim.queue_.length; i++) {
if (turing.anim.queue_[i].eventId == eventId) {
turing.anim.queue_.splice(i, 1);
return;
}
}
};
/**
* Animates CSS properties on an element.
* @param {Element} elem The element to animate.
* @param {Object.<string, string>} properties CSS property names -> new values.
* @param {number} duration How long the animation should run.
* @param {function()=} opt_doneCallback Called when animation is done.
*/
turing.anim.animate = function(elem, properties, duration, opt_doneCallback) {
var initialValue = {};
var finalValue = {};
for (var name in properties) {
initialValue[name] = parseFloat(elem.style[name] || 0);
finalValue[name] = parseFloat(properties[name]);
}
// Schedule ticks based on the current frame rate.
var numTicks = turing.anim.getNumTicks_(duration);
for (var tick = 0; tick <= numTicks; tick++) {
var progress = Math.min(1, tick / numTicks);
for (var name in properties) {
turing.anim.delayTicks(goog.bind(function(progress) {
var interp = (1 - progress) * initialValue[name] +
progress * finalValue[name];
var value = interp + (turing.anim.UNITS[name] || '');
elem.style[name] = value;
}, window, progress), tick);
}
}
if (opt_doneCallback) {
turing.anim.delayTicks(opt_doneCallback, numTicks);
}
};
/**
* Sets the CSS3 transition property for an element or does nothing if
* transitions aren't supported.
* @param {Element} elem The element to set transition for.
* @param {string} transitionValue The css value for transition.
*/
turing.anim.setTransitionStyle = function(elem, transitionValue) {
if (turing.anim.transitionPropertyName_) {
elem.style[turing.anim.transitionPropertyName_] = transitionValue;
}
};
/**
* Clears CSS3 transitions on elem.
* @param {Element} elem The element to clear transitions for.
*/
turing.anim.clearTransitionStyle = function(elem) {
// Opera doesn't seem to completely support removing an animation
// (setting it to 'none' still causes a delay when changing the left
// offset), so instead set a dummy property to animate for.
turing.anim.setTransitionStyle(elem, 'clear 0ms linear');
};
/**
* Animates changing the sprite used for an element background. Goes through
* the background list, retrieving the sprite background, and then calls
* animateThroughBackgrounds.
* @param {Element} elem The element to animate.
* @param {Array.<string>} spriteNames The names of the desired elements in the
* sprite to iterate through.
* @param {number} duration How long the animation should run.
* @param {function()=} opt_doneCallback Called when animation is done.
*/
turing.anim.animateFromSprites = function(elem, spriteNames, duration,
opt_doneCallback) {
var backgrounds = [];
for (var i = 0; i < spriteNames.length; i++) {
backgrounds[i] = turing.sprites.getBackground(spriteNames[i]);
}
turing.anim.animateThroughBackgrounds(
elem, backgrounds, duration, opt_doneCallback);
};
/**
* Animates changing the backgrounds of an element.
* @param {Element} elem The element to animate.
* @param {Array.<string>} backgrounds The CSS backgrounds to iterate through.
* @param {number} duration How long the animation should run.
* @param {function()=} opt_doneCallback Called when animation is done.
*/
turing.anim.animateThroughBackgrounds = function(elem, backgrounds, duration,
opt_doneCallback) {
// Schedule ticks based on the current frame rate.
var numTicks = turing.anim.getNumTicks_(duration);
for (var tick = 0; tick <= numTicks; tick++) {
var progress = Math.min(1, tick / numTicks);
turing.anim.delayTicks(goog.bind(function(progress) {
elem.style.background = backgrounds[
Math.min(backgrounds.length - 1,
Math.floor(progress * backgrounds.length))];
}, window, progress), tick);
}
if (opt_doneCallback) {
turing.anim.delayTicks(opt_doneCallback, numTicks);
}
};
/**
* A monolithic animation loop implemented using requestAnimationFrame. At each
* tick, it runs any functions deferred til this tick.
*
* All deferred calls are scheduled to run from this loop so that the game
* simulation and animation update synchronously without being explicitly
* stitched together through callbacks everywhere.
*
* We also tried an asynchronous approach, using CSS3 transitions and
* requestAnimationFrame to update animations and separate setTimeout calls to
* run the game. This performed better, but degraded poorly; there were odd
* skips in animation, and weird behavior when changing browser tabs since
* requestAnimationFrame and setTimeout turn down differently. With this
* approach, the game slows down uniformly under load.
*
* @private
*/
turing.anim.loop_ = function() {
window.requestAnimationFrame(function step() {
if (turing.anim.stopped_) {
return;
}
// Note we must do this even when using requestAnimationFrame, because it
// isn't 60 Hz everywhere, and we may need to throttle down to its actual
// rate for our delays to make sense.
turing.anim.throttleFrameRate_();
if (turing.anim.queueDirty_) {
// We'd like to keep frames in a priority queue but don't want to bother,
// so just sort the frame queue when it changes.
turing.anim.queue_.sort(function(a, b) {
if (a.ticks == b.ticks) {
// Guarantee the sort is stable.
return a.eventId - b.eventId;
}
return a.ticks - b.ticks;
});
turing.anim.queueDirty_ = false;
}
var numFrames = 0;
for (var i = 0, frame; frame = turing.anim.queue_[i]; i++) {
if (frame.ticks <= turing.anim.curTick_) {
frame.call();
numFrames++;
} else {
break;
}
}
turing.anim.queue_.splice(0, numFrames);
turing.anim.curTick_++;
window.requestAnimationFrame(step);
});
};
/**
* Measures and controls the interval between frames.
* @private
*/
turing.anim.throttleFrameRate_ = function() {
var tickStartTime = new Date().getTime();
// At the start of the doodle, wait until things stabilize a bit (i.e. the
// page finishes loading) before throttling the frame rate. Arbitrarily guess
// this happens after 30 frames (which is nominally ~0.5 seconds).
// Also check that lastTickStartTime is non-zero, since it will be reset to
// zero if the animation loop is stopped for any reason (and then tickLength
// below would be invalid).
if (turing.anim.curTick_ > 30 && turing.anim.lastTickStartTime_) {
var tickLength = tickStartTime - turing.anim.lastTickStartTime_;
if (tickLength >= 1.05 * turing.anim.msPerFrame_) {
// The last tick was too slow.
turing.anim.tooSlowTicks_++;
} else {
// The last tick was within tolerance.
turing.anim.tooSlowTicks_ = turing.anim.tooSlowTicks_ >> 1;
}
if (turing.anim.tooSlowTicks_ > 20) {
// Animation consistently isn't making our target frame rate; slow down
// frame rate by 20% up to a minimum frame rate.
turing.anim.msPerFrame_ = Math.min(turing.anim.MIN_FPS_MS_,
turing.anim.msPerFrame_ * 1.2);
turing.anim.tooSlowTicks_ = 0;
}
}
turing.anim.lastTickStartTime_ = tickStartTime;
};
/**
* Start animation loop.
*/
turing.anim.start = function() {
turing.anim.stopped_ = false;
turing.anim.loop_();
};
/**
* Resets controller state for frames-per-second throttling.
* @private
*/
turing.anim.resetFpsController_ = function() {
turing.anim.tooSlowTicks_ = 0;
// Wait for a tick before measuring the interval between two ticks.
turing.anim.lastTickStartTime_ = 0;
};
/**
* Emergency brake; stop animation loop next time through.
*/
turing.anim.stop = function() {
turing.anim.stopped_ = true;
turing.anim.resetFpsController_();
};
/**
* Stops the animation loop and cancels any queued animations.
*/
turing.anim.reset = function() {
turing.anim.stop();
turing.anim.queue_ = [];
turing.anim.curTick_ = 0;
turing.anim.queueDirty_ = false;
turing.anim.eventId_ = 1;
turing.anim.msPerFrame_ = turing.anim.MAX_FPS_MS_;
turing.anim.resetFpsController_();
};
/**
* @return {boolean} True iff animations are stopped.
*/
turing.anim.isStopped = function() {
return turing.anim.stopped_;
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Shows the Google logo.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.Logo');
goog.require('turing.anim');
goog.require('turing.sprites');
goog.require('turing.util');
/**
* The names of letters in the logo, in order, corresponding to sprites.
* @type {Array.<string>}
* @const
*/
turing.LOGO_LETTERS = ['G', 'o1', 'o2', 'g', 'l', 'e'];
/**
* The left offset of the logo container.
* @type {string}
* @const
*/
turing.LOGO_LEFT = '79px';
/**
* The top offset of the logo container.
* @type {string}
* @const
*/
turing.LOGO_TOP = '24px';
/**
* The tops of each letter so that they line up correctly vertically.
* @type {Array.<string>}
* @const
* @private
*/
turing.LETTER_TOPS_ = ['1px', '11px', '11px', '11px', '0', '11px'];
/**
* The lefts of each letter so that they line up correctly.
* @type {Array.<string>}
* @const
* @private
*/
turing.LETTER_LEFTS_ = ['0', '33px', '57px', '79px', '100px', '111px'];
/**
* The number of animation frames used to light up the logo letters.
* @type {number}
* @const
* @private
*/
turing.NUM_LETTER_ANIMATION_FRAMES_ = 8;
/**
* A Google logo where each letter can light up or dim individually.
* @constructor
*/
turing.Logo = function() {
/**
* Divs for each letter.
* @type {Array.<Element>}
* @private
*/
this.letters_ = [];
/**
* Container div holding all letters.
* @type {Element}
* @private
*/
this.container_;
};
/**
* Attaches the logo under a dom element.
* @param {Element} elem Parent element.
*/
turing.Logo.prototype.attachTo = function(elem) {
elem.appendChild(this.container_);
};
/**
* Creates the dom elements for the logo letters.
* @param {number} numLettersOn How many letters are initially on.
*/
turing.Logo.prototype.create = function(numLettersOn) {
this.container_ = turing.sprites.getEmptyDiv();
this.container_.style.left = turing.LOGO_LEFT;
this.container_.style.top = turing.LOGO_TOP;
for (var i = 0, letter; letter = turing.LOGO_LETTERS[i]; i++) {
var spriteName = i < numLettersOn ?
letter + (turing.NUM_LETTER_ANIMATION_FRAMES_ - 1) : letter + '0';
this.letters_[i] = turing.sprites.getDiv(spriteName);
this.letters_[i].style.left = turing.LETTER_LEFTS_[i];
this.letters_[i].style.top = turing.LETTER_TOPS_[i];
this.container_.appendChild(this.letters_[i]);
var letterSize = turing.sprites.getSize(spriteName);
}
};
/**
* Destroys the dom elements for logo letters.
*/
turing.Logo.prototype.destroy = function() {
turing.util.removeNode(this.container_);
this.container_ = null;
for (var i = 0, letter; letter = this.letters_[i++]; ) {
turing.util.removeNode(letter);
}
this.letters_.splice(0);
};
/**
* Return an array of backgrounds we can use to animate the hightlighting or
* dimming of the given letter.
* @param {string} letter The letter to animate.
* @param {boolean} startDim If true, we dim the letter instead of highlighting.
* @return {Array.<string>} The backgrounds which can be used to animate it.
* @private
*/
turing.Logo.prototype.getAnimationBackgrounds_ = function(letter, startDim) {
var backgrounds = [];
for (var i = 0; i < turing.NUM_LETTER_ANIMATION_FRAMES_; i++) {
backgrounds[i] = turing.sprites.getBackground(
letter + (startDim ? i : turing.NUM_LETTER_ANIMATION_FRAMES_ - 1 - i));
}
return backgrounds;
};
/**
* Lights up the letter at the given position.
* @param {number} pos The index of the letter to light up.
* @param {number=} opt_duration The duration to animate lighting the logo
* letter.
*/
turing.Logo.prototype.lightLetterAtPosition = function(pos, opt_duration) {
if (!this.letters_[pos]) {
return;
}
var letter = turing.LOGO_LETTERS[pos];
if (!opt_duration) {
this.letters_[pos].style.background = turing.sprites.getBackground(
letter + (turing.NUM_LETTER_ANIMATION_FRAMES_ - 1));
} else {
turing.anim.animateThroughBackgrounds(this.letters_[pos],
this.getAnimationBackgrounds_(letter, true), opt_duration);
}
};
/**
* Dims the letter at the given position.
* @param {number} pos The index of the letter to dim.
* @param {number=} opt_duration The duration to animate dimming the logo
* letter.
*/
turing.Logo.prototype.dimLetterAtPosition = function(pos, opt_duration) {
var letterDiv = this.letters_[pos];
if (!letterDiv) {
return;
}
var letter = turing.LOGO_LETTERS[pos];
if (!opt_duration) {
letterDiv.style.background =
turing.sprites.getBackground(letter + '0');
} else {
turing.anim.animateThroughBackgrounds(letterDiv,
this.getAnimationBackgrounds_(letter, false), opt_duration);
}
};
/**
* Dims all letters.
* @param {number=} opt_duration The duration to animate dimming the logo
* letters.
*/
turing.Logo.prototype.dim = function(opt_duration) {
for (var i = 0; i < this.letters_.length; i++) {
turing.anim.delay(
goog.bind(this.dimLetterAtPosition, this, i, opt_duration), 250);
}
};
/**
* Successively dim each letter of the logo from the last to the first.
* @param {function()=} opt_doneCallback Called when the logo is dim again.
*/
turing.Logo.prototype.deluminate = function(opt_doneCallback) {
var numLetters = turing.LOGO_LETTERS.length;
for (var i = 0; i < numLetters; i++) {
turing.anim.delay(
goog.bind(this.dimLetterAtPosition, this, numLetters - (i + 1), 500),
250 * i);
}
turing.anim.delay(
goog.bind(function() {
this.dim();
opt_doneCallback();
}, this), 250 * (1 + turing.LOGO_LETTERS.length) + 500);
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Animates a Turing machine tape.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.require('turing.anim');
goog.require('turing.sprites');
goog.require('turing.util');
goog.provide('turing.Tape');
/**
* How many squares of the tape are visible.
* Should be odd so that the read/write head is centered.
* @type {number}
* @const
*/
turing.NUM_VISIBLE_SQUARES = 9;
/**
* How many squares of the tape are left of the read/write head.
* @type {number}
* @const
*/
turing.NUM_VISIBLE_LEFT_SQUARES = (turing.NUM_VISIBLE_SQUARES - 1) / 2;
/**
* How many squares of the tape are right of the read/write head and may
* scroll into view. Note that this is the number currently visible plus
* up to target.length (5) extra squares. This is because when we check for
* equality, we start at the beginning of the string and scrollRight until we've
* reached the end of the string, possibly revealing an extra 5 squares.
* @type {number}
* @const
*/
turing.NUM_VISIBLE_RIGHT_SQUARES = (turing.NUM_VISIBLE_SQUARES - 1) / 2 + 5;
/**
* Number of extra squares to draw left and right of the fully visible tape
* squares. This must be at least two, since we show part of the left neighbor
* of the leftmost square while scanning right.
* @type {number}
* @const
*/
turing.NUM_MARGIN_SQUARES = 2;
/**
* How many total squares are on screen, visible or in the margins?
* @type {number}
* @const
*/
turing.NUM_SQUARES = turing.NUM_VISIBLE_SQUARES + 2 * turing.NUM_MARGIN_SQUARES;
/**
* The index of the tape square div under the read/write head when the tape is
* stationary. When the tape moves, this div slides left or right, then pops
* back into its original position showing a new symbol.
* @type {number}
* @const
*/
turing.HEAD_SQUARE = turing.NUM_MARGIN_SQUARES +
turing.NUM_VISIBLE_LEFT_SQUARES;
/**
* Z-index of the tape squares.
* @type {number}
* @const
*/
turing.SQUARE_ZINDEX = 400;
/**
* Left offset for the tape.
* @type {number}
* @const
*/
turing.TAPE_LEFT = 63;
/**
* Top offset for the tape.
* @type {number}
* @const
*/
turing.TAPE_TOP = 74;
/**
* How many pixels of the tape to either side of the visible portion are
* partially visible through the slot.
* @type {number}
* @const
*/
turing.VISIBLE_FEED_WIDTH = 7;
/**
* Height of the shadow at the bottom of the tape.
* @type {number}
* @const
*/
turing.TAPE_SHADOW_HEIGHT = 4;
/**
* Duration in ms of scan animation when tape is seeking.
* @type {number}
* @const
*/
turing.SEEK_MS = 50;
/**
* Map from tape symbol to its sprite name.
* @type {Object.<string, string>}
* @const
*/
turing.TAPE_SYMBOLS = {
'': 'tape_', '_': 'tape_', ' ': 'tape_',
'0': 'tape0', '1': 'tape1'
};
/**
* Sprite sequences to animate symbols being printed.
* @type {Object.<string, Array.<string>>}
* @const
*/
turing.PRINT_ANIMATIONS = {
'0': ['tape_', 'tape0a', 'tape0b', 'tape0c', 'tape0d', 'tape0'],
'1': ['tape_', 'tape1a', 'tape1b', 'tape1c', 'tape1d', 'tape1']
};
/**
* Sprite sequences to animate symbols being erased.
* @type {Object.<string, Array.<string>>}
* @const
*/
turing.ERASE_ANIMATIONS = {
'0': turing.PRINT_ANIMATIONS['0'].slice(0).reverse(),
'1': turing.PRINT_ANIMATIONS['1'].slice(0).reverse()
};
/**
* A Turing machine tape.
* @constructor
*/
turing.Tape = function() {
/**
* The symbols currently on the tape.
* @type {Object.<number, string>}
* @private
*/
this.contents_ = {};
/**
* The position of the read/write head.
* @type {number}
* @private
*/
this.pos_ = 0;
/**
* The maximum written tape position.
* @type {number}
* @private
*/
this.maxWrittenPosition_ = 0;
/**
* The location on the tape that the current program started from.
* @type {number}
* @private
*/
this.lastStartPos_ = 0;
/**
* Divs for each visible tape square plus one off each edge.
* @type {Array.<Element>}
* @private
*/
this.squares_ = [];
/**
* A div that holds all the square divs. It is wider than the pane.
* @type {Element}
* @private
*/
this.squareHolder_;
/**
* A div which the square holder moves around inside.
* @type {Element}
* @private
*/
this.pane_;
/**
* A div representing the read/write head.
* @type {Element}
* @private
*/
this.readWriteHead_;
/**
* A div holding the tape squares and head.
* @type {Element}
* @private
*/
this.tapeDiv_;
/**
* A div showing the hole where the left of the tape emerges.
* @type {Element}
* @private
*/
this.slotLeft_;
/**
* A div showing the hole where the right of the tape emerges.
* @type {Element}
* @private
*/
this.slotRight_;
/**
* A div with a shadow to show over the left of the tape.
* @type {Element}
* @private
*/
this.shadowLeft_;
/**
* A div with a shadow to show over the right of the tape.
* @type {Element}
* @private
*/
this.shadowRight_;
/**
* Position currently seeking to, or null if none.
* @type {?number}
* @private
*/
this.seekPos_ = null;
/**
* Is the tape currently scanning left or right?
* @type {boolean}
* @private
*/
this.scanning_ = false;
};
/**
* Attaches tape DOM tree to element.
* @param {Element} elem The parent for the tape.
*/
turing.Tape.prototype.attachTo = function(elem) {
this.redrawTape_();
elem.appendChild(this.tapeDiv_);
elem.appendChild(this.slotLeft_);
elem.appendChild(this.slotRight_);
elem.appendChild(this.shadowLeft_);
elem.appendChild(this.shadowRight_);
};
/**
* Create DOM nodes for the tape.
*/
turing.Tape.prototype.create = function() {
var squareSize = turing.sprites.getSize('tape_');
var paneWidth = turing.NUM_VISIBLE_SQUARES * squareSize.width +
2 * turing.VISIBLE_FEED_WIDTH + 2;
this.pane_ = turing.sprites.getEmptyDiv();
this.pane_.style.width = paneWidth + 'px';
this.pane_.style.height = squareSize.height + 'px';
this.pane_.style.overflow = 'hidden';
this.pane_.style.left = '0';
this.pane_.style.top = '0';
this.pane_.style.zIndex = turing.SQUARE_ZINDEX;
var holderWidth = turing.NUM_SQUARES * squareSize.width;
this.squareHolder_ = turing.sprites.getEmptyDiv();
this.squareHolder_.style.width = holderWidth + 'px';
this.squareHolder_.style.left =
-turing.NUM_MARGIN_SQUARES * squareSize.width +
turing.VISIBLE_FEED_WIDTH + 'px';
// Create visible squares plus extra squares for padding when scrolling.
for (var i = 0; i < turing.NUM_SQUARES; i++) {
this.squares_[i] = turing.sprites.getDiv('tape_');
this.squares_[i].style.display = 'inline-block';
this.squares_[i].style.position = '';
this.squareHolder_.appendChild(this.squares_[i]);
}
this.pane_.appendChild(this.squareHolder_);
var headSize = turing.sprites.getSize('head');
var extraHeadHeight = headSize.height - squareSize.height;
var extraHeadWidth = headSize.width - squareSize.width;
this.readWriteHead_ = turing.sprites.getDiv('head');
this.readWriteHead_.style.top = (-extraHeadHeight / 2 - 2) + 'px';
this.readWriteHead_.style.left = turing.VISIBLE_FEED_WIDTH +
(turing.NUM_VISIBLE_LEFT_SQUARES * squareSize.width) -
extraHeadWidth / 2 + 1 + 'px';
this.readWriteHead_.style.zIndex = turing.SQUARE_ZINDEX + 1;
this.tapeDiv_ = turing.sprites.getEmptyDiv();
this.tapeDiv_.style.top = turing.TAPE_TOP + 'px';
this.tapeDiv_.style.left = turing.TAPE_LEFT + 'px';
this.tapeDiv_.appendChild(this.pane_);
this.tapeDiv_.appendChild(this.readWriteHead_);
this.slotLeft_ = this.createSlot_('slot-left', turing.TAPE_LEFT, -1,
squareSize.height);
this.slotRight_ = this.createSlot_('slot-right', turing.TAPE_LEFT + paneWidth,
0, squareSize.height);
this.shadowLeft_ = this.createShadow_('tape-shadow-l', turing.TAPE_LEFT);
this.shadowRight_ = this.createShadow_('tape-shadow-r',
turing.TAPE_LEFT + paneWidth -
turing.sprites.getSize('tape-shadow-r').width);
};
/**
* Creates a dom node for a tape slot (a black oval on either side of the tape
* where it emerges onto the page).
* @param {string} spriteName The sprite to use.
* @param {number} leftEdge The left offset of the edge of the tape closest to
* this slot.
* @param {number} leftBump A small amount by which to move the left coordinate.
* Needed because the sizes don't round evenly.
* @param {number} squareHeight The height of a tape square.
* @return {Element} The slot div.
* @private
*/
turing.Tape.prototype.createSlot_ = function(spriteName, leftEdge,
leftBump, squareHeight) {
var size = turing.sprites.getSize(spriteName);
var slot = turing.sprites.getDiv(spriteName);
slot.style.zIndex = turing.SQUARE_ZINDEX - 1; // Behind tape.
// On Windows, browsers seem to round 57.5 up to the next pixel right,
// which looks wrong, so floor here to match cross platform.
slot.style.left = Math.floor(leftEdge - leftBump - size.width / 2) + 'px';
slot.style.top = (turing.TAPE_TOP - turing.TAPE_SHADOW_HEIGHT / 2 +
squareHeight / 2 - size.height / 2) + 'px';
return slot;
};
/**
* Creates a dom node for a tape slot shadow next to the black oval slots.
* @param {string} spriteName The sprite to use.
* @param {number} leftEdge The left offset of the edge of the tape closest to
* this slot.
* @return {Element} The slot div.
* @private
*/
turing.Tape.prototype.createShadow_ = function(spriteName, leftEdge) {
var slot = turing.sprites.getDiv(spriteName);
slot.style.zIndex = turing.SQUARE_ZINDEX + 1; // Above tape.
slot.style.left = leftEdge + 'px';
slot.style.top = turing.TAPE_TOP + 'px';
return slot;
};
/**
* Unbind event listeners, stop timers and tear down DOM.
*/
turing.Tape.prototype.destroy = function() {
for (var i = 0; i < this.squares_.length; i++) {
turing.util.removeNode(this.squares_[i]);
}
this.squares_.splice(0);
turing.util.removeNode(this.squareHolder_);
this.squareHolder_ = null;
turing.util.removeNode(this.pane_);
this.pane_ = null;
turing.util.removeNode(this.readWriteHead_);
this.readWriteHead_ = null;
turing.util.removeNode(this.tapeDiv_);
this.tapeDiv_ = null;
turing.util.removeNode(this.slotLeft_);
this.slotLeft_ = null;
turing.util.removeNode(this.slotRight_);
this.slotRight_ = null;
turing.util.removeNode(this.shadowLeft_);
this.shadowLeft_ = null;
turing.util.removeNode(this.shadowRight_);
this.shadowRight_ = null;
};
/**
* Scrolls the tape to the left.
* @param {number} waitTime Delay before scanning starts in ms.
* @param {number} scanTime Duration for scan animation in ms.
*/
turing.Tape.prototype.scanLeft = function(waitTime, scanTime) {
this.scanning_ = true;
this.pos_--;
var squareSize = turing.sprites.getSize('tape_');
var newLeft = -(turing.NUM_MARGIN_SQUARES - 1) * squareSize.width +
turing.VISIBLE_FEED_WIDTH;
turing.anim.delay(goog.bind(function() {
turing.anim.animate(this.squareHolder_, {'left': newLeft + 'px'},
scanTime, goog.bind(this.redrawTape_, this));
}, this), waitTime);
};
/**
* Scrolls the tape to the right.
* @param {number} waitTime Delay before scanning starts in ms.
* @param {number} scanTime Duration for scan animation in ms.
*/
turing.Tape.prototype.scanRight = function(waitTime, scanTime) {
this.scanning_ = true;
this.pos_++;
var squareSize = turing.sprites.getSize('tape_');
var newLeft = -(turing.NUM_MARGIN_SQUARES + 1) * squareSize.width +
turing.VISIBLE_FEED_WIDTH;
turing.anim.delay(goog.bind(function() {
turing.anim.animate(this.squareHolder_, {'left': newLeft + 'px'},
scanTime, goog.bind(this.redrawTape_, this));
}, this), waitTime);
};
/**
* Scans the tape until it reaches a particular position. This is done by
* calling scanLeft/scanRight repeatedly.
* @private
*/
turing.Tape.prototype.seek_ = function() {
if (this.seekPos_ == null) {
return;
}
if (this.pos_ < this.seekPos_) {
this.scanRight(0, turing.SEEK_MS);
} else if (this.pos_ > this.seekPos_) {
this.scanLeft(0, turing.SEEK_MS);
} else {
// We've arrived at the seek position. Nuke everything except the currently
// visible portion of the tape.
this.seekPos_ = null;
this.clearOutsideRange_(
this.pos_ - turing.NUM_VISIBLE_LEFT_SQUARES,
this.pos_ + turing.NUM_VISIBLE_RIGHT_SQUARES);
}
};
/**
* Clears tape squares not in the range [start, end].
* @param {number} start The position of the first square to keep.
* @param {number} end The position of the last square to keep.
* @private
*/
turing.Tape.prototype.clearOutsideRange_ = function(start, end) {
for (var i in this.contents_) {
i = /** @type {number} */(i); // Reassure the compiler.
if (i < start || i > end) {
this.contents_[i] = '';
}
}
};
/**
* Prints a symbol at the read/write head position.
* @param {string} symbol Symbol to print.
* @param {number} eraseTime Duration in ms for erasing old symbol.
* @param {number} printTime Duration in ms for printing new symbol.
*/
turing.Tape.prototype.print = function(symbol, eraseTime, printTime) {
var oldSymbol = this.contents_[this.pos_];
this.contents_[this.pos_] = symbol;
this.maxWrittenPosition_ = Math.max(this.pos_, this.maxWrittenPosition_);
// Always erase the old symbol and then print a new symbol, instead of
// animating changing a 0 directly to a 1 or vice versa.
this.showErase_(oldSymbol, eraseTime,
goog.bind(this.showPrint_, this, symbol, printTime));
};
/**
* Shows a symbol being erased from the tape.
* @param {string} symbol The symbol to erase.
* @param {number} time Duration in ms for erasing animation.
* @param {function()} onDone Function to call when done erasing.
* @private
*/
turing.Tape.prototype.showErase_ = function(symbol, time, onDone) {
if (symbol == '0' || symbol == '1') {
turing.anim.animateFromSprites(this.squares_[turing.HEAD_SQUARE],
turing.ERASE_ANIMATIONS[symbol], time, onDone);
} else {
// Square is already blank. Delay before calling onDone anyway so that
// there is a pause between when a print operation circle is lit and when we
// show a symbol being printed.
turing.anim.delay(onDone, time);
}
};
/**
* Shows a symbol being printed on the tape.
* @param {string} symbol The symbol to print.
* @param {number} time Duration in ms for printing animation.
* @private
*/
turing.Tape.prototype.showPrint_ = function(symbol, time) {
if (symbol == '0' || symbol == '1') {
turing.anim.animateFromSprites(this.squares_[turing.HEAD_SQUARE],
turing.PRINT_ANIMATIONS[symbol], time,
goog.bind(this.redrawSquare_, this, turing.HEAD_SQUARE));
}
// Otherwise, assume square has already been erased by showErase_.
};
/**
* Gets the symbol under the read/write head.
* @return {string} The symbol, or '_' if none.
*/
turing.Tape.prototype.getCurSymbol = function() {
return this.contents_[this.pos_] || '_';
};
/**
* Appends a string one visible tape width past the last written position on
* the tape and scans to there. Used to set up initial tape for a program after
* another program has been running for a while.
* @param {string} str The desired initial contents of the tape.
*/
turing.Tape.prototype.setString = function(str) {
this.maxWrittenPosition_ += turing.NUM_SQUARES;
var start = this.maxWrittenPosition_;
// Save this start position so we can reset to the same string if this next
// program run is not correct.
this.lastStartPos_ = start;
this.writeString_(str, start);
// We wrote str.length more characters.
this.maxWrittenPosition += str.length;
this.reinitializePositionOnTape_(str, start);
};
/**
* Similar to setString but resets to the last program start in-place.
* @param {string} str The desired initial contents of the tape.
*/
turing.Tape.prototype.resetString = function(str) {
var start = this.lastStartPos_;
this.writeString_(str, start);
// Clear everything to the left or right of the string.
this.clearOutsideRange_(start, start + str.length - 1);
this.reinitializePositionOnTape_(str, start);
};
/**
* Write the given string to the tape.
* @param {string} str The desired contents of the tape.
* @param {number} start The position to start writing the string on the tape.
* @private
*/
turing.Tape.prototype.writeString_ = function(str, start) {
// Reset the symbols on the tape.
for (var i = 0; i < str.length; i++) {
this.contents_[start + i] = str.charAt(i);
}
};
/**
* Move to the middle of the current string on the tape.
* @param {string} str The current string on the tape.
* @param {number} start The start position of the current string on the tape.
* @private
*/
turing.Tape.prototype.reinitializePositionOnTape_ = function(str, start) {
this.seekPos_ = start + Math.floor(str.length / 2);
if (!this.scanning_) {
// If the tape is already scanning, redrawTape will get called when that
// animation finishes, and will call seek_ to scan.
this.redrawTape_();
}
};
/**
* @return {number} The index of the first symbol on the tape.
* @private
*/
turing.Tape.prototype.getIndexOfFirstSymbol_ = function() {
var minValidPos = null;
for (var i in this.contents_) {
i = /** @type {number} */(i); // Reassure the compiler.
if (this.contents_[i] && this.contents_[i] != '_' &&
this.contents_[i] != ' ') {
if (minValidPos == null) {
minValidPos = i;
}
minValidPos = Math.min(minValidPos, i);
}
}
if (minValidPos == null) {
return -1;
}
return minValidPos;
};
/**
* Trigger a scan to the square that's offset spaces from the beginning of the
* string on the tape and return the contents of that square.
* @param {number} offset The number of spaces from the beginning of the string.
* @return {string} The contents of the square or the empty string.
*/
turing.Tape.prototype.scanToAndGetSymbol = function(offset) {
var index = this.getIndexOfFirstSymbol_() + offset;
if (index == -1) {
return '';
}
this.seekPos_ = index;
this.seek_();
return this.contents_[index];
};
/**
* Updates the visible portion of the tape.
* @private
*/
turing.Tape.prototype.redrawTape_ = function() {
this.scanning_ = false;
var squareSize = turing.sprites.getSize('tape_');
// Also set up the invisible squares just off the edges of the tape.
for (var i = 0; i < turing.NUM_SQUARES; i++) {
this.redrawSquare_(i);
}
this.squareHolder_.style.left =
-turing.NUM_MARGIN_SQUARES * squareSize.width +
turing.VISIBLE_FEED_WIDTH + 'px';
this.seek_();
};
/**
* Redraws one square on the tape.
* @param {number} i Index among _drawn_ squares.
* @private
*/
turing.Tape.prototype.redrawSquare_ = function(i) {
var offs = (i + this.pos_) - turing.HEAD_SQUARE;
var symbol = this.contents_[offs] || '';
var spriteName = turing.TAPE_SYMBOLS[symbol];
this.squares_[i].style.background =
turing.sprites.getBackground(spriteName);
};
/**
* Slides the entire tape assembly up to the top of the display area.
* Used to make room for larger programs in bonus mode.
*/
turing.Tape.prototype.slideUp = function() {
// 7px from the bottom of the tooltip.
turing.anim.animate(this.tapeDiv_, {'top': '27px'}, 200);
turing.anim.animate(this.shadowLeft_, {'top': '27px'}, 200);
turing.anim.animate(this.shadowRight_, {'top': '27px'}, 200);
turing.anim.animate(this.slotLeft_, {'top': '21px'}, 200);
turing.anim.animate(this.slotRight_, {'top': '21px'}, 200);
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Shows Turing machine programs as rows of operations.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.Program');
goog.require('turing.anim');
goog.require('turing.sprites');
goog.require('turing.util');
/**
* Number of rows of operations displayed in each mode.
* @type {Object.<string, number>}
* @const
*/
turing.NUM_PROGRAM_TRACKS = {
normalMode: 2,
bonusMode: 3
};
/**
* Number of operations per track in each mode. Some may be blank.
* @type {Object.<string, number>}
* @const
*/
turing.NUM_OPS_PER_TRACK = {
normalMode: 8,
bonusMode: 13
};
/**
* Left offset of program tracks.
* @type {number}
* @const
*/
turing.TRACK_LEFT = 74;
/**
* Width of a bonus mode track. As wide as the doodle will allow.
* @type {number}
* @const
*/
turing.BONUS_TRACK_WIDTH = 500;
/**
* Center vertical offsets of the buttons for each track.
* @type {Array.<number>}
* @const
* @private
*/
turing.TRACK_BUTTON_VERTICAL_MIDDLE_ = [150, 194];
/**
* Center vertical offsets of the buttons for each track in bonus mode.
* @type {Array.<number>}
* @const
* @private
*/
turing.BONUS_TRACK_BUTTON_VERTICAL_MIDDLE_ = [100, 140, 180];
/**
* Delay in ms for an op button to push in when pressed.
* This ought to be short because the user has already done something.
* @type {number}
* @const
*/
turing.OP_PUSH_IN_DELAY = 20;
/**
* Delay in ms for an op button to pop out when released.
* @type {number}
* @const
*/
turing.OP_POP_OUT_DELAY = 20;
/**
* Pixels of padding left of the first circle on the track. This is subtracted
* from total track width so that circles are centered in the non-padding area.
* @type {number}
* @const
*/
turing.TRACK_LEFT_PAD = 31;
/**
* Pixels of padding right of the last circle on the track. This is subtracted
* from total track width so that circles are centered in the non-padding area.
* @type {number}
* @const
*/
turing.TRACK_RIGHT_PAD = 9;
/**
* Pixels of padding top above the track in the track image.
* @type {number}
* @const
*/
turing.TRACK_TOP_PAD = 4;
/**
* The number of operations per program track in the current mode.
* @type {number}
* @private
*/
turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.normalMode;
/**
* The number of program tracks in the current mode.
* @type {number}
* @private
*/
turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.normalMode;
/**
* True if the game is done and we are running in bonus mode, else false if we
* are in the normal mode.
* @type {boolean}
* @private
*/
turing.inBonusMode_ = false;
/**
* Sets up program display for bonus mode.
*/
turing.switchProgramsToBonusMode = function() {
turing.inBonusMode_ = true;
turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.bonusMode;
turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.bonusMode;
};
/**
* Sets up program display for normal mode.
*/
turing.switchProgramsToNormalMode = function() {
turing.inBonusMode_ = false;
turing.numTracks_ = turing.NUM_PROGRAM_TRACKS.normalMode;
turing.numOpsPerTrack_ = turing.NUM_OPS_PER_TRACK.normalMode;
};
/**
* The current op highlight color.
* @type {string}
* @private
*/
turing.opHighlightColor_ = 'y';
/**
* Sets the op highlight color.
* @param {string} color One of 'b', 'r', 'y', 'g' to set the hilight color.
*/
turing.setOpHighlightColor = function(color) {
if (/^[bryg]$/.test(color)) {
// The color is valid.
turing.opHighlightColor_ = color;
} else {
// Invalid color. Shouldn't happen. Fall back to yellow.
turing.opHighlightColor_ = 'y';
}
};
/**
* @return {boolean} True iff program display is in bonus mode.
*/
turing.isInBonusMode = function() {
return turing.inBonusMode_;
};
/**
* A primitive step a program can do in one movement of the program counter.
* @typedef {string}
*/
turing.Op;
/**
* Map from operation strings used in stored programs to sprite names.
* @type {Object.<turing.Op, string>}
* @const
*/
turing.OP_SPRITES = {
'L': 'o-left',
'R': 'o-right',
'0': 'o-print0',
'1': 'o-print1',
'D0': 'o-down0',
'D1': 'o-down1',
'D_': 'o-down_',
'B2': 'o-back2',
'B3': 'o-back3',
'B4': 'o-back4',
'RB2': 'o-rback2',
'RB3': 'o-rback3',
'RB4': 'o-rback4',
'U0': 'o-up0',
'U1': 'o-up1',
'U_': 'o-up_',
'': 'o-blank',
// These operations are in the same spirit as the ones above, but are only
// used in bonus mode, and are not part of normal gameplay.
'_': 'o-x',
'U': 'o-blank-up',
'D': 'o-blank-down',
'B8': 'o-back8',
'B9': 'o-back9'
};
/**
* A track is a row of program operations arranged from left to right in control
* flow order.
* @param {number} verticalPosition The vertical offset of the track center.
* @param {boolean} loopTracksDown Iff true, the loop track points down, else
* up.
* @constructor
*/
turing.Track = function(verticalPosition, loopTracksDown) {
/**
* The vertical offset of the middle of this track.
* @type {number}
* @private
*/
this.verticalPosition_ = verticalPosition;
/**
* Iff true, loop branch tracks go down from the track, else up.
* @type {boolean}
* @private
*/
this.loopTracksDown_ = loopTracksDown;
/**
* This track's ops.
* @type {Array.<turing.Op>}
*/
this.ops = [];
/**
* Holds the track and operation divs.
* @type {Element}
* @private
*/
this.container_;
/**
* Divs for each operation on this track.
* @type {Array.<Element>}
* @private
*/
this.opDivs_ = [];
/**
* A div showing the path of the first loop branch on this track.
* @type {Element}
* @private
*/
this.loopBranchDiv_;
/**
* Index of the operation which is a loop branch, or null if none.
* @type {?number}
* @private
*/
this.loopBranchIndex_ = null;
/**
* Mousedown handlers for operation circles.
* @type {Array.<Function>}
* @private
*/
this.opMouseDownHandlers_ = [];
/**
* Touchstart handlers for operation circles.
* @type {Array.<Function>}
* @private
*/
this.opTouchHandlers_ = [];
/**
* Mouseup handlers for operation circles.
* @type {Array.<Function>}
* @private
*/
this.opMouseUpHandlers_ = [];
/**
* Mouseout handlers for operation circles.
* @type {Array.<Function>}
* @private
*/
this.opMouseOutHandlers_ = [];
/**
* Whether each operation is pushed in.
* @type {Array.<boolean>}
* @private
*/
this.opPushedIn_ = [];
/**
* Iff true, operations on this track are currently hidden.
* @type {boolean}
* @private
*/
this.hidden_ = true;
/**
* If true, listen to clicks on operations, else ignore them.
* @type {boolean}
* @private
*/
this.interactive_ = false;
};
/**
* Creates DOM elements for the track and its operations.
* - container: An overflow:hidden wrapper to hold everything.
* -- trackDiv: A vertically centered horizontal line (i.e. the track)
* -- ...ops: Individual ops, centered in equal-sized regions of track.
*/
turing.Track.prototype.create = function() {
// Size container based on interactive state, which is larger.
var opSize = turing.sprites.getSize('o-blank-i');
var trackSize = turing.sprites.getSize('track');
if (turing.inBonusMode_) {
trackSize.width = turing.BONUS_TRACK_WIDTH;
}
this.container_ = turing.sprites.getEmptyDiv();
this.container_.style.width = trackSize.width + 'px';
this.container_.style.height = opSize.height + 'px';
this.container_.style.zIndex = 400;
for (var i = 0; i < turing.numOpsPerTrack_; i++) {
this.createOp_(i);
}
if (!turing.inBonusMode_) {
var loopBranchTrackSize = turing.sprites.getSize('track-l4');
this.loopBranchDiv_ = turing.sprites.getDiv('track-l4');
this.loopBranchDiv_.style.display = 'none';
this.loopBranchDiv_.style.top = this.verticalPosition_ + 'px';
}
this.container_.style.zIndex = 399; // Beneath buttons.
this.container_.style.top =
(this.verticalPosition_ - opSize.height / 2) + 'px';
this.container_.style.left = turing.inBonusMode_ ?
'0' : turing.TRACK_LEFT + 'px';
};
/**
* Creates a single operation div and binds a lot of event listeners on it.
* @param {number} i The index of the operation to create.
* @private
*/
turing.Track.prototype.createOp_ = function(i) {
this.opDivs_[i] = turing.sprites.getDiv('o-dim-s');
var pos = this.getOpPosition('o-blank-s', i);
this.opDivs_[i].style.left = pos.left + 'px';
this.opDivs_[i].style.top = pos.top + 'px';
if (!turing.inBonusMode_) {
this.opMouseDownHandlers_[i] = goog.bind(this.pushInOp, this, i);
this.opTouchHandlers_[i] = goog.bind(function() {
this.opPushedIn_[i] = true;
this.popOutOp(i, true);
}, this);
this.opMouseUpHandlers_[i] = goog.bind(this.popOutOp, this, i, true);
this.opMouseOutHandlers_[i] = goog.bind(this.popOutOp, this, i, false);
turing.util.listen(this.opDivs_[i], 'mousedown',
this.opMouseDownHandlers_[i]);
turing.util.listen(this.opDivs_[i], 'touchstart',
this.opTouchHandlers_[i]);
turing.util.listen(this.opDivs_[i], 'mouseup', this.opMouseUpHandlers_[i]);
turing.util.listen(this.opDivs_[i], 'mouseout',
this.opMouseOutHandlers_[i]);
}
this.opPushedIn_[i] = false;
this.container_.appendChild(this.opDivs_[i]);
};
/**
* Computes the offset of an operation inside the track's container div.
* @param {string} spriteName The sprite used for this operation.
* @param {number} i The index of the operation.
* @return {{top: number, left: number}} The position for this operation.
*/
turing.Track.prototype.getOpPosition = function(spriteName, i) {
// Interactive operations are bigger than static operations. The track is
// sized to hold the bigger ones, and we center the smaller ones in the same
// footprint.
var bigOpSize = turing.sprites.getSize('o-blank-i');
var trackSize = turing.sprites.getSize('track');
if (turing.inBonusMode_) {
trackSize.width = turing.BONUS_TRACK_WIDTH;
}
// Center the bonus mode on the track (use the same padding as we do on the
// right, plus a few px to look correct).
var leftPadding = turing.inBonusMode_ ?
turing.TRACK_RIGHT_PAD + 4 : turing.TRACK_LEFT_PAD;
var trackWidthPerOp = (trackSize.width - turing.TRACK_RIGHT_PAD -
leftPadding) / turing.numOpsPerTrack_;
var opSize = turing.sprites.getSize(spriteName);
var xOffs = Math.ceil((bigOpSize.width - opSize.width) / 2);
var yOffs = Math.ceil((bigOpSize.height - opSize.height) / 2);
return { left: (leftPadding + Math.floor(i * trackWidthPerOp +
trackWidthPerOp / 2 - opSize.width / 2) - xOffs),
top: yOffs };
};
/**
* Sets a flag indicating whether operations on this track are currently hidden.
* If hidden, op divs are not redrawn as program execution proceeds.
* @param {boolean} hidden True iff op divs are hidden.
*/
turing.Track.prototype.setHidden = function(hidden) {
this.hidden_ = hidden;
};
/**
* Sets whether the track is currently clickable.
* No operations on the track should respond to clicks when a program is
* running or when we are changing programs.
* @param {boolean} interactive True iff track should be interactive.
*/
turing.Track.prototype.setInteractive = function(interactive) {
this.interactive_ = interactive;
this.redrawProgram();
};
/**
* Gets the ith operation div in control flow order on a track.
* @param {number} i Index into operations.
* @return {Element} The operation div.
*/
turing.Track.prototype.getOpDiv = function(i) {
return this.opDivs_[i];
};
/**
* Gets the ith operation in control flow order on a track.
* @param {number} i Index into operations.
* @return {turing.Op} The operation.
*/
turing.Track.prototype.getOp = function(i) {
return this.ops[i];
};
/**
* Sets the value of the ith operation in control flow order on track.
* @param {number} i Index into operations.
* @param {turing.Op} value Desired value.
*/
turing.Track.prototype.setOp = function(i, value) {
this.ops[i] = value;
};
/**
* Conditional branch operations from a higher track to a lower one.
* @type {Array.<turing.Op>}
* @private
* @const
*/
turing.COND_BRANCH_DOWN_OPS_ = ['D0', 'D1', 'D_'];
/**
* Conditional branch operations from a lower track to a higher one.
* @type {Array.<turing.Op>}
* @private
* @const
*/
turing.COND_BRANCH_UP_OPS_ = ['U0', 'U1', 'U_'];
/**
* Loop branch operations.
* @type {Array.<turing.Op>}
* @private
* @const
*/
turing.LOOP_BRANCH_OPS_ = ['B2', 'B3', 'B4'];
/**
* Printing operations.
* @type {Array.<turing.Op>}
* @private
* @const
*/
turing.PRINT_OPS_ = ['0', '1'];
/**
* Tape movement operations.
* @type {Array.<turing.Op>}
* @private
* @const
*/
turing.MOVE_OPS_ = ['L', 'R'];
/**
* Cycle to next valid op in this op's group.
* @param {number} i Index of relevant op.
*/
turing.Track.prototype.cycleOp = function(i) {
if (!this.interactive_) {
return;
}
var op = this.getOp(i);
if (!op || op.charAt(0) != '*') {
// This operation is not clickable.
return;
}
op = op.substr(1);
this.setOp(i, '*' + (
turing.util.getNextValue(turing.COND_BRANCH_UP_OPS_, op) ||
turing.util.getNextValue(turing.COND_BRANCH_DOWN_OPS_, op) ||
turing.util.getNextValue(turing.LOOP_BRANCH_OPS_, op) ||
turing.util.getNextValue(turing.PRINT_OPS_, op) ||
turing.util.getNextValue(turing.MOVE_OPS_, op) || op));
};
/**
* Push in an op button.
* @param {number} i Index of the relevant op.
* @param {Event} event mousedown or touchstart event.
*/
turing.Track.prototype.pushInOp = function(i, event) {
var spec = this.getOp(i);
if (!this.interactive_ || !spec || spec.charAt(0) != '*' ||
this.opPushedIn_[i]) {
// The button might still be pushed in if the pop-out animation from a
// previous click is still playing.
return;
}
this.opPushedIn_[i] = true;
var baseName = turing.Track.prototype.getOpSpriteBaseName_(spec);
turing.anim.animateFromSprites(this.opDivs_[i],
[baseName + '-i-out', baseName + '-i', baseName + '-i-in'],
turing.OP_PUSH_IN_DELAY);
};
/**
* Pop out an op button.
* @param {number} i Index of the relevant op.
* @param {boolean} shouldChange True iff we should cycle the op button.
* @param {Event} event mouseup or mouseout event.
*/
turing.Track.prototype.popOutOp = function(i, shouldChange, event) {
var spec = this.getOp(i);
if (!this.interactive_ || !spec || spec.charAt(0) != '*' ||
!this.opPushedIn_[i]) {
return;
}
if (shouldChange) {
this.cycleOp(i);
}
spec = this.getOp(i);
var baseName = turing.Track.prototype.getOpSpriteBaseName_(spec);
turing.anim.animateFromSprites(this.opDivs_[i],
[baseName + '-i-in', baseName + '-i', baseName + '-i-out'],
turing.OP_POP_OUT_DELAY,
goog.bind(function(i) {
this.opPushedIn_[i] = false;
this.redrawOp(i, false);
}, this, i));
};
/**
* Gets the base name of the sprite for the given operation.
* @param {string} spec An operation spec like D_.
* @return {string} The name of the sprite with no suffixes.
* @private
*/
turing.Track.prototype.getOpSpriteBaseName_ = function(spec) {
if (spec && spec.charAt(0) == '*') {
spec = spec.substr(1);
}
if (this.loopTracksDown_ &&
(spec == 'B2' || spec == 'B3' || spec == 'B4')) {
// Appending R reverses the direction of the loop so that it looks like it's
// pointing down to the lower track loop.
spec = 'R' + spec;
}
return turing.OP_SPRITES[spec || ''];
};
/**
* Sets the track's abstract operations, without updating or showing it.
* Makes a copy of the given array so that it can be changed without changing
* a constant program definition.
* @param {Array.<turing.Op>} ops Program operations.
*/
turing.Track.prototype.setOps = function(ops) {
this.ops = ops.slice(0); // Copy ops.
this.loopBranchIndex_ = null;
for (var i = 0; i < this.ops.length; i++) {
if (this.ops[i] && this.ops[i].match(/B/)) {
// /B/ matches operation codes containing B. Loop branches are the only
// such operations so this is a loop branch.
this.loopBranchIndex_ = i;
break;
}
}
};
/**
* Changes the operations on a track (and animates it into its new state).
* @param {Array.<turing.Op>} ops A list of new operations.
*/
turing.Track.prototype.change = function(ops) {
this.setOps(ops);
this.redrawProgram();
};
/**
* Redraws the current program.
*/
turing.Track.prototype.redrawProgram = function() {
if (!turing.inBonusMode_ && this.loopBranchIndex_ == null) {
// If there is no loop branch, hide backwards pointing track.
// (If there is a loop branch, it'll be shown from redrawOp below.)
this.loopBranchDiv_.style.display = 'none';
}
for (var i = 0; i < turing.numOpsPerTrack_; i++) {
this.redrawOp(i, false);
}
};
/**
* Updates the sprite for an operation.
* @param {number} i The index of the operation on the track.
* @param {boolean} lit Whether the operation is currently active.
*/
turing.Track.prototype.redrawOp = function(i, lit) {
if (this.hidden_) {
return;
}
var opDiv = this.getOpDiv(i);
var spec = this.getOp(i) || '';
var suffix = '';
if (spec && spec.charAt(0) == '*') {
// * means the operation is clickable.
if (this.interactive_) {
if (this.opPushedIn_[i]) {
suffix = '-i-in';
} else {
suffix = '-i-out';
}
opDiv.style.cursor = 'pointer';
} else {
// The operation is clickable, but not right now. It should be flat.
suffix = lit ? '-i-lit' : '-i';
opDiv.style.cursor = 'default';
}
} else {
// The operation is never clickable.
suffix = lit ? '-s-lit-' + turing.opHighlightColor_ : '-s';
opDiv.style.cursor = 'default';
}
var spriteName = this.getOpSpriteBaseName_(spec);
var size = turing.sprites.getSize(spriteName + suffix);
opDiv.style.background = turing.sprites.getBackground(
spriteName + suffix);
// Interactive buttons are bigger than static buttons, so we may need to
// recenter the button.
var pos = this.getOpPosition(spriteName + suffix, i);
opDiv.style.left = pos.left + 'px';
opDiv.style.top = pos.top + 'px';
opDiv.style.width = size.width + 'px';
opDiv.style.height = size.height + 'px';
if (i == this.loopBranchIndex_) {
this.redrawLoopBranchTrack_(spriteName + suffix);
}
};
/**
* Redraws the segment showing the path for a loop branch on this track.
* @param {string} opSpriteName The sprite name for the loop branch operation
* where the segment begins.
* @private
*/
turing.Track.prototype.redrawLoopBranchTrack_ = function(opSpriteName) {
if (this.loopBranchIndex_ == null || turing.inBonusMode_) {
return;
}
var spec = this.getOp(this.loopBranchIndex_);
// /(\d)$/ extracts the last single digit in the operation code, which for
// branches is the number of states to branch back (i.e. the distance).
var branchDist = spec.match(/(\d)$/);
var opSize = turing.sprites.getSize(opSpriteName);
var pos = this.getOpPosition(opSpriteName, this.loopBranchIndex_);
var loopBranchSprite = 'track-' + (this.loopTracksDown_ ? 'l' : 'u') +
branchDist[1];
var loopBranchSize = turing.sprites.getSize(loopBranchSprite);
this.loopBranchDiv_.style.background = turing.sprites.getBackground(
loopBranchSprite);
this.loopBranchDiv_.style.left = Math.floor(turing.TRACK_LEFT + pos.left -
loopBranchSize.width + opSize.width / 2 + 4) + 'px';
var middleOfButtons = this.verticalPosition_;
// For the top loop, its bottom should be aligned with the middle of the
// buttons.
var yOffs = this.loopTracksDown_ ? -3 : (-loopBranchSize.height + 2);
this.loopBranchDiv_.style.top = Math.floor(middleOfButtons + yOffs) + 'px';
this.loopBranchDiv_.style.width = loopBranchSize.width + 'px';
this.loopBranchDiv_.style.height = loopBranchSize.height + 'px';
this.loopBranchDiv_.style.display = 'block';
};
/**
* Since we're a touch device, destroy mouse handlers.
*/
turing.Track.prototype.setTouchDevice = function() {
this.destroyEventHandlers_(true);
};
/**
* Destroy the event handlers. Optionally save the touch events. This allows
* us to kill the mouse handlers if we're on a touch device. Note that we
* lazily check if we're a touch device by waiting for a touchstart event in
* turing.js rather than doing useragent parsing.
* @param {boolean=} opt_saveTouch Whether to preserve touch event handlers.
* @private
*/
turing.Track.prototype.destroyEventHandlers_ = function(opt_saveTouch) {
for (var i = 0; i < this.opMouseDownHandlers_.length; i++) {
turing.util.unlisten(this.opDivs_[i], 'mousedown',
this.opMouseDownHandlers_[i]);
}
this.opMouseDownHandlers_.splice(0);
if (!opt_saveTouch) {
for (var i = 0; i < this.opTouchHandlers_.length; i++) {
turing.util.unlisten(this.opDivs_[i], 'touchstart',
this.opTouchHandlers_[i]);
}
this.opTouchHandlers_.splice(0);
}
for (var i = 0; i < this.opMouseUpHandlers_.length; i++) {
turing.util.unlisten(this.opDivs_[i], 'mouseup',
this.opMouseUpHandlers_[i]);
}
this.opMouseUpHandlers_.splice(0);
for (var i = 0; i < this.opMouseOutHandlers_.length; i++) {
turing.util.unlisten(this.opDivs_[i], 'mouseout',
this.opMouseOutHandlers_[i]);
}
this.opMouseOutHandlers_.splice(0);
};
/**
* Cleans up dom elements and removes event listeners.
*/
turing.Track.prototype.destroy = function() {
this.destroyEventHandlers_();
for (var i = 0; i < this.opDivs_.length; i++) {
turing.util.removeNode(this.opDivs_[i]);
}
this.opDivs_.splice(0);
turing.util.removeNode(this.container_);
this.container_ = null;
turing.util.removeNode(this.loopBranchDiv_);
this.loopBranchDiv_ = null;
};
/**
* Adds to dom.
* @param {Element} elem dom parent.
*/
turing.Track.prototype.attachTo = function(elem) {
elem.appendChild(this.container_);
if (this.loopBranchDiv_) {
// Not shown in bonus mode.
elem.appendChild(this.loopBranchDiv_);
}
};
/**
* A Turing machine program shown as a set of tracks.
* @constructor
*/
turing.Program = function() {
/**
* Tracks containing operations.
* @type {Array.<turing.Track>}
* @private
*/
this.tracks_ = [];
for (var i = 0; i < turing.numTracks_; i++) {
this.tracks_[i] = new turing.Track(turing.inBonusMode_ ?
turing.BONUS_TRACK_BUTTON_VERTICAL_MIDDLE_[i] :
turing.TRACK_BUTTON_VERTICAL_MIDDLE_[i], i == 1);
}
/**
* The div containing the track image.
* @type {Element}
* @private
*/
this.trackDiv_;
/**
* Pieces of track joining the top track to the bottom track.
* @type {Array.<Element>}
* @private
*/
this.trackDescenders_ = [];
/**
* How many tracks does the current program have?
* @type {number}
* @private
*/
this.numActiveTracks_ = 0;
/**
* The current hilit operation's track number.
* @type {number}
* @private
*/
this.curTrack_ = 0;
/**
* The current hilit operation's position on its track.
* @type {number}
* @private
*/
this.curTrackPos_ = 0;
/**
* The next operation's track number.
* @type {number}
* @private
*/
this.nextTrack_ = 0;
/**
* The next operation's position on its track.
* @type {number}
* @private
*/
this.nextTrackPos_ = 0;
/**
* True iff the program should end on the next operation.
* @type {boolean}
* @private
*/
this.nextPosIsEnd_ = true;
/**
* Are the program's operations hidden?
* @type {boolean}
* @private
*/
this.hidden_ = true;
/**
* Can the user click on clickable operations right now?
* @type {boolean}
* @private
*/
this.interactive_ = false;
};
/**
* Creates dom elements for the program display.
*/
turing.Program.prototype.create = function() {
for (var i = 0; i < this.tracks_.length; i++) {
this.tracks_[i].create();
}
if (!turing.inBonusMode_) {
var opSize = turing.sprites.getSize('o-blank-i');
var middleOfTopTrack = turing.TRACK_BUTTON_VERTICAL_MIDDLE_[0];
this.trackDiv_ = turing.sprites.getDiv('track');
this.trackDiv_.style.left = turing.TRACK_LEFT + 'px';
this.trackDiv_.style.top = middleOfTopTrack - turing.TRACK_TOP_PAD + 'px';
// Bonus mode has no lines between tracks (they don't really fit).
var trackDownSize = turing.sprites.getSize('track-vert');
var trackSize = turing.sprites.getSize('track');
var trackWidthPerOp = (trackSize.width - turing.TRACK_LEFT_PAD -
turing.TRACK_RIGHT_PAD) / turing.numOpsPerTrack_;
for (var i = 0; i < turing.numOpsPerTrack_; i++) {
this.trackDescenders_[i] = turing.sprites.getDiv('track-vert');
// Vertical lines between operations on a pair of tracks are centered
// beneath those operations.
this.trackDescenders_[i].style.left = Math.floor(turing.TRACK_LEFT_PAD +
turing.TRACK_LEFT + i * trackWidthPerOp + trackWidthPerOp / 2 -
trackDownSize.width / 2 - 1) + 'px';
this.trackDescenders_[i].style.top = middleOfTopTrack + 'px';
this.trackDescenders_[i].style.zIndex = 398; // Behind operations.
this.trackDescenders_[i].style.display = 'none';
}
}
};
/**
* Cleans up dom elements and event listeners.
*/
turing.Program.prototype.destroy = function() {
for (var i = 0; i < this.tracks_.length; i++) {
this.tracks_[i].destroy();
}
turing.util.removeNode(this.trackDiv_);
for (var i = 0; i < this.trackDescenders_.length; i++) {
turing.util.removeNode(this.trackDescenders_[i]);
}
this.trackDescenders_.splice(0);
};
/**
* Attaches dom nodes beneath elem.
* @param {Element} elem Parent.
*/
turing.Program.prototype.attachTo = function(elem) {
for (var i = 0; i < this.tracks_.length; i++) {
this.tracks_[i].attachTo(elem);
}
if (!turing.inBonusMode_) {
// Bonus mode doesn't have track lines.
elem.appendChild(this.trackDiv_);
for (var i = 0; i < this.trackDescenders_.length; i++) {
elem.appendChild(this.trackDescenders_[i]);
}
}
};
/**
* Dims any lit operations.
*/
turing.Program.prototype.reset = function() {
for (var i = 0; i < turing.numTracks_; i++) {
this.tracks_[i].redrawProgram();
}
if (!turing.inBonusMode_) {
this.redrawDescenders_();
}
};
/**
* Draws lines connecting the tracks wherever there are up or down operations.
* @private
*/
turing.Program.prototype.redrawDescenders_ = function() {
for (var i = 0; i < turing.numOpsPerTrack_; i++) {
this.trackDescenders_[i].style.background =
turing.sprites.getBackground('track-vert');
var hasBranch = false;
for (var j = 0; j < turing.numTracks_; j++) {
var spec = this.tracks_[j].getOp(i);
if (!this.hidden_ && spec && spec.match(/D|U/)) {
// /D|U/ matches any conditional down-if or up-if branches (those are
// the only operations which contain 'D' or 'U').
hasBranch = true;
}
}
this.trackDescenders_[i].style.display = hasBranch ? 'block' : 'none';
}
};
/**
* Changes to a new program.
* @param {Array.<Array.<turing.Op>>} trackOps The operations for each
* valid program track. Note: This code supports 1 or 2 track programs.
* @param {boolean=} opt_hidden Iff true, change the program contents, but
* keep tracks hidden.
*/
turing.Program.prototype.change = function(trackOps, opt_hidden) {
this.curTrack_ = 0;
this.curTrackPos_ = 0;
this.nextTrack_ = 0;
this.nextTrackPos_ = 0;
this.nextPosIsEnd_ = false;
this.hidden_ = opt_hidden || false;
this.numActiveTracks_ = trackOps.length;
for (var i = 0; i < turing.numTracks_; i++) {
this.tracks_[i].setOps(trackOps[i] || []);
this.tracks_[i].setHidden(opt_hidden || false);
}
this.reset();
};
/**
* Sets whether program tracks are currently accepting clicks.
* @param {boolean} interactive True iff tracks should accept clicks.
*/
turing.Program.prototype.setInteractive = function(interactive) {
this.interactive_ = interactive;
for (var i = 0; i < turing.numTracks_; i++) {
this.tracks_[i].setInteractive(interactive);
}
};
/**
* Gets the current track number.
* @return {number} Current instruction's track.
*/
turing.Program.prototype.getCurTrack = function() {
return this.curTrack_;
};
/**
* Gets the current position on the current track.
* @return {number} Current instruction's op index within track.
*/
turing.Program.prototype.getCurTrackPos = function() {
return this.curTrackPos_;
};
/**
* @return {boolean} True iff next position is past end of program.
*/
turing.Program.prototype.isNextPosEnd = function() {
return this.nextPosIsEnd_;
};
/**
* Sets the track and position for the next operation to be run. Stays put if
* the new position is not a valid program position.
* @param {number} track The new track.
* @param {number} pos The new position.
*/
turing.Program.prototype.setNextPos = function(track, pos) {
if (track >= 0 && track < this.numActiveTracks_ &&
pos >= 0 && pos < turing.numOpsPerTrack_) {
this.nextTrack_ = track;
this.nextTrackPos_ = pos;
this.nextPosIsEnd_ = false;
} else {
this.nextPosIsEnd_ = true;
}
};
/**
* Sets the current position to the next position and redraws highlights.
*/
turing.Program.prototype.goToNextPos = function() {
this.dimCurOp();
if (!this.nextPosIsEnd_) {
this.curTrack_ = this.nextTrack_;
this.curTrackPos_ = this.nextTrackPos_;
this.lightCurOp_();
}
};
/**
* Dims the current active program operation.
*/
turing.Program.prototype.dimCurOp = function() {
this.tracks_[this.curTrack_].redrawOp(this.curTrackPos_, false);
};
/**
* Highlights the current active program operation.
* @private
*/
turing.Program.prototype.lightCurOp_ = function() {
this.tracks_[this.curTrack_].redrawOp(this.curTrackPos_, true);
};
/**
* Gets the current program operation to execute.
* @return {turing.Op} The current operation.
*/
turing.Program.prototype.getCurOp = function() {
return this.tracks_[this.curTrack_].getOp(this.curTrackPos_);
};
/**
* Notify the tracks that we're on a tablet.
*/
turing.Program.prototype.setTouchDevice = function() {
for (var i = 0; i < turing.numTracks_; i++) {
this.tracks_[i].setTouchDevice();
}
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Saves and restores persistent game state.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.GameState');
/**
* The localStorage key for the current program.
* @type {string}
* @const
* @private
*/
turing.CUR_PROGRAM_KEY_ = 'doodle-turing-p';
/**
* Minimum valid value for curProgram_.
* @type {number}
* @const
* @private
*/
turing.MIN_VALID_PROGRAM_ = 1;
/**
* Maximum valid value for curProgram_.
* @type {number}
* @const
* @private
*/
turing.MAX_VALID_PROGRAM_ = 12;
/**
* The current game state.
* @constructor
*/
turing.GameState = function() {
/**
* Index of the current program.
* @type {number}
* @private
*/
this.curProgram_ = turing.MIN_VALID_PROGRAM_;
};
/**
* @return {number} Index of current program.
*/
turing.GameState.prototype.getCurProgram = function() {
return this.curProgram_;
};
/**
* Sets index of current program.
* @param {number} curProgram The index of the current program.
*/
turing.GameState.prototype.setCurProgram = function(curProgram) {
this.curProgram_ = curProgram;
this.save();
};
/**
* Saves state using localStorage.
*/
turing.GameState.prototype.save = function() {
if (window.localStorage && window.localStorage.setItem) {
window.localStorage.setItem(turing.CUR_PROGRAM_KEY_, this.curProgram_);
}
};
/**
* Restores state using localStorage.
*/
turing.GameState.prototype.restore = function() {
if (window.localStorage && window.localStorage[turing.CUR_PROGRAM_KEY_]) {
this.curProgram_ = parseInt(
window.localStorage[turing.CUR_PROGRAM_KEY_], 10) || 0; // NaN -> 0.
if (this.curProgram_ < turing.MIN_VALID_PROGRAM_ ||
this.curProgram_ > turing.MAX_VALID_PROGRAM_) {
// If curProgram_ is corrupted, start from the first program.
this.curProgram_ = turing.MIN_VALID_PROGRAM_;
}
}
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Helpers for loading sprites.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.sprites');
goog.require('turing.deferredsprites.offsets');
goog.require('turing.sprites.offsets');
/**
* Path to the main sprite.
* @type {string}
* @const
*/
turing.sprites.PATH = 'images/sprite.png';
/**
* Path to the deferred sprite.
* @type {string}
* @const
*/
turing.sprites.DEFERRED_SPRITE_PATH = 'images/deferred_sprite.png';
/**
* Gets the width and height of the named sprite.
* @param {string} name A sprite name.
* @return {{width: number, height: number}}
*/
turing.sprites.getSize = function(name) {
var rect = turing.sprites.offsets.RECTS[name] ||
turing.deferredsprites.offsets.RECTS[name];
return {width: rect.width, height: rect.height};
};
/**
* Gets a string with background: CSS to select a sprite.
* @param {string} name The name of the desired sprite.
* @return {string} background: CSS.
*/
turing.sprites.getBackground = function(name) {
var rect = turing.sprites.offsets.RECTS[name] ||
turing.deferredsprites.offsets.RECTS[name];
if (!rect) {
// For debugging purposes, make it easy to see the missing sprite.
return 'red';
}
var deferred = !turing.sprites.offsets.RECTS[name] &&
turing.deferredsprites.offsets.RECTS[name];
var path =
deferred ? turing.sprites.DEFERRED_SPRITE_PATH : turing.sprites.PATH;
return 'url(' + path + ') ' +
-rect.x + 'px ' +
-rect.y + 'px no-repeat';
};
/**
* Gets a div containing the requested sprite.
* @param {string} name The name of the desired sprite.
* @return {Element} The sprite div.
*/
turing.sprites.getDiv = function(name) {
var div = turing.sprites.getEmptyDiv();
var rect = turing.sprites.offsets.RECTS[name];
// In practice, we should always have a sprite offset for a given name so we
// shouldn't be using these fallback values, but if we don't we render a
// 50x50 square and getBackground will return 'red' so that we can quickly
// and easily see the missing sprite.
div.style.width = rect ? (rect.width + 'px') : '50px';
div.style.height = rect ? (rect.height + 'px') : '50px';
div.style.background = turing.sprites.getBackground(name);
div.style['webkitTapHighlightColor'] = 'rgba(0,0,0,0)';
return div;
};
/**
* Gets an empty, unselectable div.
* @return {Element} The div.
*/
turing.sprites.getEmptyDiv = function() {
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.userSelect = 'none';
div.style.webkitUserSelect = 'none';
div.style['webkitTapHighlightColor'] = 'rgba(0,0,0,0)';
div.style.MozUserSelect = 'none';
div.unselectable = 'on';
return div;
};
/**
* Preloads sprites.
* @param {string} path The path to the image to preload.
* @return {Element} the image element used to preload the sprite.
*/
turing.sprites.preload = function(path) {
var img = document.createElement('img');
img.src = path;
return img;
};
|
JavaScript
|
// Copyright 2012 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Offsets for sprites. Auto-generated; do not edit.
* @author jered@google.com (Jered Wierzbicki)
*/
goog.provide('turing.sprites.offsets');
/**
* Sprite bounding box inside a combined image.
* @typedef {{x: number, y: number, width: number, height: number}}
*/
turing.sprites.offsets.Rect;
/**
* Bounding boxes of sprites in combined image.
* @type {Object.<string, turing.sprites.offsets.Rect>}
*/
turing.sprites.offsets.RECTS = {
'G0': {x: 0, y: 613, width: 35, height: 37},
'G1': {x: 35, y: 613, width: 35, height: 37},
'G2': {x: 70, y: 613, width: 35, height: 37},
'G3': {x: 105, y: 613, width: 35, height: 37},
'G4': {x: 140, y: 613, width: 35, height: 37},
'G5': {x: 175, y: 613, width: 35, height: 37},
'G6': {x: 210, y: 613, width: 35, height: 37},
'G7': {x: 245, y: 613, width: 35, height: 37},
'e0': {x: 0, y: 653, width: 22, height: 23},
'e1': {x: 22, y: 653, width: 22, height: 23},
'e2': {x: 44, y: 653, width: 22, height: 23},
'e3': {x: 66, y: 653, width: 22, height: 23},
'e4': {x: 88, y: 653, width: 22, height: 23},
'e5': {x: 110, y: 653, width: 22, height: 23},
'e6': {x: 132, y: 653, width: 22, height: 23},
'e7': {x: 154, y: 653, width: 22, height: 23},
'eq-bunny-b': {x: 137, y: 0, width: 40, height: 40},
'eq-bunny-g': {x: 217, y: 0, width: 40, height: 40},
'eq-bunny-r': {x: 257, y: 0, width: 40, height: 40},
'eq-bunny-y': {x: 177, y: 0, width: 40, height: 40},
'eq-dim': {x: 97, y: 0, width: 40, height: 40},
'eq-eq': {x: 337, y: 0, width: 40, height: 40},
'eq-neq': {x: 297, y: 0, width: 40, height: 40},
'g0': {x: 366, y: 640, width: 26, height: 36},
'g1': {x: 392, y: 640, width: 26, height: 36},
'g2': {x: 418, y: 640, width: 26, height: 36},
'g3': {x: 444, y: 640, width: 26, height: 36},
'g4': {x: 470, y: 640, width: 26, height: 36},
'g5': {x: 496, y: 640, width: 26, height: 36},
'g6': {x: 522, y: 640, width: 26, height: 36},
'g7': {x: 548, y: 640, width: 26, height: 36},
'head': {x: 286, y: 554, width: 61, height: 59},
'l0': {x: 380, y: 0, width: 16, height: 35},
'l1': {x: 396, y: 0, width: 16, height: 35},
'l2': {x: 412, y: 0, width: 16, height: 35},
'l3': {x: 428, y: 0, width: 16, height: 35},
'l4': {x: 444, y: 0, width: 16, height: 35},
'l5': {x: 460, y: 0, width: 16, height: 35},
'l6': {x: 476, y: 0, width: 16, height: 35},
'l7': {x: 492, y: 0, width: 16, height: 35},
'o-back-i': {x: 665, y: 416, width: 35, height: 45},
'o-back-i-in': {x: 665, y: 506, width: 35, height: 45},
'o-back-i-lit': {x: 665, y: 461, width: 35, height: 45},
'o-back-i-out': {x: 665, y: 326, width: 35, height: 45},
'o-back-i-out-lit': {x: 665, y: 371, width: 35, height: 45},
'o-back-s': {x: 714, y: 48, width: 34, height: 45},
'o-back-s-lit-b': {x: 714, y: 138, width: 34, height: 45},
'o-back-s-lit-g': {x: 714, y: 228, width: 34, height: 45},
'o-back-s-lit-r': {x: 714, y: 183, width: 34, height: 45},
'o-back-s-lit-y': {x: 714, y: 93, width: 34, height: 45},
'o-back2-i': {x: 385, y: 416, width: 35, height: 45},
'o-back2-i-in': {x: 385, y: 506, width: 35, height: 45},
'o-back2-i-lit': {x: 385, y: 461, width: 35, height: 45},
'o-back2-i-out': {x: 385, y: 326, width: 35, height: 45},
'o-back2-i-out-lit': {x: 385, y: 371, width: 35, height: 45},
'o-back2-s': {x: 442, y: 48, width: 34, height: 45},
'o-back2-s-lit-b': {x: 442, y: 138, width: 34, height: 45},
'o-back2-s-lit-g': {x: 442, y: 228, width: 34, height: 45},
'o-back2-s-lit-r': {x: 442, y: 183, width: 34, height: 45},
'o-back2-s-lit-y': {x: 442, y: 93, width: 34, height: 45},
'o-back3-i': {x: 420, y: 416, width: 35, height: 45},
'o-back3-i-in': {x: 420, y: 506, width: 35, height: 45},
'o-back3-i-lit': {x: 420, y: 461, width: 35, height: 45},
'o-back3-i-out': {x: 420, y: 326, width: 35, height: 45},
'o-back3-i-out-lit': {x: 420, y: 371, width: 35, height: 45},
'o-back3-s': {x: 476, y: 48, width: 34, height: 45},
'o-back3-s-lit-b': {x: 476, y: 138, width: 34, height: 45},
'o-back3-s-lit-g': {x: 476, y: 228, width: 34, height: 45},
'o-back3-s-lit-r': {x: 476, y: 183, width: 34, height: 45},
'o-back3-s-lit-y': {x: 476, y: 93, width: 34, height: 45},
'o-back4-i': {x: 455, y: 416, width: 35, height: 45},
'o-back4-i-in': {x: 455, y: 506, width: 35, height: 45},
'o-back4-i-lit': {x: 455, y: 461, width: 35, height: 45},
'o-back4-i-out': {x: 455, y: 326, width: 35, height: 45},
'o-back4-i-out-lit': {x: 455, y: 371, width: 35, height: 45},
'o-back4-s': {x: 510, y: 48, width: 34, height: 45},
'o-back4-s-lit-b': {x: 510, y: 138, width: 34, height: 45},
'o-back4-s-lit-g': {x: 510, y: 228, width: 34, height: 45},
'o-back4-s-lit-r': {x: 510, y: 183, width: 34, height: 45},
'o-back4-s-lit-y': {x: 510, y: 93, width: 34, height: 45},
'o-back8-i': {x: 595, y: 416, width: 35, height: 45},
'o-back8-i-in': {x: 595, y: 506, width: 35, height: 45},
'o-back8-i-lit': {x: 595, y: 461, width: 35, height: 45},
'o-back8-i-out': {x: 595, y: 326, width: 35, height: 45},
'o-back8-i-out-lit': {x: 595, y: 371, width: 35, height: 45},
'o-back8-s': {x: 646, y: 48, width: 34, height: 45},
'o-back8-s-lit-b': {x: 646, y: 138, width: 34, height: 45},
'o-back8-s-lit-g': {x: 646, y: 228, width: 34, height: 45},
'o-back8-s-lit-r': {x: 646, y: 183, width: 34, height: 45},
'o-back8-s-lit-y': {x: 646, y: 93, width: 34, height: 45},
'o-back9-i': {x: 630, y: 416, width: 35, height: 45},
'o-back9-i-in': {x: 630, y: 506, width: 35, height: 45},
'o-back9-i-lit': {x: 630, y: 461, width: 35, height: 45},
'o-back9-i-out': {x: 630, y: 326, width: 35, height: 45},
'o-back9-i-out-lit': {x: 630, y: 371, width: 35, height: 45},
'o-back9-s': {x: 680, y: 48, width: 34, height: 45},
'o-back9-s-lit-b': {x: 680, y: 138, width: 34, height: 45},
'o-back9-s-lit-g': {x: 680, y: 228, width: 34, height: 45},
'o-back9-s-lit-r': {x: 680, y: 183, width: 34, height: 45},
'o-back9-s-lit-y': {x: 680, y: 93, width: 34, height: 45},
'o-blank-down-i': {x: 735, y: 416, width: 35, height: 45},
'o-blank-down-i-in': {x: 735, y: 506, width: 35, height: 45},
'o-blank-down-i-lit': {x: 735, y: 461, width: 35, height: 45},
'o-blank-down-i-out': {x: 735, y: 326, width: 35, height: 45},
'o-blank-down-i-out-lit': {x: 735, y: 371, width: 35, height: 45},
'o-blank-down-s': {x: 782, y: 48, width: 34, height: 45},
'o-blank-down-s-lit-b': {x: 782, y: 138, width: 34, height: 45},
'o-blank-down-s-lit-g': {x: 782, y: 228, width: 34, height: 45},
'o-blank-down-s-lit-r': {x: 782, y: 183, width: 34, height: 45},
'o-blank-down-s-lit-y': {x: 782, y: 93, width: 34, height: 45},
'o-blank-i': {x: 0, y: 416, width: 35, height: 45},
'o-blank-i-in': {x: 0, y: 506, width: 35, height: 45},
'o-blank-i-lit': {x: 0, y: 461, width: 35, height: 45},
'o-blank-i-out': {x: 0, y: 326, width: 35, height: 45},
'o-blank-i-out-lit': {x: 0, y: 371, width: 35, height: 45},
'o-blank-s': {x: 34, y: 48, width: 34, height: 45},
'o-blank-s-lit-b': {x: 34, y: 138, width: 34, height: 45},
'o-blank-s-lit-g': {x: 34, y: 228, width: 34, height: 45},
'o-blank-s-lit-r': {x: 34, y: 183, width: 34, height: 45},
'o-blank-s-lit-y': {x: 34, y: 93, width: 34, height: 45},
'o-blank-up-i': {x: 700, y: 416, width: 35, height: 45},
'o-blank-up-i-in': {x: 700, y: 506, width: 35, height: 45},
'o-blank-up-i-lit': {x: 700, y: 461, width: 35, height: 45},
'o-blank-up-i-out': {x: 700, y: 326, width: 35, height: 45},
'o-blank-up-i-out-lit': {x: 700, y: 371, width: 35, height: 45},
'o-blank-up-s': {x: 748, y: 48, width: 34, height: 45},
'o-blank-up-s-lit-b': {x: 748, y: 138, width: 34, height: 45},
'o-blank-up-s-lit-g': {x: 748, y: 228, width: 34, height: 45},
'o-blank-up-s-lit-r': {x: 748, y: 183, width: 34, height: 45},
'o-blank-up-s-lit-y': {x: 748, y: 93, width: 34, height: 45},
'o-dim-s': {x: 0, y: 48, width: 34, height: 45},
'o-dim-s-lit-b': {x: 0, y: 138, width: 34, height: 45},
'o-dim-s-lit-g': {x: 0, y: 228, width: 34, height: 45},
'o-dim-s-lit-r': {x: 0, y: 183, width: 34, height: 45},
'o-dim-s-lit-y': {x: 0, y: 93, width: 34, height: 45},
'o-down0-i': {x: 35, y: 416, width: 35, height: 45},
'o-down0-i-in': {x: 35, y: 506, width: 35, height: 45},
'o-down0-i-lit': {x: 35, y: 461, width: 35, height: 45},
'o-down0-i-out': {x: 35, y: 326, width: 35, height: 45},
'o-down0-i-out-lit': {x: 35, y: 371, width: 35, height: 45},
'o-down0-s': {x: 102, y: 48, width: 34, height: 45},
'o-down0-s-lit-b': {x: 102, y: 138, width: 34, height: 45},
'o-down0-s-lit-g': {x: 102, y: 228, width: 34, height: 45},
'o-down0-s-lit-r': {x: 102, y: 183, width: 34, height: 45},
'o-down0-s-lit-y': {x: 102, y: 93, width: 34, height: 45},
'o-down1-i': {x: 70, y: 416, width: 35, height: 45},
'o-down1-i-in': {x: 70, y: 506, width: 35, height: 45},
'o-down1-i-lit': {x: 70, y: 461, width: 35, height: 45},
'o-down1-i-out': {x: 70, y: 326, width: 35, height: 45},
'o-down1-i-out-lit': {x: 70, y: 371, width: 35, height: 45},
'o-down1-s': {x: 136, y: 48, width: 34, height: 45},
'o-down1-s-lit-b': {x: 136, y: 138, width: 34, height: 45},
'o-down1-s-lit-g': {x: 136, y: 228, width: 34, height: 45},
'o-down1-s-lit-r': {x: 136, y: 183, width: 34, height: 45},
'o-down1-s-lit-y': {x: 136, y: 93, width: 34, height: 45},
'o-down_-i': {x: 105, y: 416, width: 35, height: 45},
'o-down_-i-in': {x: 105, y: 506, width: 35, height: 45},
'o-down_-i-lit': {x: 105, y: 461, width: 35, height: 45},
'o-down_-i-out': {x: 105, y: 326, width: 35, height: 45},
'o-down_-i-out-lit': {x: 105, y: 371, width: 35, height: 45},
'o-down_-s': {x: 170, y: 48, width: 34, height: 45},
'o-down_-s-lit-b': {x: 170, y: 138, width: 34, height: 45},
'o-down_-s-lit-g': {x: 170, y: 228, width: 34, height: 45},
'o-down_-s-lit-r': {x: 170, y: 183, width: 34, height: 45},
'o-down_-s-lit-y': {x: 170, y: 93, width: 34, height: 45},
'o-left-i': {x: 280, y: 416, width: 35, height: 45},
'o-left-i-in': {x: 280, y: 506, width: 35, height: 45},
'o-left-i-lit': {x: 280, y: 461, width: 35, height: 45},
'o-left-i-out': {x: 280, y: 326, width: 35, height: 45},
'o-left-i-out-lit': {x: 280, y: 371, width: 35, height: 45},
'o-left-s': {x: 340, y: 48, width: 34, height: 45},
'o-left-s-lit-b': {x: 340, y: 138, width: 34, height: 45},
'o-left-s-lit-g': {x: 340, y: 228, width: 34, height: 45},
'o-left-s-lit-r': {x: 340, y: 183, width: 34, height: 45},
'o-left-s-lit-y': {x: 340, y: 93, width: 34, height: 45},
'o-print0-i': {x: 350, y: 416, width: 35, height: 45},
'o-print0-i-in': {x: 350, y: 506, width: 35, height: 45},
'o-print0-i-lit': {x: 350, y: 461, width: 35, height: 45},
'o-print0-i-out': {x: 350, y: 326, width: 35, height: 45},
'o-print0-i-out-lit': {x: 350, y: 371, width: 35, height: 45},
'o-print0-s': {x: 408, y: 48, width: 34, height: 45},
'o-print0-s-lit-b': {x: 408, y: 138, width: 34, height: 45},
'o-print0-s-lit-g': {x: 408, y: 228, width: 34, height: 45},
'o-print0-s-lit-r': {x: 408, y: 183, width: 34, height: 45},
'o-print0-s-lit-y': {x: 408, y: 93, width: 34, height: 45},
'o-print1-i': {x: 315, y: 416, width: 35, height: 45},
'o-print1-i-in': {x: 315, y: 506, width: 35, height: 45},
'o-print1-i-lit': {x: 315, y: 461, width: 35, height: 45},
'o-print1-i-out': {x: 315, y: 326, width: 35, height: 45},
'o-print1-i-out-lit': {x: 315, y: 371, width: 35, height: 45},
'o-print1-s': {x: 374, y: 48, width: 34, height: 45},
'o-print1-s-lit-b': {x: 374, y: 138, width: 34, height: 45},
'o-print1-s-lit-g': {x: 374, y: 228, width: 34, height: 45},
'o-print1-s-lit-r': {x: 374, y: 183, width: 34, height: 45},
'o-print1-s-lit-y': {x: 374, y: 93, width: 34, height: 45},
'o-rback2-i': {x: 490, y: 416, width: 35, height: 45},
'o-rback2-i-in': {x: 490, y: 506, width: 35, height: 45},
'o-rback2-i-lit': {x: 490, y: 461, width: 35, height: 45},
'o-rback2-i-out': {x: 490, y: 326, width: 35, height: 45},
'o-rback2-i-out-lit': {x: 490, y: 371, width: 35, height: 45},
'o-rback2-s': {x: 544, y: 48, width: 34, height: 45},
'o-rback2-s-lit-b': {x: 544, y: 138, width: 34, height: 45},
'o-rback2-s-lit-g': {x: 544, y: 228, width: 34, height: 45},
'o-rback2-s-lit-r': {x: 544, y: 183, width: 34, height: 45},
'o-rback2-s-lit-y': {x: 544, y: 93, width: 34, height: 45},
'o-rback3-i': {x: 525, y: 416, width: 35, height: 45},
'o-rback3-i-in': {x: 525, y: 506, width: 35, height: 45},
'o-rback3-i-lit': {x: 525, y: 461, width: 35, height: 45},
'o-rback3-i-out': {x: 525, y: 326, width: 35, height: 45},
'o-rback3-i-out-lit': {x: 525, y: 371, width: 35, height: 45},
'o-rback3-s': {x: 578, y: 48, width: 34, height: 45},
'o-rback3-s-lit-b': {x: 578, y: 138, width: 34, height: 45},
'o-rback3-s-lit-g': {x: 578, y: 228, width: 34, height: 45},
'o-rback3-s-lit-r': {x: 578, y: 183, width: 34, height: 45},
'o-rback3-s-lit-y': {x: 578, y: 93, width: 34, height: 45},
'o-rback4-i': {x: 560, y: 416, width: 35, height: 45},
'o-rback4-i-in': {x: 560, y: 506, width: 35, height: 45},
'o-rback4-i-lit': {x: 560, y: 461, width: 35, height: 45},
'o-rback4-i-out': {x: 560, y: 326, width: 35, height: 45},
'o-rback4-i-out-lit': {x: 560, y: 371, width: 35, height: 45},
'o-rback4-s': {x: 612, y: 48, width: 34, height: 45},
'o-rback4-s-lit-b': {x: 612, y: 138, width: 34, height: 45},
'o-rback4-s-lit-g': {x: 612, y: 228, width: 34, height: 45},
'o-rback4-s-lit-r': {x: 612, y: 183, width: 34, height: 45},
'o-rback4-s-lit-y': {x: 612, y: 93, width: 34, height: 45},
'o-right-i': {x: 245, y: 416, width: 35, height: 45},
'o-right-i-in': {x: 245, y: 506, width: 35, height: 45},
'o-right-i-lit': {x: 245, y: 461, width: 35, height: 45},
'o-right-i-out': {x: 245, y: 326, width: 35, height: 45},
'o-right-i-out-lit': {x: 245, y: 371, width: 35, height: 45},
'o-right-s': {x: 306, y: 48, width: 34, height: 45},
'o-right-s-lit-b': {x: 306, y: 138, width: 34, height: 45},
'o-right-s-lit-g': {x: 306, y: 228, width: 34, height: 45},
'o-right-s-lit-r': {x: 306, y: 183, width: 34, height: 45},
'o-right-s-lit-y': {x: 306, y: 93, width: 34, height: 45},
'o-up0-i': {x: 140, y: 416, width: 35, height: 45},
'o-up0-i-in': {x: 140, y: 506, width: 35, height: 45},
'o-up0-i-lit': {x: 140, y: 461, width: 35, height: 45},
'o-up0-i-out': {x: 140, y: 326, width: 35, height: 45},
'o-up0-i-out-lit': {x: 140, y: 371, width: 35, height: 45},
'o-up0-s': {x: 204, y: 48, width: 34, height: 45},
'o-up0-s-lit-b': {x: 204, y: 138, width: 34, height: 45},
'o-up0-s-lit-g': {x: 204, y: 228, width: 34, height: 45},
'o-up0-s-lit-r': {x: 204, y: 183, width: 34, height: 45},
'o-up0-s-lit-y': {x: 204, y: 93, width: 34, height: 45},
'o-up1-i': {x: 175, y: 416, width: 35, height: 45},
'o-up1-i-in': {x: 175, y: 506, width: 35, height: 45},
'o-up1-i-lit': {x: 175, y: 461, width: 35, height: 45},
'o-up1-i-out': {x: 175, y: 326, width: 35, height: 45},
'o-up1-i-out-lit': {x: 175, y: 371, width: 35, height: 45},
'o-up1-s': {x: 238, y: 48, width: 34, height: 45},
'o-up1-s-lit-b': {x: 238, y: 138, width: 34, height: 45},
'o-up1-s-lit-g': {x: 238, y: 228, width: 34, height: 45},
'o-up1-s-lit-r': {x: 238, y: 183, width: 34, height: 45},
'o-up1-s-lit-y': {x: 238, y: 93, width: 34, height: 45},
'o-up_-i': {x: 210, y: 416, width: 35, height: 45},
'o-up_-i-in': {x: 210, y: 506, width: 35, height: 45},
'o-up_-i-lit': {x: 210, y: 461, width: 35, height: 45},
'o-up_-i-out': {x: 210, y: 326, width: 35, height: 45},
'o-up_-i-out-lit': {x: 210, y: 371, width: 35, height: 45},
'o-up_-s': {x: 272, y: 48, width: 34, height: 45},
'o-up_-s-lit-b': {x: 272, y: 138, width: 34, height: 45},
'o-up_-s-lit-g': {x: 272, y: 228, width: 34, height: 45},
'o-up_-s-lit-r': {x: 272, y: 183, width: 34, height: 45},
'o-up_-s-lit-y': {x: 272, y: 93, width: 34, height: 45},
'o-x-s': {x: 68, y: 48, width: 34, height: 45},
'o-x-s-lit-b': {x: 68, y: 138, width: 34, height: 45},
'o-x-s-lit-g': {x: 68, y: 228, width: 34, height: 45},
'o-x-s-lit-r': {x: 68, y: 183, width: 34, height: 45},
'o-x-s-lit-y': {x: 68, y: 93, width: 34, height: 45},
'o10': {x: 16, y: 585, width: 26, height: 25},
'o11': {x: 42, y: 585, width: 26, height: 25},
'o12': {x: 68, y: 585, width: 26, height: 25},
'o13': {x: 94, y: 585, width: 26, height: 25},
'o14': {x: 120, y: 585, width: 26, height: 25},
'o15': {x: 146, y: 585, width: 26, height: 25},
'o16': {x: 172, y: 585, width: 26, height: 25},
'o17': {x: 198, y: 585, width: 26, height: 25},
'o20': {x: 577, y: 610, width: 26, height: 25},
'o21': {x: 603, y: 610, width: 26, height: 25},
'o22': {x: 629, y: 610, width: 26, height: 25},
'o23': {x: 655, y: 610, width: 26, height: 25},
'o24': {x: 681, y: 610, width: 26, height: 25},
'o25': {x: 707, y: 610, width: 26, height: 25},
'o26': {x: 733, y: 610, width: 26, height: 25},
'o27': {x: 759, y: 610, width: 26, height: 25},
'play-flat': {x: 424, y: 276, width: 45, height: 46},
'play-in': {x: 469, y: 276, width: 45, height: 46},
'play-out': {x: 334, y: 276, width: 45, height: 46},
'play-out-lit': {x: 379, y: 276, width: 45, height: 46},
'slot-left': {x: 350, y: 610, width: 13, height: 55},
'slot-right': {x: 0, y: 554, width: 13, height: 55},
'tape-shadow-l': {x: 350, y: 554, width: 47, height: 41},
'tape-shadow-r': {x: 511, y: 0, width: 47, height: 41},
'tape0': {x: 721, y: 0, width: 40, height: 46},
'tape0a': {x: 561, y: 0, width: 40, height: 46},
'tape0b': {x: 601, y: 0, width: 40, height: 46},
'tape0c': {x: 641, y: 0, width: 40, height: 46},
'tape0d': {x: 681, y: 0, width: 40, height: 46},
'tape1': {x: 291, y: 276, width: 40, height: 46},
'tape1a': {x: 131, y: 276, width: 40, height: 46},
'tape1b': {x: 171, y: 276, width: 40, height: 46},
'tape1c': {x: 211, y: 276, width: 40, height: 46},
'tape1d': {x: 251, y: 276, width: 40, height: 46},
'tape_': {x: 243, y: 554, width: 40, height: 45},
'target-blank': {x: 0, y: 276, width: 128, height: 47},
'track': {x: 400, y: 554, width: 369, height: 53},
'track-l2': {x: 0, y: 0, width: 90, height: 27},
'track-l3': {x: 109, y: 554, width: 131, height: 27},
'track-l4': {x: 366, y: 610, width: 173, height: 27},
'track-short': {x: 0, y: 30, width: 94, height: 8},
'track-u2': {x: 16, y: 554, width: 90, height: 28},
'track-u3': {x: 517, y: 276, width: 131, height: 28},
'track-u4': {x: 577, y: 638, width: 173, height: 28},
'track-vert': {x: 286, y: 616, width: 7, height: 49}
};
|
JavaScript
|
var accessToken = "";
var url = "http://localhost:59138/token";
var headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'],
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Credendtials': 'true',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
var result = "grant_type=password&userName=admin&password=admin";
$.ajax(url, {
data: result,
type: "POST",
headers: headers
})
|
JavaScript
|
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */
/*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */
window.matchMedia = window.matchMedia || (function(doc, undefined){
var bool,
docElem = doc.documentElement,
refNode = docElem.firstElementChild || docElem.firstChild,
// fakeBody required for <FF4 when executed in <head>
fakeBody = doc.createElement('body'),
div = doc.createElement('div');
div.id = 'mq-test-1';
div.style.cssText = "position:absolute;top:-100em";
fakeBody.style.background = "none";
fakeBody.appendChild(div);
return function(q){
div.innerHTML = '­<style media="'+q+'"> #mq-test-1 { width: 42px; }</style>';
docElem.insertBefore(fakeBody, refNode);
bool = div.offsetWidth == 42;
docElem.removeChild(fakeBody);
return { matches: bool, media: q };
};
})(document);
/*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */
(function( win ){
//exposed namespace
win.respond = {};
//define update even in native-mq-supporting browsers, to avoid errors
respond.update = function(){};
//expose media query support flag for external use
respond.mediaQueriesSupported = win.matchMedia && win.matchMedia( "only all" ).matches;
//if media queries are supported, exit here
if( respond.mediaQueriesSupported ){ return; }
//define vars
var doc = win.document,
docElem = doc.documentElement,
mediastyles = [],
rules = [],
appendedEls = [],
parsedSheets = {},
resizeThrottle = 30,
head = doc.getElementsByTagName( "head" )[0] || docElem,
base = doc.getElementsByTagName( "base" )[0],
links = head.getElementsByTagName( "link" ),
requestQueue = [],
//loop stylesheets, send text content to translate
ripCSS = function(){
var sheets = links,
sl = sheets.length,
i = 0,
//vars for loop:
sheet, href, media, isCSS;
for( ; i < sl; i++ ){
sheet = sheets[ i ],
href = sheet.href,
media = sheet.media,
isCSS = sheet.rel && sheet.rel.toLowerCase() === "stylesheet";
//only links plz and prevent re-parsing
if( !!href && isCSS && !parsedSheets[ href ] ){
// selectivizr exposes css through the rawCssText expando
if (sheet.styleSheet && sheet.styleSheet.rawCssText) {
translate( sheet.styleSheet.rawCssText, href, media );
parsedSheets[ href ] = true;
} else {
if( (!/^([a-zA-Z:]*\/\/)/.test( href ) && !base)
|| href.replace( RegExp.$1, "" ).split( "/" )[0] === win.location.host ){
requestQueue.push( {
href: href,
media: media
} );
}
}
}
}
makeRequests();
},
//recurse through request queue, get css text
makeRequests = function(){
if( requestQueue.length ){
var thisRequest = requestQueue.shift();
ajax( thisRequest.href, function( styles ){
translate( styles, thisRequest.href, thisRequest.media );
parsedSheets[ thisRequest.href ] = true;
makeRequests();
} );
}
},
//find media blocks in css text, convert to style blocks
translate = function( styles, href, media ){
var qs = styles.match( /@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi ),
ql = qs && qs.length || 0,
//try to get CSS path
href = href.substring( 0, href.lastIndexOf( "/" )),
repUrls = function( css ){
return css.replace( /(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g, "$1" + href + "$2$3" );
},
useMedia = !ql && media,
//vars used in loop
i = 0,
j, fullq, thisq, eachq, eql;
//if path exists, tack on trailing slash
if( href.length ){ href += "/"; }
//if no internal queries exist, but media attr does, use that
//note: this currently lacks support for situations where a media attr is specified on a link AND
//its associated stylesheet has internal CSS media queries.
//In those cases, the media attribute will currently be ignored.
if( useMedia ){
ql = 1;
}
for( ; i < ql; i++ ){
j = 0;
//media attr
if( useMedia ){
fullq = media;
rules.push( repUrls( styles ) );
}
//parse for styles
else{
fullq = qs[ i ].match( /@media *([^\{]+)\{([\S\s]+?)$/ ) && RegExp.$1;
rules.push( RegExp.$2 && repUrls( RegExp.$2 ) );
}
eachq = fullq.split( "," );
eql = eachq.length;
for( ; j < eql; j++ ){
thisq = eachq[ j ];
mediastyles.push( {
media : thisq.split( "(" )[ 0 ].match( /(only\s+)?([a-zA-Z]+)\s?/ ) && RegExp.$2 || "all",
rules : rules.length - 1,
hasquery: thisq.indexOf("(") > -1,
minw : thisq.match( /\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" ),
maxw : thisq.match( /\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/ ) && parseFloat( RegExp.$1 ) + ( RegExp.$2 || "" )
} );
}
}
applyMedia();
},
lastCall,
resizeDefer,
// returns the value of 1em in pixels
getEmValue = function() {
var ret,
div = doc.createElement('div'),
body = doc.body,
fakeUsed = false;
div.style.cssText = "position:absolute;font-size:1em;width:1em";
if( !body ){
body = fakeUsed = doc.createElement( "body" );
body.style.background = "none";
}
body.appendChild( div );
docElem.insertBefore( body, docElem.firstChild );
ret = div.offsetWidth;
if( fakeUsed ){
docElem.removeChild( body );
}
else {
body.removeChild( div );
}
//also update eminpx before returning
ret = eminpx = parseFloat(ret);
return ret;
},
//cached container for 1em value, populated the first time it's needed
eminpx,
//enable/disable styles
applyMedia = function( fromResize ){
var name = "clientWidth",
docElemProp = docElem[ name ],
currWidth = doc.compatMode === "CSS1Compat" && docElemProp || doc.body[ name ] || docElemProp,
styleBlocks = {},
lastLink = links[ links.length-1 ],
now = (new Date()).getTime();
//throttle resize calls
if( fromResize && lastCall && now - lastCall < resizeThrottle ){
clearTimeout( resizeDefer );
resizeDefer = setTimeout( applyMedia, resizeThrottle );
return;
}
else {
lastCall = now;
}
for( var i in mediastyles ){
var thisstyle = mediastyles[ i ],
min = thisstyle.minw,
max = thisstyle.maxw,
minnull = min === null,
maxnull = max === null,
em = "em";
if( !!min ){
min = parseFloat( min ) * ( min.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
if( !!max ){
max = parseFloat( max ) * ( max.indexOf( em ) > -1 ? ( eminpx || getEmValue() ) : 1 );
}
// if there's no media query at all (the () part), or min or max is not null, and if either is present, they're true
if( !thisstyle.hasquery || ( !minnull || !maxnull ) && ( minnull || currWidth >= min ) && ( maxnull || currWidth <= max ) ){
if( !styleBlocks[ thisstyle.media ] ){
styleBlocks[ thisstyle.media ] = [];
}
styleBlocks[ thisstyle.media ].push( rules[ thisstyle.rules ] );
}
}
//remove any existing respond style element(s)
for( var i in appendedEls ){
if( appendedEls[ i ] && appendedEls[ i ].parentNode === head ){
head.removeChild( appendedEls[ i ] );
}
}
//inject active styles, grouped by media type
for( var i in styleBlocks ){
var ss = doc.createElement( "style" ),
css = styleBlocks[ i ].join( "\n" );
ss.type = "text/css";
ss.media = i;
//originally, ss was appended to a documentFragment and sheets were appended in bulk.
//this caused crashes in IE in a number of circumstances, such as when the HTML element had a bg image set, so appending beforehand seems best. Thanks to @dvelyk for the initial research on this one!
head.insertBefore( ss, lastLink.nextSibling );
if ( ss.styleSheet ){
ss.styleSheet.cssText = css;
}
else {
ss.appendChild( doc.createTextNode( css ) );
}
//push to appendedEls to track for later removal
appendedEls.push( ss );
}
},
//tweaked Ajax functions from Quirksmode
ajax = function( url, callback ) {
var req = xmlHttp();
if (!req){
return;
}
req.open( "GET", url, true );
req.onreadystatechange = function () {
if ( req.readyState != 4 || req.status != 200 && req.status != 304 ){
return;
}
callback( req.responseText );
}
if ( req.readyState == 4 ){
return;
}
req.send( null );
},
//define ajax obj
xmlHttp = (function() {
var xmlhttpmethod = false;
try {
xmlhttpmethod = new XMLHttpRequest();
}
catch( e ){
xmlhttpmethod = new ActiveXObject( "Microsoft.XMLHTTP" );
}
return function(){
return xmlhttpmethod;
};
})();
//translate CSS
ripCSS();
//expose update for re-running respond later on
respond.update = ripCSS;
//adjust on resize
function callMedia(){
applyMedia( true );
}
if( win.addEventListener ){
win.addEventListener( "resize", callMedia, false );
}
else if( win.attachEvent ){
win.attachEvent( "onresize", callMedia );
}
})(this);
|
JavaScript
|
//=============================================================================
// System : Sandcastle Help File Builder
// File : TOC.js
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 04/11/2008
// Note : Copyright 2006-2008, Eric Woodruff, All rights reserved
// Compiler: JavaScript
//
// This file contains the methods necessary to implement a simple tree view
// for the table of content with a resizable splitter and Ajax support to
// load tree nodes on demand. It also contains the script necessary to do
// full-text searches.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://www.CodePlex.com/SHFB. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.3.0.0 09/12/2006 EFW Created the code
// 1.4.0.2 06/15/2007 EFW Reworked to get rid of frame set and to add
// support for Ajax to load tree nodes on demand.
// 1.5.0.0 06/24/2007 EFW Added full-text search capabilities
// 1.6.0.7 04/01/2008 EFW Merged changes from Ferdinand Prantl to add a
// website keyword index. Added support for "topic"
// query string option.
//=============================================================================
// IE flag
var isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
// Minimum width of the TOC div
var minWidth = 100;
// Elements and sizing info
var divTOC, divSizer, topicContent, divNavOpts, divSearchOpts, divSearchResults,
divIndexOpts, divIndexResults, divTree, docBody, maxWidth, offset,
txtSearchText, chkSortByTitle;
// Last node selected
var lastNode, lastSearchNode, lastIndexNode;
// Last page with keyword index
var currentIndexPage = 0;
//============================================================================
// Initialize the tree view and resize the content
function Initialize()
{
docBody = document.getElementsByTagName("body")[0];
divTOC = document.getElementById("TOCDiv");
divSizer = document.getElementById("TOCSizer");
topicContent = document.getElementById("TopicContent");
divNavOpts = document.getElementById("divNavOpts");
divSearchOpts = document.getElementById("divSearchOpts");
divSearchResults = document.getElementById("divSearchResults");
divIndexOpts = document.getElementById("divIndexOpts");
divIndexResults = document.getElementById("divIndexResults");
divTree = document.getElementById("divTree");
txtSearchText = document.getElementById("txtSearchText");
chkSortByTitle = document.getElementById("chkSortByTitle");
// The sizes are bit off in FireFox
if(!isIE)
divNavOpts.style.width = divSearchOpts.style.width =
divIndexOpts.style.width = 292;
ResizeTree();
SyncTOC();
// Use an alternate default page if a topic is specified in
// the query string.
var queryString = document.location.search;
if(queryString != "")
{
var idx, options = queryString.split(/[\?\=\&]/);
for(idx = 0; idx < options.length; idx++)
if(options[idx] == "topic" && idx + 1 < options.length)
{
topicContent.src = options[idx + 1];
break;
}
}
}
//============================================================================
// Navigation and expand/collaps code
// Synchronize the table of content with the selected page if possible
function SyncTOC()
{
var idx, anchor, base, href, url, anchors, treeNode, saveNode;
base = window.location.href;
base = base.substr(0, base.lastIndexOf("/") + 1);
if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///")
base = base.replace("file://", "file:///");
url = GetCurrentUrl();
if(url == "")
return false;
if(url.substr(0, 5) == "file:" && url.substr(0, 8) != "file:///")
url = url.replace("file://", "file:///");
while(true)
{
anchors = divTree.getElementsByTagName("A");
anchor = null;
for(idx = 0; idx < anchors.length; idx++)
{
href = anchors[idx].href;
if(href.substring(0, 7) != 'http://' &&
href.substring(0, 8) != 'https://' &&
href.substring(0, 7) != 'file://')
href = base + href;
if(href == url)
{
anchor = anchors[idx];
break;
}
}
if(anchor == null)
{
// If it contains a "#", strip anything after that and try again
if(url.indexOf("#") != -1)
{
url = url.substr(0, url.indexOf("#"));
continue;
}
return;
}
break;
}
// If found, select it and find the parent tree node
SelectNode(anchor);
saveNode = anchor;
lastNode = null;
while(anchor != null)
{
if(anchor.className == "TreeNode")
{
treeNode = anchor;
break;
}
anchor = anchor.parentNode;
}
// Expand it and all of its parents
while(anchor != null)
{
Expand(anchor);
anchor = anchor.parentNode;
while(anchor != null)
{
if(anchor.className == "TreeNode")
break;
anchor = anchor.parentNode;
}
}
lastNode = saveNode;
// Scroll the node into view
var windowTop = lastNode.offsetTop - divTree.offsetTop - divTree.scrollTop;
var windowBottom = divTree.clientHeight - windowTop - lastNode.offsetHeight;
if(windowTop < 0)
divTree.scrollTop += windowTop - 30;
else
if(windowBottom < 0)
divTree.scrollTop -= windowBottom - 30;
}
// Get the currently loaded URL from the IFRAME
function GetCurrentUrl()
{
var base, url = "";
try
{
url = window.frames["TopicContent"].document.URL.replace(/\\/g, "/");
}
catch(e)
{
// If this happens the user probably navigated to another frameset
// that didn't make itself the topmost frameset and we don't have
// control of the other frame anymore. In that case, just reload
// our index page.
base = window.location.href;
base = base.substr(0, base.lastIndexOf("/") + 1);
if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///")
base = base.replace("file://", "file:///");
if(base.substr(0, 5) == "file:")
top.location.href = base + "Index.html";
else
top.location.href = base + "Index.aspx";
}
return url;
}
// Expand or collapse all nodes
function ExpandOrCollapseAll(expandNodes)
{
var divIdx, childIdx, img, divs = document.getElementsByTagName("DIV");
var childNodes, child, div, link, img;
for(divIdx = 0; divIdx < divs.length; divIdx++)
if(divs[divIdx].className == "Hidden" ||
divs[divIdx].className == "Visible")
{
childNodes = divs[divIdx].parentNode.childNodes;
for(childIdx = 0; childIdx < childNodes.length; childIdx++)
{
child = childNodes[childIdx];
if(child.className == "TreeNodeImg")
img = child;
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(div.className == "Visible" && !expandNodes)
{
div.className = "Hidden";
img.src = "Collapsed.gif";
}
else
if(div.className == "Hidden" && expandNodes)
{
div.className = "Visible";
img.src = "Expanded.gif";
if(div.innerHTML == "")
FillNode(div, true)
}
}
}
// Toggle the state of the specified node
function Toggle(node)
{
var i, childNodes, child, div, link;
childNodes = node.parentNode.childNodes;
for(i = 0; i < childNodes.length; i++)
{
child = childNodes[i];
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(div.className == "Visible")
{
div.className = "Hidden";
node.src = "Collapsed.gif";
}
else
{
div.className = "Visible";
node.src = "Expanded.gif";
if(div.innerHTML == "")
FillNode(div, false)
}
}
// Expand the selected node
function Expand(node)
{
var i, childNodes, child, div, img;
// If not valid, don't bother
if(GetCurrentUrl() == "")
return false;
if(node.tagName == "A")
childNodes = node.parentNode.childNodes;
else
childNodes = node.childNodes;
for(i = 0; i < childNodes.length; i++)
{
child = childNodes[i];
if(child.className == "TreeNodeImg")
img = child;
if(child.className == "Hidden" || child.className == "Visible")
{
div = child;
break;
}
}
if(lastNode != null)
lastNode.className = "UnselectedNode";
div.className = "Visible";
img.src = "Expanded.gif";
if(node.tagName == "A")
{
node.className = "SelectedNode";
lastNode = node;
}
if(div.innerHTML == "")
FillNode(div, false)
return true;
}
// Set the style of the specified node to "selected"
function SelectNode(node)
{
// If not valid, don't bother
if(GetCurrentUrl() == "")
return false;
if(lastNode != null)
lastNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastNode = node;
return true;
}
//============================================================================
// Ajax-related code used to fill the tree nodes on demand
function GetXmlHttpRequest()
{
var xmlHttp = null;
// If IE7, Mozilla, Safari, etc., use the native object.
// Otherwise, use the ActiveX control for IE5.x and IE6.
if(window.XMLHttpRequest)
xmlHttp = new XMLHttpRequest();
else
if(window.ActiveXObject)
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
return xmlHttp;
}
// Perform an AJAX-style request for the contents of a node and put the
// contents into the empty div.
function FillNode(div, expandChildren)
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
if(xmlHttp == null)
{
div.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
div.innerHTML = "Loading...";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "FillNode.aspx?Id=" + div.id + "&hash=" +
now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
div.innerHTML = xmlHttp.responseText;
if(expandChildren)
ExpandOrCollapseAll(true);
}
}
xmlHttp.send(null)
}
//============================================================================
// Resizing code
// Resize the tree div so that it fills the document body
function ResizeTree()
{
var y, newHeight;
if(self.innerHeight) // All but IE
y = self.innerHeight;
else // IE - Strict
if(document.documentElement && document.documentElement.clientHeight)
y = document.documentElement.clientHeight;
else // Everything else
if(document.body)
y = document.body.clientHeight;
newHeight = y - parseInt(divNavOpts.style.height, 10) - 6;
if(newHeight < 50)
newHeight = 50;
divTree.style.height = newHeight;
newHeight = y - parseInt(divSearchOpts.style.height, 10) - 6;
if(newHeight < 100)
newHeight = 100;
divSearchResults.style.height = newHeight;
newHeight = y - parseInt(divIndexOpts.style.height, 10) - 6;
if(newHeight < 25)
newHeight = 25;
divIndexResults.style.height = newHeight;
// Resize the content div
ResizeContent();
}
// Resize the content div
function ResizeContent()
{
if(isIE)
maxWidth = docBody.clientWidth;
else
maxWidth = docBody.clientWidth - 4;
topicContent.style.width = maxWidth - (divSizer.offsetLeft +
divSizer.offsetWidth);
maxWidth -= minWidth;
}
// This is called to prepare for dragging the sizer div
function OnMouseDown(event)
{
var x;
// Make sure the splitter is at the top of the z-index
divSizer.style.zIndex = 5000;
// The content is in an IFRAME which steals mouse events so
// hide it while resizing.
topicContent.style.display = "none";
if(isIE)
x = window.event.clientX + document.documentElement.scrollLeft +
document.body.scrollLeft;
else
x = event.clientX + window.scrollX;
// Save starting offset
offset = parseInt(divSizer.style.left, 10);
if(isNaN(offset))
offset = 0;
offset -= x;
if(isIE)
{
document.attachEvent("onmousemove", OnMouseMove);
document.attachEvent("onmouseup", OnMouseUp);
window.event.cancelBubble = true;
window.event.returnValue = false;
}
else
{
document.addEventListener("mousemove", OnMouseMove, true);
document.addEventListener("mouseup", OnMouseUp, true);
event.preventDefault();
}
}
// Resize the TOC and content divs as the sizer is dragged
function OnMouseMove(event)
{
var x, pos;
// Get cursor position with respect to the page
if(isIE)
x = window.event.clientX + document.documentElement.scrollLeft +
document.body.scrollLeft;
else
x = event.clientX + window.scrollX;
left = offset + x;
// Adjusts the width of the TOC divs
pos = (event.clientX > maxWidth) ? maxWidth :
(event.clientX < minWidth) ? minWidth : event.clientX;
divTOC.style.width = divSearchResults.style.width =
divIndexResults.style.width = divTree.style.width = pos;
if(!isIE)
pos -= 8;
divNavOpts.style.width = divSearchOpts.style.width =
divIndexOpts.style.width = pos;
// Resize the content div to fit in the remaining space
ResizeContent();
}
// Finish the drag operation when the mouse button is released
function OnMouseUp(event)
{
if(isIE)
{
document.detachEvent("onmousemove", OnMouseMove);
document.detachEvent("onmouseup", OnMouseUp);
}
else
{
document.removeEventListener("mousemove", OnMouseMove, true);
document.removeEventListener("mouseup", OnMouseUp, true);
}
// Show the content div again
topicContent.style.display = "inline";
}
//============================================================================
// Search code
function ShowHideSearch(show)
{
if(show)
{
divNavOpts.style.display = divTree.style.display = "none";
divSearchOpts.style.display = divSearchResults.style.display = "";
}
else
{
divSearchOpts.style.display = divSearchResults.style.display = "none";
divNavOpts.style.display = divTree.style.display = "";
}
}
// When enter is hit in the search text box, do the search
function OnSearchTextKeyPress(evt)
{
if(evt.keyCode == 13)
{
PerformSearch();
return false;
}
return true;
}
// Perform a keyword search
function PerformSearch()
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
if(xmlHttp == null)
{
divSearchResults.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
divSearchResults.innerHTML = "<span class=\"PaddedText\">Searching...</span>";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "SearchHelp.aspx?Keywords=" + txtSearchText.value +
"&SortByTitle=" + (chkSortByTitle.checked ? "true" : "false") +
"&hash=" + now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
divSearchResults.innerHTML = xmlHttp.responseText;
lastSearchNode = divSearchResults.childNodes[0].childNodes[1];
if(lastSearchNode != null)
{
if(lastSearchNode.tagName != "A")
lastSearchNode = lastSearchNode.nextSibling;
SelectSearchNode(lastSearchNode);
topicContent.src = lastSearchNode.href;
}
}
}
xmlHttp.send(null)
}
// Set the style of the specified search result node to "selected"
function SelectSearchNode(node)
{
if(lastSearchNode != null)
lastSearchNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastSearchNode = node;
return true;
}
//============================================================================
// KeyWordIndex code
function ShowHideIndex(show)
{
if(show)
{
PopulateIndex(currentIndexPage);
divNavOpts.style.display = divTree.style.display = "none";
divIndexOpts.style.display = divIndexResults.style.display = "";
}
else
{
divIndexOpts.style.display = divIndexResults.style.display = "none";
divNavOpts.style.display = divTree.style.display = "";
}
}
// Populate keyword index
function PopulateIndex(startIndex)
{
var xmlHttp = GetXmlHttpRequest(), now = new Date();
var firstNode;
if(xmlHttp == null)
{
divIndexResults.innerHTML = "<b>XML HTTP request not supported!</b>";
return;
}
divIndexResults.innerHTML = "<span class=\"PaddedText\">Loading " +
"keyword index...</span>";
// Add a unique hash to ensure it doesn't use cached results
xmlHttp.open("GET", "LoadIndexKeywords.aspx?StartIndex=" + startIndex +
"&hash=" + now.getTime(), true);
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
divIndexResults.innerHTML = xmlHttp.responseText;
if(startIndex > 0)
{
firstNode = divIndexResults.childNodes[1];
if(firstNode != null && !firstNode.innerHTML)
firstNode = divIndexResults.childNodes[2];
}
else
firstNode = divIndexResults.childNodes[0];
if(firstNode != null)
lastIndexNode = firstNode.childNodes[0];
if(lastIndexNode != null)
{
if(lastIndexNode.tagName != "A")
lastIndexNode = lastIndexNode.nextSibling;
SelectIndexNode(lastIndexNode);
topicContent.src = lastIndexNode.href;
}
currentIndexPage = startIndex;
}
}
xmlHttp.send(null)
}
// Set the style of the specified keyword index node to "selected"
function SelectIndexNode(node)
{
if(lastIndexNode != null)
lastIndexNode.className = "UnselectedNode";
node.className = "SelectedNode";
lastIndexNode = node;
return true;
}
// Changes the current page with keyword index forward or backward
function ChangeIndexPage(direction)
{
PopulateIndex(currentIndexPage + direction);
return false;
}
|
JavaScript
|
//=============================================================================
// System : Color Syntax Highlighter
// File : Highlight.js
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 11/13/2007
// Note : Copyright 2006, Eric Woodruff, All rights reserved
//
// This contains the script to expand and collapse the regions in the
// syntax highlighted code.
//
//=============================================================================
// Expand/collapse a region
function HighlightExpandCollapse(showId, hideId)
{
var showSpan = document.getElementById(showId),
hideSpan = document.getElementById(hideId);
showSpan.style.display = "inline";
hideSpan.style.display = "none";
}
// Copy the code if Enter or Space is hit with the image focused
function CopyColorizedCodeCheckKey(titleDiv, eventObj)
{
if(eventObj != undefined && (eventObj.keyCode == 13 ||
eventObj.keyCode == 32))
CopyColorizedCode(titleDiv);
}
// Change the icon as the mouse moves in and out of the Copy Code link
// There should be an image with the same name but an "_h" suffix just
// before the extension.
function CopyCodeChangeIcon(linkSpan)
{
var image = linkSpan.firstChild.src;
var pos = image.lastIndexOf(".");
if(linkSpan.className == "highlight-copycode")
{
linkSpan.className = "highlight-copycode_h";
linkSpan.firstChild.src = image.substr(0, pos) + "_h" +
image.substr(pos);
}
else
{
linkSpan.className = "highlight-copycode";
linkSpan.firstChild.src = image.substr(0, pos - 2) + image.substr(pos);
}
}
// Copy the code from a colorized code block to the clipboard.
function CopyColorizedCode(titleDiv)
{
var preTag, idx, line, block, htmlLines, lines, codeText, hasLineNos,
hasRegions, clip, trans, copyObject, clipID;
var reLineNo = /^\s*\d{1,4}/;
var reRegion = /^\s*\d{1,4}\+.*?\d{1,4}-/;
var reRegionText = /^\+.*?\-/;
// Find the <pre> tag containing the code. It should be in the next
// element or one of its children.
block = titleDiv.nextSibling;
while(block.nodeName == "#text")
block = block.nextSibling;
while(block.tagName != "PRE")
{
block = block.firstChild;
while(block.nodeName == "#text")
block = block.nextSibling;
}
if(block.innerText != undefined)
codeText = block.innerText;
else
codeText = block.textContent;
hasLineNos = block.innerHTML.indexOf("highlight-lineno");
hasRegions = block.innerHTML.indexOf("highlight-collapsebox");
htmlLines = block.innerHTML.split("\n");
lines = codeText.split("\n");
// Remove the line numbering and collapsible regions if present
if(hasLineNos != -1 || hasRegions != -1)
{
codeText = "";
for(idx = 0; idx < lines.length; idx++)
{
line = lines[idx];
if(hasRegions && reRegion.test(line))
line = line.replace(reRegion, "");
else
{
line = line.replace(reLineNo, "");
// Lines in expanded blocks have an extra space
if(htmlLines[idx].indexOf("highlight-expanded") != -1 ||
htmlLines[idx].indexOf("highlight-endblock") != -1)
line = line.substr(1);
}
if(hasRegions && reRegionText.test(line))
line = line.replace(reRegionText, "");
codeText += line;
// Not all browsers keep the line feed when split
if(line[line.length - 1] != "\n")
codeText += "\n";
}
}
// IE or FireFox/Netscape?
if(window.clipboardData)
window.clipboardData.setData("Text", codeText);
else
if(window.netscape)
{
// Give unrestricted access to browser APIs using XPConnect
try
{
netscape.security.PrivilegeManager.enablePrivilege(
"UniversalXPConnect");
}
catch(e)
{
alert("Universal Connect was refused, cannot copy to " +
"clipboard. Go to about:config and set " +
"signed.applets.codebase_principal_support to true to " +
"enable clipboard support.");
return;
}
// Creates an instance of nsIClipboard
clip = Components.classes[
"@mozilla.org/widget/clipboard;1"].createInstance(
Components.interfaces.nsIClipboard);
// Creates an instance of nsITransferable
if(clip)
trans = Components.classes[
"@mozilla.org/widget/transferable;1"].createInstance(
Components.interfaces.nsITransferable);
if(!trans)
{
alert("Copy to Clipboard is not supported by this browser");
return;
}
// Register the data flavor
trans.addDataFlavor("text/unicode");
// Create object to hold the data
copyObject = new Object();
// Creates an instance of nsISupportsString
copyObject = Components.classes[
"@mozilla.org/supports-string;1"].createInstance(
Components.interfaces.nsISupportsString);
// Assign the data to be copied
copyObject.data = codeText;
// Add data objects to transferable
trans.setTransferData("text/unicode", copyObject,
codeText.length * 2);
clipID = Components.interfaces.nsIClipboard;
if(!clipID)
{
alert("Copy to Clipboard is not supported by this browser");
return;
}
// Transfer the data to the clipboard
clip.setData(trans, null, clipID.kGlobalClipboard);
}
else
alert("Copy to Clipboard is not supported by this browser");
}
|
JavaScript
|
//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated. All rights reserved.
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
function ControlVersion()
{
var version;
var axo;
var e;
// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
try {
// version will be set for 7.X or greater players
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
version = axo.GetVariable("$version");
} catch (e) {
}
if (!version)
{
try {
// version will be set for 6.X players only
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
// installed player is some revision of 6.0
// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
// so we have to be careful.
// default to the first public version
version = "WIN 6,0,21,0";
// throws if AllowScripAccess does not exist (introduced in 6.0r47)
axo.AllowScriptAccess = "always";
// safe to call for 6.0r47 or greater
version = axo.GetVariable("$version");
} catch (e) {
}
}
if (!version)
{
try {
// version will be set for 4.X or 5.X player
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
version = axo.GetVariable("$version");
} catch (e) {
}
}
if (!version)
{
try {
// version will be set for 3.X player
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
version = "WIN 3,0,18,0";
} catch (e) {
}
}
if (!version)
{
try {
// version will be set for 2.X player
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
version = "WIN 2,0,0,11";
} catch (e) {
version = -1;
}
}
return version;
}
// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
// NS/Opera version >= 3 check for Flash plugin in plugin array
var flashVer = -1;
if (navigator.plugins != null && navigator.plugins.length > 0) {
if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
var descArray = flashDescription.split(" ");
var tempArrayMajor = descArray[2].split(".");
var versionMajor = tempArrayMajor[0];
var versionMinor = tempArrayMajor[1];
var versionRevision = descArray[3];
if (versionRevision == "") {
versionRevision = descArray[4];
}
if (versionRevision[0] == "d") {
versionRevision = versionRevision.substring(1);
} else if (versionRevision[0] == "r") {
versionRevision = versionRevision.substring(1);
if (versionRevision.indexOf("d") > 0) {
versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
}
}
var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
}
}
// MSN/WebTV 2.6 supports Flash 4
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
// WebTV 2.5 supports Flash 3
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
// older WebTV supports Flash 2
else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
else if ( isIE && isWin && !isOpera ) {
flashVer = ControlVersion();
}
return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
versionStr = GetSwfVer();
if (versionStr == -1 ) {
return false;
} else if (versionStr != 0) {
if(isIE && isWin && !isOpera) {
// Given "WIN 2,0,0,11"
tempArray = versionStr.split(" "); // ["WIN", "2,0,0,11"]
tempString = tempArray[1]; // "2,0,0,11"
versionArray = tempString.split(","); // ['2', '0', '0', '11']
} else {
versionArray = versionStr.split(".");
}
var versionMajor = versionArray[0];
var versionMinor = versionArray[1];
var versionRevision = versionArray[2];
// is the major.revision >= requested major.revision AND the minor version >= requested minor
if (versionMajor > parseFloat(reqMajorVer)) {
return true;
} else if (versionMajor == parseFloat(reqMajorVer)) {
if (versionMinor > parseFloat(reqMinorVer))
return true;
else if (versionMinor == parseFloat(reqMinorVer)) {
if (versionRevision >= parseFloat(reqRevision))
return true;
}
}
return false;
}
}
function AC_AddExtension(src, ext)
{
if (src.indexOf('?') != -1)
return src.replace(/\?/, ext+'?');
else
return src + ext;
}
function AC_Generateobj(objAttrs, params, embedAttrs)
{
var str = '';
if (isIE && isWin && !isOpera)
{
str += '<object ';
for (var i in objAttrs)
{
str += i + '="' + objAttrs[i] + '" ';
}
str += '>';
for (var i in params)
{
str += '<param name="' + i + '" value="' + params[i] + '" /> ';
}
str += '</object>';
}
else
{
str += '<embed ';
for (var i in embedAttrs)
{
str += i + '="' + embedAttrs[i] + '" ';
}
str += '> </embed>';
}
document.write(str);
}
function AC_FL_RunContent(){
var ret =
AC_GetArgs
( arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
, "application/x-shockwave-flash"
);
AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_SW_RunContent(){
var ret =
AC_GetArgs
( arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
, null
);
AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
var ret = new Object();
ret.embedAttrs = new Object();
ret.params = new Object();
ret.objAttrs = new Object();
for (var i=0; i < args.length; i=i+2){
var currArg = args[i].toLowerCase();
switch (currArg){
case "classid":
break;
case "pluginspage":
ret.embedAttrs[args[i]] = args[i+1];
break;
case "src":
case "movie":
args[i+1] = AC_AddExtension(args[i+1], ext);
ret.embedAttrs["src"] = args[i+1];
ret.params[srcParamName] = args[i+1];
break;
case "onafterupdate":
case "onbeforeupdate":
case "onblur":
case "oncellchange":
case "onclick":
case "ondblclick":
case "ondrag":
case "ondragend":
case "ondragenter":
case "ondragleave":
case "ondragover":
case "ondrop":
case "onfinish":
case "onfocus":
case "onhelp":
case "onmousedown":
case "onmouseup":
case "onmouseover":
case "onmousemove":
case "onmouseout":
case "onkeypress":
case "onkeydown":
case "onkeyup":
case "onload":
case "onlosecapture":
case "onpropertychange":
case "onreadystatechange":
case "onrowsdelete":
case "onrowenter":
case "onrowexit":
case "onrowsinserted":
case "onstart":
case "onscroll":
case "onbeforeeditfocus":
case "onactivate":
case "onbeforedeactivate":
case "ondeactivate":
case "type":
case "codebase":
case "id":
ret.objAttrs[args[i]] = args[i+1];
break;
case "width":
case "height":
case "align":
case "vspace":
case "hspace":
case "class":
case "title":
case "accesskey":
case "name":
case "tabindex":
ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
break;
default:
ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
}
}
ret.objAttrs["classid"] = classid;
if (mimeType) ret.embedAttrs["type"] = mimeType;
return ret;
}
|
JavaScript
|
'use strict';
var EditorState = {
CLEAN:0, // NO CHANGES
DIRTY:1, // UNSAVED CHANGES
SAVE:2, // SAVE IN PROGRESS
LOAD:3, // LOADING
READONLY:4
};
google.load('picker', '1');
//gapi.load('drive-share');
angular.module('app', ['app.filters', 'app.services', 'app.directives'])
.constant('saveInterval', 15000)
.constant('appId', [[YOUR_CLIENT_ID]])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/edit/:id', {templateUrl:'Content/partials/editor.html', controller:EditorCtrl})
.otherwise({redirectTo:'/edit/'});
}]);
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
var directive = {};
var service = { value: {} };
var DEPENDENCIES = {
'angular.js': 'http://code.angularjs.org/angular-' + angular.version.full + '.min.js',
'angular-resource.js': 'http://code.angularjs.org/angular-resource-' + angular.version.full + '.min.js',
'angular-sanitize.js': 'http://code.angularjs.org/angular-sanitize-' + angular.version.full + '.min.js',
'angular-cookies.js': 'http://code.angularjs.org/angular-cookies-' + angular.version.full + '.min.js'
};
function escape(text) {
return text.
replace(/\&/g, '&').
replace(/\</g, '<').
replace(/\>/g, '>').
replace(/"/g, '"');
}
/**
* http://stackoverflow.com/questions/451486/pre-tag-loses-line-breaks-when-setting-innerhtml-in-ie
* http://stackoverflow.com/questions/195363/inserting-a-newline-into-a-pre-tag-ie-javascript
*/
function setHtmlIe8SafeWay(element, html) {
var newElement = angular.element('<pre>' + html + '</pre>');
element.html('');
element.append(newElement.contents());
return element;
}
directive.jsFiddle = function(getEmbeddedTemplate, escape, script) {
return {
terminal: true,
link: function(scope, element, attr) {
var name = '',
stylesheet = '<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">\n',
fields = {
html: '',
css: '',
js: ''
};
angular.forEach(attr.jsFiddle.split(' '), function(file, index) {
var fileType = file.split('.')[1];
if (fileType == 'html') {
if (index == 0) {
fields[fileType] +=
'<div ng-app' + (attr.module ? '="' + attr.module + '"' : '') + '>\n' +
getEmbeddedTemplate(file, 2);
} else {
fields[fileType] += '\n\n\n <!-- CACHE FILE: ' + file + ' -->\n' +
' <script type="text/ng-template" id="' + file + '">\n' +
getEmbeddedTemplate(file, 4) +
' </script>\n';
}
} else {
fields[fileType] += getEmbeddedTemplate(file) + '\n';
}
});
fields.html += '</div>\n';
setHtmlIe8SafeWay(element,
'<form class="jsfiddle" method="post" action="http://jsfiddle.net/api/post/library/pure/" target="_blank">' +
hiddenField('title', 'AngularJS Example: ' + name) +
hiddenField('css', '</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> \n' +
stylesheet +
script.angular +
(attr.resource ? script.resource : '') +
'<style>\n' +
fields.css) +
hiddenField('html', fields.html) +
hiddenField('js', fields.js) +
'<button class="btn btn-primary"><i class="icon-white icon-pencil"></i> Edit Me</button>' +
'</form>');
function hiddenField(name, value) {
return '<input type="hidden" name="' + name + '" value="' + escape(value) + '">';
}
}
}
};
directive.code = function() {
return {restrict: 'E', terminal: true};
};
directive.prettyprint = ['reindentCode', function(reindentCode) {
return {
restrict: 'C',
terminal: true,
compile: function(element) {
element.html(window.prettyPrintOne(reindentCode(element.html()), undefined, true));
}
};
}];
directive.ngSetText = ['getEmbeddedTemplate', function(getEmbeddedTemplate) {
return {
restrict: 'CA',
priority: 10,
compile: function(element, attr) {
setHtmlIe8SafeWay(element, escape(getEmbeddedTemplate(attr.ngSetText)));
}
}
}]
directive.ngHtmlWrap = ['reindentCode', 'templateMerge', function(reindentCode, templateMerge) {
return {
compile: function(element, attr) {
var properties = {
head: '',
module: '',
body: element.text()
},
html = "<!doctype html>\n<html ng-app{{module}}>\n <head>\n{{head:4}} </head>\n <body>\n{{body:4}} </body>\n</html>";
angular.forEach((attr.ngHtmlWrap || '').split(' '), function(dep) {
if (!dep) return;
dep = DEPENDENCIES[dep] || dep;
var ext = dep.split(/\./).pop();
if (ext == 'css') {
properties.head += '<link rel="stylesheet" href="' + dep + '" type="text/css">\n';
} else if(ext == 'js') {
properties.head += '<script src="' + dep + '"></script>\n';
} else {
properties.module = '="' + dep + '"';
}
});
setHtmlIe8SafeWay(element, escape(templateMerge(html, properties)));
}
}
}];
directive.ngSetHtml = ['getEmbeddedTemplate', function(getEmbeddedTemplate) {
return {
restrict: 'CA',
priority: 10,
compile: function(element, attr) {
setHtmlIe8SafeWay(element, getEmbeddedTemplate(attr.ngSetHtml));
}
}
}];
directive.ngEvalJavascript = ['getEmbeddedTemplate', function(getEmbeddedTemplate) {
return {
compile: function (element, attr) {
var script = getEmbeddedTemplate(attr.ngEvalJavascript);
try {
if (window.execScript) { // IE
window.execScript(script || '""'); // IE complains when evaling empty string
} else {
window.eval(script);
}
} catch (e) {
if (window.console) {
window.console.log(script, '\n', e);
} else {
window.alert(e);
}
}
}
};
}];
directive.ngEmbedApp = ['$templateCache', '$browser', '$rootScope', '$location', function($templateCache, $browser, docsRootScope, $location) {
return {
terminal: true,
link: function(scope, element, attrs) {
var modules = [];
modules.push(['$provide', function($provide) {
$provide.value('$templateCache', $templateCache);
$provide.value('$anchorScroll', angular.noop);
$provide.value('$browser', $browser);
$provide.provider('$location', function() {
this.$get = ['$rootScope', function($rootScope) {
docsRootScope.$on('$locationChangeSuccess', function(event, oldUrl, newUrl) {
$rootScope.$broadcast('$locationChangeSuccess', oldUrl, newUrl);
});
return $location;
}];
this.html5Mode = angular.noop;
});
$provide.decorator('$timeout', ['$rootScope', '$delegate', function($rootScope, $delegate) {
return angular.extend(function(fn, delay) {
if (delay && delay > 50) {
return setTimeout(function() {
$rootScope.$apply(fn);
}, delay);
} else {
return $delegate.apply(this, arguments);
}
}, $delegate);
}]);
$provide.decorator('$rootScope', ['$delegate', function(embedRootScope) {
docsRootScope.$watch(function() {
embedRootScope.$digest();
});
return embedRootScope;
}]);
}]);
if (attrs.ngEmbedApp) modules.push(attrs.ngEmbedApp);
element.bind('click', function(event) {
if (event.target.attributes.getNamedItem('ng-click')) {
event.preventDefault();
}
});
angular.bootstrap(element, modules);
}
};
}];
service.reindentCode = function() {
return function (text, spaces) {
if (!text) return text;
var lines = text.split(/\r?\n/);
var prefix = ' '.substr(0, spaces || 0);
var i;
// remove any leading blank lines
while (lines.length && lines[0].match(/^\s*$/)) lines.shift();
// remove any trailing blank lines
while (lines.length && lines[lines.length - 1].match(/^\s*$/)) lines.pop();
var minIndent = 999;
for (i = 0; i < lines.length; i++) {
var line = lines[0];
var reindentCode = line.match(/^\s*/)[0];
if (reindentCode !== line && reindentCode.length < minIndent) {
minIndent = reindentCode.length;
}
}
for (i = 0; i < lines.length; i++) {
lines[i] = prefix + lines[i].substring(minIndent);
}
lines.push('');
return lines.join('\n');
}
};
service.templateMerge = ['reindentCode', function(indentCode) {
return function(template, properties) {
return template.replace(/\{\{(\w+)(?:\:(\d+))?\}\}/g, function(_, key, indent) {
var value = properties[key];
if (indent) {
value = indentCode(value, indent);
}
return value == undefined ? '' : value;
});
};
}];
service.getEmbeddedTemplate = ['reindentCode', function(reindentCode) {
return function (id) {
var element = document.getElementById(id);
if (!element) {
return null;
}
return reindentCode(angular.element(element).html(), 0);
}
}];
angular.module('bootstrapPrettify', []).directive(directive).factory(service);
// Copyright (C) 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview
* some functions for browser-side pretty printing of code contained in html.
*
* <p>
* For a fairly comprehensive set of languages see the
* <a href="http://google-code-prettify.googlecode.com/svn/trunk/README.html#langs">README</a>
* file that came with this source. At a minimum, the lexer should work on a
* number of languages including C and friends, Java, Python, Bash, SQL, HTML,
* XML, CSS, Javascript, and Makefiles. It works passably on Ruby, PHP and Awk
* and a subset of Perl, but, because of commenting conventions, doesn't work on
* Smalltalk, Lisp-like, or CAML-like languages without an explicit lang class.
* <p>
* Usage: <ol>
* <li> include this source file in an html page via
* {@code <script type="text/javascript" src="/path/to/prettify.js"></script>}
* <li> define style rules. See the example page for examples.
* <li> mark the {@code <pre>} and {@code <code>} tags in your source with
* {@code class=prettyprint.}
* You can also use the (html deprecated) {@code <xmp>} tag, but the pretty
* printer needs to do more substantial DOM manipulations to support that, so
* some css styles may not be preserved.
* </ol>
* That's it. I wanted to keep the API as simple as possible, so there's no
* need to specify which language the code is in, but if you wish, you can add
* another class to the {@code <pre>} or {@code <code>} element to specify the
* language, as in {@code <pre class="prettyprint lang-java">}. Any class that
* starts with "lang-" followed by a file extension, specifies the file type.
* See the "lang-*.js" files in this directory for code that implements
* per-language file handlers.
* <p>
* Change log:<br>
* cbeust, 2006/08/22
* <blockquote>
* Java annotations (start with "@") are now captured as literals ("lit")
* </blockquote>
* @requires console
*/
// JSLint declarations
/*global console, document, navigator, setTimeout, window, define */
/**
* Split {@code prettyPrint} into multiple timeouts so as not to interfere with
* UI events.
* If set to {@code false}, {@code prettyPrint()} is synchronous.
*/
window['PR_SHOULD_USE_CONTINUATION'] = true;
/**
* Find all the {@code <pre>} and {@code <code>} tags in the DOM with
* {@code class=prettyprint} and prettify them.
*
* @param {Function?} opt_whenDone if specified, called when the last entry
* has been finished.
*/
var prettyPrintOne;
/**
* Pretty print a chunk of code.
*
* @param {string} sourceCodeHtml code as html
* @return {string} code as html, but prettier
*/
var prettyPrint;
(function () {
var win = window;
// Keyword lists for various languages.
// We use things that coerce to strings to make them compact when minified
// and to defeat aggressive optimizers that fold large string constants.
var FLOW_CONTROL_KEYWORDS = ["break,continue,do,else,for,if,return,while"];
var C_KEYWORDS = [FLOW_CONTROL_KEYWORDS,"auto,case,char,const,default," +
"double,enum,extern,float,goto,int,long,register,short,signed,sizeof," +
"static,struct,switch,typedef,union,unsigned,void,volatile"];
var COMMON_KEYWORDS = [C_KEYWORDS,"catch,class,delete,false,import," +
"new,operator,private,protected,public,this,throw,true,try,typeof"];
var CPP_KEYWORDS = [COMMON_KEYWORDS,"alignof,align_union,asm,axiom,bool," +
"concept,concept_map,const_cast,constexpr,decltype," +
"dynamic_cast,explicit,export,friend,inline,late_check," +
"mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast," +
"template,typeid,typename,using,virtual,where"];
var JAVA_KEYWORDS = [COMMON_KEYWORDS,
"abstract,boolean,byte,extends,final,finally,implements,import," +
"instanceof,null,native,package,strictfp,super,synchronized,throws," +
"transient"];
var CSHARP_KEYWORDS = [JAVA_KEYWORDS,
"as,base,by,checked,decimal,delegate,descending,dynamic,event," +
"fixed,foreach,from,group,implicit,in,interface,internal,into,is,let," +
"lock,object,out,override,orderby,params,partial,readonly,ref,sbyte," +
"sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort," +
"var,virtual,where"];
var COFFEE_KEYWORDS = "all,and,by,catch,class,else,extends,false,finally," +
"for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then," +
"throw,true,try,unless,until,when,while,yes";
var JSCRIPT_KEYWORDS = [COMMON_KEYWORDS,
"debugger,eval,export,function,get,null,set,undefined,var,with," +
"Infinity,NaN"];
var PERL_KEYWORDS = "caller,delete,die,do,dump,elsif,eval,exit,foreach,for," +
"goto,if,import,last,local,my,next,no,our,print,package,redo,require," +
"sub,undef,unless,until,use,wantarray,while,BEGIN,END";
var PYTHON_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "and,as,assert,class,def,del," +
"elif,except,exec,finally,from,global,import,in,is,lambda," +
"nonlocal,not,or,pass,print,raise,try,with,yield," +
"False,True,None"];
var RUBY_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "alias,and,begin,case,class," +
"def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo," +
"rescue,retry,self,super,then,true,undef,unless,until,when,yield," +
"BEGIN,END"];
var SH_KEYWORDS = [FLOW_CONTROL_KEYWORDS, "case,done,elif,esac,eval,fi," +
"function,in,local,set,then,until"];
var ALL_KEYWORDS = [
CPP_KEYWORDS, CSHARP_KEYWORDS, JSCRIPT_KEYWORDS, PERL_KEYWORDS +
PYTHON_KEYWORDS, RUBY_KEYWORDS, SH_KEYWORDS];
var C_TYPES = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)\b/;
// token style names. correspond to css classes
/**
* token style for a string literal
* @const
*/
var PR_STRING = 'str';
/**
* token style for a keyword
* @const
*/
var PR_KEYWORD = 'kwd';
/**
* token style for a comment
* @const
*/
var PR_COMMENT = 'com';
/**
* token style for a type
* @const
*/
var PR_TYPE = 'typ';
/**
* token style for a literal value. e.g. 1, null, true.
* @const
*/
var PR_LITERAL = 'lit';
/**
* token style for a punctuation string.
* @const
*/
var PR_PUNCTUATION = 'pun';
/**
* token style for plain text.
* @const
*/
var PR_PLAIN = 'pln';
/**
* token style for an sgml tag.
* @const
*/
var PR_TAG = 'tag';
/**
* token style for a markup declaration such as a DOCTYPE.
* @const
*/
var PR_DECLARATION = 'dec';
/**
* token style for embedded source.
* @const
*/
var PR_SOURCE = 'src';
/**
* token style for an sgml attribute name.
* @const
*/
var PR_ATTRIB_NAME = 'atn';
/**
* token style for an sgml attribute value.
* @const
*/
var PR_ATTRIB_VALUE = 'atv';
/**
* A class that indicates a section of markup that is not code, e.g. to allow
* embedding of line numbers within code listings.
* @const
*/
var PR_NOCODE = 'nocode';
/**
* A set of tokens that can precede a regular expression literal in
* javascript
* http://web.archive.org/web/20070717142515/http://www.mozilla.org/js/language/js20/rationale/syntax.html
* has the full list, but I've removed ones that might be problematic when
* seen in languages that don't support regular expression literals.
*
* <p>Specifically, I've removed any keywords that can't precede a regexp
* literal in a syntactically legal javascript program, and I've removed the
* "in" keyword since it's not a keyword in many languages, and might be used
* as a count of inches.
*
* <p>The link above does not accurately describe EcmaScript rules since
* it fails to distinguish between (a=++/b/i) and (a++/b/i) but it works
* very well in practice.
*
* @private
* @const
*/
var REGEXP_PRECEDER_PATTERN = '(?:^^\\.?|[+-]|[!=]=?=?|\\#|%=?|&&?=?|\\(|\\*=?|[+\\-]=|->|\\/=?|::?|<<?=?|>>?>?=?|,|;|\\?|@|\\[|~|{|\\^\\^?=?|\\|\\|?=?|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*';
// CAVEAT: this does not properly handle the case where a regular
// expression immediately follows another since a regular expression may
// have flags for case-sensitivity and the like. Having regexp tokens
// adjacent is not valid in any language I'm aware of, so I'm punting.
// TODO: maybe style special characters inside a regexp as punctuation.
/**
* Given a group of {@link RegExp}s, returns a {@code RegExp} that globally
* matches the union of the sets of strings matched by the input RegExp.
* Since it matches globally, if the input strings have a start-of-input
* anchor (/^.../), it is ignored for the purposes of unioning.
* @param {Array.<RegExp>} regexs non multiline, non-global regexs.
* @return {RegExp} a global regex.
*/
function combinePrefixPatterns(regexs) {
var capturedGroupIndex = 0;
var needToFoldCase = false;
var ignoreCase = false;
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.ignoreCase) {
ignoreCase = true;
} else if (/[a-z]/i.test(regex.source.replace(
/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, ''))) {
needToFoldCase = true;
ignoreCase = false;
break;
}
}
var escapeCharToCodeUnit = {
'b': 8,
't': 9,
'n': 0xa,
'v': 0xb,
'f': 0xc,
'r': 0xd
};
function decodeEscape(charsetPart) {
var cc0 = charsetPart.charCodeAt(0);
if (cc0 !== 92 /* \\ */) {
return cc0;
}
var c1 = charsetPart.charAt(1);
cc0 = escapeCharToCodeUnit[c1];
if (cc0) {
return cc0;
} else if ('0' <= c1 && c1 <= '7') {
return parseInt(charsetPart.substring(1), 8);
} else if (c1 === 'u' || c1 === 'x') {
return parseInt(charsetPart.substring(2), 16);
} else {
return charsetPart.charCodeAt(1);
}
}
function encodeEscape(charCode) {
if (charCode < 0x20) {
return (charCode < 0x10 ? '\\x0' : '\\x') + charCode.toString(16);
}
var ch = String.fromCharCode(charCode);
return (ch === '\\' || ch === '-' || ch === ']' || ch === '^')
? "\\" + ch : ch;
}
function caseFoldCharset(charSet) {
var charsetParts = charSet.substring(1, charSet.length - 1).match(
new RegExp(
'\\\\u[0-9A-Fa-f]{4}'
+ '|\\\\x[0-9A-Fa-f]{2}'
+ '|\\\\[0-3][0-7]{0,2}'
+ '|\\\\[0-7]{1,2}'
+ '|\\\\[\\s\\S]'
+ '|-'
+ '|[^-\\\\]',
'g'));
var ranges = [];
var inverse = charsetParts[0] === '^';
var out = ['['];
if (inverse) { out.push('^'); }
for (var i = inverse ? 1 : 0, n = charsetParts.length; i < n; ++i) {
var p = charsetParts[i];
if (/\\[bdsw]/i.test(p)) { // Don't muck with named groups.
out.push(p);
} else {
var start = decodeEscape(p);
var end;
if (i + 2 < n && '-' === charsetParts[i + 1]) {
end = decodeEscape(charsetParts[i + 2]);
i += 2;
} else {
end = start;
}
ranges.push([start, end]);
// If the range might intersect letters, then expand it.
// This case handling is too simplistic.
// It does not deal with non-latin case folding.
// It works for latin source code identifiers though.
if (!(end < 65 || start > 122)) {
if (!(end < 65 || start > 90)) {
ranges.push([Math.max(65, start) | 32, Math.min(end, 90) | 32]);
}
if (!(end < 97 || start > 122)) {
ranges.push([Math.max(97, start) & ~32, Math.min(end, 122) & ~32]);
}
}
}
}
// [[1, 10], [3, 4], [8, 12], [14, 14], [16, 16], [17, 17]]
// -> [[1, 12], [14, 14], [16, 17]]
ranges.sort(function (a, b) { return (a[0] - b[0]) || (b[1] - a[1]); });
var consolidatedRanges = [];
var lastRange = [];
for (var i = 0; i < ranges.length; ++i) {
var range = ranges[i];
if (range[0] <= lastRange[1] + 1) {
lastRange[1] = Math.max(lastRange[1], range[1]);
} else {
consolidatedRanges.push(lastRange = range);
}
}
for (var i = 0; i < consolidatedRanges.length; ++i) {
var range = consolidatedRanges[i];
out.push(encodeEscape(range[0]));
if (range[1] > range[0]) {
if (range[1] + 1 > range[0]) { out.push('-'); }
out.push(encodeEscape(range[1]));
}
}
out.push(']');
return out.join('');
}
function allowAnywhereFoldCaseAndRenumberGroups(regex) {
// Split into character sets, escape sequences, punctuation strings
// like ('(', '(?:', ')', '^'), and runs of characters that do not
// include any of the above.
var parts = regex.source.match(
new RegExp(
'(?:'
+ '\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]' // a character set
+ '|\\\\u[A-Fa-f0-9]{4}' // a unicode escape
+ '|\\\\x[A-Fa-f0-9]{2}' // a hex escape
+ '|\\\\[0-9]+' // a back-reference or octal escape
+ '|\\\\[^ux0-9]' // other escape sequence
+ '|\\(\\?[:!=]' // start of a non-capturing group
+ '|[\\(\\)\\^]' // start/end of a group, or line start
+ '|[^\\x5B\\x5C\\(\\)\\^]+' // run of other characters
+ ')',
'g'));
var n = parts.length;
// Maps captured group numbers to the number they will occupy in
// the output or to -1 if that has not been determined, or to
// undefined if they need not be capturing in the output.
var capturedGroups = [];
// Walk over and identify back references to build the capturedGroups
// mapping.
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
// groups are 1-indexed, so max group index is count of '('
++groupIndex;
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue) {
if (decimalValue <= groupIndex) {
capturedGroups[decimalValue] = -1;
} else {
// Replace with an unambiguous escape sequence so that
// an octal escape sequence does not turn into a backreference
// to a capturing group from an earlier regex.
parts[i] = encodeEscape(decimalValue);
}
}
}
}
// Renumber groups and reduce capturing groups to non-capturing groups
// where possible.
for (var i = 1; i < capturedGroups.length; ++i) {
if (-1 === capturedGroups[i]) {
capturedGroups[i] = ++capturedGroupIndex;
}
}
for (var i = 0, groupIndex = 0; i < n; ++i) {
var p = parts[i];
if (p === '(') {
++groupIndex;
if (!capturedGroups[groupIndex]) {
parts[i] = '(?:';
}
} else if ('\\' === p.charAt(0)) {
var decimalValue = +p.substring(1);
if (decimalValue && decimalValue <= groupIndex) {
parts[i] = '\\' + capturedGroups[decimalValue];
}
}
}
// Remove any prefix anchors so that the output will match anywhere.
// ^^ really does mean an anchored match though.
for (var i = 0; i < n; ++i) {
if ('^' === parts[i] && '^' !== parts[i + 1]) { parts[i] = ''; }
}
// Expand letters to groups to handle mixing of case-sensitive and
// case-insensitive patterns if necessary.
if (regex.ignoreCase && needToFoldCase) {
for (var i = 0; i < n; ++i) {
var p = parts[i];
var ch0 = p.charAt(0);
if (p.length >= 2 && ch0 === '[') {
parts[i] = caseFoldCharset(p);
} else if (ch0 !== '\\') {
// TODO: handle letters in numeric escapes.
parts[i] = p.replace(
/[a-zA-Z]/g,
function (ch) {
var cc = ch.charCodeAt(0);
return '[' + String.fromCharCode(cc & ~32, cc | 32) + ']';
});
}
}
}
return parts.join('');
}
var rewritten = [];
for (var i = 0, n = regexs.length; i < n; ++i) {
var regex = regexs[i];
if (regex.global || regex.multiline) { throw new Error('' + regex); }
rewritten.push(
'(?:' + allowAnywhereFoldCaseAndRenumberGroups(regex) + ')');
}
return new RegExp(rewritten.join('|'), ignoreCase ? 'gi' : 'g');
}
/**
* Split markup into a string of source code and an array mapping ranges in
* that string to the text nodes in which they appear.
*
* <p>
* The HTML DOM structure:</p>
* <pre>
* (Element "p"
* (Element "b"
* (Text "print ")) ; #1
* (Text "'Hello '") ; #2
* (Element "br") ; #3
* (Text " + 'World';")) ; #4
* </pre>
* <p>
* corresponds to the HTML
* {@code <p><b>print </b>'Hello '<br> + 'World';</p>}.</p>
*
* <p>
* It will produce the output:</p>
* <pre>
* {
* sourceCode: "print 'Hello '\n + 'World';",
* // 1 2
* // 012345678901234 5678901234567
* spans: [0, #1, 6, #2, 14, #3, 15, #4]
* }
* </pre>
* <p>
* where #1 is a reference to the {@code "print "} text node above, and so
* on for the other text nodes.
* </p>
*
* <p>
* The {@code} spans array is an array of pairs. Even elements are the start
* indices of substrings, and odd elements are the text nodes (or BR elements)
* that contain the text for those substrings.
* Substrings continue until the next index or the end of the source.
* </p>
*
* @param {Node} node an HTML DOM subtree containing source-code.
* @param {boolean} isPreformatted true if white-space in text nodes should
* be considered significant.
* @return {Object} source code and the text nodes in which they occur.
*/
function extractSourceSpans(node, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var chunks = [];
var length = 0;
var spans = [];
var k = 0;
function walk(node) {
switch (node.nodeType) {
case 1: // Element
if (nocode.test(node.className)) { return; }
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
var nodeName = node.nodeName.toLowerCase();
if ('br' === nodeName || 'li' === nodeName) {
chunks[k] = '\n';
spans[k << 1] = length++;
spans[(k++ << 1) | 1] = node;
}
break;
case 3: case 4: // Text
var text = node.nodeValue;
if (text.length) {
if (!isPreformatted) {
text = text.replace(/[ \t\r\n]+/g, ' ');
} else {
text = text.replace(/\r\n?/g, '\n'); // Normalize newlines.
}
// TODO: handle tabs here?
chunks[k] = text;
spans[k << 1] = length;
length += text.length;
spans[(k++ << 1) | 1] = node;
}
break;
}
}
walk(node);
return {
sourceCode: chunks.join('').replace(/\n$/, ''),
spans: spans
};
}
/**
* Apply the given language handler to sourceCode and add the resulting
* decorations to out.
* @param {number} basePos the index of sourceCode within the chunk of source
* whose decorations are already present on out.
*/
function appendDecorations(basePos, sourceCode, langHandler, out) {
if (!sourceCode) { return; }
var job = {
sourceCode: sourceCode,
basePos: basePos
};
langHandler(job);
out.push.apply(out, job.decorations);
}
var notWs = /\S/;
/**
* Given an element, if it contains only one child element and any text nodes
* it contains contain only space characters, return the sole child element.
* Otherwise returns undefined.
* <p>
* This is meant to return the CODE element in {@code <pre><code ...>} when
* there is a single child element that contains all the non-space textual
* content, but not to return anything where there are multiple child elements
* as in {@code <pre><code>...</code><code>...</code></pre>} or when there
* is textual content.
*/
function childContentWrapper(element) {
var wrapper = undefined;
for (var c = element.firstChild; c; c = c.nextSibling) {
var type = c.nodeType;
wrapper = (type === 1) // Element Node
? (wrapper ? element : c)
: (type === 3) // Text Node
? (notWs.test(c.nodeValue) ? element : wrapper)
: wrapper;
}
return wrapper === element ? undefined : wrapper;
}
/** Given triples of [style, pattern, context] returns a lexing function,
* The lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
* where index_n is an index into the sourceCode, and style_n is a style
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
* all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form
* [style : string, pattern : RegExp, DEPRECATED, shortcut : string].
*
* Style is a style constant like PR_PLAIN, or can be a string of the
* form 'lang-FOO', where FOO is a language extension describing the
* language of the portion of the token in $1 after pattern executes.
* E.g., if style is 'lang-lisp', and group 1 contains the text
* '(hello (world))', then that portion of the token will be passed to the
* registered lisp handler for formatting.
* The text before and after group 1 will be restyled using this decorator
* so decorators should take care that this doesn't result in infinite
* recursion. For example, the HTML lexer rule for SCRIPT elements looks
* something like ['lang-js', /<[s]cript>(.+?)<\/script>/]. This may match
* '<script>foo()<\/script>', which would cause the current decorator to
* be called with '<script>' which would not match the same rule since
* group 1 must not be empty, so it would be instead styled as PR_TAG by
* the generic tag rule. The handler registered for the 'js' extension would
* then be called with 'foo()', and finally, the current decorator would
* be called with '<\/script>' which would not match the original rule and
* so the generic tag rule would identify it as a tag.
*
* Pattern must only match prefixes, and if it matches a prefix, then that
* match is considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token
* recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array} shortcutStylePatterns patterns that always start with
* a known character. Must have a shortcut string.
* @param {Array} fallthroughStylePatterns patterns that will be tried in
* order if the shortcut ones fail. May have shortcuts.
*
* @return {function (Object)} a
* function that takes source code and returns a list of decorations.
*/
function createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns) {
var shortcuts = {};
var tokenizer;
(function () {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
var allRegexs = [];
var regexKeys = {};
for (var i = 0, n = allPatterns.length; i < n; ++i) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for (var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
var regex = patternParts[1];
var k = '' + regex;
if (!regexKeys.hasOwnProperty(k)) {
allRegexs.push(regex);
regexKeys[k] = null;
}
}
allRegexs.push(/[\0-\uffff]/);
tokenizer = combinePrefixPatterns(allRegexs);
})();
var nPatterns = fallthroughStylePatterns.length;
/**
* Lexes job.sourceCode and produces an output array job.decorations of
* style classes preceded by the position at which they start in
* job.sourceCode in order.
*
* @param {Object} job an object like <pre>{
* sourceCode: {string} sourceText plain text,
* basePos: {int} position of job.sourceCode in the larger chunk of
* sourceCode.
* }</pre>
*/
var decorate = function (job) {
var sourceCode = job.sourceCode, basePos = job.basePos;
/** Even entries are positions in source in ascending order. Odd enties
* are style markers (e.g., PR_COMMENT) that run from that position until
* the end.
* @type {Array.<number|string>}
*/
var decorations = [basePos, PR_PLAIN];
var pos = 0; // index into sourceCode
var tokens = sourceCode.match(tokenizer) || [];
var styleCache = {};
for (var ti = 0, nTokens = tokens.length; ti < nTokens; ++ti) {
var token = tokens[ti];
var style = styleCache[token];
var match = void 0;
var isEmbedded;
if (typeof style === 'string') {
isEmbedded = false;
} else {
var patternParts = shortcuts[token.charAt(0)];
if (patternParts) {
match = token.match(patternParts[1]);
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
match = token.match(patternParts[1]);
if (match) {
style = patternParts[0];
break;
}
}
if (!match) { // make sure that we make progress
style = PR_PLAIN;
}
}
isEmbedded = style.length >= 5 && 'lang-' === style.substring(0, 5);
if (isEmbedded && !(match && typeof match[1] === 'string')) {
isEmbedded = false;
style = PR_SOURCE;
}
if (!isEmbedded) { styleCache[token] = style; }
}
var tokenStart = pos;
pos += token.length;
if (!isEmbedded) {
decorations.push(basePos + tokenStart, style);
} else { // Treat group 1 as an embedded block of source code.
var embeddedSource = match[1];
var embeddedSourceStart = token.indexOf(embeddedSource);
var embeddedSourceEnd = embeddedSourceStart + embeddedSource.length;
if (match[2]) {
// If embeddedSource can be blank, then it would match at the
// beginning which would cause us to infinitely recurse on the
// entire token, so we catch the right context in match[2].
embeddedSourceEnd = token.length - match[2].length;
embeddedSourceStart = embeddedSourceEnd - embeddedSource.length;
}
var lang = style.substring(5);
// Decorate the left of the embedded source
appendDecorations(
basePos + tokenStart,
token.substring(0, embeddedSourceStart),
decorate, decorations);
// Decorate the embedded source
appendDecorations(
basePos + tokenStart + embeddedSourceStart,
embeddedSource,
langHandlerForExtension(lang, embeddedSource),
decorations);
// Decorate the right of the embedded section
appendDecorations(
basePos + tokenStart + embeddedSourceEnd,
token.substring(embeddedSourceEnd),
decorate, decorations);
}
}
job.decorations = decorations;
};
return decorate;
}
/** returns a function that produces a list of decorations from source text.
*
* This code treats ", ', and ` as string delimiters, and \ as a string
* escape. It does not recognize perl's qq() style strings.
* It has no special handling for double delimiter escapes as in basic, or
* the tripled delimiters used in python, but should work on those regardless
* although in those cases a single string literal may be broken up into
* multiple adjacent string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {Object} options a set of optional parameters.
* @return {function (Object)} a function that examines the source code
* in the input job and builds the decoration list.
*/
function sourceDecorator(options) {
var shortcutStylePatterns = [], fallthroughStylePatterns = [];
if (options['tripleQuotedStrings']) {
// '''multi-line-string''', 'single-line-string', and double-quoted
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,
null, '\'"']);
} else if (options['multiLineStrings']) {
// 'multi-line-string', "multi-line-string"
shortcutStylePatterns.push(
[PR_STRING, /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,
null, '\'"`']);
} else {
// 'single-line-string', "single-line-string"
shortcutStylePatterns.push(
[PR_STRING,
/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,
null, '"\'']);
}
if (options['verbatimStrings']) {
// verbatim-string-literal production from the C# grammar. See issue 93.
fallthroughStylePatterns.push(
[PR_STRING, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]);
}
var hc = options['hashComments'];
if (hc) {
if (options['cStyleComments']) {
if (hc > 1) { // multiline hash comments
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, '#']);
} else {
// Stop C preprocessor declarations at an unclosed open comment
shortcutStylePatterns.push(
[PR_COMMENT, /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,
null, '#']);
}
// #include <stdio.h>
fallthroughStylePatterns.push(
[PR_STRING,
/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h(?:h|pp|\+\+)?|[a-z]\w*)>/,
null]);
} else {
shortcutStylePatterns.push([PR_COMMENT, /^#[^\r\n]*/, null, '#']);
}
}
if (options['cStyleComments']) {
fallthroughStylePatterns.push([PR_COMMENT, /^\/\/[^\r\n]*/, null]);
fallthroughStylePatterns.push(
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]);
}
if (options['regexLiterals']) {
/**
* @const
*/
var REGEX_LITERAL = (
// A regular expression literal starts with a slash that is
// not followed by * or / so that it is not confused with
// comments.
'/(?=[^/*])'
// and then contains any number of raw characters,
+ '(?:[^/\\x5B\\x5C]'
// escape sequences (\x5C),
+ '|\\x5C[\\s\\S]'
// or non-nesting character sets (\x5B\x5D);
+ '|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+'
// finally closed by a /.
+ '/');
fallthroughStylePatterns.push(
['lang-regex',
new RegExp('^' + REGEXP_PRECEDER_PATTERN + '(' + REGEX_LITERAL + ')')
]);
}
var types = options['types'];
if (types) {
fallthroughStylePatterns.push([PR_TYPE, types]);
}
var keywords = ("" + options['keywords']).replace(/^ | $/g, '');
if (keywords.length) {
fallthroughStylePatterns.push(
[PR_KEYWORD,
new RegExp('^(?:' + keywords.replace(/[\s,]+/g, '|') + ')\\b'),
null]);
}
shortcutStylePatterns.push([PR_PLAIN, /^\s+/, null, ' \r\n\t\xA0']);
fallthroughStylePatterns.push(
// TODO(mikesamuel): recognize non-latin letters and numerals in idents
[PR_LITERAL, /^@[a-z_$][a-z_$@0-9]*/i, null],
[PR_TYPE, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null],
[PR_PLAIN, /^[a-z_$][a-z_$@0-9]*/i, null],
[PR_LITERAL,
new RegExp(
'^(?:'
// A hex number
+ '0x[a-f0-9]+'
// or an octal or decimal number,
+ '|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)'
// possibly in scientific notation
+ '(?:e[+\\-]?\\d+)?'
+ ')'
// with an optional modifier like UL for unsigned long
+ '[a-z]*', 'i'),
null, '0123456789'],
// Don't treat escaped quotes in bash as starting strings. See issue 144.
[PR_PLAIN, /^\\[\s\S]?/, null],
[PR_PUNCTUATION, /^.[^\s\w\.$@\'\"\`\/\#\\]*/, null]);
return createSimpleLexer(shortcutStylePatterns, fallthroughStylePatterns);
}
var decorateSource = sourceDecorator({
'keywords': ALL_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'multiLineStrings': true,
'regexLiterals': true
});
/**
* Given a DOM subtree, wraps it in a list, and puts each line into its own
* list item.
*
* @param {Node} node modified in place. Its content is pulled into an
* HTMLOListElement, and each line is moved into a separate list item.
* This requires cloning elements, so the input might not have unique
* IDs after numbering.
* @param {boolean} isPreformatted true iff white-space in text nodes should
* be treated as significant.
*/
function numberLines(node, opt_startLineNum, isPreformatted) {
var nocode = /(?:^|\s)nocode(?:\s|$)/;
var lineBreak = /\r\n?|\n/;
var document = node.ownerDocument;
var li = document.createElement('li');
while (node.firstChild) {
li.appendChild(node.firstChild);
}
// An array of lines. We split below, so this is initialized to one
// un-split line.
var listItems = [li];
function walk(node) {
switch (node.nodeType) {
case 1: // Element
if (nocode.test(node.className)) { break; }
if ('br' === node.nodeName) {
breakAfter(node);
// Discard the <BR> since it is now flush against a </LI>.
if (node.parentNode) {
node.parentNode.removeChild(node);
}
} else {
for (var child = node.firstChild; child; child = child.nextSibling) {
walk(child);
}
}
break;
case 3: case 4: // Text
if (isPreformatted) {
var text = node.nodeValue;
var match = text.match(lineBreak);
if (match) {
var firstLine = text.substring(0, match.index);
node.nodeValue = firstLine;
var tail = text.substring(match.index + match[0].length);
if (tail) {
var parent = node.parentNode;
parent.insertBefore(
document.createTextNode(tail), node.nextSibling);
}
breakAfter(node);
if (!firstLine) {
// Don't leave blank text nodes in the DOM.
node.parentNode.removeChild(node);
}
}
}
break;
}
}
// Split a line after the given node.
function breakAfter(lineEndNode) {
// If there's nothing to the right, then we can skip ending the line
// here, and move root-wards since splitting just before an end-tag
// would require us to create a bunch of empty copies.
while (!lineEndNode.nextSibling) {
lineEndNode = lineEndNode.parentNode;
if (!lineEndNode) { return; }
}
function breakLeftOf(limit, copy) {
// Clone shallowly if this node needs to be on both sides of the break.
var rightSide = copy ? limit.cloneNode(false) : limit;
var parent = limit.parentNode;
if (parent) {
// We clone the parent chain.
// This helps us resurrect important styling elements that cross lines.
// E.g. in <i>Foo<br>Bar</i>
// should be rewritten to <li><i>Foo</i></li><li><i>Bar</i></li>.
var parentClone = breakLeftOf(parent, 1);
// Move the clone and everything to the right of the original
// onto the cloned parent.
var next = limit.nextSibling;
parentClone.appendChild(rightSide);
for (var sibling = next; sibling; sibling = next) {
next = sibling.nextSibling;
parentClone.appendChild(sibling);
}
}
return rightSide;
}
var copiedListItem = breakLeftOf(lineEndNode.nextSibling, 0);
// Walk the parent chain until we reach an unattached LI.
for (var parent;
// Check nodeType since IE invents document fragments.
(parent = copiedListItem.parentNode) && parent.nodeType === 1;) {
copiedListItem = parent;
}
// Put it on the list of lines for later processing.
listItems.push(copiedListItem);
}
// Split lines while there are lines left to split.
for (var i = 0; // Number of lines that have been split so far.
i < listItems.length; // length updated by breakAfter calls.
++i) {
walk(listItems[i]);
}
// Make sure numeric indices show correctly.
if (opt_startLineNum === (opt_startLineNum|0)) {
listItems[0].setAttribute('value', opt_startLineNum);
}
var ol = document.createElement('ol');
ol.className = 'linenums';
var offset = Math.max(0, ((opt_startLineNum - 1 /* zero index */)) | 0) || 0;
for (var i = 0, n = listItems.length; i < n; ++i) {
li = listItems[i];
// Stick a class on the LIs so that stylesheets can
// color odd/even rows, or any other row pattern that
// is co-prime with 10.
li.className = 'L' + ((i + offset) % 10);
if (!li.firstChild) {
li.appendChild(document.createTextNode('\xA0'));
}
ol.appendChild(li);
}
node.appendChild(ol);
}
/**
* Breaks {@code job.sourceCode} around style boundaries in
* {@code job.decorations} and modifies {@code job.sourceNode} in place.
* @param {Object} job like <pre>{
* sourceCode: {string} source as plain text,
* spans: {Array.<number|Node>} alternating span start indices into source
* and the text node or element (e.g. {@code <BR>}) corresponding to that
* span.
* decorations: {Array.<number|string} an array of style classes preceded
* by the position at which they start in job.sourceCode in order
* }</pre>
* @private
*/
function recombineTagsAndDecorations(job) {
var isIE8OrEarlier = /\bMSIE\s(\d+)/.exec(navigator.userAgent);
isIE8OrEarlier = isIE8OrEarlier && +isIE8OrEarlier[1] <= 8;
var newlineRe = /\n/g;
var source = job.sourceCode;
var sourceLength = source.length;
// Index into source after the last code-unit recombined.
var sourceIndex = 0;
var spans = job.spans;
var nSpans = spans.length;
// Index into spans after the last span which ends at or before sourceIndex.
var spanIndex = 0;
var decorations = job.decorations;
var nDecorations = decorations.length;
// Index into decorations after the last decoration which ends at or before
// sourceIndex.
var decorationIndex = 0;
// Remove all zero-length decorations.
decorations[nDecorations] = sourceLength;
var decPos, i;
for (i = decPos = 0; i < nDecorations;) {
if (decorations[i] !== decorations[i + 2]) {
decorations[decPos++] = decorations[i++];
decorations[decPos++] = decorations[i++];
} else {
i += 2;
}
}
nDecorations = decPos;
// Simplify decorations.
for (i = decPos = 0; i < nDecorations;) {
var startPos = decorations[i];
// Conflate all adjacent decorations that use the same style.
var startDec = decorations[i + 1];
var end = i + 2;
while (end + 2 <= nDecorations && decorations[end + 1] === startDec) {
end += 2;
}
decorations[decPos++] = startPos;
decorations[decPos++] = startDec;
i = end;
}
nDecorations = decorations.length = decPos;
var sourceNode = job.sourceNode;
var oldDisplay;
if (sourceNode) {
oldDisplay = sourceNode.style.display;
sourceNode.style.display = 'none';
}
try {
var decoration = null;
while (spanIndex < nSpans) {
var spanStart = spans[spanIndex];
var spanEnd = spans[spanIndex + 2] || sourceLength;
var decEnd = decorations[decorationIndex + 2] || sourceLength;
var end = Math.min(spanEnd, decEnd);
var textNode = spans[spanIndex + 1];
var styledText;
if (textNode.nodeType !== 1 // Don't muck with <BR>s or <LI>s
// Don't introduce spans around empty text nodes.
&& (styledText = source.substring(sourceIndex, end))) {
// This may seem bizarre, and it is. Emitting LF on IE causes the
// code to display with spaces instead of line breaks.
// Emitting Windows standard issue linebreaks (CRLF) causes a blank
// space to appear at the beginning of every line but the first.
// Emitting an old Mac OS 9 line separator makes everything spiffy.
if (isIE8OrEarlier) {
styledText = styledText.replace(newlineRe, '\r');
}
textNode.nodeValue = styledText;
var document = textNode.ownerDocument;
var span = document.createElement('span');
span.className = decorations[decorationIndex + 1];
var parentNode = textNode.parentNode;
parentNode.replaceChild(span, textNode);
span.appendChild(textNode);
if (sourceIndex < spanEnd) { // Split off a text node.
spans[spanIndex + 1] = textNode
// TODO: Possibly optimize by using '' if there's no flicker.
= document.createTextNode(source.substring(end, spanEnd));
parentNode.insertBefore(textNode, span.nextSibling);
}
}
sourceIndex = end;
if (sourceIndex >= spanEnd) {
spanIndex += 2;
}
if (sourceIndex >= decEnd) {
decorationIndex += 2;
}
}
} finally {
if (sourceNode) {
sourceNode.style.display = oldDisplay;
}
}
}
/** Maps language-specific file extensions to handlers. */
var langHandlerRegistry = {};
/** Register a language handler for the given file extensions.
* @param {function (Object)} handler a function from source code to a list
* of decorations. Takes a single argument job which describes the
* state of the computation. The single parameter has the form
* {@code {
* sourceCode: {string} as plain text.
* decorations: {Array.<number|string>} an array of style classes
* preceded by the position at which they start in
* job.sourceCode in order.
* The language handler should assigned this field.
* basePos: {int} the position of source in the larger source chunk.
* All positions in the output decorations array are relative
* to the larger source chunk.
* } }
* @param {Array.<string>} fileExtensions
*/
function registerLangHandler(handler, fileExtensions) {
for (var i = fileExtensions.length; --i >= 0;) {
var ext = fileExtensions[i];
if (!langHandlerRegistry.hasOwnProperty(ext)) {
langHandlerRegistry[ext] = handler;
} else if (win['console']) {
console['warn']('cannot override language handler %s', ext);
}
}
}
function langHandlerForExtension(extension, source) {
if (!(extension && langHandlerRegistry.hasOwnProperty(extension))) {
// Treat it as markup if the first non whitespace character is a < and
// the last non-whitespace character is a >.
extension = /^\s*</.test(source)
? 'default-markup'
: 'default-code';
}
return langHandlerRegistry[extension];
}
registerLangHandler(decorateSource, ['default-code']);
registerLangHandler(
createSimpleLexer(
[],
[
[PR_PLAIN, /^[^<?]+/],
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/],
[PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/],
// Unescaped content in an unknown language
['lang-', /^<\?([\s\S]+?)(?:\?>|$)/],
['lang-', /^<%([\s\S]+?)(?:%>|$)/],
[PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/],
['lang-', /^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],
// Unescaped content in javascript. (Or possibly vbscript).
['lang-js', /^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],
// Contains unescaped stylesheet content
['lang-css', /^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],
['lang-in.tag', /^(<\/?[a-z][^<>]*>)/i]
]),
['default-markup', 'htm', 'html', 'mxml', 'xhtml', 'xml', 'xsl']);
registerLangHandler(
createSimpleLexer(
[
[PR_PLAIN, /^[\s]+/, null, ' \t\r\n'],
[PR_ATTRIB_VALUE, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, '\"\'']
],
[
[PR_TAG, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],
[PR_ATTRIB_NAME, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],
['lang-uq.val', /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],
[PR_PUNCTUATION, /^[=<>\/]+/],
['lang-js', /^on\w+\s*=\s*\"([^\"]+)\"/i],
['lang-js', /^on\w+\s*=\s*\'([^\']+)\'/i],
['lang-js', /^on\w+\s*=\s*([^\"\'>\s]+)/i],
['lang-css', /^style\s*=\s*\"([^\"]+)\"/i],
['lang-css', /^style\s*=\s*\'([^\']+)\'/i],
['lang-css', /^style\s*=\s*([^\"\'>\s]+)/i]
]),
['in.tag']);
registerLangHandler(
createSimpleLexer([], [[PR_ATTRIB_VALUE, /^[\s\S]+/]]), ['uq.val']);
registerLangHandler(sourceDecorator({
'keywords': CPP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'types': C_TYPES
}), ['c', 'cc', 'cpp', 'cxx', 'cyc', 'm']);
registerLangHandler(sourceDecorator({
'keywords': 'null,true,false'
}), ['json']);
registerLangHandler(sourceDecorator({
'keywords': CSHARP_KEYWORDS,
'hashComments': true,
'cStyleComments': true,
'verbatimStrings': true,
'types': C_TYPES
}), ['cs']);
registerLangHandler(sourceDecorator({
'keywords': JAVA_KEYWORDS,
'cStyleComments': true
}), ['java']);
registerLangHandler(sourceDecorator({
'keywords': SH_KEYWORDS,
'hashComments': true,
'multiLineStrings': true
}), ['bsh', 'csh', 'sh']);
registerLangHandler(sourceDecorator({
'keywords': PYTHON_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'tripleQuotedStrings': true
}), ['cv', 'py']);
registerLangHandler(sourceDecorator({
'keywords': PERL_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': true
}), ['perl', 'pl', 'pm']);
registerLangHandler(sourceDecorator({
'keywords': RUBY_KEYWORDS,
'hashComments': true,
'multiLineStrings': true,
'regexLiterals': true
}), ['rb']);
registerLangHandler(sourceDecorator({
'keywords': JSCRIPT_KEYWORDS,
'cStyleComments': true,
'regexLiterals': true
}), ['js']);
registerLangHandler(sourceDecorator({
'keywords': COFFEE_KEYWORDS,
'hashComments': 3, // ### style block comments
'cStyleComments': true,
'multilineStrings': true,
'tripleQuotedStrings': true,
'regexLiterals': true
}), ['coffee']);
registerLangHandler(
createSimpleLexer([], [[PR_STRING, /^[\s\S]+/]]), ['regex']);
function applyDecorator(job) {
var opt_langExtension = job.langExtension;
try {
// Extract tags, and convert the source code to plain text.
var sourceAndSpans = extractSourceSpans(job.sourceNode, job.pre);
/** Plain text. @type {string} */
var source = sourceAndSpans.sourceCode;
job.sourceCode = source;
job.spans = sourceAndSpans.spans;
job.basePos = 0;
// Apply the appropriate language handler
langHandlerForExtension(opt_langExtension, source)(job);
// Integrate the decorations and tags back into the source code,
// modifying the sourceNode in place.
recombineTagsAndDecorations(job);
} catch (e) {
if (win['console']) {
console['log'](e && e['stack'] ? e['stack'] : e);
}
}
}
/**
* @param sourceCodeHtml {string} The HTML to pretty print.
* @param opt_langExtension {string} The language name to use.
* Typically, a filename extension like 'cpp' or 'java'.
* @param opt_numberLines {number|boolean} True to number lines,
* or the 1-indexed number of the first line in sourceCodeHtml.
*/
function prettyPrintOne(sourceCodeHtml, opt_langExtension, opt_numberLines) {
// PATCHED: http://code.google.com/p/google-code-prettify/issues/detail?id=213
var container = document.createElement('div');
// This could cause images to load and onload listeners to fire.
// E.g. <img onerror="alert(1337)" src="nosuchimage.png">.
// We assume that the inner HTML is from a trusted source.
container.innerHTML = '<pre>' + sourceCodeHtml + '</pre>';
container = container.firstChild;
if (opt_numberLines) {
numberLines(container, opt_numberLines, true);
}
var job = {
langExtension: opt_langExtension,
numberLines: opt_numberLines,
sourceNode: container,
pre: 1
};
applyDecorator(job);
return container.innerHTML;
}
function prettyPrint(opt_whenDone) {
function byTagName(tn) { return document.getElementsByTagName(tn); }
// fetch a list of nodes to rewrite
var codeSegments = [byTagName('pre'), byTagName('code'), byTagName('xmp')];
var elements = [];
for (var i = 0; i < codeSegments.length; ++i) {
for (var j = 0, n = codeSegments[i].length; j < n; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
var clock = Date;
if (!clock['now']) {
clock = { 'now': function () { return +(new Date); } };
}
// The loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
var prettyPrintingJob;
var langExtensionRe = /\blang(?:uage)?-([\w.]+)(?!\S)/;
var prettyPrintRe = /\bprettyprint\b/;
var prettyPrintedRe = /\bprettyprinted\b/;
var preformattedTagNameRe = /pre|xmp/i;
var codeRe = /^code$/i;
var preCodeXmpRe = /^(?:pre|code|xmp)$/i;
function doWork() {
var endTime = (win['PR_SHOULD_USE_CONTINUATION'] ?
clock['now']() + 250 /* ms */ :
Infinity);
for (; k < elements.length && clock['now']() < endTime; k++) {
var cs = elements[k];
var className = cs.className;
if (prettyPrintRe.test(className)
// Don't redo this if we've already done it.
// This allows recalling pretty print to just prettyprint elements
// that have been added to the page since last call.
&& !prettyPrintedRe.test(className)) {
// make sure this is not nested in an already prettified element
var nested = false;
for (var p = cs.parentNode; p; p = p.parentNode) {
var tn = p.tagName;
if (preCodeXmpRe.test(tn)
&& p.className && prettyPrintRe.test(p.className)) {
nested = true;
break;
}
}
if (!nested) {
// Mark done. If we fail to prettyprint for whatever reason,
// we shouldn't try again.
cs.className += ' prettyprinted';
// If the classes includes a language extensions, use it.
// Language extensions can be specified like
// <pre class="prettyprint lang-cpp">
// the language extension "cpp" is used to find a language handler
// as passed to PR.registerLangHandler.
// HTML5 recommends that a language be specified using "language-"
// as the prefix instead. Google Code Prettify supports both.
// http://dev.w3.org/html5/spec-author-view/the-code-element.html
var langExtension = className.match(langExtensionRe);
// Support <pre class="prettyprint"><code class="language-c">
var wrapper;
if (!langExtension && (wrapper = childContentWrapper(cs))
&& codeRe.test(wrapper.tagName)) {
langExtension = wrapper.className.match(langExtensionRe);
}
if (langExtension) { langExtension = langExtension[1]; }
var preformatted;
if (preformattedTagNameRe.test(cs.tagName)) {
preformatted = 1;
} else {
var currentStyle = cs['currentStyle'];
var whitespace = (
currentStyle
? currentStyle['whiteSpace']
: (document.defaultView
&& document.defaultView.getComputedStyle)
? document.defaultView.getComputedStyle(cs, null)
.getPropertyValue('white-space')
: 0);
preformatted = whitespace
&& 'pre' === whitespace.substring(0, 3);
}
// Look for a class like linenums or linenums:<n> where <n> is the
// 1-indexed number of the first line.
var lineNums = cs.className.match(/\blinenums\b(?::(\d+))?/);
lineNums = lineNums
? lineNums[1] && lineNums[1].length ? +lineNums[1] : true
: false;
if (lineNums) { numberLines(cs, lineNums, preformatted); }
// do the pretty printing
prettyPrintingJob = {
langExtension: langExtension,
sourceNode: cs,
numberLines: lineNums,
pre: preformatted
};
applyDecorator(prettyPrintingJob);
}
}
}
if (k < elements.length) {
// finish up in a continuation
setTimeout(doWork, 250);
} else if (opt_whenDone) {
opt_whenDone();
}
}
doWork();
}
/**
* Contains functions for creating and registering new language handlers.
* @type {Object}
*/
var PR = win['PR'] = {
'createSimpleLexer': createSimpleLexer,
'registerLangHandler': registerLangHandler,
'sourceDecorator': sourceDecorator,
'PR_ATTRIB_NAME': PR_ATTRIB_NAME,
'PR_ATTRIB_VALUE': PR_ATTRIB_VALUE,
'PR_COMMENT': PR_COMMENT,
'PR_DECLARATION': PR_DECLARATION,
'PR_KEYWORD': PR_KEYWORD,
'PR_LITERAL': PR_LITERAL,
'PR_NOCODE': PR_NOCODE,
'PR_PLAIN': PR_PLAIN,
'PR_PUNCTUATION': PR_PUNCTUATION,
'PR_SOURCE': PR_SOURCE,
'PR_STRING': PR_STRING,
'PR_TAG': PR_TAG,
'PR_TYPE': PR_TYPE,
'prettyPrintOne': win['prettyPrintOne'] = prettyPrintOne,
'prettyPrint': win['prettyPrint'] = prettyPrint
};
// Make PR available via the Asynchronous Module Definition (AMD) API.
// Per https://github.com/amdjs/amdjs-api/wiki/AMD:
// The Asynchronous Module Definition (AMD) API specifies a
// mechanism for defining modules such that the module and its
// dependencies can be asynchronously loaded.
// ...
// To allow a clear indicator that a global define function (as
// needed for script src browser loading) conforms to the AMD API,
// any global define function SHOULD have a property called "amd"
// whose value is an object. This helps avoid conflict with any
// other existing JavaScript code that could have defined a define()
// function that does not conform to the AMD API.
if (typeof define === "function" && define['amd']) {
define("google-code-prettify", [], function () {
return PR;
});
}
})();
})(window, window.angular);
angular.element(document).find('head').append('<style type="text/css">.com{color:#93a1a1;}.lit{color:#195f91;}.pun,.opn,.clo{color:#93a1a1;}.fun{color:#dc322f;}.str,.atv{color:#D14;}.kwd,.linenums .tag{color:#1e347b;}.typ,.atn,.dec,.var{color:teal;}.pln{color:#48484c;}.prettyprint{padding:8px;background-color:#f7f7f9;border:1px solid #e1e1e8;}.prettyprint.linenums{-webkit-box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;-moz-box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;box-shadow:inset 40px 0 0 #fbfbfc,inset 41px 0 0 #ececf0;}ol.linenums{margin:0 0 0 33px;}ol.linenums li{padding-left:12px;color:#bebec5;line-height:18px;text-shadow:0 1px 0 #fff;}</style>');
|
JavaScript
|
/**
* Configuration for jstd scenario adapter
*/
var jstdScenarioAdapter = {
relativeUrlPrefix: '/build/docs/'
};
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
var directive = {};
directive.dropdownToggle =
['$document', '$location', '$window',
function ($document, $location, $window) {
var openElement = null, close;
return {
restrict: 'C',
link: function(scope, element, attrs) {
scope.$watch(function(){return $location.path();}, function() {
close && close();
});
element.parent().bind('click', function(event) {
close && close();
});
element.bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
var iWasOpen = false;
if (openElement) {
iWasOpen = openElement === element;
close();
}
if (!iWasOpen){
element.parent().addClass('open');
openElement = element;
close = function (event) {
event && event.preventDefault();
event && event.stopPropagation();
$document.unbind('click', close);
element.parent().removeClass('open');
close = null;
openElement = null;
}
$document.bind('click', close);
}
});
}
};
}];
directive.tabbable = function() {
return {
restrict: 'C',
compile: function(element) {
var navTabs = angular.element('<ul class="nav nav-tabs"></ul>'),
tabContent = angular.element('<div class="tab-content"></div>');
tabContent.append(element.contents());
element.append(navTabs).append(tabContent);
},
controller: ['$scope', '$element', function($scope, $element) {
var navTabs = $element.contents().eq(0),
ngModel = $element.controller('ngModel') || {},
tabs = [],
selectedTab;
ngModel.$render = function() {
var $viewValue = this.$viewValue;
if (selectedTab ? (selectedTab.value != $viewValue) : $viewValue) {
if(selectedTab) {
selectedTab.paneElement.removeClass('active');
selectedTab.tabElement.removeClass('active');
selectedTab = null;
}
if($viewValue) {
for(var i = 0, ii = tabs.length; i < ii; i++) {
if ($viewValue == tabs[i].value) {
selectedTab = tabs[i];
break;
}
}
if (selectedTab) {
selectedTab.paneElement.addClass('active');
selectedTab.tabElement.addClass('active');
}
}
}
};
this.addPane = function(element, attr) {
var li = angular.element('<li><a href></a></li>'),
a = li.find('a'),
tab = {
paneElement: element,
paneAttrs: attr,
tabElement: li
};
tabs.push(tab);
attr.$observe('value', update)();
attr.$observe('title', function(){ update(); a.text(tab.title); })();
function update() {
tab.title = attr.title;
tab.value = attr.value || attr.title;
if (!ngModel.$setViewValue && (!ngModel.$viewValue || tab == selectedTab)) {
// we are not part of angular
ngModel.$viewValue = tab.value;
}
ngModel.$render();
}
navTabs.append(li);
li.bind('click', function(event) {
event.preventDefault();
event.stopPropagation();
if (ngModel.$setViewValue) {
$scope.$apply(function() {
ngModel.$setViewValue(tab.value);
ngModel.$render();
});
} else {
// we are not part of angular
ngModel.$viewValue = tab.value;
ngModel.$render();
}
});
return function() {
tab.tabElement.remove();
for(var i = 0, ii = tabs.length; i < ii; i++ ) {
if (tab == tabs[i]) {
tabs.splice(i, 1);
}
}
};
}
}]
};
};
directive.tabPane = function() {
return {
require: '^tabbable',
restrict: 'C',
link: function(scope, element, attrs, tabsCtrl) {
element.bind('$remove', tabsCtrl.addPane(element, attrs));
}
};
};
angular.module('bootstrap', []).directive(directive);
})(window, window.angular);
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngResource
* @description
*/
/**
* @ngdoc object
* @name ngResource.$resource
* @requires $http
*
* @description
* A factory which creates a resource object that lets you interact with
* [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
*
* The returned resource object has action methods which provide high-level behaviors without
* the need to interact with the low level {@link ng.$http $http} service.
*
* @param {string} url A parameterized URL template with parameters prefixed by `:` as in
* `/user/:username`.
*
* @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
* `actions` methods.
*
* Each key value in the parameter object is first bound to url template if present and then any
* excess keys are appended to the url search query after the `?`.
*
* Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
* URL `/path/greet?salutation=Hello`.
*
* If the parameter value is prefixed with `@` then the value of that parameter is extracted from
* the data object (useful for non-GET operations).
*
* @param {Object.<Object>=} actions Hash with declaration of custom action that should extend the
* default set of resource actions. The declaration should be created in the following format:
*
* {action1: {method:?, params:?, isArray:?},
* action2: {method:?, params:?, isArray:?},
* ...}
*
* Where:
*
* - `action` – {string} – The name of action. This name becomes the name of the method on your
* resource object.
* - `method` – {string} – HTTP request method. Valid methods are: `GET`, `POST`, `PUT`, `DELETE`,
* and `JSONP`
* - `params` – {object=} – Optional set of pre-bound parameters for this action.
* - isArray – {boolean=} – If true then the returned object for this action is an array, see
* `returns` section.
*
* @returns {Object} A resource "class" object with methods for the default set of resource actions
* optionally extended with custom `actions`. The default set contains these actions:
*
* { 'get': {method:'GET'},
* 'save': {method:'POST'},
* 'query': {method:'GET', isArray:true},
* 'remove': {method:'DELETE'},
* 'delete': {method:'DELETE'} };
*
* Calling these methods invoke an {@link ng.$http} with the specified http method,
* destination and parameters. When the data is returned from the server then the object is an
* instance of the resource class `save`, `remove` and `delete` actions are available on it as
* methods with the `$` prefix. This allows you to easily perform CRUD operations (create, read,
* update, delete) on server-side data like this:
* <pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It is important to realize that invoking a $resource object method immediately returns an
* empty reference (object or array depending on `isArray`). Once the data is returned from the
* server the existing reference is populated with the actual data. This is a useful trick since
* usually the resource is assigned to a model which is then rendered by the view. Having an empty
* object results in no rendering, once the data arrives from the server then the object is
* populated with the data and the view automatically re-renders itself showing the new data. This
* means that in most case one never has to write a callback function for the action methods.
*
* The action methods on the class object or instance object can be invoked with the following
* parameters:
*
* - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
* - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
* - non-GET instance actions: `instance.$action([parameters], [success], [error])`
*
*
* @example
*
* # Credit card resource
*
* <pre>
// Define CreditCard class
var CreditCard = $resource('/user/:userId/card/:cardId',
{userId:123, cardId:'@id'}, {
charge: {method:'POST', params:{charge:true}}
});
// We can retrieve a collection from the server
var cards = CreditCard.query(function() {
// GET: /user/123/card
// server returns: [ {id:456, number:'1234', name:'Smith'} ];
var card = cards[0];
// each item is an instance of CreditCard
expect(card instanceof CreditCard).toEqual(true);
card.name = "J. Smith";
// non GET methods are mapped onto the instances
card.$save();
// POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
// server returns: {id:456, number:'1234', name: 'J. Smith'};
// our custom method is mapped as well.
card.$charge({amount:9.99});
// POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
});
// we can create an instance as well
var newCard = new CreditCard({number:'0123'});
newCard.name = "Mike Smith";
newCard.$save();
// POST: /user/123/card {number:'0123', name:'Mike Smith'}
// server returns: {id:789, number:'01234', name: 'Mike Smith'};
expect(newCard.id).toEqual(789);
* </pre>
*
* The object returned from this function execution is a resource "class" which has "static" method
* for each action in the definition.
*
* Calling these methods invoke `$http` on the `url` template with the given `method` and `params`.
* When the data is returned from the server then the object is an instance of the resource type and
* all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
* operations (create, read, update, delete) on server-side data.
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
var user = User.get({userId:123}, function() {
user.abc = true;
user.$save();
});
</pre>
*
* It's worth noting that the success callback for `get`, `query` and other method gets passed
* in the response that came from the server as well as $http header getter function, so one
* could rewrite the above example and get access to http headers as:
*
<pre>
var User = $resource('/user/:userId', {userId:'@id'});
User.get({userId:123}, function(u, getResponseHeaders){
u.abc = true;
u.$save(function(u, putResponseHeaders) {
//u => saved user object
//putResponseHeaders => $http header getter
});
});
</pre>
* # Buzz client
Let's look at what a buzz client created with the `$resource` service looks like:
<doc:example>
<doc:source jsfiddle="false">
<script>
function BuzzController($resource) {
this.userId = 'googlebuzz';
this.Activity = $resource(
'https://www.googleapis.com/buzz/v1/activities/:userId/:visibility/:activityId/:comments',
{alt:'json', callback:'JSON_CALLBACK'},
{get:{method:'JSONP', params:{visibility:'@self'}}, replies: {method:'JSONP', params:{visibility:'@self', comments:'@comments'}}}
);
}
BuzzController.prototype = {
fetch: function() {
this.activities = this.Activity.get({userId:this.userId});
},
expandReplies: function(activity) {
activity.replies = this.Activity.replies({userId:this.userId, activityId:activity.id});
}
};
BuzzController.$inject = ['$resource'];
</script>
<div ng-controller="BuzzController">
<input ng-model="userId"/>
<button ng-click="fetch()">fetch</button>
<hr/>
<div ng-repeat="item in activities.data.items">
<h1 style="font-size: 15px;">
<img src="{{item.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{item.actor.profileUrl}}">{{item.actor.name}}</a>
<a href ng-click="expandReplies(item)" style="float: right;">Expand replies: {{item.links.replies[0].count}}</a>
</h1>
{{item.object.content | html}}
<div ng-repeat="reply in item.replies.data.items" style="margin-left: 20px;">
<img src="{{reply.actor.thumbnailUrl}}" style="max-height:30px;max-width:30px;"/>
<a href="{{reply.actor.profileUrl}}">{{reply.actor.name}}</a>: {{reply.content | html}}
</div>
</div>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
angular.module('ngResource', ['ng']).
factory('$resource', ['$http', '$parse', function($http, $parse) {
var DEFAULT_ACTIONS = {
'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
};
var noop = angular.noop,
forEach = angular.forEach,
extend = angular.extend,
copy = angular.copy,
isFunction = angular.isFunction,
getter = function(obj, path) {
return $parse(path)(obj);
};
/**
* We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
function Route(template, defaults) {
this.template = template = template + '#';
this.defaults = defaults || {};
var urlParams = this.urlParams = {};
forEach(template.split(/\W/), function(param){
if (param && template.match(new RegExp("[^\\\\]:" + param + "\\W"))) {
urlParams[param] = true;
}
});
this.template = template.replace(/\\:/g, ':');
}
Route.prototype = {
url: function(params) {
var self = this,
url = this.template,
encodedVal;
params = params || {};
forEach(this.urlParams, function(_, urlParam){
encodedVal = encodeUriSegment(params[urlParam] || self.defaults[urlParam] || "");
url = url.replace(new RegExp(":" + urlParam + "(\\W)"), encodedVal + "$1");
});
url = url.replace(/\/?#$/, '');
var query = [];
forEach(params, function(value, key){
if (!self.urlParams[key]) {
query.push(encodeUriQuery(key) + '=' + encodeUriQuery(value));
}
});
query.sort();
url = url.replace(/\/*$/, '');
return url + (query.length ? '?' + query.join('&') : '');
}
};
function ResourceFactory(url, paramDefaults, actions) {
var route = new Route(url);
actions = extend({}, DEFAULT_ACTIONS, actions);
function extractParams(data){
var ids = {};
forEach(paramDefaults || {}, function(value, key){
ids[key] = value.charAt && value.charAt(0) == '@' ? getter(data, value.substr(1)) : value;
});
return ids;
}
function Resource(value){
copy(value || {}, this);
}
forEach(actions, function(action, name) {
var hasBody = action.method == 'POST' || action.method == 'PUT' || action.method == 'PATCH';
Resource[name] = function(a1, a2, a3, a4) {
var params = {};
var data;
var success = noop;
var error = null;
switch(arguments.length) {
case 4:
error = a4;
success = a3;
//fallthrough
case 3:
case 2:
if (isFunction(a2)) {
if (isFunction(a1)) {
success = a1;
error = a2;
break;
}
success = a2;
error = a3;
//fallthrough
} else {
params = a1;
data = a2;
success = a3;
break;
}
case 1:
if (isFunction(a1)) success = a1;
else if (hasBody) data = a1;
else params = a1;
break;
case 0: break;
default:
throw "Expected between 0-4 arguments [params, data, success, error], got " +
arguments.length + " arguments.";
}
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
$http({
method: action.method,
url: route.url(extend({}, extractParams(data), action.params || {}, params)),
data: data
}).then(function(response) {
var data = response.data;
if (data) {
if (action.isArray) {
value.length = 0;
forEach(data, function(item) {
value.push(new Resource(item));
});
} else {
copy(data, value);
}
}
(success||noop)(value, response.headers);
}, error);
return value;
};
Resource.bind = function(additionalParamDefaults){
return ResourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
};
Resource.prototype['$' + name] = function(a1, a2, a3) {
var params = extractParams(this),
success = noop,
error;
switch(arguments.length) {
case 3: params = a1; success = a2; error = a3; break;
case 2:
case 1:
if (isFunction(a1)) {
success = a1;
error = a2;
} else {
params = a1;
success = a2 || noop;
}
case 0: break;
default:
throw "Expected between 1-3 arguments [params, success, error], got " +
arguments.length + " arguments.";
}
var data = hasBody ? this : undefined;
Resource[name].call(this, params, data, success, error);
};
});
return Resource;
}
return ResourceFactory;
}]);
})(window, window.angular);
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document, undefined) {
'use strict';
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
function fromCharCode(code) {return String.fromCharCode(code);}
var Error = window.Error,
/** holds major version number for IE or NaN for real browsers */
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isObject(obj) && isNumber(obj.length)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value) };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
*/
function extend(dst) {
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value == 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value != 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value != null && typeof value == 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value == 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value == 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value == 'function';}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
}
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw Error("Can't copy equivalent objects or arrays");
if (isArray(source)) {
while(destination.length) {
destination.pop();
}
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
*
* During a property comparision, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only be identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
keySet = {};
for(key in o1) {
if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
return false;
}
keySet[key] = true;
}
for(key in o2) {
if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (/^\$+/.test(key)) {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
return jqLite('<div>').append(element).html().
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp on optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap on application. Only
* one directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* ot the root of the page.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
element = jqLite(element);
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(
['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator){
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error of the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configure information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Option configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider.directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which needs to be performed when the injector with
* with the current module is finished loading.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.0.0', // all of these placeholder strings will be replaced by rake's
major: 1, // compile task
minor: 0,
dot: 0,
codeName: 'temporal-domination'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0}
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/)
* - [children()](http://api.jquery.com/children/)
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name.
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/)
* - [parent()](http://api.jquery.com/parent/)
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [unbind()](http://api.jquery.com/unbind/)
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
*
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch() {
var list = [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
events = element.data('events');
if ( (fns = events && events.$destroy) ) {
forEach(fns, function(fn){
fn.handler();
});
}
} else {
fireEvent = !fireEvent;
}
for(childIndex = 0, childLength = (children = element.children()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw Error('selectors not implemented');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteUnbind(element, type, fn) {
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
JQLiteUnbind(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data = JQLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function JQLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType == 9) {
element = element.find('html');
}
while (element.length) {
if (value = element.data(name)) return value;
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
JQLite(window).bind('load', trigger); // fallback to window.onload for others
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form'.split(','), function(value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController ,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: extend((msie < 9)
? function(element, value) {
if (element.nodeType == 1 /** Element */) {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
if (fn === JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
function createEventHandler(element, events) {
var eventHandler = function (event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function bindFn(element, type, fn){
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events = {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var counter = 0;
events.mouseenter = [];
events.mouseleave = [];
bindFn(element, 'mouseover', function(event) {
counter++;
if (counter == 1) {
handle(event, 'mouseenter');
}
});
bindFn(element, 'mouseout', function(event) {
counter --;
if (counter == 0) {
handle(event, 'mouseleave');
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type]
}
eventFns.push(fn);
});
},
unbind: JQLiteUnbind,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeName != '#text')
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes;
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
return element.nextSibling;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* A map where multiple values can be added to the same key such that they form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype = {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick of your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn')
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following ways are all valid way of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $inject.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $inject.invoke(explicit);
*
* // inline
* $inject.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments come form the function annotation.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is used by the injector
* to determine which services need to be injected into the function when the function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
* the function into a string using `toString()` method and extracting the argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
* are supported.
*
* # The `$injector` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
* inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tempFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with the `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* });
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* )};
*
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instanciated. The function is called using the {@link AUTO.$injector#invoke
* injector.invoke} method and is therefore fully injectable. Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = createInternalInjector(providerCache, function() {
throw Error("Unknown provider: " + path.join(' <- '));
}),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
try {
for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = invokeArgs[0] == '$injector'
? providerInjector
: providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + String(module[module.length - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !== 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args = [],
$inject = annotate(fn),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, path)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a') result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $locaiton.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function() {return $location.hash();}, function() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base');
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
if (lastCookies.length > 20) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " +
"were already set (" + lastCookies.length + " > 20 )");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1));
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a defered task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get = ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects.
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
* - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key) — Removes a key-value pair from the cache.
* - `{void}` `removeAll() — Removes all cached values.
* - `{void}` `destroy() — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw Error('cacheId ' + cacheId + ' taken');
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link ng.$compileProvider.directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directive with compiler
*
* @param {string} name name of the directive.
* @param {function} directiveFactory An injectable directive factory function.
* @returns {ng.$compileProvider} Self for chaining.
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ';
/**
* @ngdoc function
* @name ng.$compileProvider.directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
* info.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
$$observers = this.$$observers;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
return compile;
//================================
function compile($compileNode, transcludeFn, maxPriority) {
if (!($compileNode instanceof jqLite)) {
// jquery always rewraps, where as we need to preserve the original selector so that we can modify it.
$compileNode = jqLite($compileNode);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNode, function(node, index){
if (node.nodeType == 3 /* text node */) {
$compileNode[index] = jqLite(node).wrap('<span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority);
return function(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn
? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!!
: $compileNode;
$linkNode.data('$scope', scope);
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
* rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
: null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = nodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
return transcludeFn(transcludeScope, cloneFn).
bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node ands them to the directive collection which is sorted.
*
* @param node node to search
* @param directives an array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs the shared attrs object which is used to populate the normalized attributes.
* @param {number=} max directive priority
*/
function collectDirectives(node, directives, attrs, maxPriority) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
attr = nAttrs[j];
if (attr.specified) {
name = attr.name;
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name == 'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority);
}
}
// use class as directive
className = node.className;
if (isString(className)) {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Once the directives have been collected their compile functions is executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached..
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement} $rootElement If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace widgets on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolatedScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolatedScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = jqLite(compileNode);
$compileNode = templateAttrs.$$element =
jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->');
compileNode = $compileNode[0];
replaceWith($rootElement, jqLite($template[0]), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directiveValue = directive.template) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
$template = jqLite('<div>' + trim(directiveValue) + '</div>').contents();
compileNode = $template[0];
if (directive.replace) {
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
}
replaceWith($rootElement, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require = directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data', optional = false;
if (isString(require)) {
while((value = require.charAt(0)) == '^' || value == '?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require + 'Controller');
if (!value && !optional) {
throw Error("No controller: " + require);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newScopeDirective && isObject(newScopeDirective.scope)) {
var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
var parentScope = scope.$parent || scope;
forEach(newScopeDirective.scope, function(definiton, scopeName) {
var match = definiton.match(LOCAL_REGEXP) || [],
attrName = match[2]|| scopeName,
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = parentScope;
break;
}
case '=': {
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
' (directive: ' + newScopeDirective.name + ')');
};
lastValue = scope[scopeName] = parentGet(parentScope);
scope.$watch(function() {
var parentValue = parentGet(parentScope);
if (parentValue !== scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, lastValue = scope[scopeName]);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope, locals);
}
break;
}
default: {
throw Error('Invalid isolate scope definition for directive ' +
newScopeDirective.name + ': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority) {
var match = false;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i<ii; i++) {
try {
directive = directives[i];
if ( (maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
tDirectives.push(directive);
match = true;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
controller: null, templateUrl: null, transclude: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
if (replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn);
while(linkQueue.length) {
var controller = linkQueue.pop(),
linkRootElement = linkQueue.pop(),
beforeTemplateLinkNode = linkQueue.pop(),
scope = linkQueue.pop(),
linkNode = compileNode;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective.name + ', ' +
directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function(scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function(value) {
node[0].nodeValue = value;
});
})
});
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (name === 'class') {
// we need to interpolate classes again, in the case the element was replaced
// and therefore the two class attrs got merged - we want to interpolate the result
interpolateFn = $interpolate(attr[name], true);
}
attr[name] = undefined;
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function(value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, $element, newNode) {
var oldNode = $element[0],
parent = oldNode.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == oldNode) {
$rootElement[i] = newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] = oldNode[jqLite.expando];
$element[0] = newNode;
}
}];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:DiRective
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which contains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if(isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler}
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log){
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* @ngdoc function
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Deafults to `{{` and `}}`.
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @prop {string=} value new value to set the starting symbol to.
*/
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @prop {string=} value new value to set the ending symbol to.
*/
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return startSymbol;
}
};
this.$get = ['$parse', function($parse) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @returns {function(context)} an interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
return function(text, mustHaveExpression) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while(index < length) {
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
(index != startIndex) && parts.push(text.substring(index, startIndex));
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
};
fn.exp = text;
fn.parts = parts;
return fn;
}
};
}];
}
var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url);
match = {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) !== 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(newAbsoluteUrl) {
var match = matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype = {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=} search New search params - string or hash object
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) : search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl = $browser.url(),
initUrlParts = matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath = $browser.baseHref() || '/';
pathPrefix = pathPrefixFromBase(basePath);
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location = new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location = new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
}
} else {
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
}
$rootElement.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
if (elm[0] === $rootElement[0]) return;
elm = elm.parent();
}
var absHref = elm.prop('href'),
rewrittenUrl = $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), $location.$$replace);
$location.$$replace = false;
afterLocationChange(oldUrl);
}
});
}
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<doc:example>
<doc:source>
<script>
function LogCtrl($log) {
this.$log = $log;
this.message = 'Hello World!';
}
</script>
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $LogProvider(){
this.$get = ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}];
}
var OPERATORS = {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);},
'-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName;
while (index < text.length) {
var ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
var ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function(self, locals){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(self, locals){
return left.assign(self, right(self, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
return extend(
function(self, locals) {
return getter(object(self, locals), locals);
},
{
assign:function(self, value, locals) {
return setter(object(self, locals), field, value);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(self, locals){
var args = [],
context = contextGetter ? contextGetter(self, locals) : self;
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
var fnPtr = fn(self, locals) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object () {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return function(self, locals){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
var value = keyValue.value(self, locals);
object[keyValue.key] = value;
}
return object;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accesbile by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
};
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
: function(scope, locals) {
var i = 0, val
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against (Topically a scope object).
* * `locals`: local variables context object, useful for overriding values in `context`.
*
* The return function also has an `assign` property, if the expression is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise apis are to
* asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* );
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as apis
* that can be used for signaling the successful or unsuccessful completion of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
* or rejected calls one of the success or error callbacks asynchronously as soon as the result
* is available. The callbacks are called with a single argument the result or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api of a promise returns a new derived promise, it is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and it's value will be
* // the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful apis like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - $q promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref = function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with on object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
var when = function(value, callback, errback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = promises.length,
results = [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example.
*/
function $RouteProvider(){
var routes = {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exacly match the
* route definition.
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{function()=}` – Controller fn that should be associated with newly
* created scope.
* - `template` – `{string=}` – html template as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` – `{string=}` – path to an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, they will be
* resolved and converted to a value before the controller is instantiated and the
* `$aftreRouteChange` event is fired. The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
routes[path] = extend({reloadOnSearch: true}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] = {redirectTo: path};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occurs.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var matcher = switchRouteMatcher,
forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
params = [],
dst = {};
forEach(when.split(/\W/), function(param) {
if (param) {
var paramRegExp = new RegExp(":" + param + "([\\W])");
if (regex.match(paramRegExp)) {
regex = regex.replace(paramRegExp, "([^\\/]*)$1");
params.push(param);
}
}
});
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$route === last.$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys = [],
values = [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value));
});
if (isDefined(template = next.template)) {
} else if (isDefined(template = next.templateUrl)) {
template = $http.get(template, {cache: $templateCache}).
then(function(response) { return response.data; });
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals = {};
forEach(values, function(value, index) {
locals[keys[index]] = value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next == $route.current) {
if (next) {
next.locals = locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', next, last);
}
}, function(error) {
if (next == $route.current) {
$rootScope.$broadcast('$routeChangeError', next, last, error);
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = matcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = valueFn({});
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope ware heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive from speed as well as memory:
* - no closures, instead ups prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the begging (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using array would be slow since inserts in meddle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iteration the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
angular.injector(['ng']).invoke(function($rootScope) {
var scope = $rootScope.$new();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
this.greeting = this.salutation + ' ' + this.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$asyncQueue = [];
this.$$listeners = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate if true then the scoped does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not se parent scope properties.
* When creating widgets it is useful for the widget to not accidently read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isFunction(isolate)) {
// TODO: remove at some point
throw Error('API-CHANGE: Use $controller to instantiate controllers.');
}
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$asyncQueue = [];
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression' are not equal (with the exception of the initial run
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 100 to prevent infinity loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather then for refference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider.directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider.directive directives}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
counter = counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty = false;
current = target;
do {
asyncQueue = current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(dirty && !(ttl--)) {
clearPhase();
throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Remove the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it chance to
* perform any necessary cleanup.
*/
$destroy: function() {
if ($rootScope == this) return; // we can't remove the root node;
var parent = this.$parent;
this.$broadcast('$destroy');
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating engular expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
* event life cycle.
*
* @param {string} name Event name to listen on.
* @param {function(event)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*
* The event listener function format is: `function(event)`. The `event` object passed into the
* listener has the following attributes
*
* - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - {Scope}: the current scope which is handling the event.
* - `name` - {string}: Name of the event.
* - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation
* (available only for events that were `$emit`-ed).
* - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true.
* - `defaultPrevented` - {boolean}: true if `preventDefault` was called.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
arrayRemove(namedListeners, listener);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1);
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
forEach(current.$$listeners[name], function(listener) {
try {
listener.apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
});
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw Error($rootScope.$$phase + ' already in progress');
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's uniqueue we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $config = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data, true);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {'Content-Type': 'application/json;charset=utf-8'},
put: {'Content-Type': 'application/json;charset=utf-8'}
}
};
var providerResponseInterceptors = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http'),
responseInterceptors = [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor)
? $injector.get(interceptor)
: $injector.invoke(interceptor)
);
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBacked
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patters this doesn't matter much, for advanced usage,
* it is important to familiarize yourself with these apis and guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an http request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with status
* // code outside of the <200, 400) range
* });
* </pre>
*
* Since the returned value of calling the $http function is a Promise object, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the api signature and type info below for more
* details.
*
*
* # Shortcut methods
*
* Since all invocation of the $http service require definition of the http method and url and
* POST and PUT requests require response body/data to be provided as well, shortcut methods
* were created to simplify using the api:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain http headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from this configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with name equal to the lower-cased http method name, e.g.
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
* fassion as described above.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - if the `data` property of the request config object contains an object, serialize it into
* JSON format.
*
* Response transformations:
*
* - if XSRF prefix is detected, strip it (see Security Considerations section below)
* - if json response is detected, deserialize it using a JSON parser
*
* To override these transformation locally, specify transform functions as `transformRequest`
* and/or `transformResponse` properties of the config object. To globally override the default
* transforms, override the `$httpProvider.defaults.transformRequest` and
* `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`.
*
*
* # Caching
*
* To enable caching set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same url that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response for the first request.
*
*
* # Response interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability} allows third party web-site to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides following mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
* runs on your domain could read the cookie, your server can be assured that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have read the token. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript making
* up its own tokens). We recommend that the token is a digest of your site's authentication
* cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
* `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
* - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number}` – timeout in milliseconds.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(config) {
config.method = uppercase(config.method);
var reqTransformFn = config.transformRequest || $config.transformRequest,
respTransformFn = config.transformResponse || $config.transformResponse,
defHeaders = $config.headers,
reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
defHeaders.common, defHeaders[lowercase(config.method)], config.headers),
reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise = sendReq(config, reqData, reqHeaders);
// transform future response
promise = promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise = interceptor(promise);
});
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers, respTransformFn)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = $config;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if (config.cache && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache : defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
$rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (isObject(value)) {
value = toJson(value);
}
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
completeRequest(
callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders());
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status = -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
}
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a the timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, who's execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {*} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is annotated with dependencies and is
* responsible for creating a the filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression | [ filter_name ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"å><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:search">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!(array instanceof Array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text){
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path = key;
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
if (numStr.indexOf('e') !== -1) {
formatedText = numStr;
} else {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var offset = date.getTimezoneOffset();
return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ).
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.limit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
<tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!(array instanceof Array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/*
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* <a href="" ng-click="model.$save()">Save</a>
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
// turn <a href ng-click="..">link</a> into a link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href) {
attr.$set('href', '');
}
return function(scope, element) {
element.bind('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe('');
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
<select id="select" ng-multiple="checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-href are interpolated
forEach(['src', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect
if (msie) element.prop(attrName, value);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containg forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {};
// init state
form.$name = attrs.name;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
form.$addControl = function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
};
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveDir = {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
formElement.bind('submit', function(event) {
event.preventDefault();
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
scope[alias] = controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] = undefined;
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
var formDirective = valueFn(formDirectiveDir);
var ngFormDirective = valueFn(extend(copy(formDirectiveDir), {restrict: 'EAC'}));
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\w*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less then `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<span class="error" ng-show="myForm.list.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = trim(element.val());
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.bind('input', listener);
} else {
var timeout;
element.bind('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
});
// if user paste into input using mouse, we need "change" event to catch it
element.bind('change', listener);
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern = new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.bind('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
* all of these functions to sanitize / convert the value as well as validate.
*
* @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
*
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
' (' + startingTag($element) + ')');
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
if ($error[validationErrorKey] === !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `formatters` and if resulted value is valid, updates the model and
* calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl = this;
$scope.$watch(ngModelGet, function(value) {
// ignore change from view
if (ctrl.$modelValue === value) return;
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while(idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-seperated string into an array of strings.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value) && !equals(parse(ctrl.$viewValue), value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function(value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when
* it's desirable to put bindings into template that is momentarily displayed by the browser in its
* raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
* bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
scope.$watch(attr[name], function(newVal, oldVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && (newVal !== oldVal)) {
if (isObject(oldVal) && !isArray(oldVal))
oldVal = map(oldVal, function(v, k) { if (v) return k });
element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal);
}
if (isObject(newVal) && !isArray(newVal))
newVal = map(newVal, function(v, k) { if (v) return k });
if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); }
}, true);
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the classes
* new classes are added.
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class {
color: red;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` works exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], .ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the `{@link ng.$route}`
* service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update.
<doc:example>
<doc:source>
<script>
function SettingsController($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div ng-controller="SettingsController">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
* This directive should be used on the root element of the application (typically the `<html>`
* element or other element with the {@link ng.directive:ngApp ngApp}
* directive).
*
* If enabled the performance of template expression evaluator will suffer slightly, so don't enable
* this mode unless you need it.
*
* @element html
*/
var ngCspDirective = ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.bind(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example>
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]').text()).toEqual('');
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile',
function($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
scope.$watch(srcExp, function(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
if (childScope) childScope.$destroy();
childScope = scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp),
whensExpFns = {};
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + offset + '}}'));
});
scope.$watch(function() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
* * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
* * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective = ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr){
var expression = attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
lhs + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is an array of objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be returned from the iterator.
// We expect this to be a rare case.
var lastOrder = new HashQueueMap();
scope.$watch(function(scope){
var index, length,
collection = scope.$eval(rhs),
collectionLength = size(collection, true),
childScope,
// Same as lastOrder but it has the current state. It will become the
// lastOrder on the next iteration.
nextOrder = new HashQueueMap(),
key, value, // key/value of iteration
array, last, // last object information {scope, element, index}
cursor = iterStartElement; // current position of the node
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order of iteration over obj props
array = [];
for(key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
array.push(key);
}
}
array.sort();
} else {
array = collection || [];
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = array.length; index < length; index++) {
key = (collection === array) ? index : array[index];
value = collection[key];
last = lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = last.scope;
nextOrder.push(value, last);
if (index === last.index) {
// do nothing
cursor = last.element;
} else {
// existing item which got moved
last.index = index;
// This may be a noop, if the element is next, but I don't know of a good way to
// figure this out, since it would require extra DOM access, so let's just hope that
// the browsers realizes that it is noop, and treats it as such.
cursor.after(last.element);
cursor = last.element;
}
} else {
// new item which we don't know about
childScope = scope.$new();
}
childScope[valueIdent] = value;
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === (collectionLength - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone){
cursor.after(clone);
last = {
scope: childScope,
element: (cursor = clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array = lastOrder[key];
while(array.length) {
value = array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder = nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngShow, function(value){
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion
* of the HTML conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngHide, function(value){
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* Conditionally change the DOM structure.
*
* @usageContent
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</script>
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH = 'ng-switch';
var ngSwitchDirective = valueFn({
restrict: 'EA',
compile: function(element, attr) {
var watchExpr = attr.ngSwitch || attr.on,
cases = {};
element.data(NG_SWITCH, cases);
return function(scope, element){
var selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = selectedScope = null;
}
if ((selectedTransclude = cases['!' + value] || cases['?'])) {
scope.$eval(attr.change);
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
});
}
});
};
}
});
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['!' + attrs.ngSwitchWhen] = transclude;
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['?'] = transclude;
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { title:'bind' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$transclude', '$element', function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.template = {{$route.current.template}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll, $compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link = $compile(element.contents()),
current = $route.current,
controller;
lastScope = current.scope = scope.$new();
if (current.controller) {
locals.$scope = lastScope;
controller = $controller(current.controller, locals);
element.contents().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*˝˝
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can currently
* be bound to string values only.
*
* @param {string} name assignable expression to data-bind to.
* @param {string=} required The control is considered valid only if value is entered.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({ terminal: true });
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
nullModelCtrl = {$setViewValue: noop};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
}
self.addOption = function(value) {
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value == '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.children(), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.bind('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.children(), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] = key;
locals[valueName] = collection[key];
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element;
if (multiple) {
selectedSet = new HashMap(modelValue);
} else if (modelValue === null || nullOption) {
// if we are not multiselect, and we are null then we have to add the nullOption
optionGroups[''].push({selected:modelValue === null, id:'', label:''});
selectedSet = true;
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
} else {
selected = modelValue === valueFn(scope, locals);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: displayFn(scope, locals) || '', // what will be seen by the user
selected: selected // determine if we should be selected
});
}
if (!multiple && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
if (existingOption.element.selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
require: '^select',
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr, selectCtrl) {
if (selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.bind('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
//try to bind to jquery now so that one can write angular.element().read()
//but we will rebind on bootstrap again.
bindJQuery();
publishExternalAPI(angular);
jqLite(document).ready(function() {
angularInit(document, bootstrap);
});
})(window, document);
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak{display:none;}ng\\:form{display:block;}</style>');
|
JavaScript
|
/*!
* jQuery JavaScript Library v1.7.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Wed Mar 21 12:46:34 2012 -0700
*/
(function( window, undefined ) {
'use strict';
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
fired = true;
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
pixelMargin: true
};
// jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
paddingMarginBorderVisibility, paddingMarginBorder,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
paddingMarginBorder = "padding:0;margin:0;border:";
positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
"<table " + style + "' cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
div.innerHTML = "";
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.width = div.style.padding = "1px";
div.style.border = 0;
div.style.overflow = "hidden";
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div style='width:5px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
}
div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
if ( window.getComputedStyle ) {
div.style.marginTop = "1%";
support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
}
if ( typeof container.style.zoom !== "undefined" ) {
container.style.zoom = 1;
}
body.removeChild( container );
marginDiv = div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise( object );
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
quick: selector && quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process events on disabled elements (#6911, #8165)
if ( cur.disabled !== true ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( var type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
Expr.match.globalPOS = origPOS;
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.globalPOS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery.clean( arguments );
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery.clean(arguments) );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
null;
}
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
type: "GET",
global: false,
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
// Clear flags for bubbling special change/submit events, they must
// be reattached when the newly cloned events are first activated
dest.removeAttribute( "_submit_attached" );
dest.removeAttribute( "_change_attached" );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType, script, j,
ret = [];
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div"),
safeChildNodes = safeFragment.childNodes,
remove;
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Clear elements from DocumentFragment (safeFragment or otherwise)
// to avoid hoarding elements. Fixes #11356
if ( div ) {
div.parentNode.removeChild( div );
// Guard against -1 index exceptions in FF3.6
if ( safeChildNodes.length > 0 ) {
remove = safeChildNodes[ safeChildNodes.length - 1 ];
if ( remove && remove.parentNode ) {
remove.parentNode.removeChild( remove );
}
}
}
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
script = ret[i];
if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
} else {
if ( script.nodeType === 1 ) {
var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( script );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
rrelNum = /^([\-+])=([\-+.\de]+)/,
rmargin = /^margin/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
// order is important!
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {},
ret, name;
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// DEPRECATED in 1.3, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle, width,
style = elem.style;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
// A tribute to the "awesome hack by Dean Edwards"
// WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
// which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
width = style.width;
style.width = ret;
ret = computedStyle.width;
style.width = width;
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( rnumnonpx.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
i = name === "width" ? 1 : 0,
len = 4;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i += 2 ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i += 2 ) {
val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
}
}
}
return val + "px";
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWidthOrHeight( elem, name, extra );
} else {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
}
}
},
set: function( elem, value ) {
return rnum.test( value ) ?
value + "px" :
value;
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "margin-right" );
} else {
return elem.style.marginRight;
}
});
}
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( (display === "" && jQuery.css(elem, "display") === "none") ||
!jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e, hooks, replace,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
// first pass over propertys to expand / normalize
for ( p in prop ) {
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
replace = hooks.expand( prop[ name ] );
delete prop[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'p' from above because we have the correct "name"
for ( p in replace ) {
if ( ! ( p in prop ) ) {
prop[ p ] = replace[ p ];
}
}
}
}
for ( name in prop ) {
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p ) {
return p;
},
swing: function( p ) {
return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
if ( self.options.hide ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
} else if ( self.options.show ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.end );
}
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Ensure props that can't be negative don't go there on undershoot easing
jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
// exclude marginTop, marginLeft, marginBottom and marginRight from this list
if ( prop.indexOf( "margin" ) ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var getOffset,
rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
getOffset = function( elem, doc, docElem, box ) {
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow( doc ),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
getOffset = function( elem, doc, docElem ) {
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var elem = this[0],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return null;
}
if ( elem === doc.body ) {
return jQuery.offset.bodyOffset( elem );
}
return getOffset( elem, doc, doc.documentElement );
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, null );
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document){
var _jQuery = window.jQuery.noConflict(true);
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
function fromCharCode(code) {return String.fromCharCode(code);}
var Error = window.Error,
/** holds major version number for IE or NaN for real browsers */
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isObject(obj) && isNumber(obj.length)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value) };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
*/
function extend(dst) {
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value == 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value != 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value != null && typeof value == 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value == 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value == 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value == 'function';}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
}
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw Error("Can't copy equivalent objects or arrays");
if (isArray(source)) {
while(destination.length) {
destination.pop();
}
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
*
* During a property comparision, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only be identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
keySet = {};
for(key in o1) {
if (key.charAt(0) !== '$' && !isFunction(o1[key]) && !equals(o1[key], o2[key])) {
return false;
}
keySet[key] = true;
}
for(key in o2) {
if (!keySet[key] && key.charAt(0) !== '$' && !isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (/^\$+/.test(key)) {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
return jqLite('<div>').append(element).html().
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom mehtod because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace((pctEncodeSpaces ? null : /%20/g), '+');
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp on optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap on application. Only
* one directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* ot the root of the page.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
element = jqLite(element);
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(
['$rootScope', '$rootElement', '$compile', '$injector', function(scope, element, compile, injector){
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator){
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error of the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configure information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Option configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider.directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which needs to be performed when the injector with
* with the current module is finished loading.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.0.0', // all of these placeholder strings will be replaced by rake's
major: 1, // compile task
minor: 0,
dot: 0,
codeName: 'temporal-domination'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0}
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/)
* - [children()](http://api.jquery.com/children/)
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name.
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/)
* - [parent()](http://api.jquery.com/parent/)
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [unbind()](http://api.jquery.com/unbind/)
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular privides an additional method to both jQuery and jQuery lite:
*
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch() {
var list = [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
events = element.data('events');
if ( (fns = events && events.$destroy) ) {
forEach(fns, function(fn){
fn.handler();
});
}
} else {
fireEvent = !fireEvent;
}
for(childIndex = 0, childLength = (children = element.children()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw Error('selectors not implemented');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteUnbind(element, type, fn) {
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
JQLiteUnbind(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data = JQLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, selector) {
if (selector) {
forEach(selector.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function JQLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType == 9) {
element = element.find('html');
}
while (element.length) {
if (value = element.data(name)) return value;
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
JQLite(window).bind('load', trigger); // fallback to window.onload for others
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form'.split(','), function(value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController ,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: extend((msie < 9)
? function(element, value) {
if (element.nodeType == 1 /** Element */) {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
if (fn === JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
function createEventHandler(element, events) {
var eventHandler = function (event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function bindFn(element, type, fn){
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events = {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var counter = 0;
events.mouseenter = [];
events.mouseleave = [];
bindFn(element, 'mouseover', function(event) {
counter++;
if (counter == 1) {
handle(event, 'mouseenter');
}
});
bindFn(element, 'mouseout', function(event) {
counter --;
if (counter == 0) {
handle(event, 'mouseleave');
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type]
}
eventFns.push(fn);
});
},
unbind: JQLiteUnbind,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeName != '#text')
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes;
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
return element.nextSibling;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* A map where multiple values can be added to the same key such that they form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype = {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick of your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn')
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following ways are all valid way of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $inject.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $inject.invoke(explicit);
*
* // inline
* $inject.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments come form the function annotation.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is used by the injector
* to determine which services need to be injected into the function when the function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
* the function into a string using `toString()` method and extracting the argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
* are supported.
*
* # The `$injector` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
* inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tempFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with the `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* });
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* )};
*
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instanciated. The function is called using the {@link AUTO.$injector#invoke
* injector.invoke} method and is therefore fully injectable. Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = createInternalInjector(providerCache, function() {
throw Error("Unknown provider: " + path.join(' <- '));
}),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
try {
for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = invokeArgs[0] == '$injector'
? providerInjector
: providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + String(module[module.length - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !== 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args = [],
$inject = annotate(fn),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key, path)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a') result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $locaiton.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function() {return $location.hash();}, function() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base');
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : href;
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
if (lastCookies.length > 20) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because too many cookies " +
"were already set (" + lastCookies.length + " > 20 )");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
lastCookies[unescape(cookie.substring(0, index))] = unescape(cookie.substring(index + 1));
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a defered task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get = ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects.
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
* - `{{*}} `get({string} key) — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key) — Removes a key-value pair from the cache.
* - `{void}` `removeAll() — Removes all cached values.
* - `{void}` `destroy() — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw Error('cacheId ' + cacheId + ' taken');
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link ng.$compileProvider.directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directive with compiler
*
* @param {string} name name of the directive.
* @param {function} directiveFactory An injectable directive factory function.
* @returns {ng.$compileProvider} Self for chaining.
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ';
/**
* @ngdoc function
* @name ng.$compileProvider.directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
* info.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
$$observers = this.$$observers;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
return compile;
//================================
function compile($compileNode, transcludeFn, maxPriority) {
if (!($compileNode instanceof jqLite)) {
// jquery always rewraps, where as we need to preserve the original selector so that we can modify it.
$compileNode = jqLite($compileNode);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNode, function(node, index){
if (node.nodeType == 3 /* text node */) {
$compileNode[index] = jqLite(node).wrap('<span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNode, transcludeFn, $compileNode, maxPriority);
return function(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn
? JQLitePrototype.clone.call($compileNode) // IMPORTANT!!!
: $compileNode;
$linkNode.data('$scope', scope);
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
* rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
: null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn;
for(var i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = nodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
return transcludeFn(transcludeScope, cloneFn).
bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node ands them to the directive collection which is sorted.
*
* @param node node to search
* @param directives an array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs the shared attrs object which is used to populate the normalized attributes.
* @param {number=} max directive priority
*/
function collectDirectives(node, directives, attrs, maxPriority) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
attr = nAttrs[j];
if (attr.specified) {
name = attr.name;
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name == 'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority);
}
}
// use class as directive
className = node.className;
if (isString(className)) {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Once the directives have been collected their compile functions is executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached..
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement} $rootElement If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace widgets on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, $rootElement) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolatedScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope', newIsolatedScopeDirective, directive, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolatedScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = jqLite(compileNode);
$compileNode = templateAttrs.$$element =
jqLite('<!-- ' + directiveName + ': ' + templateAttrs[directiveName] + ' -->');
compileNode = $compileNode[0];
replaceWith($rootElement, jqLite($template[0]), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directiveValue = directive.template) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
$template = jqLite('<div>' + trim(directiveValue) + '</div>').contents();
compileNode = $template[0];
if (directive.replace) {
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
}
replaceWith($rootElement, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, $rootElement, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require = directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data', optional = false;
if (isString(require)) {
while((value = require.charAt(0)) == '^' || value == '?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require + 'Controller');
if (!value && !optional) {
throw Error("No controller: " + require);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newScopeDirective && isObject(newScopeDirective.scope)) {
var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
var parentScope = scope.$parent || scope;
forEach(newScopeDirective.scope, function(definiton, scopeName) {
var match = definiton.match(LOCAL_REGEXP) || [],
attrName = match[2]|| scopeName,
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = parentScope;
break;
}
case '=': {
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
' (directive: ' + newScopeDirective.name + ')');
};
lastValue = scope[scopeName] = parentGet(parentScope);
scope.$watch(function() {
var parentValue = parentGet(parentScope);
if (parentValue !== scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, lastValue = scope[scopeName]);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope, locals);
}
break;
}
default: {
throw Error('Invalid isolate scope definition for directive ' +
newScopeDirective.name + ': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority) {
var match = false;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i<ii; i++) {
try {
directive = directives[i];
if ( (maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
tDirectives.push(directive);
match = true;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
controller: null, templateUrl: null, transclude: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
if (replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, $compileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn = compileNodes($compileNode.contents(), childTranscludeFn);
while(linkQueue.length) {
var controller = linkQueue.pop(),
linkRootElement = linkQueue.pop(),
beforeTemplateLinkNode = linkQueue.pop(),
scope = linkQueue.pop(),
linkNode = compileNode;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective.name + ', ' +
directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function(scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function(value) {
node[0].nodeValue = value;
});
})
});
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (name === 'class') {
// we need to interpolate classes again, in the case the element was replaced
// and therefore the two class attrs got merged - we want to interpolate the result
interpolateFn = $interpolate(attr[name], true);
}
attr[name] = undefined;
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function(value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, $element, newNode) {
var oldNode = $element[0],
parent = oldNode.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == oldNode) {
$rootElement[i] = newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] = oldNode[jqLite.expando];
$element[0] = newNode;
}
}];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:DiRective
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which contains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if(isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler}
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log){
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* @ngdoc function
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Deafults to `{{` and `}}`.
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @prop {string=} value new value to set the starting symbol to.
*/
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @prop {string=} value new value to set the ending symbol to.
*/
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return startSymbol;
}
};
this.$get = ['$parse', function($parse) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @returns {function(context)} an interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
return function(text, mustHaveExpression) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while(index < length) {
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
(index != startIndex) && parts.push(text.substring(index, startIndex));
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
};
fn.exp = text;
fn.parts = parts;
return fn;
}
};
}];
}
var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?([\w\.-]*)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url);
match = {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) !== 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(newAbsoluteUrl) {
var match = matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype = {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=} search New search params - string or hash object
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) : search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl = $browser.url(),
initUrlParts = matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath = $browser.baseHref() || '/';
pathPrefix = pathPrefixFromBase(basePath);
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location = new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location = new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
}
} else {
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
}
$rootElement.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
if (elm[0] === $rootElement[0]) return;
elm = elm.parent();
}
var absHref = elm.prop('href'),
rewrittenUrl = $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), $location.$$replace);
$location.$$replace = false;
afterLocationChange(oldUrl);
}
});
}
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<doc:example>
<doc:source>
<script>
function LogCtrl($log) {
this.$log = $log;
this.message = 'Hello World!';
}
</script>
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $LogProvider(){
this.$get = ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}];
}
var OPERATORS = {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)+(isDefined(b)?b:0);},
'-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName;
while (index < text.length) {
var ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
var ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function(self, locals){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(self, locals){
return left.assign(self, right(self, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
return extend(
function(self, locals) {
return getter(object(self, locals), locals);
},
{
assign:function(self, value, locals) {
return setter(object(self, locals), field, value);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(self, locals){
var args = [],
context = contextGetter ? contextGetter(self, locals) : self;
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
var fnPtr = fn(self, locals) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object () {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return function(self, locals){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
var value = keyValue.value(self, locals);
object[keyValue.key] = value;
}
return object;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accesbile by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
};
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
: function(scope, locals) {
var i = 0, val
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against (Topically a scope object).
* * `locals`: local variables context object, useful for overriding values in `context`.
*
* The return function also has an `assign` property, if the expression is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise apis are to
* asynchronous programing what `try`, `catch` and `throw` keywords are to synchronous programing.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* );
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred apis make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as apis
* that can be used for signaling the successful or unsuccessful completion of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
* or rejected calls one of the success or error callbacks asynchronously as soon as the result
* is available. The callbacks are called with a single argument the result or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api of a promise returns a new derived promise, it is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and it's value will be
* // the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful apis like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - $q promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - Q has many more features that $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref = function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with on object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
var when = function(value, callback, errback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value coresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = promises.length,
results = [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example.
*/
function $RouteProvider(){
var routes = {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exacly match the
* route definition.
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{function()=}` – Controller fn that should be associated with newly
* created scope.
* - `template` – `{string=}` – html template as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` – `{string=}` – path to an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, they will be
* resolved and converted to a value before the controller is instantiated and the
* `$aftreRouteChange` event is fired. The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
routes[path] = extend({reloadOnSearch: true}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] = {redirectTo: path};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occurs.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var matcher = switchRouteMatcher,
forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
var regex = '^' + when.replace(/([\.\\\(\)\^\$])/g, "\\$1") + '$',
params = [],
dst = {};
forEach(when.split(/\W/), function(param) {
if (param) {
var paramRegExp = new RegExp(":" + param + "([\\W])");
if (regex.match(paramRegExp)) {
regex = regex.replace(paramRegExp, "([^\\/]*)$1");
params.push(param);
}
}
});
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$route === last.$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys = [],
values = [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isFunction(value) ? $injector.invoke(value) : $injector.get(value));
});
if (isDefined(template = next.template)) {
} else if (isDefined(template = next.templateUrl)) {
template = $http.get(template, {cache: $templateCache}).
then(function(response) { return response.data; });
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals = {};
forEach(values, function(value, index) {
locals[keys[index]] = value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next == $route.current) {
if (next) {
next.locals = locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', next, last);
}
}, function(error) {
if (next == $route.current) {
$rootScope.$broadcast('$routeChangeError', next, last, error);
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = matcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = valueFn({});
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope ware heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive from speed as well as memory:
* - no closures, instead ups prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the begging (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using array would be slow since inserts in meddle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iteration the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
angular.injector(['ng']).invoke(function($rootScope) {
var scope = $rootScope.$new();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
this.greeting = this.salutation + ' ' + this.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$asyncQueue = [];
this.$$listeners = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate if true then the scoped does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not se parent scope properties.
* When creating widgets it is useful for the widget to not accidently read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isFunction(isolate)) {
// TODO: remove at some point
throw Error('API-CHANGE: Use $controller to instantiate controllers.');
}
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$asyncQueue = [];
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression' are not equal (with the exception of the initial run
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 100 to prevent infinity loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register an `watchExpression` function with no `listener`. (Since `watchExpression`,
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { counter = counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather then for refference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Process all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider.directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider.directive directives}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
counter = counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty = false;
current = target;
do {
asyncQueue = current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(dirty && !(ttl--)) {
clearPhase();
throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Remove the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it chance to
* perform any necessary cleanup.
*/
$destroy: function() {
if ($rootScope == this) return; // we can't remove the root node;
var parent = this.$parent;
this.$broadcast('$destroy');
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating engular expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listen on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
* event life cycle.
*
* @param {string} name Event name to listen on.
* @param {function(event)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*
* The event listener function format is: `function(event)`. The `event` object passed into the
* listener has the following attributes
*
* - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - {Scope}: the current scope which is handling the event.
* - `name` - {string}: Name of the event.
* - `stopPropagation` - {function=}: calling `stopPropagation` function will cancel further event propagation
* (available only for events that were `$emit`-ed).
* - `preventDefault` - {function}: calling `preventDefault` sets `defaultPrevented` flag to true.
* - `defaultPrevented` - {boolean}: true if `preventDefault` was called.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
arrayRemove(namedListeners, listener);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1);
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
forEach(current.$$listeners[name], function(listener) {
try {
listener.apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
});
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw Error($rootScope.$$phase + ' already in progress');
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's uniqueue we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<input ng-init="$window = $service('$window'); greeting='Hello World!'" type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</doc:source>
<doc:scenario>
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $config = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data, true);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {'Content-Type': 'application/json;charset=utf-8'},
put: {'Content-Type': 'application/json;charset=utf-8'}
}
};
var providerResponseInterceptors = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http'),
responseInterceptors = [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor)
? $injector.get(interceptor)
: $injector.invoke(interceptor)
);
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBacked
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patters this doesn't matter much, for advanced usage,
* it is important to familiarize yourself with these apis and guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an http request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with status
* // code outside of the <200, 400) range
* });
* </pre>
*
* Since the returned value of calling the $http function is a Promise object, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the api signature and type info below for more
* details.
*
*
* # Shortcut methods
*
* Since all invocation of the $http service require definition of the http method and url and
* POST and PUT requests require response body/data to be provided as well, shortcut methods
* were created to simplify using the api:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain http headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$httpProvider.defaults.headers.post`: (header defaults for HTTP POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for HTTP PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from this configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with name equal to the lower-cased http method name, e.g.
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in a similar
* fassion as described above.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - if the `data` property of the request config object contains an object, serialize it into
* JSON format.
*
* Response transformations:
*
* - if XSRF prefix is detected, strip it (see Security Considerations section below)
* - if json response is detected, deserialize it using a JSON parser
*
* To override these transformation locally, specify transform functions as `transformRequest`
* and/or `transformResponse` properties of the config object. To globally override the default
* transforms, override the `$httpProvider.defaults.transformRequest` and
* `$httpProvider.defaults.transformResponse` properties of the `$httpProvider`.
*
*
* # Caching
*
* To enable caching set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same url that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response for the first request.
*
*
* # Response interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON Vulnerability} allows third party web-site to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSON#JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides following mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
* runs on your domain could read the cookie, your server can be assured that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on first HTTP GET request. On subsequent non-GET requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have read the token. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript making
* up its own tokens). We recommend that the token is a digest of your site's authentication
* cookie with {@link http://en.wikipedia.org/wiki/Rainbow_table salt for added security}.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
* `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
* - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number}` – timeout in milliseconds.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(config) {
config.method = uppercase(config.method);
var reqTransformFn = config.transformRequest || $config.transformRequest,
respTransformFn = config.transformResponse || $config.transformResponse,
defHeaders = $config.headers,
reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
defHeaders.common, defHeaders[lowercase(config.method)], config.headers),
reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise = sendReq(config, reqData, reqHeaders);
// transform future response
promise = promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise = interceptor(promise);
});
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers, respTransformFn)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = $config;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if (config.cache && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache : defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
$rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (isObject(value)) {
value = toJson(value);
}
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
completeRequest(
callback, status || xhr.status, xhr.responseText, xhr.getAllResponseHeaders());
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status = -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
}
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a the timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, who's execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to false skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {*} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is annotated with dependencies and is
* responsible for creating a the filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression | [ filter_name ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"å><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th><tr>
<tr ng-repeat="friend in friends | filter:search">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!(array instanceof Array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text){
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path = key;
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
if (numStr.indexOf('e') !== -1) {
formatedText = numStr;
} else {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize) formatedText += decimalSep + fraction.substr(0, fractionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var offset = date.getTimezoneOffset();
return padNumber(offset / 60, 2) + padNumber(Math.abs(offset % 60), 2);
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and it's
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ).
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} \-?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.limit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
<tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!(array instanceof Array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/*
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* <a href="" ng-click="model.$save()">Save</a>
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
// turn <a href ng-click="..">link</a> into a link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href) {
attr.$set('href', '');
}
return function(scope, element) {
element.bind('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe('');
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
<select id="select" ng-multiple="checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-href are interpolated
forEach(['src', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect
if (msie) element.prop(attrName, value);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containg forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `REQUIRED`, `URL` or `EMAIL`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {};
// init state
form.$name = attrs.name;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
form.$addControl = function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
};
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.REQUIRED">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.REQUIRED = {{!!myForm.$error.REQUIRED}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveDir = {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
formElement.bind('submit', function(event) {
event.preventDefault();
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
scope[alias] = controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] = undefined;
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
var formDirective = valueFn(formDirectiveDir);
var ngFormDirective = valueFn(extend(copy(formDirectiveDir), {restrict: 'EAC'}));
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\w*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less then `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater then `min`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<span class="error" ng-show="myForm.list.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = trim(element.val());
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.bind('input', listener);
} else {
var timeout;
element.bind('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
});
// if user paste into input using mouse, we need "change" event to catch it
element.bind('change', listener);
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern = new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.bind('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
* all of these functions to sanitize / convert the value as well as validate.
*
* @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
*
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
' (' + startingTag($element) + ')');
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
if ($error[validationErrorKey] === !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `formatters` and if resulted value is valid, updates the model and
* calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl = this;
$scope.$watch(ngModelGet, function(value) {
// ignore change from view
if (ctrl.$modelValue === value) return;
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while(idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-seperated string into an array of strings.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value) && !equals(parse(ctrl.$viewValue), value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function(value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* Once scenario in which the use of `ngBind` is prefered over `{{ expression }}` binding is when
* it's desirable to put bindings into template that is momentarily displayed by the browser in its
* raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
* bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
scope.$watch(attr[name], function(newVal, oldVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && (newVal !== oldVal)) {
if (isObject(oldVal) && !isArray(oldVal))
oldVal = map(oldVal, function(v, k) { if (v) return k });
element.removeClass(isArray(oldVal) ? oldVal.join(' ') : oldVal);
}
if (isObject(newVal) && !isArray(newVal))
newVal = map(newVal, function(v, k) { if (v) return k });
if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); }
}, true);
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the classes
* new classes are added.
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class {
color: red;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` works exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], .ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the `{@link ng.$route}`
* service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update.
<doc:example>
<doc:source>
<script>
function SettingsController($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div ng-controller="SettingsController">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
* This directive should be used on the root element of the application (typically the `<html>`
* element or other element with the {@link ng.directive:ngApp ngApp}
* directive).
*
* If enabled the performance of template expression evaluator will suffer slightly, so don't enable
* this mode unless you need it.
*
* @element html
*/
var ngCspDirective = ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.bind(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example>
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]').text()).toEqual('');
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile',
function($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
scope.$watch(srcExp, function(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
if (childScope) childScope.$destroy();
childScope = scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp),
whensExpFns = {};
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, '{{' + numberExp + '-' + offset + '}}'));
});
scope.$watch(function() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!whens[value]) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
* * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
* * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective = ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr){
var expression = attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
lhs + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is an array of objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be returned from the iterator.
// We expect this to be a rare case.
var lastOrder = new HashQueueMap();
scope.$watch(function(scope){
var index, length,
collection = scope.$eval(rhs),
collectionLength = size(collection, true),
childScope,
// Same as lastOrder but it has the current state. It will become the
// lastOrder on the next iteration.
nextOrder = new HashQueueMap(),
key, value, // key/value of iteration
array, last, // last object information {scope, element, index}
cursor = iterStartElement; // current position of the node
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order of iteration over obj props
array = [];
for(key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
array.push(key);
}
}
array.sort();
} else {
array = collection || [];
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = array.length; index < length; index++) {
key = (collection === array) ? index : array[index];
value = collection[key];
last = lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = last.scope;
nextOrder.push(value, last);
if (index === last.index) {
// do nothing
cursor = last.element;
} else {
// existing item which got moved
last.index = index;
// This may be a noop, if the element is next, but I don't know of a good way to
// figure this out, since it would require extra DOM access, so let's just hope that
// the browsers realizes that it is noop, and treats it as such.
cursor.after(last.element);
cursor = last.element;
}
} else {
// new item which we don't know about
childScope = scope.$new();
}
childScope[valueIdent] = value;
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === (collectionLength - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone){
cursor.after(clone);
last = {
scope: childScope,
element: (cursor = clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array = lastOrder[key];
while(array.length) {
value = array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder = nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngShow, function(value){
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion
* of the HTML conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngHide, function(value){
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* Conditionally change the DOM structure.
*
* @usageContent
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</script>
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH = 'ng-switch';
var ngSwitchDirective = valueFn({
restrict: 'EA',
compile: function(element, attr) {
var watchExpr = attr.ngSwitch || attr.on,
cases = {};
element.data(NG_SWITCH, cases);
return function(scope, element){
var selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = selectedScope = null;
}
if ((selectedTransclude = cases['!' + value] || cases['?'])) {
scope.$eval(attr.change);
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
});
}
});
};
}
});
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['!' + attrs.ngSwitchWhen] = transclude;
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
compile: function(element, attrs, transclude) {
var cases = element.inheritedData(NG_SWITCH);
assertArg(cases);
cases['?'] = transclude;
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { title:'bind' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$transclude', '$element', function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.template = {{$route.current.template}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll, $compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link = $compile(element.contents()),
current = $route.current,
controller;
lastScope = current.scope = scope.$new();
if (current.controller) {
locals.$scope = lastScope;
controller = $controller(current.controller, locals);
element.contents().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*˝˝
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can currently
* be bound to string values only.
*
* @param {string} name assignable expression to data-bind to.
* @param {string=} required The control is considered valid only if value is entered.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({ terminal: true });
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
nullModelCtrl = {$setViewValue: noop};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
}
self.addOption = function(value) {
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value == '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.children(), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.bind('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.children(), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] = key;
locals[valueName] = collection[key];
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element;
if (multiple) {
selectedSet = new HashMap(modelValue);
} else if (modelValue === null || nullOption) {
// if we are not multiselect, and we are null then we have to add the nullOption
optionGroups[''].push({selected:modelValue === null, id:'', label:''});
selectedSet = true;
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
} else {
selected = modelValue === valueFn(scope, locals);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: displayFn(scope, locals) || '', // what will be seen by the user
selected: selected // determine if we should be selected
});
}
if (!multiple && !selectedSet) {
// nothing was selected, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
if (existingOption.element.selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
require: '^select',
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr, selectCtrl) {
if (selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.bind('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
/**
* Setup file for the Scenario.
* Must be first in the compilation/bootstrap list.
*/
// Public namespace
angular.scenario = angular.scenario || {};
/**
* Defines a new output format.
*
* @param {string} name the name of the new output format
* @param {function()} fn function(context, runner) that generates the output
*/
angular.scenario.output = angular.scenario.output || function(name, fn) {
angular.scenario.output[name] = fn;
};
/**
* Defines a new DSL statement. If your factory function returns a Future
* it's returned, otherwise the result is assumed to be a map of functions
* for chaining. Chained functions are subject to the same rules.
*
* Note: All functions on the chain are bound to the chain scope so values
* set on "this" in your statement function are available in the chained
* functions.
*
* @param {string} name The name of the statement
* @param {function()} fn Factory function(), return a function for
* the statement.
*/
angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
angular.scenario.dsl[name] = function() {
function executeStatement(statement, args) {
var result = statement.apply(this, args);
if (angular.isFunction(result) || result instanceof angular.scenario.Future)
return result;
var self = this;
var chain = angular.extend({}, result);
angular.forEach(chain, function(value, name) {
if (angular.isFunction(value)) {
chain[name] = function() {
return executeStatement.call(self, value, arguments);
};
} else {
chain[name] = value;
}
});
return chain;
}
var statement = fn.apply(this, arguments);
return function() {
return executeStatement.call(this, statement, arguments);
};
};
};
/**
* Defines a new matcher for use with the expects() statement. The value
* this.actual (like in Jasmine) is available in your matcher to compare
* against. Your function should return a boolean. The future is automatically
* created for you.
*
* @param {string} name The name of the matcher
* @param {function()} fn The matching function(expected).
*/
angular.scenario.matcher = angular.scenario.matcher || function(name, fn) {
angular.scenario.matcher[name] = function(expected) {
var prefix = 'expect ' + this.future.name + ' ';
if (this.inverse) {
prefix += 'not ';
}
var self = this;
this.addFuture(prefix + name + ' ' + angular.toJson(expected),
function(done) {
var error;
self.actual = self.future.value;
if ((self.inverse && fn.call(self, expected)) ||
(!self.inverse && !fn.call(self, expected))) {
error = 'expected ' + angular.toJson(expected) +
' but was ' + angular.toJson(self.actual);
}
done(error);
});
};
};
/**
* Initialize the scenario runner and run !
*
* Access global window and document object
* Access $runner through closure
*
* @param {Object=} config Config options
*/
angular.scenario.setUpAndRun = function(config) {
var href = window.location.href;
var body = _jQuery(document.body);
var output = [];
var objModel = new angular.scenario.ObjectModel($runner);
if (config && config.scenario_output) {
output = config.scenario_output.split(',');
}
angular.forEach(angular.scenario.output, function(fn, name) {
if (!output.length || indexOf(output,name) != -1) {
var context = body.append('<div></div>').find('div:last');
context.attr('id', name);
fn.call({}, context, $runner, objModel);
}
});
if (!/^http/.test(href) && !/^https/.test(href)) {
body.append('<p id="system-error"></p>');
body.find('#system-error').text(
'Scenario runner must be run using http or https. The protocol ' +
href.split(':')[0] + ':// is not supported.'
);
return;
}
var appFrame = body.append('<div id="application"></div>').find('#application');
var application = new angular.scenario.Application(appFrame);
$runner.on('RunnerEnd', function() {
appFrame.css('display', 'none');
appFrame.find('iframe').attr('src', 'about:blank');
});
$runner.on('RunnerError', function(error) {
if (window.console) {
console.log(formatException(error));
} else {
// Do something for IE
alert(error);
}
});
$runner.run(application);
};
/**
* Iterates through list with iterator function that must call the
* continueFunction to continute iterating.
*
* @param {Array} list list to iterate over
* @param {function()} iterator Callback function(value, continueFunction)
* @param {function()} done Callback function(error, result) called when
* iteration finishes or an error occurs.
*/
function asyncForEach(list, iterator, done) {
var i = 0;
function loop(error, index) {
if (index && index > i) {
i = index;
}
if (error || i >= list.length) {
done(error);
} else {
try {
iterator(list[i++], loop);
} catch (e) {
done(e);
}
}
}
loop();
}
/**
* Formats an exception into a string with the stack trace, but limits
* to a specific line length.
*
* @param {Object} error The exception to format, can be anything throwable
* @param {Number=} [maxStackLines=5] max lines of the stack trace to include
* default is 5.
*/
function formatException(error, maxStackLines) {
maxStackLines = maxStackLines || 5;
var message = error.toString();
if (error.stack) {
var stack = error.stack.split('\n');
if (stack[0].indexOf(message) === -1) {
maxStackLines++;
stack.unshift(error.message);
}
message = stack.slice(0, maxStackLines).join('\n');
}
return message;
}
/**
* Returns a function that gets the file name and line number from a
* location in the stack if available based on the call site.
*
* Note: this returns another function because accessing .stack is very
* expensive in Chrome.
*
* @param {Number} offset Number of stack lines to skip
*/
function callerFile(offset) {
var error = new Error();
return function() {
var line = (error.stack || '').split('\n')[offset];
// Clean up the stack trace line
if (line) {
if (line.indexOf('@') !== -1) {
// Firefox
line = line.substring(line.indexOf('@')+1);
} else {
// Chrome
line = line.substring(line.indexOf('(')+1).replace(')', '');
}
}
return line || '';
};
}
/**
* Triggers a browser event. Attempts to choose the right event if one is
* not specified.
*
* @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement
* @param {string} type Optional event type.
* @param {Array.<string>=} keys Optional list of pressed keys
* (valid values: 'alt', 'meta', 'shift', 'ctrl')
*/
function browserTrigger(element, type, keys) {
if (element && !element.nodeName) element = element[0];
if (!element) return;
if (!type) {
type = {
'text': 'change',
'textarea': 'change',
'hidden': 'change',
'password': 'change',
'button': 'click',
'submit': 'click',
'reset': 'click',
'image': 'click',
'checkbox': 'click',
'radio': 'click',
'select-one': 'change',
'select-multiple': 'change'
}[lowercase(element.type)] || 'click';
}
if (lowercase(nodeName_(element)) == 'option') {
element.parentNode.value = element.value;
element = element.parentNode;
type = 'change';
}
keys = keys || [];
function pressed(key) {
return indexOf(keys, key) !== -1;
}
if (msie < 9) {
switch(element.type) {
case 'radio':
case 'checkbox':
element.checked = !element.checked;
break;
}
// WTF!!! Error: Unspecified error.
// Don't know why, but some elements when detached seem to be in inconsistent state and
// calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error)
// forcing the browser to compute the element position (by reading its CSS)
// puts the element in consistent state.
element.style.posLeft;
// TODO(vojta): create event objects with pressed keys to get it working on IE<9
var ret = element.fireEvent('on' + type);
if (lowercase(element.type) == 'submit') {
while(element) {
if (lowercase(element.nodeName) == 'form') {
element.fireEvent('onsubmit');
break;
}
element = element.parentNode;
}
}
return ret;
} else {
var evnt = document.createEvent('MouseEvents'),
originalPreventDefault = evnt.preventDefault,
iframe = _jQuery('#application iframe')[0],
appWindow = iframe ? iframe.contentWindow : window,
fakeProcessDefault = true,
finalProcessDefault;
// igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208
appWindow.angular['ff-684208-preventDefault'] = false;
evnt.preventDefault = function() {
fakeProcessDefault = false;
return originalPreventDefault.apply(evnt, arguments);
};
evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'),
pressed('shift'), pressed('meta'), 0, element);
element.dispatchEvent(evnt);
finalProcessDefault = !(appWindow.angular['ff-684208-preventDefault'] || !fakeProcessDefault);
delete appWindow.angular['ff-684208-preventDefault'];
return finalProcessDefault;
}
}
/**
* Don't use the jQuery trigger method since it works incorrectly.
*
* jQuery notifies listeners and then changes the state of a checkbox and
* does not create a real browser event. A real click changes the state of
* the checkbox and then notifies listeners.
*
* To work around this we instead use our own handler that fires a real event.
*/
(function(fn){
var parentTrigger = fn.trigger;
fn.trigger = function(type) {
if (/(click|change|keydown|blur|input)/.test(type)) {
var processDefaults = [];
this.each(function(index, node) {
processDefaults.push(browserTrigger(node, type));
});
// this is not compatible with jQuery - we return an array of returned values,
// so that scenario runner know whether JS code has preventDefault() of the event or not...
return processDefaults;
}
return parentTrigger.apply(this, arguments);
};
})(_jQuery.fn);
/**
* Finds all bindings with the substring match of name and returns an
* array of their values.
*
* @param {string} bindExp The name to match
* @return {Array.<string>} String of binding values
*/
_jQuery.fn.bindings = function(windowJquery, bindExp) {
var result = [], match,
bindSelector = '.ng-binding:visible';
if (angular.isString(bindExp)) {
bindExp = bindExp.replace(/\s/g, '');
match = function (actualExp) {
if (actualExp) {
actualExp = actualExp.replace(/\s/g, '');
if (actualExp == bindExp) return true;
if (actualExp.indexOf(bindExp) == 0) {
return actualExp.charAt(bindExp.length) == '|';
}
}
}
} else if (bindExp) {
match = function(actualExp) {
return actualExp && bindExp.exec(actualExp);
}
} else {
match = function(actualExp) {
return !!actualExp;
};
}
var selection = this.find(bindSelector);
if (this.is(bindSelector)) {
selection = selection.add(this);
}
function push(value) {
if (value == undefined) {
value = '';
} else if (typeof value != 'string') {
value = angular.toJson(value);
}
result.push('' + value);
}
selection.each(function() {
var element = windowJquery(this),
binding;
if (binding = element.data('$binding')) {
if (typeof binding == 'string') {
if (match(binding)) {
push(element.scope().$eval(binding));
}
} else {
if (!angular.isArray(binding)) {
binding = [binding];
}
for(var fns, j=0, jj=binding.length; j<jj; j++) {
fns = binding[j];
if (fns.parts) {
fns = fns.parts;
} else {
fns = [fns];
}
for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) {
if(match((fn = fns[i]).exp)) {
push(fn(scope = scope || element.scope()));
}
}
}
}
}
});
return result;
};
/**
* Represents the application currently being tested and abstracts usage
* of iframes or separate windows.
*
* @param {Object} context jQuery wrapper around HTML context.
*/
angular.scenario.Application = function(context) {
this.context = context;
context.append(
'<h2>Current URL: <a href="about:blank">None</a></h2>' +
'<div id="test-frames"></div>'
);
};
/**
* Gets the jQuery collection of frames. Don't use this directly because
* frames may go stale.
*
* @private
* @return {Object} jQuery collection
*/
angular.scenario.Application.prototype.getFrame_ = function() {
return this.context.find('#test-frames iframe:last');
};
/**
* Gets the window of the test runner frame. Always favor executeAction()
* instead of this method since it prevents you from getting a stale window.
*
* @private
* @return {Object} the window of the frame
*/
angular.scenario.Application.prototype.getWindow_ = function() {
var contentWindow = this.getFrame_().prop('contentWindow');
if (!contentWindow)
throw 'Frame window is not accessible.';
return contentWindow;
};
/**
* Changes the location of the frame.
*
* @param {string} url The URL. If it begins with a # then only the
* hash of the page is changed.
* @param {function()} loadFn function($window, $document) Called when frame loads.
* @param {function()} errorFn function(error) Called if any error when loading.
*/
angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) {
var self = this;
var frame = this.getFrame_();
//TODO(esprehn): Refactor to use rethrow()
errorFn = errorFn || function(e) { throw e; };
if (url === 'about:blank') {
errorFn('Sandbox Error: Navigating to about:blank is not allowed.');
} else if (url.charAt(0) === '#') {
url = frame.attr('src').split('#')[0] + url;
frame.attr('src', url);
this.executeAction(loadFn);
} else {
frame.remove();
this.context.find('#test-frames').append('<iframe>');
frame = this.getFrame_();
frame.load(function() {
frame.unbind();
try {
self.executeAction(loadFn);
} catch (e) {
errorFn(e);
}
}).attr('src', url);
}
this.context.find('> h2 a').attr('href', url).text(url);
};
/**
* Executes a function in the context of the tested application. Will wait
* for all pending angular xhr requests before executing.
*
* @param {function()} action The callback to execute. function($window, $document)
* $document is a jQuery wrapped document.
*/
angular.scenario.Application.prototype.executeAction = function(action) {
var self = this;
var $window = this.getWindow_();
if (!$window.document) {
throw 'Sandbox Error: Application document not accessible.';
}
if (!$window.angular) {
return action.call(this, $window, _jQuery($window.document));
}
angularInit($window.document, function(element) {
var $injector = $window.angular.element(element).injector();
var $element = _jQuery(element);
$element.injector = function() {
return $injector;
};
$injector.invoke(function($browser){
$browser.notifyWhenNoOutstandingRequests(function() {
action.call(self, $window, $element);
});
});
});
};
/**
* The representation of define blocks. Don't used directly, instead use
* define() in your tests.
*
* @param {string} descName Name of the block
* @param {Object} parent describe or undefined if the root.
*/
angular.scenario.Describe = function(descName, parent) {
this.only = parent && parent.only;
this.beforeEachFns = [];
this.afterEachFns = [];
this.its = [];
this.children = [];
this.name = descName;
this.parent = parent;
this.id = angular.scenario.Describe.id++;
/**
* Calls all before functions.
*/
var beforeEachFns = this.beforeEachFns;
this.setupBefore = function() {
if (parent) parent.setupBefore.call(this);
angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this);
};
/**
* Calls all after functions.
*/
var afterEachFns = this.afterEachFns;
this.setupAfter = function() {
angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this);
if (parent) parent.setupAfter.call(this);
};
};
// Shared Unique ID generator for every describe block
angular.scenario.Describe.id = 0;
// Shared Unique ID generator for every it (spec)
angular.scenario.Describe.specId = 0;
/**
* Defines a block to execute before each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.beforeEach = function(body) {
this.beforeEachFns.push(body);
};
/**
* Defines a block to execute after each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.afterEach = function(body) {
this.afterEachFns.push(body);
};
/**
* Creates a new describe block that's a child of this one.
*
* @param {string} name Name of the block. Appended to the parent block's name.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.describe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
this.children.push(child);
body.call(child);
};
/**
* Same as describe() but makes ddescribe blocks the only to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.ddescribe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
child.only = true;
this.children.push(child);
body.call(child);
};
/**
* Use to disable a describe block.
*/
angular.scenario.Describe.prototype.xdescribe = angular.noop;
/**
* Defines a test.
*
* @param {string} name Name of the test.
* @param {function()} vody Body of the block.
*/
angular.scenario.Describe.prototype.it = function(name, body) {
this.its.push({
id: angular.scenario.Describe.specId++,
definition: this,
only: this.only,
name: name,
before: this.setupBefore,
body: body,
after: this.setupAfter
});
};
/**
* Same as it() but makes iit tests the only test to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.iit = function(name, body) {
this.it.apply(this, arguments);
this.its[this.its.length-1].only = true;
};
/**
* Use to disable a test block.
*/
angular.scenario.Describe.prototype.xit = angular.noop;
/**
* Gets an array of functions representing all the tests (recursively).
* that can be executed with SpecRunner's.
*
* @return {Array<Object>} Array of it blocks {
* definition : Object // parent Describe
* only: boolean
* name: string
* before: Function
* body: Function
* after: Function
* }
*/
angular.scenario.Describe.prototype.getSpecs = function() {
var specs = arguments[0] || [];
angular.forEach(this.children, function(child) {
child.getSpecs(specs);
});
angular.forEach(this.its, function(it) {
specs.push(it);
});
var only = [];
angular.forEach(specs, function(it) {
if (it.only) {
only.push(it);
}
});
return (only.length && only) || specs;
};
/**
* A future action in a spec.
*
* @param {string} name of the future action
* @param {function()} future callback(error, result)
* @param {function()} Optional. function that returns the file/line number.
*/
angular.scenario.Future = function(name, behavior, line) {
this.name = name;
this.behavior = behavior;
this.fulfilled = false;
this.value = undefined;
this.parser = angular.identity;
this.line = line || function() { return ''; };
};
/**
* Executes the behavior of the closure.
*
* @param {function()} doneFn Callback function(error, result)
*/
angular.scenario.Future.prototype.execute = function(doneFn) {
var self = this;
this.behavior(function(error, result) {
self.fulfilled = true;
if (result) {
try {
result = self.parser(result);
} catch(e) {
error = e;
}
}
self.value = error || result;
doneFn(error, result);
});
};
/**
* Configures the future to convert it's final with a function fn(value)
*
* @param {function()} fn function(value) that returns the parsed value
*/
angular.scenario.Future.prototype.parsedWith = function(fn) {
this.parser = fn;
return this;
};
/**
* Configures the future to parse it's final value from JSON
* into objects.
*/
angular.scenario.Future.prototype.fromJson = function() {
return this.parsedWith(angular.fromJson);
};
/**
* Configures the future to convert it's final value from objects
* into JSON.
*/
angular.scenario.Future.prototype.toJson = function() {
return this.parsedWith(angular.toJson);
};
/**
* Maintains an object tree from the runner events.
*
* @param {Object} runner The scenario Runner instance to connect to.
*
* TODO(esprehn): Every output type creates one of these, but we probably
* want one global shared instance. Need to handle events better too
* so the HTML output doesn't need to do spec model.getSpec(spec.id)
* silliness.
*
* TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
*/
angular.scenario.ObjectModel = function(runner) {
var self = this;
this.specMap = {};
this.listeners = [];
this.value = {
name: '',
children: {}
};
runner.on('SpecBegin', function(spec) {
var block = self.value,
definitions = [];
angular.forEach(self.getDefinitionPath(spec), function(def) {
if (!block.children[def.name]) {
block.children[def.name] = {
id: def.id,
name: def.name,
children: {},
specs: {}
};
}
block = block.children[def.name];
definitions.push(def.name);
});
var it = self.specMap[spec.id] =
block.specs[spec.name] =
new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);
// forward the event
self.emit('SpecBegin', it);
});
runner.on('SpecError', function(spec, error) {
var it = self.getSpec(spec.id);
it.status = 'error';
it.error = error;
// forward the event
self.emit('SpecError', it, error);
});
runner.on('SpecEnd', function(spec) {
var it = self.getSpec(spec.id);
complete(it);
// forward the event
self.emit('SpecEnd', it);
});
runner.on('StepBegin', function(spec, step) {
var it = self.getSpec(spec.id);
var step = new angular.scenario.ObjectModel.Step(step.name);
it.steps.push(step);
// forward the event
self.emit('StepBegin', it, step);
});
runner.on('StepEnd', function(spec) {
var it = self.getSpec(spec.id);
var step = it.getLastStep();
if (step.name !== step.name)
throw 'Events fired in the wrong order. Step names don\'t match.';
complete(step);
// forward the event
self.emit('StepEnd', it, step);
});
runner.on('StepFailure', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('failure', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepFailure', it, modelStep, error);
});
runner.on('StepError', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('error', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepError', it, modelStep, error);
});
runner.on('RunnerEnd', function() {
self.emit('RunnerEnd');
});
function complete(item) {
item.endTime = new Date().getTime();
item.duration = item.endTime - item.startTime;
item.status = item.status || 'success';
}
};
/**
* Adds a listener for an event.
*
* @param {string} eventName Name of the event to add a handler for
* @param {function()} listener Function that will be called when event is fired
*/
angular.scenario.ObjectModel.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.ObjectModel.prototype.emit = function(eventName) {
var self = this,
args = Array.prototype.slice.call(arguments, 1),
eventName = eventName.toLowerCase();
if (this.listeners[eventName]) {
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
}
};
/**
* Computes the path of definition describe blocks that wrap around
* this spec.
*
* @param spec Spec to compute the path for.
* @return {Array<Describe>} The describe block path
*/
angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
var path = [];
var currentDefinition = spec.definition;
while (currentDefinition && currentDefinition.name) {
path.unshift(currentDefinition);
currentDefinition = currentDefinition.parent;
}
return path;
};
/**
* Gets a spec by id.
*
* @param {string} The id of the spec to get the object for.
* @return {Object} the Spec instance
*/
angular.scenario.ObjectModel.prototype.getSpec = function(id) {
return this.specMap[id];
};
/**
* A single it block.
*
* @param {string} id Id of the spec
* @param {string} name Name of the spec
* @param {Array<string>=} definitionNames List of all describe block names that wrap this spec
*/
angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
this.id = id;
this.name = name;
this.startTime = new Date().getTime();
this.steps = [];
this.fullDefinitionName = (definitionNames || []).join(' ');
};
/**
* Adds a new step to the Spec.
*
* @param {string} step Name of the step (really name of the future)
* @return {Object} the added step
*/
angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
var step = new angular.scenario.ObjectModel.Step(name);
this.steps.push(step);
return step;
};
/**
* Gets the most recent step.
*
* @return {Object} the step
*/
angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
return this.steps[this.steps.length-1];
};
/**
* Set status of the Spec from given Step
*
* @param {angular.scenario.ObjectModel.Step} step
*/
angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) {
if (!this.status || step.status == 'error') {
this.status = step.status;
this.error = step.error;
this.line = step.line;
}
};
/**
* A single step inside a Spec.
*
* @param {string} step Name of the step
*/
angular.scenario.ObjectModel.Step = function(name) {
this.name = name;
this.startTime = new Date().getTime();
};
/**
* Helper method for setting all error status related properties
*
* @param {string} status
* @param {string} error
* @param {string} line
*/
angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
this.status = status;
this.error = error;
this.line = line;
};
/**
* The representation of define blocks. Don't used directly, instead use
* define() in your tests.
*
* @param {string} descName Name of the block
* @param {Object} parent describe or undefined if the root.
*/
angular.scenario.Describe = function(descName, parent) {
this.only = parent && parent.only;
this.beforeEachFns = [];
this.afterEachFns = [];
this.its = [];
this.children = [];
this.name = descName;
this.parent = parent;
this.id = angular.scenario.Describe.id++;
/**
* Calls all before functions.
*/
var beforeEachFns = this.beforeEachFns;
this.setupBefore = function() {
if (parent) parent.setupBefore.call(this);
angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this);
};
/**
* Calls all after functions.
*/
var afterEachFns = this.afterEachFns;
this.setupAfter = function() {
angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this);
if (parent) parent.setupAfter.call(this);
};
};
// Shared Unique ID generator for every describe block
angular.scenario.Describe.id = 0;
// Shared Unique ID generator for every it (spec)
angular.scenario.Describe.specId = 0;
/**
* Defines a block to execute before each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.beforeEach = function(body) {
this.beforeEachFns.push(body);
};
/**
* Defines a block to execute after each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.afterEach = function(body) {
this.afterEachFns.push(body);
};
/**
* Creates a new describe block that's a child of this one.
*
* @param {string} name Name of the block. Appended to the parent block's name.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.describe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
this.children.push(child);
body.call(child);
};
/**
* Same as describe() but makes ddescribe blocks the only to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.ddescribe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
child.only = true;
this.children.push(child);
body.call(child);
};
/**
* Use to disable a describe block.
*/
angular.scenario.Describe.prototype.xdescribe = angular.noop;
/**
* Defines a test.
*
* @param {string} name Name of the test.
* @param {function()} vody Body of the block.
*/
angular.scenario.Describe.prototype.it = function(name, body) {
this.its.push({
id: angular.scenario.Describe.specId++,
definition: this,
only: this.only,
name: name,
before: this.setupBefore,
body: body,
after: this.setupAfter
});
};
/**
* Same as it() but makes iit tests the only test to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.iit = function(name, body) {
this.it.apply(this, arguments);
this.its[this.its.length-1].only = true;
};
/**
* Use to disable a test block.
*/
angular.scenario.Describe.prototype.xit = angular.noop;
/**
* Gets an array of functions representing all the tests (recursively).
* that can be executed with SpecRunner's.
*
* @return {Array<Object>} Array of it blocks {
* definition : Object // parent Describe
* only: boolean
* name: string
* before: Function
* body: Function
* after: Function
* }
*/
angular.scenario.Describe.prototype.getSpecs = function() {
var specs = arguments[0] || [];
angular.forEach(this.children, function(child) {
child.getSpecs(specs);
});
angular.forEach(this.its, function(it) {
specs.push(it);
});
var only = [];
angular.forEach(specs, function(it) {
if (it.only) {
only.push(it);
}
});
return (only.length && only) || specs;
};
/**
* Runner for scenarios
*
* Has to be initialized before any test is loaded,
* because it publishes the API into window (global space).
*/
angular.scenario.Runner = function($window) {
this.listeners = [];
this.$window = $window;
this.rootDescribe = new angular.scenario.Describe();
this.currentDescribe = this.rootDescribe;
this.api = {
it: this.it,
iit: this.iit,
xit: angular.noop,
describe: this.describe,
ddescribe: this.ddescribe,
xdescribe: angular.noop,
beforeEach: this.beforeEach,
afterEach: this.afterEach
};
angular.forEach(this.api, angular.bind(this, function(fn, key) {
this.$window[key] = angular.bind(this, fn);
}));
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.Runner.prototype.emit = function(eventName) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
eventName = eventName.toLowerCase();
if (!this.listeners[eventName])
return;
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
};
/**
* Adds a listener for an event.
*
* @param {string} eventName The name of the event to add a handler for
* @param {string} listener The fn(...) that takes the extra arguments from emit()
*/
angular.scenario.Runner.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Defines a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.describe = function(name, body) {
var self = this;
this.currentDescribe.describe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Same as describe, but makes ddescribe the only blocks to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.ddescribe = function(name, body) {
var self = this;
this.currentDescribe.ddescribe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Defines a test in a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.it = function(name, body) {
this.currentDescribe.it(name, body);
};
/**
* Same as it, but makes iit tests the only tests to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.iit = function(name, body) {
this.currentDescribe.iit(name, body);
};
/**
* Defines a function to be called before each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.beforeEach = function(body) {
this.currentDescribe.beforeEach(body);
};
/**
* Defines a function to be called after each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.afterEach = function(body) {
this.currentDescribe.afterEach(body);
};
/**
* Creates a new spec runner.
*
* @private
* @param {Object} scope parent scope
*/
angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
var child = scope.$new();
var Cls = angular.scenario.SpecRunner;
// Export all the methods to child scope manually as now we don't mess controllers with scopes
// TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current
for (var name in Cls.prototype)
child[name] = angular.bind(child, Cls.prototype[name]);
Cls.call(child);
return child;
};
/**
* Runs all the loaded tests with the specified runner class on the
* provided application.
*
* @param {angular.scenario.Application} application App to remote control.
*/
angular.scenario.Runner.prototype.run = function(application) {
var self = this;
var $root = angular.injector(['ng']).get('$rootScope');
angular.extend($root, this);
angular.forEach(angular.scenario.Runner.prototype, function(fn, name) {
$root[name] = angular.bind(self, fn);
});
$root.application = application;
$root.emit('RunnerBegin');
asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) {
var dslCache = {};
var runner = self.createSpecRunner_($root);
angular.forEach(angular.scenario.dsl, function(fn, key) {
dslCache[key] = fn.call($root);
});
angular.forEach(angular.scenario.dsl, function(fn, key) {
self.$window[key] = function() {
var line = callerFile(3);
var scope = runner.$new();
// Make the dsl accessible on the current chain
scope.dsl = {};
angular.forEach(dslCache, function(fn, key) {
scope.dsl[key] = function() {
return dslCache[key].apply(scope, arguments);
};
});
// Make these methods work on the current chain
scope.addFuture = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFuture.apply(scope, arguments);
};
scope.addFutureAction = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFutureAction.apply(scope, arguments);
};
return scope.dsl[key].apply(scope, arguments);
};
});
runner.run(spec, function() {
runner.$destroy();
specDone.apply(this, arguments);
});
},
function(error) {
if (error) {
self.emit('RunnerError', error);
}
self.emit('RunnerEnd');
});
};
/**
* This class is the "this" of the it/beforeEach/afterEach method.
* Responsibilities:
* - "this" for it/beforeEach/afterEach
* - keep state for single it/beforeEach/afterEach execution
* - keep track of all of the futures to execute
* - run single spec (execute each future)
*/
angular.scenario.SpecRunner = function() {
this.futures = [];
this.afterIndex = 0;
};
/**
* Executes a spec which is an it block with associated before/after functions
* based on the describe nesting.
*
* @param {Object} spec A spec object
* @param {function()} specDone function that is called when the spec finshes. Function(error, index)
*/
angular.scenario.SpecRunner.prototype.run = function(spec, specDone) {
var self = this;
this.spec = spec;
this.emit('SpecBegin', spec);
try {
spec.before.call(this);
spec.body.call(this);
this.afterIndex = this.futures.length;
spec.after.call(this);
} catch (e) {
this.emit('SpecError', spec, e);
this.emit('SpecEnd', spec);
specDone();
return;
}
var handleError = function(error, done) {
if (self.error) {
return done();
}
self.error = true;
done(null, self.afterIndex);
};
asyncForEach(
this.futures,
function(future, futureDone) {
self.step = future;
self.emit('StepBegin', spec, future);
try {
future.execute(function(error) {
if (error) {
self.emit('StepFailure', spec, future, error);
self.emit('StepEnd', spec, future);
return handleError(error, futureDone);
}
self.emit('StepEnd', spec, future);
self.$window.setTimeout(function() { futureDone(); }, 0);
});
} catch (e) {
self.emit('StepError', spec, future, e);
self.emit('StepEnd', spec, future);
handleError(e, futureDone);
}
},
function(e) {
if (e) {
self.emit('SpecError', spec, e);
}
self.emit('SpecEnd', spec);
// Call done in a timeout so exceptions don't recursively
// call this function
self.$window.setTimeout(function() { specDone(); }, 0);
}
);
};
/**
* Adds a new future action.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) {
var future = new angular.scenario.Future(name, angular.bind(this, behavior), line);
this.futures.push(future);
return future;
};
/**
* Adds a new future action to be executed on the application window.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) {
var self = this;
var NG = /\[ng\\\:/;
return this.addFuture(name, function(done) {
this.application.executeAction(function($window, $document) {
//TODO(esprehn): Refactor this so it doesn't need to be in here.
$document.elements = function(selector) {
var args = Array.prototype.slice.call(arguments, 1);
selector = (self.selector || '') + ' ' + (selector || '');
selector = _jQuery.trim(selector) || '*';
angular.forEach(args, function(value, index) {
selector = selector.replace('$' + (index + 1), value);
});
var result = $document.find(selector);
if (selector.match(NG)) {
result = result.add(selector.replace(NG, '[ng-'), $document);
}
if (!result.length) {
throw {
type: 'selector',
message: 'Selector ' + selector + ' did not match any elements.'
};
}
return result;
};
try {
behavior.call(self, $window, $document, done);
} catch(e) {
if (e.type && e.type === 'selector') {
done(e.message);
} else {
throw e;
}
}
});
}, line);
};
/**
* Shared DSL statements that are useful to all scenarios.
*/
/**
* Usage:
* pause() pauses until you call resume() in the console
*/
angular.scenario.dsl('pause', function() {
return function() {
return this.addFuture('pausing for you to resume', function(done) {
this.emit('InteractivePause', this.spec, this.step);
this.$window.resume = function() { done(); };
});
};
});
/**
* Usage:
* sleep(seconds) pauses the test for specified number of seconds
*/
angular.scenario.dsl('sleep', function() {
return function(time) {
return this.addFuture('sleep for ' + time + ' seconds', function(done) {
this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000);
});
};
});
/**
* Usage:
* browser().navigateTo(url) Loads the url into the frame
* browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to
* browser().reload() refresh the page (reload the same URL)
* browser().window.href() window.location.href
* browser().window.path() window.location.pathname
* browser().window.search() window.location.search
* browser().window.hash() window.location.hash without # prefix
* browser().location().url() see ng.$location#url
* browser().location().path() see ng.$location#path
* browser().location().search() see ng.$location#search
* browser().location().hash() see ng.$location#hash
*/
angular.scenario.dsl('browser', function() {
var chain = {};
chain.navigateTo = function(url, delegate) {
var application = this.application;
return this.addFuture("browser navigate to '" + url + "'", function(done) {
if (delegate) {
url = delegate.call(this, url);
}
application.navigateTo(url, function() {
done(null, url);
}, done);
});
};
chain.reload = function() {
var application = this.application;
return this.addFutureAction('browser reload', function($window, $document, done) {
var href = $window.location.href;
application.navigateTo(href, function() {
done(null, href);
}, done);
});
};
chain.window = function() {
var api = {};
api.href = function() {
return this.addFutureAction('window.location.href', function($window, $document, done) {
done(null, $window.location.href);
});
};
api.path = function() {
return this.addFutureAction('window.location.path', function($window, $document, done) {
done(null, $window.location.pathname);
});
};
api.search = function() {
return this.addFutureAction('window.location.search', function($window, $document, done) {
done(null, $window.location.search);
});
};
api.hash = function() {
return this.addFutureAction('window.location.hash', function($window, $document, done) {
done(null, $window.location.hash.replace('#', ''));
});
};
return api;
};
chain.location = function() {
var api = {};
api.url = function() {
return this.addFutureAction('$location.url()', function($window, $document, done) {
done(null, $document.injector().get('$location').url());
});
};
api.path = function() {
return this.addFutureAction('$location.path()', function($window, $document, done) {
done(null, $document.injector().get('$location').path());
});
};
api.search = function() {
return this.addFutureAction('$location.search()', function($window, $document, done) {
done(null, $document.injector().get('$location').search());
});
};
api.hash = function() {
return this.addFutureAction('$location.hash()', function($window, $document, done) {
done(null, $document.injector().get('$location').hash());
});
};
return api;
};
return function() {
return chain;
};
});
/**
* Usage:
* expect(future).{matcher} where matcher is one of the matchers defined
* with angular.scenario.matcher
*
* ex. expect(binding("name")).toEqual("Elliott")
*/
angular.scenario.dsl('expect', function() {
var chain = angular.extend({}, angular.scenario.matcher);
chain.not = function() {
this.inverse = true;
return chain;
};
return function(future) {
this.future = future;
return chain;
};
});
/**
* Usage:
* using(selector, label) scopes the next DSL element selection
*
* ex.
* using('#foo', "'Foo' text field").input('bar')
*/
angular.scenario.dsl('using', function() {
return function(selector, label) {
this.selector = _jQuery.trim((this.selector||'') + ' ' + selector);
if (angular.isString(label) && label.length) {
this.label = label + ' ( ' + this.selector + ' )';
} else {
this.label = this.selector;
}
return this.dsl;
};
});
/**
* Usage:
* binding(name) returns the value of the first matching binding
*/
angular.scenario.dsl('binding', function() {
return function(name) {
return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) {
var values = $document.elements().bindings($window.angular.element, name);
if (!values.length) {
return done("Binding selector '" + name + "' did not match.");
}
done(null, values[0]);
});
};
});
/**
* Usage:
* input(name).enter(value) enters value in input with specified name
* input(name).check() checks checkbox
* input(name).select(value) selects the radio button with specified name/value
* input(name).val() returns the value of the input.
*/
angular.scenario.dsl('input', function() {
var chain = {};
var supportInputEvent = 'oninput' in document.createElement('div');
chain.enter = function(value, event) {
return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
input.val(value);
input.trigger(event || supportInputEvent && 'input' || 'change');
done();
});
};
chain.check = function() {
return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox');
input.trigger('click');
done();
});
};
chain.select = function(value) {
return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) {
var input = $document.
elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio');
input.trigger('click');
done();
});
};
chain.val = function() {
return this.addFutureAction("return input val", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
done(null,input.val());
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* repeater('#products table', 'Product List').count() number of rows
* repeater('#products table', 'Product List').row(1) all bindings in row as an array
* repeater('#products table', 'Product List').column('product.name') all values across all rows in an array
*/
angular.scenario.dsl('repeater', function() {
var chain = {};
chain.count = function() {
return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.column = function(binding) {
return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) {
done(null, $document.elements().bindings($window.angular.element, binding));
});
};
chain.row = function(index) {
return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) {
var matches = $document.elements().slice(index, index + 1);
if (!matches.length)
return done('row ' + index + ' out of bounds');
done(null, matches.bindings($window.angular.element));
});
};
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Usage:
* select(name).option('value') select one option
* select(name).options('value1', 'value2', ...) select options from a multi select
*/
angular.scenario.dsl('select', function() {
var chain = {};
chain.option = function(value) {
return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) {
var select = $document.elements('select[ng\\:model="$1"]', this.name);
var option = select.find('option[value="' + value + '"]');
if (option.length) {
select.val(value);
} else {
option = select.find('option:contains("' + value + '")');
if (option.length) {
select.val(option.val());
}
}
select.trigger('change');
done();
});
};
chain.options = function() {
var values = arguments;
return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) {
var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name);
select.val(values);
select.trigger('change');
done();
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* element(selector, label).count() get the number of elements that match selector
* element(selector, label).click() clicks an element
* element(selector, label).query(fn) executes fn(selectedElements, done)
* element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
* element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
*/
angular.scenario.dsl('element', function() {
var KEY_VALUE_METHODS = ['attr', 'css', 'prop'];
var VALUE_METHODS = [
'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
];
var chain = {};
chain.count = function() {
return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.click = function() {
return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) {
var elements = $document.elements();
var href = elements.attr('href');
var eventProcessDefault = elements.trigger('click')[0];
if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
this.application.navigateTo(href, function() {
done();
}, done);
} else {
done();
}
});
};
chain.query = function(fn) {
return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) {
fn.call(this, $document.elements(), done);
});
};
angular.forEach(KEY_VALUE_METHODS, function(methodName) {
chain[methodName] = function(name, value) {
var args = arguments,
futureName = (args.length == 1)
? "element '" + this.label + "' get " + methodName + " '" + name + "'"
: "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
angular.forEach(VALUE_METHODS, function(methodName) {
chain[methodName] = function(value) {
var args = arguments,
futureName = (args.length == 0)
? "element '" + this.label + "' " + methodName
: futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Matchers for implementing specs. Follows the Jasmine spec conventions.
*/
angular.scenario.matcher('toEqual', function(expected) {
return angular.equals(this.actual, expected);
});
angular.scenario.matcher('toBe', function(expected) {
return this.actual === expected;
});
angular.scenario.matcher('toBeDefined', function() {
return angular.isDefined(this.actual);
});
angular.scenario.matcher('toBeTruthy', function() {
return this.actual;
});
angular.scenario.matcher('toBeFalsy', function() {
return !this.actual;
});
angular.scenario.matcher('toMatch', function(expected) {
return new RegExp(expected).test(this.actual);
});
angular.scenario.matcher('toBeNull', function() {
return this.actual === null;
});
angular.scenario.matcher('toContain', function(expected) {
return includes(this.actual, expected);
});
angular.scenario.matcher('toBeLessThan', function(expected) {
return this.actual < expected;
});
angular.scenario.matcher('toBeGreaterThan', function(expected) {
return this.actual > expected;
});
/**
* User Interface for the Scenario Runner.
*
* TODO(esprehn): This should be refactored now that ObjectModel exists
* to use angular bindings for the UI.
*/
angular.scenario.output('html', function(context, runner, model) {
var specUiMap = {},
lastStepUiMap = {};
context.append(
'<div id="header">' +
' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' +
' <ul id="status-legend" class="status-display">' +
' <li class="status-error">0 Errors</li>' +
' <li class="status-failure">0 Failures</li>' +
' <li class="status-success">0 Passed</li>' +
' </ul>' +
'</div>' +
'<div id="specs">' +
' <div class="test-children"></div>' +
'</div>'
);
runner.on('InteractivePause', function(spec) {
var ui = lastStepUiMap[spec.id];
ui.find('.test-title').
html('paused... <a href="javascript:resume()">resume</a> when ready.');
});
runner.on('SpecBegin', function(spec) {
var ui = findContext(spec);
ui.find('> .tests').append(
'<li class="status-pending test-it"></li>'
);
ui = ui.find('> .tests li:last');
ui.append(
'<div class="test-info">' +
' <p class="test-title">' +
' <span class="timer-result"></span>' +
' <span class="test-name"></span>' +
' </p>' +
'</div>' +
'<div class="scrollpane">' +
' <ol class="test-actions"></ol>' +
'</div>'
);
ui.find('> .test-info .test-name').text(spec.name);
ui.find('> .test-info').click(function() {
var scrollpane = ui.find('> .scrollpane');
var actions = scrollpane.find('> .test-actions');
var name = context.find('> .test-info .test-name');
if (actions.find(':visible').length) {
actions.hide();
name.removeClass('open').addClass('closed');
} else {
actions.show();
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
name.removeClass('closed').addClass('open');
}
});
specUiMap[spec.id] = ui;
});
runner.on('SpecError', function(spec, error) {
var ui = specUiMap[spec.id];
ui.append('<pre></pre>');
ui.find('> pre').text(formatException(error));
});
runner.on('SpecEnd', function(spec) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
ui.removeClass('status-pending');
ui.addClass('status-' + spec.status);
ui.find("> .test-info .timer-result").text(spec.duration + "ms");
if (spec.status === 'success') {
ui.find('> .test-info .test-name').addClass('closed');
ui.find('> .scrollpane .test-actions').hide();
}
updateTotals(spec.status);
});
runner.on('StepBegin', function(spec, step) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>');
var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last');
stepUi.append(
'<div class="timer-result"></div>' +
'<div class="test-title"></div>'
);
stepUi.find('> .test-title').text(step.name);
var scrollpane = stepUi.parents('.scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
runner.on('StepFailure', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepError', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepEnd', function(spec, step) {
var stepUi = lastStepUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
stepUi.find('.timer-result').text(step.duration + 'ms');
stepUi.removeClass('status-pending');
stepUi.addClass('status-' + step.status);
var scrollpane = specUiMap[spec.id].find('> .scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
/**
* Finds the context of a spec block defined by the passed definition.
*
* @param {Object} The definition created by the Describe object.
*/
function findContext(spec) {
var currentContext = context.find('#specs');
angular.forEach(model.getDefinitionPath(spec), function(defn) {
var id = 'describe-' + defn.id;
if (!context.find('#' + id).length) {
currentContext.find('> .test-children').append(
'<div class="test-describe" id="' + id + '">' +
' <h2></h2>' +
' <div class="test-children"></div>' +
' <ul class="tests"></ul>' +
'</div>'
);
context.find('#' + id).find('> h2').text('describe: ' + defn.name);
}
currentContext = context.find('#' + id);
});
return context.find('#describe-' + spec.definition.id);
}
/**
* Updates the test counter for the status.
*
* @param {string} the status.
*/
function updateTotals(status) {
var legend = context.find('#status-legend .status-' + status);
var parts = legend.text().split(' ');
var value = (parts[0] * 1) + 1;
legend.text(value + ' ' + parts[1]);
}
/**
* Add an error to a step.
*
* @param {Object} The JQuery wrapped context
* @param {function()} fn() that should return the file/line number of the error
* @param {Object} the error.
*/
function addError(context, line, error) {
context.find('.test-title').append('<pre></pre>');
var message = _jQuery.trim(line() + '\n\n' + formatException(error));
context.find('.test-title pre:last').text(message);
}
});
/**
* Generates JSON output into a context.
*/
angular.scenario.output('json', function(context, runner, model) {
model.on('RunnerEnd', function() {
context.text(angular.toJson(model.value));
});
});
/**
* Generates XML output into a context.
*/
angular.scenario.output('xml', function(context, runner, model) {
var $ = function(args) {return new context.init(args);};
model.on('RunnerEnd', function() {
var scenario = $('<scenario></scenario>');
context.append(scenario);
serializeXml(scenario, model.value);
});
/**
* Convert the tree into XML.
*
* @param {Object} context jQuery context to add the XML to.
* @param {Object} tree node to serialize
*/
function serializeXml(context, tree) {
angular.forEach(tree.children, function(child) {
var describeContext = $('<describe></describe>');
describeContext.attr('id', child.id);
describeContext.attr('name', child.name);
context.append(describeContext);
serializeXml(describeContext, child);
});
var its = $('<its></its>');
context.append(its);
angular.forEach(tree.specs, function(spec) {
var it = $('<it></it>');
it.attr('id', spec.id);
it.attr('name', spec.name);
it.attr('duration', spec.duration);
it.attr('status', spec.status);
its.append(it);
angular.forEach(spec.steps, function(step) {
var stepContext = $('<step></step>');
stepContext.attr('name', step.name);
stepContext.attr('duration', step.duration);
stepContext.attr('status', step.status);
it.append(stepContext);
if (step.error) {
var error = $('<error></error>');
stepContext.append(error);
error.text(formatException(stepContext.error));
}
});
});
}
});
/**
* Creates a global value $result with the result of the runner.
*/
angular.scenario.output('object', function(context, runner, model) {
runner.$window.$result = model.value;
});
bindJQuery();
publishExternalAPI(angular);
var $runner = new angular.scenario.Runner(window),
scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1],
config = {};
angular.forEach(script.attributes, function(attr) {
var match = attr.name.match(/ng[:\-](.*)/);
if (match) {
config[match[1]] = attr.value || true;
}
});
if (config.autotest) {
JQLite(document).ready(function() {
angular.scenario.setUpAndRun(config);
});
}
})(window, document);
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>');
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>');
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*
* TODO(vojta): wrap whole file into closure during build
*/
/**
* @ngdoc overview
* @name angular.mock
* @description
*
* Namespace from 'angular-mocks.js' which contains testing related code.
*/
angular.mock = {};
/**
* ! This is a private undocumented service !
*
* @name ngMock.$browser
*
* @description
* This service is a mock implementation of {@link ng.$browser}. It provides fake
* implementation for commonly used browser apis that are hard to test, e.g. setTimeout, xhr,
* cookies, etc...
*
* The api of this service is the same as that of the real {@link ng.$browser $browser}, except
* that there are several helper methods available which can be used in tests.
*/
angular.mock.$BrowserProvider = function() {
this.$get = function(){
return new angular.mock.$Browser();
};
};
angular.mock.$Browser = function() {
var self = this;
this.isMock = true;
self.$$url = "http://server/";
self.$$lastUrl = self.$$url; // used by url polling fn
self.pollFns = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = angular.noop;
self.$$incOutstandingRequestCount = angular.noop;
// register url polling fn
self.onUrlChange = function(listener) {
self.pollFns.push(
function() {
if (self.$$lastUrl != self.$$url) {
self.$$lastUrl = self.$$url;
listener(self.$$url);
}
}
);
return listener;
};
self.cookieHash = {};
self.lastCookieHash = {};
self.deferredFns = [];
self.deferredNextId = 0;
self.defer = function(fn, delay) {
delay = delay || 0;
self.deferredFns.push({time:(self.defer.now + delay), fn:fn, id: self.deferredNextId});
self.deferredFns.sort(function(a,b){ return a.time - b.time;});
return self.deferredNextId++;
};
self.defer.now = 0;
self.defer.cancel = function(deferId) {
var fnIndex;
angular.forEach(self.deferredFns, function(fn, index) {
if (fn.id === deferId) fnIndex = index;
});
if (fnIndex !== undefined) {
self.deferredFns.splice(fnIndex, 1);
return true;
}
return false;
};
/**
* @name ngMock.$browser#defer.flush
* @methodOf ngMock.$browser
*
* @description
* Flushes all pending requests and executes the defer callbacks.
*
* @param {number=} number of milliseconds to flush. See {@link #defer.now}
*/
self.defer.flush = function(delay) {
if (angular.isDefined(delay)) {
self.defer.now += delay;
} else {
if (self.deferredFns.length) {
self.defer.now = self.deferredFns[self.deferredFns.length-1].time;
} else {
throw Error('No deferred tasks to be flushed');
}
}
while (self.deferredFns.length && self.deferredFns[0].time <= self.defer.now) {
self.deferredFns.shift().fn();
}
};
/**
* @name ngMock.$browser#defer.now
* @propertyOf ngMock.$browser
*
* @description
* Current milliseconds mock time.
*/
self.$$baseHref = '';
self.baseHref = function() {
return this.$$baseHref;
};
};
angular.mock.$Browser.prototype = {
/**
* @name ngMock.$browser#poll
* @methodOf ngMock.$browser
*
* @description
* run all fns in pollFns
*/
poll: function poll() {
angular.forEach(this.pollFns, function(pollFn){
pollFn();
});
},
addPollFn: function(pollFn) {
this.pollFns.push(pollFn);
return pollFn;
},
url: function(url, replace) {
if (url) {
this.$$url = url;
return this;
}
return this.$$url;
},
cookies: function(name, value) {
if (name) {
if (value == undefined) {
delete this.cookieHash[name];
} else {
if (angular.isString(value) && //strings only
value.length <= 4096) { //strict cookie storage limits
this.cookieHash[name] = value;
}
}
} else {
if (!angular.equals(this.cookieHash, this.lastCookieHash)) {
this.lastCookieHash = angular.copy(this.cookieHash);
this.cookieHash = angular.copy(this.cookieHash);
}
return this.cookieHash;
}
},
notifyWhenNoOutstandingRequests: function(fn) {
fn();
}
};
/**
* @ngdoc object
* @name ngMock.$exceptionHandlerProvider
*
* @description
* Configures the mock implementation of {@link ng.$exceptionHandler} to rethrow or to log errors passed
* into the `$exceptionHandler`.
*/
/**
* @ngdoc object
* @name ngMock.$exceptionHandler
*
* @description
* Mock implementation of {@link ng.$exceptionHandler} that rethrows or logs errors passed
* into it. See {@link ngMock.$exceptionHandlerProvider $exceptionHandlerProvider} for configuration
* information.
*/
angular.mock.$ExceptionHandlerProvider = function() {
var handler;
/**
* @ngdoc method
* @name ngMock.$exceptionHandlerProvider#mode
* @methodOf ngMock.$exceptionHandlerProvider
*
* @description
* Sets the logging mode.
*
* @param {string} mode Mode of operation, defaults to `rethrow`.
*
* - `rethrow`: If any errors are are passed into the handler in tests, it typically
* means that there is a bug in the application or test, so this mock will
* make these tests fail.
* - `log`: Sometimes it is desirable to test that an error is throw, for this case the `log` mode stores the
* error and allows later assertion of it.
* See {@link ngMock.$log#assertEmpty assertEmpty()} and
* {@link ngMock.$log#reset reset()}
*/
this.mode = function(mode) {
switch(mode) {
case 'rethrow':
handler = function(e) {
throw e;
};
break;
case 'log':
var errors = [];
handler = function(e) {
if (arguments.length == 1) {
errors.push(e);
} else {
errors.push([].slice.call(arguments, 0));
}
};
handler.errors = errors;
break;
default:
throw Error("Unknown mode '" + mode + "', only 'log'/'rethrow' modes are allowed!");
}
};
this.$get = function() {
return handler;
};
this.mode('rethrow');
};
/**
* @ngdoc service
* @name ngMock.$log
*
* @description
* Mock implementation of {@link ng.$log} that gathers all logged messages in arrays
* (one array per logging level). These arrays are exposed as `logs` property of each of the
* level-specific log function, e.g. for level `error` the array is exposed as `$log.error.logs`.
*
*/
angular.mock.$LogProvider = function() {
function concat(array1, array2, index) {
return array1.concat(Array.prototype.slice.call(array2, index));
}
this.$get = function () {
var $log = {
log: function() { $log.log.logs.push(concat([], arguments, 0)); },
warn: function() { $log.warn.logs.push(concat([], arguments, 0)); },
info: function() { $log.info.logs.push(concat([], arguments, 0)); },
error: function() { $log.error.logs.push(concat([], arguments, 0)); }
};
/**
* @ngdoc method
* @name ngMock.$log#reset
* @methodOf ngMock.$log
*
* @description
* Reset all of the logging arrays to empty.
*/
$log.reset = function () {
/**
* @ngdoc property
* @name ngMock.$log#log.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.log.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#warn.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.warn.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#info.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.info.logs = [];
/**
* @ngdoc property
* @name ngMock.$log#error.logs
* @propertyOf ngMock.$log
*
* @description
* Array of logged messages.
*/
$log.error.logs = [];
};
/**
* @ngdoc method
* @name ngMock.$log#assertEmpty
* @methodOf ngMock.$log
*
* @description
* Assert that the all of the logging methods have no logged messages. If messages present, an exception is thrown.
*/
$log.assertEmpty = function() {
var errors = [];
angular.forEach(['error', 'warn', 'info', 'log'], function(logLevel) {
angular.forEach($log[logLevel].logs, function(log) {
angular.forEach(log, function (logItem) {
errors.push('MOCK $log (' + logLevel + '): ' + String(logItem) + '\n' + (logItem.stack || ''));
});
});
});
if (errors.length) {
errors.unshift("Expected $log to be empty! Either a message was logged unexpectedly, or an expected " +
"log message was not checked and removed:");
errors.push('');
throw new Error(errors.join('\n---------\n'));
}
};
$log.reset();
return $log;
};
};
(function() {
var R_ISO8061_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?:\:?(\d\d)(?:\:?(\d\d)(?:\.(\d{3}))?)?)?(Z|([+-])(\d\d):?(\d\d)))?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8061_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
function int(str) {
return parseInt(str, 10);
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
/**
* @ngdoc object
* @name angular.mock.TzDate
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available mock class of `Date`.
*
* Mock of the Date type which has its timezone specified via constroctor arg.
*
* The main purpose is to create Date-like instances with timezone fixed to the specified timezone
* offset, so that we can test code that depends on local timezone settings without dependency on
* the time zone settings of the machine where the code is running.
*
* @param {number} offset Offset of the *desired* timezone in hours (fractions will be honored)
* @param {(number|string)} timestamp Timestamp representing the desired time in *UTC*
*
* @example
* !!!! WARNING !!!!!
* This is not a complete Date object so only methods that were implemented can be called safely.
* To make matters worse, TzDate instances inherit stuff from Date via a prototype.
*
* We do our best to intercept calls to "unimplemented" methods, but since the list of methods is
* incomplete we might be missing some non-standard methods. This can result in errors like:
* "Date.prototype.foo called on incompatible Object".
*
* <pre>
* var newYearInBratislava = new TzDate(-1, '2009-12-31T23:00:00Z');
* newYearInBratislava.getTimezoneOffset() => -60;
* newYearInBratislava.getFullYear() => 2010;
* newYearInBratislava.getMonth() => 0;
* newYearInBratislava.getDate() => 1;
* newYearInBratislava.getHours() => 0;
* newYearInBratislava.getMinutes() => 0;
* </pre>
*
*/
angular.mock.TzDate = function (offset, timestamp) {
var self = new Date(0);
if (angular.isString(timestamp)) {
var tsStr = timestamp;
self.origDate = jsonStringToDate(timestamp);
timestamp = self.origDate.getTime();
if (isNaN(timestamp))
throw {
name: "Illegal Argument",
message: "Arg '" + tsStr + "' passed into TzDate constructor is not a valid date string"
};
} else {
self.origDate = new Date(timestamp);
}
var localOffset = new Date(timestamp).getTimezoneOffset();
self.offsetDiff = localOffset*60*1000 - offset*1000*60*60;
self.date = new Date(timestamp + self.offsetDiff);
self.getTime = function() {
return self.date.getTime() - self.offsetDiff;
};
self.toLocaleDateString = function() {
return self.date.toLocaleDateString();
};
self.getFullYear = function() {
return self.date.getFullYear();
};
self.getMonth = function() {
return self.date.getMonth();
};
self.getDate = function() {
return self.date.getDate();
};
self.getHours = function() {
return self.date.getHours();
};
self.getMinutes = function() {
return self.date.getMinutes();
};
self.getSeconds = function() {
return self.date.getSeconds();
};
self.getTimezoneOffset = function() {
return offset * 60;
};
self.getUTCFullYear = function() {
return self.origDate.getUTCFullYear();
};
self.getUTCMonth = function() {
return self.origDate.getUTCMonth();
};
self.getUTCDate = function() {
return self.origDate.getUTCDate();
};
self.getUTCHours = function() {
return self.origDate.getUTCHours();
};
self.getUTCMinutes = function() {
return self.origDate.getUTCMinutes();
};
self.getUTCSeconds = function() {
return self.origDate.getUTCSeconds();
};
self.getUTCMilliseconds = function() {
return self.origDate.getUTCMilliseconds();
};
self.getDay = function() {
return self.date.getDay();
};
// provide this method only on browsers that already have it
if (self.toISOString) {
self.toISOString = function() {
return padNumber(self.origDate.getUTCFullYear(), 4) + '-' +
padNumber(self.origDate.getUTCMonth() + 1, 2) + '-' +
padNumber(self.origDate.getUTCDate(), 2) + 'T' +
padNumber(self.origDate.getUTCHours(), 2) + ':' +
padNumber(self.origDate.getUTCMinutes(), 2) + ':' +
padNumber(self.origDate.getUTCSeconds(), 2) + '.' +
padNumber(self.origDate.getUTCMilliseconds(), 3) + 'Z'
}
}
//hide all methods not implemented in this mock that the Date prototype exposes
var unimplementedMethods = ['getMilliseconds', 'getUTCDay',
'getYear', 'setDate', 'setFullYear', 'setHours', 'setMilliseconds',
'setMinutes', 'setMonth', 'setSeconds', 'setTime', 'setUTCDate', 'setUTCFullYear',
'setUTCHours', 'setUTCMilliseconds', 'setUTCMinutes', 'setUTCMonth', 'setUTCSeconds',
'setYear', 'toDateString', 'toGMTString', 'toJSON', 'toLocaleFormat', 'toLocaleString',
'toLocaleTimeString', 'toSource', 'toString', 'toTimeString', 'toUTCString', 'valueOf'];
angular.forEach(unimplementedMethods, function(methodName) {
self[methodName] = function() {
throw Error("Method '" + methodName + "' is not implemented in the TzDate mock");
};
});
return self;
};
//make "tzDateInstance instanceof Date" return true
angular.mock.TzDate.prototype = Date.prototype;
})();
/**
* @ngdoc function
* @name angular.mock.debug
* @description
*
* *NOTE*: this is not an injectable instance, just a globally available function.
*
* Method for serializing common angular objects (scope, elements, etc..) into strings, useful for debugging.
*
* This method is also available on window, where it can be used to display objects on debug console.
*
* @param {*} object - any object to turn into string.
* @return {string} a serialized string of the argument
*/
angular.mock.dump = function(object) {
return serialize(object);
function serialize(object) {
var out;
if (angular.isElement(object)) {
object = angular.element(object);
out = angular.element('<div></div>');
angular.forEach(object, function(element) {
out.append(angular.element(element).clone());
});
out = out.html();
} else if (angular.isArray(object)) {
out = [];
angular.forEach(object, function(o) {
out.push(serialize(o));
});
out = '[ ' + out.join(', ') + ' ]';
} else if (angular.isObject(object)) {
if (angular.isFunction(object.$eval) && angular.isFunction(object.$apply)) {
out = serializeScope(object);
} else if (object instanceof Error) {
out = object.stack || ('' + object.name + ': ' + object.message);
} else {
out = angular.toJson(object, true);
}
} else {
out = String(object);
}
return out;
}
function serializeScope(scope, offset) {
offset = offset || ' ';
var log = [offset + 'Scope(' + scope.$id + '): {'];
for ( var key in scope ) {
if (scope.hasOwnProperty(key) && !key.match(/^(\$|this)/)) {
log.push(' ' + key + ': ' + angular.toJson(scope[key]));
}
}
var child = scope.$$childHead;
while(child) {
log.push(serializeScope(child, offset + ' '));
child = child.$$nextSibling;
}
log.push('}');
return log.join('\n' + offset);
}
};
/**
* @ngdoc object
* @name ngMock.$httpBackend
* @description
* Fake HTTP backend implementation suitable for unit testing application that use the
* {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for end-to-end testing or backend-less
* development please see {@link ngMockE2E.$httpBackend e2e $httpBackend mock}.
*
* During unit testing, we want our unit tests to run quickly and have no external dependencies so
* we don’t want to send {@link https://developer.mozilla.org/en/xmlhttprequest XHR} or
* {@link http://en.wikipedia.org/wiki/JSONP JSONP} requests to a real server. All we really need is
* to verify whether a certain request has been sent or not, or alternatively just let the
* application make requests, respond with pre-trained responses and assert that the end result is
* what we expect it to be.
*
* This mock implementation can be used to respond with static or dynamic responses via the
* `expect` and `when` apis and their shortcuts (`expectGET`, `whenPOST`, etc).
*
* When an Angular application needs some data from a server, it calls the $http service, which
* sends the request to a real server using $httpBackend service. With dependency injection, it is
* easy to inject $httpBackend mock (which has the same API as $httpBackend) and use it to verify
* the requests and respond with some testing data without sending a request to real server.
*
* There are two ways to specify what test data should be returned as http responses by the mock
* backend when the code under test makes http requests:
*
* - `$httpBackend.expect` - specifies a request expectation
* - `$httpBackend.when` - specifies a backend definition
*
*
* # Request Expectations vs Backend Definitions
*
* Request expectations provide a way to make assertions about requests made by the application and
* to define responses for those requests. The test will fail if the expected requests are not made
* or they are made in the wrong order.
*
* Backend definitions allow you to define a fake backend for your application which doesn't assert
* if a particular request was made or not, it just returns a trained response if a request is made.
* The test will pass whether or not the request gets made during testing.
*
*
* <table class="table">
* <tr><th width="220px"></th><th>Request expectations</th><th>Backend definitions</th></tr>
* <tr>
* <th>Syntax</th>
* <td>.expect(...).respond(...)</td>
* <td>.when(...).respond(...)</td>
* </tr>
* <tr>
* <th>Typical usage</th>
* <td>strict unit tests</td>
* <td>loose (black-box) unit testing</td>
* </tr>
* <tr>
* <th>Fulfills multiple requests</th>
* <td>NO</td>
* <td>YES</td>
* </tr>
* <tr>
* <th>Order of requests matters</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Request required</th>
* <td>YES</td>
* <td>NO</td>
* </tr>
* <tr>
* <th>Response required</th>
* <td>optional (see below)</td>
* <td>YES</td>
* </tr>
* </table>
*
* In cases where both backend definitions and request expectations are specified during unit
* testing, the request expectations are evaluated first.
*
* If a request expectation has no response specified, the algorithm will search your backend
* definitions for an appropriate response.
*
* If a request didn't match any expectation or if the expectation doesn't have the response
* defined, the backend definitions are evaluated in sequential order to see if any of them match
* the request. The response from the first matched definition is returned.
*
*
* # Flushing HTTP requests
*
* The $httpBackend used in production, always responds to requests with responses asynchronously.
* If we preserved this behavior in unit testing, we'd have to create async unit tests, which are
* hard to write, follow and maintain. At the same time the testing mock, can't respond
* synchronously because that would change the execution of the code under test. For this reason the
* mock $httpBackend has a `flush()` method, which allows the test to explicitly flush pending
* requests and thus preserving the async api of the backend, while allowing the test to execute
* synchronously.
*
*
* # Unit testing with mock $httpBackend
*
* <pre>
// controller
function MyController($scope, $http) {
$http.get('/auth.py').success(function(data) {
$scope.user = data;
});
this.saveMessage = function(message) {
$scope.status = 'Saving...';
$http.post('/add-msg.py', message).success(function(response) {
$scope.status = '';
}).error(function() {
$scope.status = 'ERROR!';
});
};
}
// testing controller
var $http;
beforeEach(inject(function($injector) {
$httpBackend = $injector.get('$httpBackend');
// backend definition common for all tests
$httpBackend.when('GET', '/auth.py').respond({userId: 'userX'}, {'A-Token': 'xxx'});
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should fetch authentication token', function() {
$httpBackend.expectGET('/auth.py');
var controller = scope.$new(MyController);
$httpBackend.flush();
});
it('should send msg to server', function() {
// now you don’t care about the authentication, but
// the controller will still send the request and
// $httpBackend will respond without you having to
// specify the expectation and response for this request
$httpBackend.expectPOST('/add-msg.py', 'message content').respond(201, '');
var controller = scope.$new(MyController);
$httpBackend.flush();
controller.saveMessage('message content');
expect(controller.status).toBe('Saving...');
$httpBackend.flush();
expect(controller.status).toBe('');
});
it('should send auth header', function() {
$httpBackend.expectPOST('/add-msg.py', undefined, function(headers) {
// check if the header was send, if it wasn't the expectation won't
// match the request and the test will fail
return headers['Authorization'] == 'xxx';
}).respond(201, '');
var controller = scope.$new(MyController);
controller.saveMessage('whatever');
$httpBackend.flush();
});
</pre>
*/
angular.mock.$HttpBackendProvider = function() {
this.$get = [createHttpBackendMock];
};
/**
* General factory function for $httpBackend mock.
* Returns instance for unit testing (when no arguments specified):
* - passing through is disabled
* - auto flushing is disabled
*
* Returns instance for e2e testing (when `$delegate` and `$browser` specified):
* - passing through (delegating request to real backend) is enabled
* - auto flushing is enabled
*
* @param {Object=} $delegate Real $httpBackend instance (allow passing through if specified)
* @param {Object=} $browser Auto-flushing enabled if specified
* @return {Object} Instance of $httpBackend mock
*/
function createHttpBackendMock($delegate, $browser) {
var definitions = [],
expectations = [],
responses = [],
responsesPush = angular.bind(responses, responses.push);
function createResponse(status, data, headers) {
if (angular.isFunction(status)) return status;
return function() {
return angular.isNumber(status)
? [status, data, headers]
: [200, status, data];
};
}
// TODO(vojta): change params to: method, url, data, headers, callback
function $httpBackend(method, url, data, callback, headers) {
var xhr = new MockXhr(),
expectation = expectations[0],
wasExpected = false;
function prettyPrint(data) {
return (angular.isString(data) || angular.isFunction(data) || data instanceof RegExp)
? data
: angular.toJson(data);
}
if (expectation && expectation.match(method, url)) {
if (!expectation.matchData(data))
throw Error('Expected ' + expectation + ' with different data\n' +
'EXPECTED: ' + prettyPrint(expectation.data) + '\nGOT: ' + data);
if (!expectation.matchHeaders(headers))
throw Error('Expected ' + expectation + ' with different headers\n' +
'EXPECTED: ' + prettyPrint(expectation.headers) + '\nGOT: ' +
prettyPrint(headers));
expectations.shift();
if (expectation.response) {
responses.push(function() {
var response = expectation.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(response[0], response[1], xhr.getAllResponseHeaders());
});
return;
}
wasExpected = true;
}
var i = -1, definition;
while ((definition = definitions[++i])) {
if (definition.match(method, url, data, headers || {})) {
if (definition.response) {
// if $browser specified, we do auto flush all requests
($browser ? $browser.defer : responsesPush)(function() {
var response = definition.response(method, url, data, headers);
xhr.$$respHeaders = response[2];
callback(response[0], response[1], xhr.getAllResponseHeaders());
});
} else if (definition.passThrough) {
$delegate(method, url, data, callback, headers);
} else throw Error('No response defined !');
return;
}
}
throw wasExpected ?
Error('No response defined !') :
Error('Unexpected request: ' + method + ' ' + url + '\n' +
(expectation ? 'Expected ' + expectation : 'No more request expected'));
}
/**
* @ngdoc method
* @name ngMock.$httpBackend#when
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.when = function(method, url, data, headers) {
var definition = new MockHttpExpectation(method, url, data, headers),
chain = {
respond: function(status, data, headers) {
definition.response = createResponse(status, data, headers);
}
};
if ($browser) {
chain.passThrough = function() {
definition.passThrough = true;
};
}
definitions.push(definition);
return chain;
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenGET
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenHEAD
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenDELETE
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenPOST
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenPUT
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#whenJSONP
* @methodOf ngMock.$httpBackend
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
createShortMethods('when');
/**
* @ngdoc method
* @name ngMock.$httpBackend#expect
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current expectation.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
*/
$httpBackend.expect = function(method, url, data, headers) {
var expectation = new MockHttpExpectation(method, url, data, headers);
expectations.push(expectation);
return {
respond: function(status, data, headers) {
expectation.response = createResponse(status, data, headers);
}
};
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectGET
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for GET requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled. See #expect for more info.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectHEAD
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for HEAD requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectDELETE
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for DELETE requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPOST
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for POST requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPUT
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for PUT requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectPATCH
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for PATCH requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {Object=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
/**
* @ngdoc method
* @name ngMock.$httpBackend#expectJSONP
* @methodOf ngMock.$httpBackend
* @description
* Creates a new request expectation for JSONP requests. For more info see `expect()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` method that control how a matched
* request is handled.
*/
createShortMethods('expect');
/**
* @ngdoc method
* @name ngMock.$httpBackend#flush
* @methodOf ngMock.$httpBackend
* @description
* Flushes all pending requests using the trained responses.
*
* @param {number=} count Number of responses to flush (in the order they arrived). If undefined,
* all pending requests will be flushed. If there are no pending requests when the flush method
* is called an exception is thrown (as this typically a sign of programming error).
*/
$httpBackend.flush = function(count) {
if (!responses.length) throw Error('No pending request to flush !');
if (angular.isDefined(count)) {
while (count--) {
if (!responses.length) throw Error('No more pending request to flush !');
responses.shift()();
}
} else {
while (responses.length) {
responses.shift()();
}
}
$httpBackend.verifyNoOutstandingExpectation();
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#verifyNoOutstandingExpectation
* @methodOf ngMock.$httpBackend
* @description
* Verifies that all of the requests defined via the `expect` api were made. If any of the
* requests were not made, verifyNoOutstandingExpectation throws an exception.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* <pre>
* afterEach($httpBackend.verifyExpectations);
* </pre>
*/
$httpBackend.verifyNoOutstandingExpectation = function() {
if (expectations.length) {
throw Error('Unsatisfied requests: ' + expectations.join(', '));
}
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#verifyNoOutstandingRequest
* @methodOf ngMock.$httpBackend
* @description
* Verifies that there are no outstanding requests that need to be flushed.
*
* Typically, you would call this method following each test case that asserts requests using an
* "afterEach" clause.
*
* <pre>
* afterEach($httpBackend.verifyNoOutstandingRequest);
* </pre>
*/
$httpBackend.verifyNoOutstandingRequest = function() {
if (responses.length) {
throw Error('Unflushed requests: ' + responses.length);
}
};
/**
* @ngdoc method
* @name ngMock.$httpBackend#resetExpectations
* @methodOf ngMock.$httpBackend
* @description
* Resets all request expectations, but preserves all backend definitions. Typically, you would
* call resetExpectations during a multiple-phase test when you want to reuse the same instance of
* $httpBackend mock.
*/
$httpBackend.resetExpectations = function() {
expectations.length = 0;
responses.length = 0;
};
return $httpBackend;
function createShortMethods(prefix) {
angular.forEach(['GET', 'DELETE', 'JSONP'], function(method) {
$httpBackend[prefix + method] = function(url, headers) {
return $httpBackend[prefix](method, url, undefined, headers)
}
});
angular.forEach(['PUT', 'POST', 'PATCH'], function(method) {
$httpBackend[prefix + method] = function(url, data, headers) {
return $httpBackend[prefix](method, url, data, headers)
}
});
}
}
function MockHttpExpectation(method, url, data, headers) {
this.data = data;
this.headers = headers;
this.match = function(m, u, d, h) {
if (method != m) return false;
if (!this.matchUrl(u)) return false;
if (angular.isDefined(d) && !this.matchData(d)) return false;
if (angular.isDefined(h) && !this.matchHeaders(h)) return false;
return true;
};
this.matchUrl = function(u) {
if (!url) return true;
if (angular.isFunction(url.test)) return url.test(u);
return url == u;
};
this.matchHeaders = function(h) {
if (angular.isUndefined(headers)) return true;
if (angular.isFunction(headers)) return headers(h);
return angular.equals(headers, h);
};
this.matchData = function(d) {
if (angular.isUndefined(data)) return true;
if (data && angular.isFunction(data.test)) return data.test(d);
if (data && !angular.isString(data)) return angular.toJson(data) == d;
return data == d;
};
this.toString = function() {
return method + ' ' + url;
};
}
function MockXhr() {
// hack for testing $http, $httpBackend
MockXhr.$$lastInstance = this;
this.open = function(method, url, async) {
this.$$method = method;
this.$$url = url;
this.$$async = async;
this.$$reqHeaders = {};
this.$$respHeaders = {};
};
this.send = function(data) {
this.$$data = data;
};
this.setRequestHeader = function(key, value) {
this.$$reqHeaders[key] = value;
};
this.getResponseHeader = function(name) {
// the lookup must be case insensitive, that's why we try two quick lookups and full scan at last
var header = this.$$respHeaders[name];
if (header) return header;
name = angular.lowercase(name);
header = this.$$respHeaders[name];
if (header) return header;
header = undefined;
angular.forEach(this.$$respHeaders, function(headerVal, headerName) {
if (!header && angular.lowercase(headerName) == name) header = headerVal;
});
return header;
};
this.getAllResponseHeaders = function() {
var lines = [];
angular.forEach(this.$$respHeaders, function(value, key) {
lines.push(key + ': ' + value);
});
return lines.join('\n');
};
this.abort = angular.noop;
}
/**
* @ngdoc function
* @name ngMock.$timeout
* @description
*
* This service is just a simple decorator for {@link ng.$timeout $timeout} service
* that adds a "flush" method.
*/
/**
* @ngdoc method
* @name ngMock.$timeout#flush
* @methodOf ngMock.$timeout
* @description
*
* Flushes the queue of pending tasks.
*/
/**
*
*/
angular.mock.$RootElementProvider = function() {
this.$get = function() {
return angular.element('<div ng-app></div>');
}
};
/**
* @ngdoc overview
* @name ngMock
* @description
*
* The `ngMock` is an angular module which is used with `ng` module and adds unit-test configuration as well as useful
* mocks to the {@link AUTO.$injector $injector}.
*/
angular.module('ngMock', ['ng']).provider({
$browser: angular.mock.$BrowserProvider,
$exceptionHandler: angular.mock.$ExceptionHandlerProvider,
$log: angular.mock.$LogProvider,
$httpBackend: angular.mock.$HttpBackendProvider,
$rootElement: angular.mock.$RootElementProvider
}).config(function($provide) {
$provide.decorator('$timeout', function($delegate, $browser) {
$delegate.flush = function() {
$browser.defer.flush();
};
return $delegate;
});
});
/**
* @ngdoc overview
* @name ngMockE2E
* @description
*
* The `ngMockE2E` is an angular module which contains mocks suitable for end-to-end testing.
* Currently there is only one mock present in this module -
* the {@link ngMockE2E.$httpBackend e2e $httpBackend} mock.
*/
angular.module('ngMockE2E', ['ng']).config(function($provide) {
$provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator);
});
/**
* @ngdoc object
* @name ngMockE2E.$httpBackend
* @description
* Fake HTTP backend implementation suitable for end-to-end testing or backend-less development of
* applications that use the {@link ng.$http $http service}.
*
* *Note*: For fake http backend implementation suitable for unit testing please see
* {@link ngMock.$httpBackend unit-testing $httpBackend mock}.
*
* This implementation can be used to respond with static or dynamic responses via the `when` api
* and its shortcuts (`whenGET`, `whenPOST`, etc) and optionally pass through requests to the
* real $httpBackend for specific requests (e.g. to interact with certain remote apis or to fetch
* templates from a webserver).
*
* As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application
* is being developed with the real backend api replaced with a mock, it is often desirable for
* certain category of requests to bypass the mock and issue a real http request (e.g. to fetch
* templates or static files from the webserver). To configure the backend with this behavior
* use the `passThrough` request handler of `when` instead of `respond`.
*
* Additionally, we don't want to manually have to flush mocked out requests like we do during unit
* testing. For this reason the e2e $httpBackend automatically flushes mocked out requests
* automatically, closely simulating the behavior of the XMLHttpRequest object.
*
* To setup the application to run with this http backend, you have to create a module that depends
* on the `ngMockE2E` and your application modules and defines the fake backend:
*
* <pre>
* myAppDev = angular.module('myAppDev', ['myApp', 'ngMockE2E']);
* myAppDev.run(function($httpBackend) {
* phones = [{name: 'phone1'}, {name: 'phone2'}];
*
* // returns the current list of phones
* $httpBackend.whenGET('/phones').respond(phones);
*
* // adds a new phone to the phones array
* $httpBackend.whenPOST('/phones').respond(function(method, url, data) {
* phones.push(angular.fromJSON(data));
* });
* $httpBackend.whenGET(/^\/templates\//).passThrough();
* //...
* });
* </pre>
*
* Afterwards, bootstrap your app with this new module.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#when
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition.
*
* @param {string} method HTTP method.
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers or function that receives http header
* object and returns true if the headers match the current definition.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*
* - respond – `{function([status,] data[, headers])|function(function(method, url, data, headers)}`
* – The respond method takes a set of static data to be returned or a function that can return
* an array containing response status (number), response data (string) and response headers
* (Object).
* - passThrough – `{function()}` – Any request matching a backend definition with `passThrough`
* handler, will be pass through to the real backend (an XHR request will be made to the
* server.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenGET
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for GET requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenHEAD
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for HEAD requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenDELETE
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for DELETE requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPOST
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for POST requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPUT
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for PUT requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenPATCH
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for PATCH requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @param {(string|RegExp)=} data HTTP request body.
* @param {(Object|function(Object))=} headers HTTP headers.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
/**
* @ngdoc method
* @name ngMockE2E.$httpBackend#whenJSONP
* @methodOf ngMockE2E.$httpBackend
* @description
* Creates a new backend definition for JSONP requests. For more info see `when()`.
*
* @param {string|RegExp} url HTTP url.
* @returns {requestHandler} Returns an object with `respond` and `passThrough` methods that
* control how a matched request is handled.
*/
angular.mock.e2e = {};
angular.mock.e2e.$httpBackendDecorator = ['$delegate', '$browser', createHttpBackendMock];
angular.mock.clearDataCache = function() {
var key,
cache = angular.element.cache;
for(key in cache) {
if (cache.hasOwnProperty(key)) {
var handle = cache[key].handle;
handle && angular.element(handle.elem).unbind();
delete cache[key];
}
}
};
window.jstestdriver && (function(window) {
/**
* Global method to output any number of objects into JSTD console. Useful for debugging.
*/
window.dump = function() {
var args = [];
angular.forEach(arguments, function(arg) {
args.push(angular.mock.dump(arg));
});
jstestdriver.console.log.apply(jstestdriver.console, args);
if (window.console) {
window.console.log.apply(window.console, args);
}
};
})(window);
window.jasmine && (function(window) {
afterEach(function() {
var spec = getCurrentSpec();
spec.$injector = null;
spec.$modules = null;
angular.mock.clearDataCache();
});
function getCurrentSpec() {
return jasmine.getEnv().currentSpec;
}
function isSpecRunning() {
var spec = getCurrentSpec();
return spec && spec.queue.running;
}
/**
* @ngdoc function
* @name angular.mock.module
* @description
*
* *NOTE*: This is function is also published on window for easy access.<br>
* *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}.
*
* This function registers a module configuration code. It collects the configuration information
* which will be used when the injector is created by {@link angular.mock.inject inject}.
*
* See {@link angular.mock.inject inject} for usage example
*
* @param {...(string|Function)} fns any number of modules which are represented as string
* aliases or as anonymous module initialization functions. The modules are used to
* configure the injector. The 'ng' and 'ngMock' modules are automatically loaded.
*/
window.module = angular.mock.module = function() {
var moduleFns = Array.prototype.slice.call(arguments, 0);
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
var spec = getCurrentSpec();
if (spec.$injector) {
throw Error('Injector already created, can not register a module!');
} else {
var modules = spec.$modules || (spec.$modules = []);
angular.forEach(moduleFns, function(module) {
modules.push(module);
});
}
}
};
/**
* @ngdoc function
* @name angular.mock.inject
* @description
*
* *NOTE*: This is function is also published on window for easy access.<br>
* *NOTE*: Only available with {@link http://pivotal.github.com/jasmine/ jasmine}.
*
* The inject function wraps a function into an injectable function. The inject() creates new
* instance of {@link AUTO.$injector $injector} per test, which is then used for
* resolving references.
*
* See also {@link angular.mock.module module}
*
* Example of what a typical jasmine tests looks like with the inject method.
* <pre>
*
* angular.module('myApplicationModule', [])
* .value('mode', 'app')
* .value('version', 'v1.0.1');
*
*
* describe('MyApp', function() {
*
* // You need to load modules that you want to test,
* // it loads only the "ng" module by default.
* beforeEach(module('myApplicationModule'));
*
*
* // inject() is used to inject arguments of all given functions
* it('should provide a version', inject(function(mode, version) {
* expect(version).toEqual('v1.0.1');
* expect(mode).toEqual('app');
* }));
*
*
* // The inject and module method can also be used inside of the it or beforeEach
* it('should override a version and test the new version is injected', function() {
* // module() takes functions or strings (module aliases)
* module(function($provide) {
* $provide.value('version', 'overridden'); // override version here
* });
*
* inject(function(version) {
* expect(version).toEqual('overridden');
* });
* ));
* });
*
* </pre>
*
* @param {...Function} fns any number of functions which will be injected using the injector.
*/
window.inject = angular.mock.inject = function() {
var blockFns = Array.prototype.slice.call(arguments, 0);
var stack = new Error('Declaration Location').stack;
return isSpecRunning() ? workFn() : workFn;
/////////////////////
function workFn() {
var spec = getCurrentSpec();
var modules = spec.$modules || [];
modules.unshift('ngMock');
modules.unshift('ng');
var injector = spec.$injector;
if (!injector) {
injector = spec.$injector = angular.injector(modules);
}
for(var i = 0, ii = blockFns.length; i < ii; i++) {
try {
injector.invoke(blockFns[i] || angular.noop, this);
} catch (e) {
if(e.stack) e.stack += '\n' + stack;
throw e;
}
}
}
}
})(window);
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngSanitize
* @description
*/
/*
* HTML Parser By Misko Hevery (misko@hevery.com)
* based on: HTML Parser By John Resig (ejohn.org)
* Original code by Erik Arvidsson, Mozilla Public License
* http://erik.eae.net/simplehtmlparser/simplehtmlparser.js
*
* // Use like so:
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
*/
/**
* @ngdoc service
* @name ngSanitize.$sanitize
* @function
*
* @description
* The input is sanitized by parsing the html into tokens. All safe tokens (from a whitelist) are
* then serialized back to properly escaped html string. This means that no unsafe input can make
* it into the returned string, however, since our parser is more strict than a typical browser
* parser, it's possible that some obscure input, which would be recognized as valid HTML by a
* browser, won't make it through the sanitizer.
*
* @param {string} html Html input.
* @returns {string} Sanitized html.
*
* @example
<doc:example module="ngSanitize">
<doc:source>
<script>
function Ctrl($scope) {
$scope.snippet =
'<p style="color:blue">an html\n' +
'<em onmouseover="this.textContent=\'PWN3D!\'">click here</em>\n' +
'snippet</p>';
}
</script>
<div ng-controller="Ctrl">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="html-filter">
<td>html filter</td>
<td>
<pre><div ng-bind-html="snippet"><br/></div></pre>
</td>
<td>
<div ng-bind-html="snippet"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br/></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
<tr id="html-unsafe-filter">
<td>unsafe html filter</td>
<td><pre><div ng-bind-html-unsafe="snippet"><br/></div></pre></td>
<td><div ng-bind-html-unsafe="snippet"></div></td>
</tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should sanitize the html snippet ', function() {
expect(using('#html-filter').element('div').html()).
toBe('<p>an html\n<em>click here</em>\nsnippet</p>');
});
it('should escape snippet without any filter', function() {
expect(using('#escaped-html').element('div').html()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should inline raw snippet if filtered as unsafe', function() {
expect(using('#html-unsafe-filter').element("div").html()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
input('snippet').enter('new <b>text</b>');
expect(using('#html-filter').binding('snippet')).toBe('new <b>text</b>');
expect(using('#escaped-html').element('div').html()).toBe("new <b>text</b>");
expect(using('#html-unsafe-filter').binding("snippet")).toBe('new <b>text</b>');
});
</doc:scenario>
</doc:example>
*/
var $sanitize = function(html) {
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf));
return buf.join('');
};
// Regular Expressions for parsing tags and attributes
var START_TAG_REGEXP = /^<\s*([\w:-]+)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*>/,
END_TAG_REGEXP = /^<\s*\/\s*([\w:-]+)[^>]*>/,
ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
BEGIN_TAG_REGEXP = /^</,
BEGING_END_TAGE_REGEXP = /^<\s*\//,
COMMENT_REGEXP = /<!--(.*?)-->/g,
CDATA_REGEXP = /<!\[CDATA\[(.*?)]]>/g,
URI_REGEXP = /^((ftp|https?):\/\/|mailto:|#)/,
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g; // Match everything outside of normal chars and " (quote character)
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = makeMap("area,br,col,hr,img,wbr");
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
optionalEndTagInlineElements = makeMap("rp,rt"),
optionalEndTagElements = angular.extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements);
// Safe Block Elements - HTML5
var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article,aside," +
"blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,h6," +
"header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
// Inline Elements - HTML5
var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b,bdi,bdo," +
"big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,samp,small," +
"span,strike,strong,sub,sup,time,tt,u,var"));
// Special Elements (can contain anything)
var specialElements = makeMap("script,style");
var validElements = angular.extend({}, voidElements, blockElements, inlineElements, optionalEndTagElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap");
var validAttrs = angular.extend({}, uriAttrs, makeMap(
'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
'scope,scrolling,shape,span,start,summary,target,title,type,'+
'valign,value,vspace,width'));
function makeMap(str) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) obj[items[i]] = true;
return obj;
}
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParser( html, handler ) {
var index, chars, match, stack = [], last = html;
stack.last = function() { return stack[ stack.length - 1 ]; };
while ( html ) {
chars = true;
// Make sure we're not in a script or style element
if ( !stack.last() || !specialElements[ stack.last() ] ) {
// Comment
if ( html.indexOf("<!--") === 0 ) {
index = html.indexOf("-->");
if ( index >= 0 ) {
if (handler.comment) handler.comment( html.substring( 4, index ) );
html = html.substring( index + 3 );
chars = false;
}
// end tag
} else if ( BEGING_END_TAGE_REGEXP.test(html) ) {
match = html.match( END_TAG_REGEXP );
if ( match ) {
html = html.substring( match[0].length );
match[0].replace( END_TAG_REGEXP, parseEndTag );
chars = false;
}
// start tag
} else if ( BEGIN_TAG_REGEXP.test(html) ) {
match = html.match( START_TAG_REGEXP );
if ( match ) {
html = html.substring( match[0].length );
match[0].replace( START_TAG_REGEXP, parseStartTag );
chars = false;
}
}
if ( chars ) {
index = html.indexOf("<");
var text = index < 0 ? html : html.substring( 0, index );
html = index < 0 ? "" : html.substring( index );
if (handler.chars) handler.chars( decodeEntities(text) );
}
} else {
html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'), function(all, text){
text = text.
replace(COMMENT_REGEXP, "$1").
replace(CDATA_REGEXP, "$1");
if (handler.chars) handler.chars( decodeEntities(text) );
return "";
});
parseEndTag( "", stack.last() );
}
if ( html == last ) {
throw "Parse Error: " + html;
}
last = html;
}
// Clean up any remaining tags
parseEndTag();
function parseStartTag( tag, tagName, rest, unary ) {
tagName = angular.lowercase(tagName);
if ( blockElements[ tagName ] ) {
while ( stack.last() && inlineElements[ stack.last() ] ) {
parseEndTag( "", stack.last() );
}
}
if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) {
parseEndTag( "", tagName );
}
unary = voidElements[ tagName ] || !!unary;
if ( !unary )
stack.push( tagName );
var attrs = {};
rest.replace(ATTR_REGEXP, function(match, name, doubleQuotedValue, singleQoutedValue, unqoutedValue) {
var value = doubleQuotedValue
|| singleQoutedValue
|| unqoutedValue
|| '';
attrs[name] = decodeEntities(value);
});
if (handler.start) handler.start( tagName, attrs, unary );
}
function parseEndTag( tag, tagName ) {
var pos = 0, i;
tagName = angular.lowercase(tagName);
if ( tagName )
// Find the closest opened tag of the same type
for ( pos = stack.length - 1; pos >= 0; pos-- )
if ( stack[ pos ] == tagName )
break;
if ( pos >= 0 ) {
// Close all the open elements, up the stack
for ( i = stack.length - 1; i >= pos; i-- )
if (handler.end) handler.end( stack[ i ] );
// Remove the open elements from the stack
stack.length = pos;
}
}
}
/**
* decodes all entities into regular string
* @param value
* @returns {string} A string with decoded entities.
*/
var hiddenPre=document.createElement("pre");
function decodeEntities(value) {
hiddenPre.innerHTML=value.replace(/</g,"<");
return hiddenPre.innerText || hiddenPre.textContent || '';
}
/**
* Escapes all potentially dangerous characters, so that the
* resulting string can be safely inserted into attribute or
* element text.
* @param value
* @returns escaped text
*/
function encodeEntities(value) {
return value.
replace(/&/g, '&').
replace(NON_ALPHANUMERIC_REGEXP, function(value){
return '&#' + value.charCodeAt(0) + ';';
}).
replace(/</g, '<').
replace(/>/g, '>');
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.jain('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriter(buf){
var ignore = false;
var out = angular.bind(buf, buf.push);
return {
start: function(tag, attrs, unary){
tag = angular.lowercase(tag);
if (!ignore && specialElements[tag]) {
ignore = tag;
}
if (!ignore && validElements[tag] == true) {
out('<');
out(tag);
angular.forEach(attrs, function(value, key){
var lkey=angular.lowercase(key);
if (validAttrs[lkey]==true && (uriAttrs[lkey]!==true || value.match(URI_REGEXP))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out(unary ? '/>' : '>');
}
},
end: function(tag){
tag = angular.lowercase(tag);
if (!ignore && validElements[tag] == true) {
out('</');
out(tag);
out('>');
}
if (tag == ignore) {
ignore = false;
}
},
chars: function(chars){
if (!ignore) {
out(encodeEntities(chars));
}
}
};
}
// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).value('$sanitize', $sanitize);
/**
* @ngdoc directive
* @name ngSanitize.directive:ngBindHtml
*
* @description
* Creates a binding that will sanitize the result of evaluating the `expression` with the
* {@link ngSanitize.$sanitize $sanitize} service and innerHTML the result into the current element.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*/
angular.module('ngSanitize').directive('ngBindHtml', ['$sanitize', function($sanitize) {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
scope.$watch(attr.ngBindHtml, function(value) {
value = $sanitize(value);
element.html(value || '');
});
};
}]);
/**
* @ngdoc filter
* @name ngSanitize.filter:linky
* @function
*
* @description
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
* plain email address links.
*
* @param {string} text Input text.
* @returns {string} Html-linkified text.
*
* @example
<doc:example module="ngSanitize">
<doc:source>
<script>
function Ctrl($scope) {
$scope.snippet =
'Pretty text with some links:\n'+
'http://angularjs.org/,\n'+
'mailto:us@somewhere.org,\n'+
'another@somewhere.org,\n'+
'and one more: ftp://127.0.0.1/.';
}
</script>
<div ng-controller="Ctrl">
Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<table>
<tr>
<td>Filter</td>
<td>Source</td>
<td>Rendered</td>
</tr>
<tr id="linky-filter">
<td>linky filter</td>
<td>
<pre><div ng-bind-html="snippet | linky"><br></div></pre>
</td>
<td>
<div ng-bind-html="snippet | linky"></div>
</td>
</tr>
<tr id="escaped-html">
<td>no filter</td>
<td><pre><div ng-bind="snippet"><br></div></pre></td>
<td><div ng-bind="snippet"></div></td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should linkify the snippet with urls', function() {
expect(using('#linky-filter').binding('snippet | linky')).
toBe('Pretty text with some links: ' +
'<a href="http://angularjs.org/">http://angularjs.org/</a>, ' +
'<a href="mailto:us@somewhere.org">us@somewhere.org</a>, ' +
'<a href="mailto:another@somewhere.org">another@somewhere.org</a>, ' +
'and one more: <a href="ftp://127.0.0.1/">ftp://127.0.0.1/</a>.');
});
it ('should not linkify snippet without the linky filter', function() {
expect(using('#escaped-html').binding('snippet')).
toBe("Pretty text with some links:\n" +
"http://angularjs.org/,\n" +
"mailto:us@somewhere.org,\n" +
"another@somewhere.org,\n" +
"and one more: ftp://127.0.0.1/.");
});
it('should update', function() {
input('snippet').enter('new http://link.');
expect(using('#linky-filter').binding('snippet | linky')).
toBe('new <a href="http://link">http://link</a>.');
expect(using('#escaped-html').binding('snippet')).toBe('new http://link.');
});
</doc:scenario>
</doc:example>
*/
angular.module('ngSanitize').filter('linky', function() {
var LINKY_URL_REGEXP = /((ftp|https?):\/\/|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s\.\;\,\(\)\{\}\<\>]/,
MAILTO_REGEXP = /^mailto:/;
return function(text) {
if (!text) return text;
var match;
var raw = text;
var html = [];
// TODO(vojta): use $sanitize instead
var writer = htmlSanitizeWriter(html);
var url;
var i;
while ((match = raw.match(LINKY_URL_REGEXP))) {
// We can not end in these as they are sometimes found at the end of the sentence
url = match[0];
// if we did not match ftp/http/mailto then assume mailto
if (match[2] == match[3]) url = 'mailto:' + url;
i = match.index;
writer.chars(raw.substr(0, i));
writer.start('a', {href:url});
writer.chars(match[0].replace(MAILTO_REGEXP, ''));
writer.end('a');
raw = raw.substring(i + match[0].length);
}
writer.chars(raw);
return html.join('');
};
});
})(window, window.angular);
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configure information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
'use strict';
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Option configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider.directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which needs to be performed when the injector with
* with the current module is finished loading.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
)(window);
/**
* Closure compiler type information
*
* @typedef { {
* requires: !Array.<string>,
* invokeQueue: !Array.<Array.<*>>,
*
* service: function(string, Function):angular.Module,
* factory: function(string, Function):angular.Module,
* value: function(string, *):angular.Module,
*
* filter: function(string, Function):angular.Module,
*
* init: function(Function):angular.Module
* } }
*/
angular.Module;
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window) {
'use strict';
/**
* JSTestDriver adapter for angular scenario tests
*
* Example of jsTestDriver.conf for running scenario tests with JSTD:
<pre>
server: http://localhost:9877
load:
- lib/angular-scenario.js
- lib/jstd-scenario-adapter-config.js
- lib/jstd-scenario-adapter.js
# your test files go here #
proxy:
- {matcher: "/your-prefix/*", server: "http://localhost:8000/"}
</pre>
*
* For more information on how to configure jstd proxy, see {@link http://code.google.com/p/js-test-driver/wiki/Proxy}
* Note the order of files - it's important !
*
* Example of jstd-scenario-adapter-config.js
<pre>
var jstdScenarioAdapter = {
relativeUrlPrefix: '/your-prefix/'
};
</pre>
*
* Whenever you use <code>browser().navigateTo('relativeUrl')</code> in your scenario test, the relativeUrlPrefix will be prepended.
* You have to configure this to work together with JSTD proxy.
*
* Let's assume you are using the above configuration (jsTestDriver.conf and jstd-scenario-adapter-config.js):
* Now, when you call <code>browser().navigateTo('index.html')</code> in your scenario test, the browser will open /your-prefix/index.html.
* That matches the proxy, so JSTD will proxy this request to http://localhost:8000/index.html.
*/
/**
* Custom type of test case
*
* @const
* @see jstestdriver.TestCaseInfo
*/
var SCENARIO_TYPE = 'scenario';
/**
* Plugin for JSTestDriver
* Connection point between scenario's jstd output and jstestdriver.
*
* @see jstestdriver.PluginRegistrar
*/
function JstdPlugin() {
var nop = function() {};
this.reportResult = nop;
this.reportEnd = nop;
this.runScenario = nop;
this.name = 'Angular Scenario Adapter';
/**
* Called for each JSTD TestCase
*
* Handles only SCENARIO_TYPE test cases. There should be only one fake TestCase.
* Runs all scenario tests (under one fake TestCase) and report all results to JSTD.
*
* @param {jstestdriver.TestRunConfiguration} configuration
* @param {Function} onTestDone
* @param {Function} onAllTestsComplete
* @returns {boolean} True if this type of test is handled by this plugin, false otherwise
*/
this.runTestConfiguration = function(configuration, onTestDone, onAllTestsComplete) {
if (configuration.getTestCaseInfo().getType() != SCENARIO_TYPE) return false;
this.reportResult = onTestDone;
this.reportEnd = onAllTestsComplete;
this.runScenario();
return true;
};
this.getTestRunsConfigurationFor = function(testCaseInfos, expressions, testRunsConfiguration) {
testRunsConfiguration.push(
new jstestdriver.TestRunConfiguration(
new jstestdriver.TestCaseInfo(
'Angular Scenario Tests', function() {}, SCENARIO_TYPE), []));
return true;
};
}
/**
* Singleton instance of the plugin
* Accessed using closure by:
* - jstd output (reports to this plugin)
* - initScenarioAdapter (register the plugin to jstd)
*/
var plugin = new JstdPlugin();
/**
* Initialise scenario jstd-adapter
* (only if jstestdriver is defined)
*
* @param {Object} jstestdriver Undefined when run from browser (without jstd)
* @param {Function} initScenarioAndRun Function that inits scenario and runs all the tests
* @param {Object=} config Configuration object, supported properties:
* - relativeUrlPrefix: prefix for all relative links when navigateTo()
*/
function initScenarioAdapter(jstestdriver, initScenarioAndRun, config) {
if (jstestdriver) {
// create and register ScenarioPlugin
jstestdriver.pluginRegistrar.register(plugin);
plugin.runScenario = initScenarioAndRun;
/**
* HACK (angular.scenario.Application.navigateTo)
*
* We need to navigate to relative urls when running from browser (without JSTD),
* because we want to allow running scenario tests without creating its own virtual host.
* For example: http://angular.local/build/docs/docs-scenario.html
*
* On the other hand, when running with JSTD, we need to navigate to absolute urls,
* because of JSTD proxy. (proxy, because of same domain policy)
*
* So this hack is applied only if running with JSTD and change all relative urls to absolute.
*/
var appProto = angular.scenario.Application.prototype,
navigateTo = appProto.navigateTo,
relativeUrlPrefix = config && config.relativeUrlPrefix || '/';
appProto.navigateTo = function(url, loadFn, errorFn) {
if (url.charAt(0) != '/' && url.charAt(0) != '#' &&
url != 'about:blank' && !url.match(/^https?/)) {
url = relativeUrlPrefix + url;
}
return navigateTo.call(this, url, loadFn, errorFn);
};
}
}
/**
* Builds proper TestResult object from given model spec
*
* TODO(vojta) report error details
*
* @param {angular.scenario.ObjectModel.Spec} spec
* @returns {jstestdriver.TestResult}
*/
function createTestResultFromSpec(spec) {
var map = {
success: 'PASSED',
error: 'ERROR',
failure: 'FAILED'
};
return new jstestdriver.TestResult(
spec.fullDefinitionName,
spec.name,
jstestdriver.TestResult.RESULT[map[spec.status]],
spec.error || '',
spec.line || '',
spec.duration);
}
/**
* Generates JSTD output (jstestdriver.TestResult)
*/
angular.scenario.output('jstd', function(context, runner, model) {
model.on('SpecEnd', function(spec) {
plugin.reportResult(createTestResultFromSpec(spec));
});
model.on('RunnerEnd', function() {
plugin.reportEnd();
});
});
initScenarioAdapter(window.jstestdriver, angular.scenario.setUpAndRun, window.jstdScenarioAdapter);
})(window);
|
JavaScript
|
/**
* @license AngularJS v1.0.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {
'use strict';
/**
* @ngdoc overview
* @name ngCookies
*/
angular.module('ngCookies', ['ng']).
/**
* @ngdoc object
* @name ngCookies.$cookies
* @requires $browser
*
* @description
* Provides read/write access to browser's cookies.
*
* Only a simple Object is exposed and by adding or removing properties to/from
* this object, new cookies are created/deleted at the end of current $eval.
*
* @example
*/
factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) {
var cookies = {},
lastCookies = {},
lastBrowserCookies,
runEval = false,
copy = angular.copy,
isUndefined = angular.isUndefined;
//creates a poller fn that copies all cookies from the $browser to service & inits the service
$browser.addPollFn(function() {
var currentCookies = $browser.cookies();
if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl
lastBrowserCookies = currentCookies;
copy(currentCookies, lastCookies);
copy(currentCookies, cookies);
if (runEval) $rootScope.$apply();
}
})();
runEval = true;
//at the end of each eval, push cookies
//TODO: this should happen before the "delayed" watches fire, because if some cookies are not
// strings or browser refuses to store some cookies, we update the model in the push fn.
$rootScope.$watch(push);
return cookies;
/**
* Pushes all the cookies from the service to the browser and verifies if all cookies were stored.
*/
function push() {
var name,
value,
browserCookies,
updated;
//delete any cookies deleted in $cookies
for (name in lastCookies) {
if (isUndefined(cookies[name])) {
$browser.cookies(name, undefined);
}
}
//update all cookies updated in $cookies
for(name in cookies) {
value = cookies[name];
if (!angular.isString(value)) {
if (angular.isDefined(lastCookies[name])) {
cookies[name] = lastCookies[name];
} else {
delete cookies[name];
}
} else if (value !== lastCookies[name]) {
$browser.cookies(name, value);
updated = true;
}
}
//verify what was actually stored
if (updated){
updated = false;
browserCookies = $browser.cookies();
for (name in cookies) {
if (cookies[name] !== browserCookies[name]) {
//delete or reset all cookies that the browser dropped from $cookies
if (isUndefined(browserCookies[name])) {
delete cookies[name];
} else {
cookies[name] = browserCookies[name];
}
updated = true;
}
}
}
}
}]).
/**
* @ngdoc object
* @name ngCookies.$cookieStore
* @requires $cookies
*
* @description
* Provides a key-value (string-object) storage, that is backed by session cookies.
* Objects put or retrieved from this storage are automatically serialized or
* deserialized by angular's toJson/fromJson.
* @example
*/
factory('$cookieStore', ['$cookies', function($cookies) {
return {
/**
* @ngdoc method
* @name ngCookies.$cookieStore#get
* @methodOf ngCookies.$cookieStore
*
* @description
* Returns the value of given cookie key
*
* @param {string} key Id to use for lookup.
* @returns {Object} Deserialized cookie value.
*/
get: function(key) {
return angular.fromJson($cookies[key]);
},
/**
* @ngdoc method
* @name ngCookies.$cookieStore#put
* @methodOf ngCookies.$cookieStore
*
* @description
* Sets a value for given cookie key
*
* @param {string} key Id for the `value`.
* @param {Object} value Value to be stored.
*/
put: function(key, value) {
$cookies[key] = angular.toJson(value);
},
/**
* @ngdoc method
* @name ngCookies.$cookieStore#remove
* @methodOf ngCookies.$cookieStore
*
* @description
* Remove given cookie
*
* @param {string} key Id of the key-value pair to delete.
*/
remove: function(key) {
delete $cookies[key];
}
};
}]);
})(window, window.angular);
|
JavaScript
|
'use strict';
function UserCtrl($scope, backend) {
$scope.user = null;
$scope.login = function () {
backend.user().then(function (response) {
$scope.user = response.data;
});
}
$scope.login();
}
function EditorCtrl($scope, $location, $routeParams, $timeout, editor, doc, autosaver) {
console.log($routeParams);
$scope.editor = editor;
$scope.doc = doc;
$scope.$on('saved',
function (event) {
$location.path('/edit/' + doc.resource_id);
});
if ($routeParams.id) {
editor.load($routeParams.id);
} else {
// New doc, but defer to next event cycle to ensure init
$timeout(function () {
editor.create();
},
1);
}
}
function ShareCtrl($scope, appId, doc) {
/*
var client = gapi.drive.share.ShareClient(appId);
$scope.enabled = function() {
return doc.resource_id != null;
};
$scope.share = function() {
client.setItemIds([doc.resource_id]);
client.showSharingSettings();
}
*/
}
function MenuCtrl($scope, $location, appId) {
var onFilePicked = function (data) {
$scope.$apply(function () {
if (data.action == 'picked') {
var id = data.docs[0].id;
$location.path('/edit/' + id);
}
});
};
$scope.open = function () {
var view = new google.picker.View(google.picker.ViewId.DOCS);
view.setMimeTypes('text/plain');
var picker = new google.picker.PickerBuilder()
.setAppId(appId)
.addView(view)
.setCallback(angular.bind(this, onFilePicked))
.build();
picker.setVisible(true);
};
$scope.create = function () {
this.editor.create();
};
$scope.save = function () {
this.editor.save(true);
}
}
function RenameCtrl($scope, doc) {
$('#rename-dialog').on('show',
function () {
$scope.$apply(function () {
$scope.newFileName = doc.info.title;
});
});
$scope.save = function () {
doc.info.title = $scope.newFileName;
$('#rename-dialog').modal('hide');
};
}
function AboutCtrl($scope, backend) {
$('#about-dialog').on('show',
function () {
backend.about().then(function (result) {
$scope.info = result.data;
});
});
}
|
JavaScript
|
'use strict';
/* Filters */
angular.module('app.filters', [])
.filter('saveStateFormatter',
function () {
return function (state) {
if (state == EditorState.DIRTY) {
return 'You have unsaved changes';
} else if (state == EditorState.SAVE) {
return 'Saving...';
} else if (state == EditorState.LOAD) {
return 'Loading...';
} else if (state == EditorState.READONLY) {
return "Read only"
} else {
return 'All changes saved';
}
};
})
.filter('bytes',
function () {
return function (bytes) {
bytes = parseInt(bytes);
if (isNaN(bytes)) {
return "...";
}
var units = [' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB'];
var p = bytes > 0 ? Math.floor(Math.log(bytes) / Math.LN2 / 10) : 0;
var u = Math.round(bytes / Math.pow(2, 10 * p));
return u + units[p];
}
});
|
JavaScript
|
'use strict';
var module = angular.module('app.services', []);
var ONE_HOUR_IN_MS = 1000 * 60 * 60;
// Shared model for current document
module.factory('doc',
function ($rootScope) {
var service = $rootScope.$new(true);
service.dirty = false;
service.lastSave = 0;
service.timeSinceLastSave = function () {
return new Date().getTime() - this.lastSave;
};
service.$watch('info',
function (newValue, oldValue) {
service.dirty = true;
},
true);
service.$watch('info',
function() {
service.dirty = false;
});
return service;
});
module.factory('editor',
function (doc, backend, $q, $rootScope, $log) {
var editor = null;
var EditSession = require("ace/edit_session").EditSession;
var service = {
loading:false,
saving:false,
rebind:function (element) {
editor = ace.edit(element);
},
snapshot:function () {
doc.dirty = false;
var data = angular.extend({}, doc.info);
data.resource_id = doc.resource_id;
if (doc.info.editable) {
data.content = editor.getSession().getValue();
}
return data;
},
create:function () {
$log.info("Creating new doc");
this.updateEditor({
content:'',
labels:{
starred:false
},
editable:true,
title:'Untitled document',
description:'',
mimeType:'text/plain',
resource_id:null
});
},
load:function (id, reload) {
$log.info("Loading resource", id, doc.resource_id);
if (!reload && doc.info && id == doc.resource_id) {
return $q.when(doc.info);
}
this.loading = true;
return backend.load(id).then(angular.bind(this,
function (result) {
this.loading = false;
this.updateEditor(result.data);
$rootScope.$broadcast('loaded', doc.info);
return result;
}), angular.bind(this,
function (result) {
$log.warn("Error loading", result);
this.loading = false;
$rootScope.$broadcast('error', {
action:'load',
message:"An error occured while loading the file"
});
return result;
}));
},
save:function (newRevision) {
$log.info("Saving file", newRevision);
if (this.saving || this.loading) {
throw 'Save called from incorrect state';
}
this.saving = true;
var file = this.snapshot();
// Force revision if first save of the session
newRevision = newRevision || doc.timeSinceLastSave() > ONE_HOUR_IN_MS;
var promise = backend.save(file, newRevision);
promise.then(angular.bind(this,
function (result) {
$log.info("Saved file", result);
this.saving = false;
doc.resource_id = result.data;
doc.lastSave = new Date().getTime();
$rootScope.$broadcast('saved', doc.info);
return doc.info;
}), angular.bind(this,
function (result) {
this.saving = false;
doc.dirty = true;
$rootScope.$broadcast('error', {
action:'save',
message:"An error occured while saving the file"
});
return result;
}));
return promise;
},
updateEditor:function (fileInfo) {
$log.info("Updating editor", fileInfo);
var session = new EditSession(fileInfo.content);
session.on('change', function () {
doc.dirty = true;
$rootScope.$apply();
});
fileInfo.content = null;
doc.lastSave = 0;
doc.info = fileInfo;
doc.resource_id = fileInfo.id;
editor.setSession(session);
editor.setReadOnly(!doc.info.editable);
editor.focus();
},
state:function () {
if (this.loading) {
return EditorState.LOAD;
} else if (this.saving) {
return EditorState.SAVE;
} else if (doc.dirty) {
return EditorState.DIRTY;
} else if (!doc.info.editable) {
return EditorState.READONLY;
}
return EditorState.CLEAN;
}
};
return service;
});
module.factory('backend',
function ($http, $log) {
var jsonTransform = function (data, headers) {
return angular.fromJson(data);
};
var service = {
user:function () {
return $http.get('/user', {transformResponse:jsonTransform});
},
about:function () {
return $http.get('/about', {transformResponse:jsonTransform});
},
load:function (id) {
return $http.get('/svc', {
transformResponse:jsonTransform,
params:{
'file_id':id
}
});
},
save:function (fileInfo, newRevision) {
$log.info('Saving', fileInfo);
return $http({
url:'/svc',
method:fileInfo.resource_id ? 'PUT' : 'POST',
headers:{
'Content-Type':'application/json'
},
params:{
'newRevision':newRevision
},
transformResponse:jsonTransform,
data:JSON.stringify(fileInfo)
});
}
};
return service;
});
module.factory('autosaver',
function (editor, saveInterval, $timeout) {
var saveFn = function () {
if (editor.state() == EditorState.DIRTY) {
editor.save(false);
}
};
var createTimeout = function () {
return $timeout(saveFn, saveInterval).then(createTimeout);
}
return createTimeout();
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/tomorrow_night_blue', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-tomorrow-night-blue";
exports.cssText = "\
.ace-tomorrow-night-blue .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-tomorrow-night-blue .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-tomorrow-night-blue .ace_gutter {\
background: #022346;\
color: #7388b5;\
}\
\
.ace-tomorrow-night-blue .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-tomorrow-night-blue .ace_scroller {\
background-color: #002451;\
}\
\
.ace-tomorrow-night-blue .ace_text-layer {\
cursor: text;\
color: #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_cursor {\
border-left: 2px solid #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_selection {\
background: #003F8E;\
}\
\
.ace-tomorrow-night-blue.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #002451;\
border-radius: 2px;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_step {\
background: rgb(127, 111, 19);\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #404F7D;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_active_line {\
background: #00346E;\
}\
\
.ace-tomorrow-night-blue .ace_gutter_active_line {\
background-color: #022040;\
}\
\
.ace-tomorrow-night-blue .ace_marker-layer .ace_selected_word {\
border: 1px solid #003F8E;\
}\
\
.ace-tomorrow-night-blue .ace_invisible {\
color: #404F7D;\
}\
\
.ace-tomorrow-night-blue .ace_keyword, .ace-tomorrow-night-blue .ace_meta {\
color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_keyword.ace_operator {\
color:#99FFFF;\
}\
\
.ace-tomorrow-night-blue .ace_constant.ace_language {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_constant.ace_numeric {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_constant.ace_other {\
color:#FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_invalid {\
color:#FFFFFF;\
background-color:#F99DA5;\
}\
\
.ace-tomorrow-night-blue .ace_invalid.ace_deprecated {\
color:#FFFFFF;\
background-color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_support.ace_constant {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_fold {\
background-color: #BBDAFF;\
border-color: #FFFFFF;\
}\
\
.ace-tomorrow-night-blue .ace_support.ace_function {\
color:#BBDAFF;\
}\
\
.ace-tomorrow-night-blue .ace_storage {\
color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_storage.ace_type, .ace-tomorrow-night-blue .ace_support.ace_type{\
color:#EBBBFF;\
}\
\
.ace-tomorrow-night-blue .ace_variable {\
color:#BBDAFF;\
}\
\
.ace-tomorrow-night-blue .ace_variable.ace_parameter {\
color:#FFC58F;\
}\
\
.ace-tomorrow-night-blue .ace_string {\
color:#D1F1A9;\
}\
\
.ace-tomorrow-night-blue .ace_string.ace_regexp {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_comment {\
color:#7285B7;\
}\
\
.ace-tomorrow-night-blue .ace_variable {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_meta.ace_tag {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_entity.ace_other.ace_attribute-name {\
color:#FF9DA4;\
}\
\
.ace-tomorrow-night-blue .ace_entity.ace_name.ace_function {\
color:#BBDAFF;\
}\
\
.ace-tomorrow-night-blue .ace_markup.ace_underline {\
text-decoration:underline;\
}\
\
.ace-tomorrow-night-blue .ace_markup.ace_heading {\
color:#D1F1A9;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/cobalt', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-cobalt";
exports.cssText = "\
.ace-cobalt .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-cobalt .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-cobalt .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-cobalt .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-cobalt .ace_scroller {\
background-color: #002240;\
}\
\
.ace-cobalt .ace_text-layer {\
cursor: text;\
color: #FFFFFF;\
}\
\
.ace-cobalt .ace_cursor {\
border-left: 2px solid #FFFFFF;\
}\
\
.ace-cobalt .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #FFFFFF;\
}\
\
.ace-cobalt .ace_marker-layer .ace_selection {\
background: rgba(179, 101, 57, 0.75);\
}\
\
.ace-cobalt.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #002240;\
border-radius: 2px;\
}\
\
.ace-cobalt .ace_marker-layer .ace_step {\
background: rgb(127, 111, 19);\
}\
\
.ace-cobalt .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgba(255, 255, 255, 0.15);\
}\
\
.ace-cobalt .ace_marker-layer .ace_active_line {\
background: rgba(0, 0, 0, 0.35);\
}\
\
.ace-cobalt .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-cobalt .ace_marker-layer .ace_selected_word {\
border: 1px solid rgba(179, 101, 57, 0.75);\
}\
\
.ace-cobalt .ace_invisible {\
color: rgba(255, 255, 255, 0.15);\
}\
\
.ace-cobalt .ace_keyword, .ace-cobalt .ace_meta {\
color:#FF9D00;\
}\
\
.ace-cobalt .ace_constant, .ace-cobalt .ace_constant.ace_other {\
color:#FF628C;\
}\
\
.ace-cobalt .ace_constant.ace_character, {\
color:#FF628C;\
}\
\
.ace-cobalt .ace_constant.ace_character.ace_escape, {\
color:#FF628C;\
}\
\
.ace-cobalt .ace_invalid {\
color:#F8F8F8;\
background-color:#800F00;\
}\
\
.ace-cobalt .ace_support {\
color:#80FFBB;\
}\
\
.ace-cobalt .ace_support.ace_constant {\
color:#EB939A;\
}\
\
.ace-cobalt .ace_fold {\
background-color: #FF9D00;\
border-color: #FFFFFF;\
}\
\
.ace-cobalt .ace_support.ace_function {\
color:#FFB054;\
}\
\
.ace-cobalt .ace_storage {\
color:#FFEE80;\
}\
\
.ace-cobalt .ace_string.ace_regexp {\
color:#80FFC2;\
}\
\
.ace-cobalt .ace_comment {\
font-style:italic;\
color:#0088FF;\
}\
\
.ace-cobalt .ace_variable {\
color:#CCCCCC;\
}\
\
.ace-cobalt .ace_variable.ace_language {\
color:#FF80E1;\
}\
\
.ace-cobalt .ace_meta.ace_tag {\
color:#9EFFFF;\
}\
\
.ace-cobalt .ace_markup.ace_underline {\
text-decoration:underline;\
}\
\
.ace-cobalt .ace_markup.ace_heading {\
color:#C8E4FD;\
background-color:#001221;\
}\
\
.ace-cobalt .ace_markup.ace_list {\
background-color:#130D26;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/clouds', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-clouds";
exports.cssText = "\
.ace-clouds .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-clouds .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-clouds .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-clouds .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-clouds .ace_scroller {\
background-color: #FFFFFF;\
}\
\
.ace-clouds .ace_text-layer {\
cursor: text;\
color: #000000;\
}\
\
.ace-clouds .ace_cursor {\
border-left: 2px solid #000000;\
}\
\
.ace-clouds .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #000000;\
}\
\
.ace-clouds .ace_marker-layer .ace_selection {\
background: #BDD5FC;\
}\
\
.ace-clouds.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #FFFFFF;\
border-radius: 2px;\
}\
\
.ace-clouds .ace_marker-layer .ace_step {\
background: rgb(255, 255, 0);\
}\
\
.ace-clouds .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #BFBFBF;\
}\
\
.ace-clouds .ace_marker-layer .ace_active_line {\
background: #FFFBD1;\
}\
\
.ace-clouds .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-clouds .ace_marker-layer .ace_selected_word {\
border: 1px solid #BDD5FC;\
}\
\
.ace-clouds .ace_invisible {\
color: #BFBFBF;\
}\
\
.ace-clouds .ace_keyword, .ace-clouds .ace_meta {\
color:#AF956F;\
}\
\
.ace-clouds .ace_keyword.ace_operator {\
color:#484848;\
}\
\
.ace-clouds .ace_constant.ace_language {\
color:#39946A;\
}\
\
.ace-clouds .ace_constant.ace_numeric {\
color:#46A609;\
}\
\
.ace-clouds .ace_invalid {\
background-color:#FF002A;\
}\
\
.ace-clouds .ace_fold {\
background-color: #AF956F;\
border-color: #000000;\
}\
\
.ace-clouds .ace_support.ace_function {\
color:#C52727;\
}\
\
.ace-clouds .ace_storage {\
color:#C52727;\
}\
\
.ace-clouds .ace_string {\
color:#5D90CD;\
}\
\
.ace-clouds .ace_comment {\
color:#BCC8BA;\
}\
\
.ace-clouds .ace_entity.ace_other.ace_attribute-name {\
color:#606060;\
}\
\
.ace-clouds .ace_markup.ace_underline {\
text-decoration:underline;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/solarized_light', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-solarized-light";
exports.cssText = "\
.ace-solarized-light .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-solarized-light .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-solarized-light .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-solarized-light .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-solarized-light .ace_scroller {\
background-color: #FDF6E3;\
}\
\
.ace-solarized-light .ace_text-layer {\
cursor: text;\
color: #586E75;\
}\
\
.ace-solarized-light .ace_cursor {\
border-left: 2px solid #000000;\
}\
\
.ace-solarized-light .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #000000;\
}\
\
.ace-solarized-light .ace_marker-layer .ace_selection {\
background: #073642;\
}\
\
.ace-solarized-light.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #FDF6E3;\
border-radius: 2px;\
}\
\
.ace-solarized-light .ace_marker-layer .ace_step {\
background: rgb(255, 255, 0);\
}\
\
.ace-solarized-light .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgba(147, 161, 161, 0.50);\
}\
\
.ace-solarized-light .ace_marker-layer .ace_active_line {\
background: #EEE8D5;\
}\
\
.ace-solarized-light .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-solarized-light .ace_marker-layer .ace_selected_word {\
border: 1px solid #073642;\
}\
\
.ace-solarized-light .ace_invisible {\
color: rgba(147, 161, 161, 0.50);\
}\
\
.ace-solarized-light .ace_keyword, .ace-solarized-light .ace_meta {\
color:#859900;\
}\
\
.ace-solarized-light .ace_constant.ace_language {\
color:#B58900;\
}\
\
.ace-solarized-light .ace_constant.ace_numeric {\
color:#D33682;\
}\
\
.ace-solarized-light .ace_constant.ace_other {\
color:#CB4B16;\
}\
\
.ace-solarized-light .ace_fold {\
background-color: #268BD2;\
border-color: #586E75;\
}\
\
.ace-solarized-light .ace_support.ace_function {\
color:#268BD2;\
}\
\
.ace-solarized-light .ace_storage {\
color:#073642;\
}\
\
.ace-solarized-light .ace_variable {\
color:#268BD2;\
}\
\
.ace-solarized-light .ace_string {\
color:#2AA198;\
}\
\
.ace-solarized-light .ace_string.ace_regexp {\
color:#D30102;\
}\
\
.ace-solarized-light .ace_comment {\
color:#93A1A1;\
}\
\
.ace-solarized-light .ace_variable.ace_language {\
color:#268BD2;\
}\
\
.ace-solarized-light .ace_entity.ace_other.ace_attribute-name {\
color:#93A1A1;\
}\
\
.ace-solarized-light .ace_entity.ace_name.ace_function {\
color:#268BD2;\
}\
\
.ace-solarized-light .ace_markup.ace_underline {\
text-decoration:underline;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
JavaScript
|
define('ace/mode/latex', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/latex_highlight_rules', 'ace/range'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var LatexHighlightRules = require("./latex_highlight_rules").LatexHighlightRules;
var Range = require("../range").Range;
var Mode = function()
{
this.$tokenizer = new Tokenizer(new LatexHighlightRules().getRules());
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
// This code is adapted from ruby.js
var outdent = true;
// LaTeX comments begin with % and go to the end of the line
var commentRegEx = /^(\s*)\%/;
for (var i = startRow; i <= endRow; i++) {
if (!commentRegEx.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i = startRow; i <= endRow; i++) {
var line = doc.getLine(i);
var m = line.match(commentRegEx);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "%");
}
};
// There is no universally accepted way of indenting a tex document
// so just maintain the indentation of the previous line
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/latex_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var LatexHighlightRules = function() {
this.$rules = {
"start" : [{
// A tex command e.g. \foo
token : "keyword",
regex : "\\\\(?:[^a-zA-Z]|[a-zA-Z]+)",
}, {
// Curly and square braces
token : "lparen",
regex : "[[({]"
}, {
// Curly and square braces
token : "rparen",
regex : "[\\])}]"
}, {
// Inline math between two $ symbols
token : "string",
regex : "\\$(?:(?:\\\\.)|(?:[^\\$\\\\]))*?\\$"
}, {
// A comment. Tex comments start with % and go to
// the end of the line
token : "comment",
regex : "%.*$"
}]
};
};
oop.inherits(LatexHighlightRules, TextHighlightRules);
exports.LatexHighlightRules = LatexHighlightRules;
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/svg', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/svg_highlight_rules', 'ace/mode/folding/mixed', 'ace/mode/folding/xml', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var XmlMode = require("./xml").Mode;
var JavaScriptMode = require("./javascript").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var SvgHighlightRules = require("./svg_highlight_rules").SvgHighlightRules;
var MixedFoldMode = require("./folding/mixed").FoldMode;
var XmlFoldMode = require("./folding/xml").FoldMode;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
XmlMode.call(this);
this.highlighter = new SvgHighlightRules();
this.$tokenizer = new Tokenizer(this.highlighter.getRules());
this.$embeds = this.highlighter.getEmbeds();
this.createModeDelegates({
"js-": JavaScriptMode
});
this.foldingRules = new MixedFoldMode(new XmlFoldMode({}), {
"js-": new CStyleFoldMode()
});
};
oop.inherits(Mode, XmlMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var XmlFoldMode = require("./folding/xml").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules());
this.$behaviour = new XmlBehaviour();
this.foldingRules = new XmlFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var xmlUtil = require("./xml_util");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var XmlHighlightRules = function() {
// regexp must not have capturing parentheses
// regexps are ordered -> the first match is used
this.$rules = {
start : [{
token : "text",
regex : "<\\!\\[CDATA\\[",
next : "cdata"
}, {
token : "xml_pe",
regex : "<\\?.*?\\?>"
}, {
token : "comment",
merge : true,
regex : "<\\!--",
next : "comment"
}, {
token : "xml_pe",
regex : "<\\!.*?>"
}, {
token : "meta.tag", // opening tag
regex : "<\\/?",
next : "tag"
}, {
token : "text",
regex : "\\s+"
}, {
token : "constant.character.entity",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}, {
token : "text",
regex : "[^<]+"
}],
cdata : [{
token : "text",
regex : "\\]\\]>",
next : "start"
}, {
token : "text",
regex : "\\s+"
}, {
token : "text",
regex : "(?:[^\\]]|\\](?!\\]>))+"
}],
comment : [{
token : "comment",
regex : ".*?-->",
next : "start"
}, {
token : "comment",
merge : true,
regex : ".+"
}]
};
xmlUtil.tag(this.$rules, "tag", "start");
};
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
});
define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) {
var lang = require("../lib/lang");
var formTags = lang.arrayToMap(
("button|form|input|label|select|textarea").split("|")
);
var tableTags = lang.arrayToMap(
("table|tbody|td|tfoot|th|tr").split("|")
);
function string(state) {
return [{
token : "string",
regex : '".*?"'
}, {
token : "string", // multi line string start
merge : true,
regex : '["].*',
next : state + "_qqstring"
}, {
token : "string",
regex : "'.*?'"
}, {
token : "string", // multi line string start
merge : true,
regex : "['].*",
next : state + "_qstring"
}];
}
function multiLineString(quote, state) {
return [{
token : "string",
merge : true,
regex : ".*?" + quote,
next : state
}, {
token : "string",
merge : true,
regex : '.+'
}];
}
exports.tag = function(states, name, nextState) {
states[name] = [{
token : "text",
regex : "\\s+"
}, {
//token : "meta.tag",
token : function(value) {
if ( value==='a' ) {
return "meta.tag.anchor";
}
else if ( value==='img' ) {
return "meta.tag.image";
}
else if ( value==='script' ) {
return "meta.tag.script";
}
else if ( value==='style' ) {
return "meta.tag.style";
}
else if (formTags.hasOwnProperty(value.toLowerCase())) {
return "meta.tag.form";
}
else if (tableTags.hasOwnProperty(value.toLowerCase())) {
return "meta.tag.table";
}
else {
return "meta.tag";
}
},
merge : true,
regex : "[-_a-zA-Z0-9:]+",
next : name + "_embed_attribute_list"
}, {
token: "empty",
regex: "",
next : name + "_embed_attribute_list"
}];
states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list");
states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list");
states[name + "_embed_attribute_list"] = [{
token : "meta.tag",
merge : true,
regex : "\/?>",
next : nextState
}, {
token : "keyword.operator",
regex : "="
}, {
token : "entity.other.attribute-name",
regex : "[-_a-zA-Z0-9:]+"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "text",
regex : "\\s+"
}].concat(string(name));
};
});
define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var XmlBehaviour = function () {
this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '<') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return false;
} else {
return {
text: '<>',
selection: [1, 1]
}
}
} else if (text == '>') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '>') { // need some kind of matching check here
return {
text: '',
selection: [1, 1]
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChars = line.substring(cursor.column, cursor.column + 2);
if (rightChars == '</') {
var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString();
var next_indent = this.$getIndent(session.doc.getLine(cursor.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
}
}
}
});
}
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = function () {
this.add("braces", "insertion", function (state, action, editor, session, text) {
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '{' + selected + '}',
selection: false
};
} else {
return {
text: '{}',
selection: [1, 1]
};
}
} else if (text == '}') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1});
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString());
var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '(' + selected + ')',
selection: false
};
} else {
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
// We're escaped.
if (leftChar == '\\') {
return null;
}
// Find what token we're inside.
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
// Try and be smart about when we auto insert.
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
// Ignore input and move right one if we're typing over the closing quote.
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) {
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function(voidElements) {
BaseFoldMode.call(this);
this.voidElements = voidElements || {};
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (tag.closing)
return foldStyle == "markbeginend" ? "end" : "";
if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()])
return "";
if (tag.selfClosing)
return "";
if (tag.value.indexOf("/" + tag.tagName) !== -1)
return "";
return "start";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var value = "";
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.indexOf("meta.tag") === 0)
value += token.value;
else
value += lang.stringRepeat(" ", token.value.length);
}
return this._parseTag(value);
};
this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/;
this._parseTag = function(tag) {
var match = this.tagRe.exec(tag);
var column = this.tagRe.lastIndex || 0;
this.tagRe.lastIndex = 0;
return {
value: tag,
match: match ? match[2] : "",
closing: match ? !!match[3] : false,
selfClosing: match ? !!match[5] || match[2] == "/>" : false,
tagName: match ? match[4] : "",
column: match[1] ? column + match[1].length : column
};
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var start;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!start) {
var start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
}
value += token.value;
if (value.indexOf(">") !== -1) {
var tag = this._parseTag(value);
tag.start = start;
tag.end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
iterator.stepForward();
return tag;
}
}
} while(token = iterator.stepForward());
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var end;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!end) {
end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
}
value = token.value + value;
if (value.indexOf("<") !== -1) {
var tag = this._parseTag(value);
tag.end = end;
tag.start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
iterator.stepBackward();
return tag;
}
}
} while(token = iterator.stepBackward());
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length-1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
}
else if (this.voidElements[tag.tagName]) {
return;
}
else if (this.voidElements[top.tagName]) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag.match)
return null;
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.column);
var start = {
row: row,
column: firstTag.column + firstTag.tagName.length + 2
};
while (tag = this._readTagForward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0)
return Range.fromPoints(start, tag.start);
}
else {
stack.push(tag)
}
}
}
else {
var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length);
var end = {
row: row,
column: firstTag.column
};
while (tag = this._readTagBackward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
return Range.fromPoints(tag.start, end);
}
}
else {
stack.push(tag)
}
}
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
var re = /^(\s*)\/\//;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "//");
}
};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "regex_allowed") {
var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || state == "regex_allowed") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("jslint", function(results) {
var errors = [];
for (var i=0; i<results.data.length; i++) {
var error = results.data[i];
if (error)
errors.push({
row: error.line-1,
column: error.character-1,
text: error.reason,
type: "warning",
lint: error
});
}
session.setAnnotations(errors);
});
worker.on("narcissus", function(e) {
session.setAnnotations([e.data]);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var unicode = require("../unicode");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = function() {
// see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects
var globals = lang.arrayToMap(
// Constructors
("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" +
// E4X
"Namespace|QName|XML|XMLList|" +
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
// Errors
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" +
"SyntaxError|TypeError|URIError|" +
// Non-constructor functions
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" +
"isNaN|parseFloat|parseInt|" +
// Other
"JSON|Math|" +
// Pseudo
"this|arguments|prototype|window|document"
).split("|")
);
var keywords = lang.arrayToMap(
("break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" +
"const|yield|import|get|set").split("|")
);
// keywords which can be followed by regular expressions
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield";
var deprecated = lang.arrayToMap(
("__parent__|__count__|escape|unescape|with|__proto__").split("|")
);
var definitions = lang.arrayToMap(("const|let|var|function").split("|"));
var buildinConstants = lang.arrayToMap(
("null|Infinity|NaN|undefined").split("|")
);
var futureReserved = lang.arrayToMap(
("class|enum|extends|super|export|implements|private|" +
"public|interface|package|protected|static").split("|")
);
// TODO: Unicode escape sequences
var identifierRe = "[" + unicode.packages.L + "\\$_]["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]*\\b";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-6][0-7]?|" + // oct
"37[0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "comment",
regex : /\/\/.*$/
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
merge : true,
regex : /\/\*/,
next : "comment"
}, {
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hex
regex : /0[xX][0-9a-fA-F]+\b/
}, {
token : "constant.numeric", // float
regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
}, { // match stuff like: Sound.prototype.play = function() { }
token : [
"storage.type",
"punctuation.operator",
"support.function",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: Sound.prototype.play = myfunc
token : [
"storage.type",
"punctuation.operator",
"support.function",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)",
next: "function_arguments"
}, { // match stuff like: Sound.play = function() { }
token : [
"storage.type",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: play = function() { }
token : [
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match regular function like: function myFunc(arg) { }
token : [
"storage.type",
"text",
"entity.name.function",
"text",
"paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: foobar: function() { }
token : [
"entity.name.function",
"text",
"punctuation.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // Attempt to match : function() { } (this is for issues with 'foo': function() { })
token : [
"text",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : "constant.language.boolean",
regex : /(?:true|false)\b/
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "regex_allowed"
}, {
token : ["punctuation.operator", "support.function"],
regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : ["punctuation.operator", "support.function.dom"],
regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : ["punctuation.operator", "support.constant"],
regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/
}, {
token : function(value) {
if (globals.hasOwnProperty(value))
return "variable.language";
else if (deprecated.hasOwnProperty(value))
return "invalid.deprecated";
else if (definitions.hasOwnProperty(value))
return "storage.type";
else if (keywords.hasOwnProperty(value))
return "keyword";
else if (buildinConstants.hasOwnProperty(value))
return "constant.language";
else if (futureReserved.hasOwnProperty(value))
return "invalid.illegal";
else if (value == "debugger")
return "invalid.deprecated";
else
return "identifier";
},
regex : identifierRe
}, {
token : "keyword.operator",
regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,
next : "regex_allowed"
}, {
token : "punctuation.operator",
regex : /\?|\:|\,|\;|\./,
next : "regex_allowed"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "regex_allowed"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token : "keyword.operator",
regex : /\/=?/,
next : "regex_allowed"
}, {
token: "comment",
regex: /^#!.*$/
}, {
token : "text",
regex : /\s+/
}
],
// regular expressions are only allowed after certain tokens. This
// makes sure we don't mix up regexps with the divison operator
"regex_allowed": [
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment_regex_allowed"
}, {
token : "comment",
regex : "\\/\\/.*$"
}, {
token: "string.regexp",
regex: "\\/",
next: "regex",
merge: true
}, {
token : "text",
regex : "\\s+"
}, {
// immediately return to the start mode without matching
// anything
token: "empty",
regex: "",
next: "start"
}
],
"regex": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
// flag
token: "string.regexp",
regex: "/\\w*",
next: "start",
merge: true
}, {
token: "string.regexp",
regex: "[^\\\\/\\[]+",
merge: true
}, {
token: "string.regexp.charachterclass",
regex: "\\[",
next: "regex_character_class",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"regex_character_class": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "string.regexp.charachterclass",
regex: "]",
next: "regex",
merge: true
}, {
token: "string.regexp.charachterclass",
regex: "[^\\\\\\]]+",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe,
}, {
token: "punctuation.operator",
regex: "[, ]+",
merge: true
}, {
token: "punctuation.operator",
regex: "$",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"comment_regex_allowed" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
merge : true,
next : "regex_allowed"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
merge : true,
next : "start"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : '[^"\\\\]+',
merge : true
}, {
token : "string",
regex : "\\\\$",
next : "qqstring",
merge : true
}, {
token : "string",
regex : '"|$',
next : "start",
merge : true
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "[^'\\\\]+",
merge : true
}, {
token : "string",
regex : "\\\\$",
next : "qstring",
merge : true
}, {
token : "string",
regex : "'|$",
next : "start",
merge : true
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
});
define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc",
merge : true,
regex : "\\s+"
}, {
token : "comment.doc",
merge : true,
regex : "TODO"
}, {
token : "comment.doc",
merge : true,
regex : "[^@\\*]+"
}, {
token : "comment.doc",
merge : true,
regex : "."
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
merge : true,
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
merge : true,
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/svg_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_highlight_rules', 'ace/mode/xml_util'], function(require, exports, module) {
var oop = require("../lib/oop");
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var xmlUtil = require("./xml_util");
var SvgHighlightRules = function() {
XmlHighlightRules.call(this);
this.$rules.start.splice(3, 0, {
token : "meta.tag",
regex : "<(?=\s*script)",
next : "script"
});
xmlUtil.tag(this.$rules, "script", "js-start");
this.embedRules(JavaScriptHighlightRules, "js-", [{
token: "comment",
regex: "\\/\\/.*(?=<\\/script>)",
next: "tag"
}, {
token: "meta.tag",
regex: "<\\/(?=script)",
next: "tag"
}]);
};
oop.inherits(SvgHighlightRules, XmlHighlightRules);
exports.SvgHighlightRules = SvgHighlightRules;
});
define('ace/mode/folding/mixed', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(defaultMode, subModes) {
this.defaultMode = defaultMode;
this.subModes = subModes;
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.$getMode = function(state) {
for (var key in this.subModes) {
if (state.indexOf(key) === 0)
return this.subModes[key];
}
return null;
};
this.$tryMode = function(state, session, foldStyle, row) {
var mode = this.$getMode(state);
return (mode ? mode.getFoldWidget(session, foldStyle, row) : "");
};
this.getFoldWidget = function(session, foldStyle, row) {
return (
this.$tryMode(session.getState(row-1), session, foldStyle, row) ||
this.$tryMode(session.getState(row), session, foldStyle, row) ||
this.defaultMode.getFoldWidget(session, foldStyle, row)
);
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var mode = this.$getMode(session.getState(row-1));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.$getMode(session.getState(row));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.defaultMode;
return mode.getFoldWidgetRange(session, foldStyle, row);
};
}).call(FoldMode.prototype);
});
|
JavaScript
|
"no use strict";
var console = {
log: function(msg) {
postMessage({type: "log", data: msg});
}
};
var window = {
console: console
};
var normalizeModule = function(parentId, moduleName) {
// normalize plugin requires
if (moduleName.indexOf("!") !== -1) {
var chunks = moduleName.split("!");
return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
}
// normalize relative requires
if (moduleName.charAt(0) == ".") {
var base = parentId.split("/").slice(0, -1).join("/");
var moduleName = base + "/" + moduleName;
while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
var previous = moduleName;
var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
}
}
return moduleName;
};
var require = function(parentId, id) {
var id = normalizeModule(parentId, id);
var module = require.modules[id];
if (module) {
if (!module.initialized) {
module.exports = module.factory().exports;
module.initialized = true;
}
return module.exports;
}
var chunks = id.split("/");
chunks[0] = require.tlns[chunks[0]] || chunks[0];
var path = chunks.join("/") + ".js";
require.id = id;
importScripts(path);
return require(parentId, id);
};
require.modules = {};
require.tlns = {};
var define = function(id, deps, factory) {
if (arguments.length == 2) {
factory = deps;
} else if (arguments.length == 1) {
factory = id;
id = require.id;
}
if (id.indexOf("text!") === 0)
return;
var req = function(deps, factory) {
return require(id, deps, factory);
};
require.modules[id] = {
factory: function() {
var module = {
exports: {}
};
var returnExports = factory(req, module.exports, module);
if (returnExports)
module.exports = returnExports;
return module;
}
};
};
function initBaseUrls(topLevelNamespaces) {
require.tlns = topLevelNamespaces;
}
function initSender() {
var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter;
var oop = require(null, "ace/lib/oop");
var Sender = function() {};
(function() {
oop.implement(this, EventEmitter);
this.callback = function(data, callbackId) {
postMessage({
type: "call",
id: callbackId,
data: data
});
};
this.emit = function(name, data) {
postMessage({
type: "event",
name: name,
data: data
});
};
}).call(Sender.prototype);
return new Sender();
}
var main;
var sender;
onmessage = function(e) {
var msg = e.data;
if (msg.command) {
main[msg.command].apply(main, msg.args);
}
else if (msg.init) {
initBaseUrls(msg.tlns);
require(null, "ace/lib/fixoldbrowsers");
sender = initSender();
var clazz = require(null, msg.module)[msg.classname];
main = new clazz(sender);
}
else if (msg.event && sender) {
sender._emit(msg.event, msg.data);
}
};
// vim:set ts=4 sts=4 sw=4 st:
// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project)
// -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified
// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
// -- Irakli Gozalishvili Copyright (C) 2010 MIT License
/*!
Copyright (c) 2009, 280 North Inc. http://280north.com/
MIT License. http://github.com/280north/narwhal/blob/master/README.md
*/
define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) {
require("./regexp");
require("./es5-shim");
});
define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) {
//---------------------------------
// Private variables
//---------------------------------
var real = {
exec: RegExp.prototype.exec,
test: RegExp.prototype.test,
match: String.prototype.match,
replace: String.prototype.replace,
split: String.prototype.split
},
compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups
compliantLastIndexIncrement = function () {
var x = /^/g;
real.test.call(x, "");
return !x.lastIndex;
}();
if (compliantLastIndexIncrement && compliantExecNpcg)
return;
//---------------------------------
// Overriden native methods
//---------------------------------
// Adds named capture support (with backreferences returned as `result.name`), and fixes two
// cross-browser issues per ES3:
// - Captured values for nonparticipating capturing groups should be returned as `undefined`,
// rather than the empty string.
// - `lastIndex` should not be incremented after zero-length matches.
RegExp.prototype.exec = function (str) {
var match = real.exec.apply(this, arguments),
name, r2;
if ( typeof(str) == 'string' && match) {
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", ""));
// Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed
// matching due to characters outside the match
real.replace.call(str.slice(match.index), r2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined)
match[i] = undefined;
}
});
}
// Attach named capture properties
if (this._xregexp && this._xregexp.captureNames) {
for (var i = 1; i < match.length; i++) {
name = this._xregexp.captureNames[i - 1];
if (name)
match[name] = match[i];
}
}
// Fix browsers that increment `lastIndex` after zero-length matches
if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
}
return match;
};
// Don't override `test` if it won't change anything
if (!compliantLastIndexIncrement) {
// Fix browser bug in native method
RegExp.prototype.test = function (str) {
// Use the native `exec` to skip some processing overhead, even though the overriden
// `exec` would take care of the `lastIndex` fix
var match = real.exec.call(this, str);
// Fix browsers that increment `lastIndex` after zero-length matches
if (match && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
return !!match;
};
}
//---------------------------------
// Private helper functions
//---------------------------------
function getNativeFlags (regex) {
return (regex.global ? "g" : "") +
(regex.ignoreCase ? "i" : "") +
(regex.multiline ? "m" : "") +
(regex.extended ? "x" : "") + // Proposed for ES4; included in AS3
(regex.sticky ? "y" : "");
};
function indexOf (array, item, from) {
if (Array.prototype.indexOf) // Use the native array method if available
return array.indexOf(item, from);
for (var i = from || 0; i < array.length; i++) {
if (array[i] === item)
return i;
}
return -1;
};
});
// vim: ts=4 sts=4 sw=4 expandtab
// -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License
// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project)
// -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA
// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
// -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License
// -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License
// -- kossnocorp Sasha Koss XXX TODO License or CLA
// -- bryanforbes Bryan Forbes XXX TODO License or CLA
// -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence
// -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License
// -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License
// -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain)
// -- iwyg XXX TODO License or CLA
// -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License
// -- xavierm02 Montillet Xavier XXX TODO License or CLA
// -- Raynos Raynos XXX TODO License or CLA
// -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License
// -- rwldrn Rick Waldron Copyright (C) 2011 MIT License
// -- lexer Alexey Zakharov XXX TODO License or CLA
/*!
Copyright (c) 2009, 280 North Inc. http://280north.com/
MIT License. http://github.com/280north/narwhal/blob/master/README.md
*/
define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) {
/*
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
*
* @module
*/
/*whatsupdoc*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (typeof target != "function")
throw new TypeError(); // TODO message
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var F = function(){};
F.prototype = target.prototype;
var self = new F;
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (result !== null && Object(result) === result)
return result;
return self;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
// XXX bound.length is never writable, so don't even try
//
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var slice = prototypeOfArray.slice;
var toString = call.bind(prototypeOfObject.toString);
var owns = call.bind(prototypeOfObject.hasOwnProperty);
// If JS engine supports accessors creating shortcuts.
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return toString(obj) == "[object Array]";
};
}
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var self = toObject(this),
thisp = arguments[1],
i = 0,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object context
fun.call(thisp, self[i], i, self);
}
i++;
}
};
}
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var self = toObject(this),
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, self);
}
return result;
};
}
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
result = [],
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, self))
result.push(self[i]);
}
return result;
};
}
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, self))
return false;
}
return true;
};
}
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, self))
return true;
}
return false;
};
}
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var self = toObject(this),
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
// no value to return if no initial value and an empty array
if (!length && arguments.length == 1)
throw new TypeError(); // TODO message
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length)
throw new TypeError(); // TODO message
} while (true);
}
for (; i < length; i++) {
if (i in self)
result = fun.call(void 0, result, self[i], i, self);
}
return result;
};
}
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var self = toObject(this),
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
// no value to return if no initial value, empty array
if (!length && arguments.length == 1)
throw new TypeError(); // TODO message
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError(); // TODO message
} while (true);
}
do {
if (i in this)
result = fun.call(void 0, result, self[i], i, self);
} while (i--);
return result;
};
}
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = toObject(this),
length = self.length >>> 0;
if (!length)
return -1;
var i = 0;
if (arguments.length > 1)
i = toInteger(arguments[1]);
// handle negative indices
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = toObject(this),
length = self.length >>> 0;
if (!length)
return -1;
var i = length - 1;
if (arguments.length > 1)
i = Math.min(i, toInteger(arguments[1]));
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i])
return i;
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.2
// http://es5.github.com/#x15.2.3.2
if (!Object.getPrototypeOf) {
// https://github.com/kriskowal/es5-shim/issues#issue/2
// http://ejohn.org/blog/objectgetprototypeof/
// recommended by fschaefer on github
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || (
object.constructor ?
object.constructor.prototype :
prototypeOfObject
);
};
}
// ES5 15.2.3.3
// http://es5.github.com/#x15.2.3.3
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
"non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT + object);
// If object does not owns property return undefined immediately.
if (!owns(object, property))
return;
var descriptor, getter, setter;
// If object has a property then it's for sure both `enumerable` and
// `configurable`.
descriptor = { enumerable: true, configurable: true };
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it's owned by an object.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
// Once we have getter and setter we can put values back.
object.__proto__ = prototype;
if (getter || setter) {
if (getter) descriptor.get = getter;
if (setter) descriptor.set = setter;
// If it was accessor property we're done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
return descriptor;
};
}
// ES5 15.2.3.4
// http://es5.github.com/#x15.2.3.4
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
// ES5 15.2.3.5
// http://es5.github.com/#x15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype != "object")
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (properties !== void 0)
Object.defineProperties(object, properties);
return object;
};
}
// ES5 15.2.3.6
// http://es5.github.com/#x15.2.3.6
// Patch for WebKit and IE8 standard mode
// Designed by hax <hax.github.com>
// related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
// IE8 Reference:
// http://msdn.microsoft.com/en-us/library/dd282900.aspx
// http://msdn.microsoft.com/en-us/library/dd229916.aspx
// WebKit Bugs:
// https://bugs.webkit.org/show_bug.cgi?id=36423
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
// returns falsy
}
}
// check whether defineProperty works if it's given. Otherwise,
// shim partially.
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
// make a valiant attempt to use the real defineProperty
// for I8's DOM elements.
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors)
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get"))
defineGetter(object, property, descriptor.get);
if (owns(descriptor, "set"))
defineSetter(object, property, descriptor.set);
}
return object;
};
}
// ES5 15.2.3.7
// http://es5.github.com/#x15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
// ES5 15.2.3.8
// http://es5.github.com/#x15.2.3.8
if (!Object.seal) {
Object.seal = function seal(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.9
// http://es5.github.com/#x15.2.3.9
if (!Object.freeze) {
Object.freeze = function freeze(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// detect a Rhino bug and patch it
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object == "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
// ES5 15.2.3.10
// http://es5.github.com/#x15.2.3.10
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.11
// http://es5.github.com/#x15.2.3.11
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
// ES5 15.2.3.12
// http://es5.github.com/#x15.2.3.12
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
// ES5 15.2.3.13
// http://es5.github.com/#x15.2.3.13
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
// 1. If Type(O) is not Object throw a TypeError exception.
if (Object(object) === object) {
throw new TypeError(); // TODO message
}
// 2. Return the Boolean value of the [[Extensible]] internal property of O.
var name = '';
while (owns(object, name)) {
name += '?';
}
object[name] = true;
var returnValue = owns(object, name);
delete object[name];
return returnValue;
};
}
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
if (!Object.keys) {
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null})
hasDontEnumBug = false;
Object.keys = function keys(object) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError("Object.keys called on a non-object");
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) {
Date.prototype.toISOString = function toISOString() {
var result, length, value, year;
if (!isFinite(this))
throw new RangeError;
// the date time string format is specified in 15.9.1.15.
result = [this.getUTCMonth() + 1, this.getUTCDate(),
this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = this.getUTCFullYear();
year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two digits.
if (value < 10)
result[length] = "0" + value;
}
// pad milliseconds to have three digits.
return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." +
("000" + this.getUTCMilliseconds()).slice(-3) + "Z";
}
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
if (!Date.prototype.toJSON) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ToPrimitive(O, hint Number).
// 3. If tv is a Number and is not finite, return null.
// XXX
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof this.toISOString != "function")
throw new TypeError(); // TODO message
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return this.toISOString();
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
var Date = function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length == 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp("^" +
"(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year
"(?:-(\\d{2})" + // optional month capture
"(?:-(\\d{2})" + // optional day capture
"(?:" + // capture hours:minutes:seconds.milliseconds
"T(\\d{2})" + // hours capture
":(\\d{2})" + // minutes capture
"(?:" + // optional :seconds.milliseconds
":(\\d{2})" + // seconds capture
"(?:\\.(\\d{3}))?" + // milliseconds capture
")?" +
"(?:" + // capture UTC offset component
"Z|" + // UTC capture
"(?:" + // offset specifier +/-hours:minutes
"([-+])" + // sign capture
"(\\d{2})" + // hours offset capture
":(\\d{2})" + // minutes offset capture
")" +
")?)?)?)?" +
"$");
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate)
Date[key] = NativeDate[key];
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle simplified ISO 8601 strings
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
match.shift(); // kill match[0], the full match
// parse months, days, hours, minutes, seconds, and milliseconds
for (var i = 1; i < 7; i++) {
// provide default values if necessary
match[i] = +(match[i] || (i < 3 ? 1 : 0));
// match[1] is the month. Months are 0-11 in JavaScript
// `Date` objects, but 1-12 in ISO notation, so we
// decrement.
if (i == 1)
match[i]--;
}
// parse the UTC offset component
var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop();
// compute the explicit time zone offset if specified
var offset = 0;
if (sign) {
// detect invalid offsets and return early
if (hourOffset > 23 || minuteOffset > 59)
return NaN;
// express the provided time zone offset in minutes. The offset is
// negative for time zones west of UTC; positive otherwise.
offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1);
}
// Date.UTC for years between 0 and 99 converts year to 1900 + year
// The Gregorian calendar has a 400-year cycle, so
// to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...),
// where 12622780800000 - number of milliseconds in Gregorian calendar 400 years
var year = +match[0];
if (0 <= year && year <= 99) {
match[0] = year + 400;
return NativeDate.UTC.apply(this, match) + offset - 12622780800000;
}
// compute a new UTC date value, accounting for the optional offset
return NativeDate.UTC.apply(this, match) + offset;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
//
// String
// ======
//
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
};
}
//
// Util
// ======
//
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
var toInteger = function (n) {
n = +n;
if (n !== n) // isNaN
n = 0;
else if (n !== 0 && n !== (1/0) && n !== -(1/0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
return n;
};
var prepareString = "a"[0] != "a",
// ES5 9.9
// http://es5.github.com/#x9.9
toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError(); // TODO message
}
// If the implementation doesn't support by-index access of
// string characters (ex. IE < 7), split the string
if (prepareString && typeof o == "string" && o) {
return o.split("");
}
return Object(o);
};
});
define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) {
var EventEmitter = {};
EventEmitter._emit =
EventEmitter._dispatchEvent = function(eventName, e) {
this._eventRegistry = this._eventRegistry || {};
this._defaultHandlers = this._defaultHandlers || {};
var listeners = this._eventRegistry[eventName] || [];
var defaultHandler = this._defaultHandlers[eventName];
if (!listeners.length && !defaultHandler)
return;
e = e || {};
e.type = eventName;
if (!e.stopPropagation) {
e.stopPropagation = function() {
this.propagationStopped = true;
};
}
if (!e.preventDefault) {
e.preventDefault = function() {
this.defaultPrevented = true;
};
}
for (var i=0; i<listeners.length; i++) {
listeners[i](e);
if (e.propagationStopped)
break;
}
if (defaultHandler && !e.defaultPrevented)
return defaultHandler(e);
};
EventEmitter.setDefaultHandler = function(eventName, callback) {
this._defaultHandlers = this._defaultHandlers || {};
if (this._defaultHandlers[eventName])
throw new Error("The default handler for '" + eventName + "' is already set");
this._defaultHandlers[eventName] = callback;
};
EventEmitter.on =
EventEmitter.addEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
var listeners = this._eventRegistry[eventName] = [];
if (listeners.indexOf(callback) == -1)
listeners.push(callback);
};
EventEmitter.removeListener =
EventEmitter.removeEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
return;
var index = listeners.indexOf(callback);
if (index !== -1)
listeners.splice(index, 1);
};
EventEmitter.removeAllListeners = function(eventName) {
if (this._eventRegistry) this._eventRegistry[eventName] = [];
};
exports.EventEmitter = EventEmitter;
});
define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.inherits = (function() {
var tempCtor = function() {};
return function(ctor, superCtor) {
tempCtor.prototype = superCtor.prototype;
ctor.super_ = superCtor.prototype;
ctor.prototype = new tempCtor();
ctor.prototype.constructor = ctor;
};
}());
exports.mixin = function(obj, mixin) {
for (var key in mixin) {
obj[key] = mixin[key];
}
};
exports.implement = function(proto, mixin) {
exports.mixin(proto, mixin);
};
});
define('ace/mode/css_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/css/csslint'], function(require, exports, module) {
var oop = require("../lib/oop");
var Mirror = require("../worker/mirror").Mirror;
var CSSLint = require("./css/csslint").CSSLint;
var Worker = exports.Worker = function(sender) {
Mirror.call(this, sender);
this.setTimeout(200);
};
oop.inherits(Worker, Mirror);
(function() {
this.onUpdate = function() {
var value = this.doc.getValue();
var result = CSSLint.verify(value);
this.sender.emit("csslint", result.messages.map(function(msg) {
delete msg.rule;
return msg;
}));
};
}).call(Worker.prototype);
});
define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) {
var Document = require("../document").Document;
var lang = require("../lib/lang");
var Mirror = exports.Mirror = function(sender) {
this.sender = sender;
var doc = this.doc = new Document("");
var deferredUpdate = this.deferredUpdate = lang.deferredCall(this.onUpdate.bind(this));
var _self = this;
sender.on("change", function(e) {
doc.applyDeltas([e.data]);
deferredUpdate.schedule(_self.$timeout);
});
};
(function() {
this.$timeout = 500;
this.setTimeout = function(timeout) {
this.$timeout = timeout;
};
this.setValue = function(value) {
this.doc.setValue(value);
this.deferredUpdate.schedule(this.$timeout);
};
this.getValue = function(callbackId) {
this.sender.callback(this.doc.getValue(), callbackId);
};
this.onUpdate = function() {
// abstract method
};
}).call(Mirror.prototype);
});
define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) {
var oop = require("./lib/oop");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var Range = require("./range").Range;
var Anchor = require("./anchor").Anchor;
/**
* new Document([text])
* - text (String | Array): The starting text
*
* Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty.
*
**/
var Document = function(text) {
this.$lines = [];
// There has to be one line at least in the document. If you pass an empty
// string to the insert function, nothing will happen. Workaround.
if (text.length == 0) {
this.$lines = [""];
} else if (Array.isArray(text)) {
this.insertLines(0, text);
} else {
this.insert({row: 0, column:0}, text);
}
};
(function() {
oop.implement(this, EventEmitter);
this.setValue = function(text) {
var len = this.getLength();
this.remove(new Range(0, 0, len, this.getLine(len-1).length));
this.insert({row: 0, column:0}, text);
};
this.getValue = function() {
return this.getAllLines().join(this.getNewLineCharacter());
};
this.createAnchor = function(row, column) {
return new Anchor(this, row, column);
};
// check for IE split bug
if ("aaa".split(/a/).length == 0)
this.$split = function(text) {
return text.replace(/\r\n|\r/g, "\n").split("\n");
}
else
this.$split = function(text) {
return text.split(/\r\n|\r|\n/);
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r\n|\r|\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getNewLineCharacter = function() {
switch (this.$newLineMode) {
case "windows":
return "\r\n";
case "unix":
return "\n";
case "auto":
return this.$autoNewLine;
}
};
this.$autoNewLine = "\n";
this.$newLineMode = "auto";
this.setNewLineMode = function(newLineMode) {
if (this.$newLineMode === newLineMode)
return;
this.$newLineMode = newLineMode;
};
this.getNewLineMode = function() {
return this.$newLineMode;
};
this.isNewLine = function(text) {
return (text == "\r\n" || text == "\r" || text == "\n");
};
this.getLine = function(row) {
return this.$lines[row] || "";
};
this.getLines = function(firstRow, lastRow) {
return this.$lines.slice(firstRow, lastRow + 1);
};
this.getAllLines = function() {
return this.getLines(0, this.getLength());
};
this.getLength = function() {
return this.$lines.length;
};
this.getTextRange = function(range) {
if (range.start.row == range.end.row) {
return this.$lines[range.start.row].substring(range.start.column,
range.end.column);
}
else {
var lines = this.getLines(range.start.row+1, range.end.row-1);
lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column));
lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column));
return lines.join(this.getNewLineCharacter());
}
};
this.$clipPosition = function(position) {
var length = this.getLength();
if (position.row >= length) {
position.row = Math.max(0, length - 1);
position.column = this.getLine(length-1).length;
}
return position;
};
this.insert = function(position, text) {
if (!text || text.length === 0)
return position;
position = this.$clipPosition(position);
// only detect new lines if the document has no line break yet
if (this.getLength() <= 1)
this.$detectNewLine(text);
var lines = this.$split(text);
var firstLine = lines.splice(0, 1)[0];
var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0];
position = this.insertInLine(position, firstLine);
if (lastLine !== null) {
position = this.insertNewLine(position); // terminate first line
position = this.insertLines(position.row, lines);
position = this.insertInLine(position, lastLine || "");
}
return position;
};
this.insertLines = function(row, lines) {
if (lines.length == 0)
return {row: row, column: 0};
// apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF)
// to circumvent that we have to break huge inserts into smaller chunks here
if (lines.length > 0xFFFF) {
var end = this.insertLines(row, lines.slice(0xFFFF));
lines = lines.slice(0, 0xFFFF);
}
var args = [row, 0];
args.push.apply(args, lines);
this.$lines.splice.apply(this.$lines, args);
var range = new Range(row, 0, row + lines.length, 0);
var delta = {
action: "insertLines",
range: range,
lines: lines
};
this._emit("change", { data: delta });
return end || range.end;
};
this.insertNewLine = function(position) {
position = this.$clipPosition(position);
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column);
this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length));
var end = {
row : position.row + 1,
column : 0
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: this.getNewLineCharacter()
};
this._emit("change", { data: delta });
return end;
};
this.insertInLine = function(position, text) {
if (text.length == 0)
return position;
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column) + text
+ line.substring(position.column);
var end = {
row : position.row,
column : position.column + text.length
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: text
};
this._emit("change", { data: delta });
return end;
};
this.remove = function(range) {
// clip to document
range.start = this.$clipPosition(range.start);
range.end = this.$clipPosition(range.end);
if (range.isEmpty())
return range.start;
var firstRow = range.start.row;
var lastRow = range.end.row;
if (range.isMultiLine()) {
var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1;
var lastFullRow = lastRow - 1;
if (range.end.column > 0)
this.removeInLine(lastRow, 0, range.end.column);
if (lastFullRow >= firstFullRow)
this.removeLines(firstFullRow, lastFullRow);
if (firstFullRow != firstRow) {
this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length);
this.removeNewLine(range.start.row);
}
}
else {
this.removeInLine(firstRow, range.start.column, range.end.column);
}
return range.start;
};
this.removeInLine = function(row, startColumn, endColumn) {
if (startColumn == endColumn)
return;
var range = new Range(row, startColumn, row, endColumn);
var line = this.getLine(row);
var removed = line.substring(startColumn, endColumn);
var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length);
this.$lines.splice(row, 1, newLine);
var delta = {
action: "removeText",
range: range,
text: removed
};
this._emit("change", { data: delta });
return range.start;
};
this.removeLines = function(firstRow, lastRow) {
var range = new Range(firstRow, 0, lastRow + 1, 0);
var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1);
var delta = {
action: "removeLines",
range: range,
nl: this.getNewLineCharacter(),
lines: removed
};
this._emit("change", { data: delta });
return removed;
};
this.removeNewLine = function(row) {
var firstLine = this.getLine(row);
var secondLine = this.getLine(row+1);
var range = new Range(row, firstLine.length, row+1, 0);
var line = firstLine + secondLine;
this.$lines.splice(row, 2, line);
var delta = {
action: "removeText",
range: range,
text: this.getNewLineCharacter()
};
this._emit("change", { data: delta });
};
this.replace = function(range, text) {
if (text.length == 0 && range.isEmpty())
return range.start;
// Shortcut: If the text we want to insert is the same as it is already
// in the document, we don't have to replace anything.
if (text == this.getTextRange(range))
return range.end;
this.remove(range);
if (text) {
var end = this.insert(range.start, text);
}
else {
end = range.start;
}
return end;
};
this.applyDeltas = function(deltas) {
for (var i=0; i<deltas.length; i++) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.insertLines(range.start.row, delta.lines);
else if (delta.action == "insertText")
this.insert(range.start, delta.text);
else if (delta.action == "removeLines")
this.removeLines(range.start.row, range.end.row - 1);
else if (delta.action == "removeText")
this.remove(range);
}
};
this.revertDeltas = function(deltas) {
for (var i=deltas.length-1; i>=0; i--) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.removeLines(range.start.row, range.end.row - 1);
else if (delta.action == "insertText")
this.remove(range);
else if (delta.action == "removeLines")
this.insertLines(range.start.row, delta.lines);
else if (delta.action == "removeText")
this.insert(range.start, delta.text);
}
};
}).call(Document.prototype);
exports.Document = Document;
});
define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* class Range
*
* This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column.
*
**/
/**
* new Range(startRow, startColumn, endRow, endColumn)
* - startRow (Number): The starting row
* - startColumn (Number): The starting column
* - endRow (Number): The ending row
* - endColumn (Number): The ending column
*
* Creates a new `Range` object with the given starting and ending row and column points.
*
**/
var Range = function(startRow, startColumn, endRow, endColumn) {
this.start = {
row: startRow,
column: startColumn
};
this.end = {
row: endRow,
column: endColumn
};
};
(function() {
/**
* Range.isEqual(range) -> Boolean
* - range (Range): A range to check against
*
* Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`.
*
**/
this.isEqual = function(range) {
return this.start.row == range.start.row &&
this.end.row == range.end.row &&
this.start.column == range.start.column &&
this.end.column == range.end.column
};
this.toString = function() {
return ("Range: [" + this.start.row + "/" + this.start.column +
"] -> [" + this.end.row + "/" + this.end.column + "]");
};
this.contains = function(row, column) {
return this.compare(row, column) == 0;
};
this.compareRange = function(range) {
var cmp,
end = range.end,
start = range.start;
cmp = this.compare(end.row, end.column);
if (cmp == 1) {
cmp = this.compare(start.row, start.column);
if (cmp == 1) {
return 2;
} else if (cmp == 0) {
return 1;
} else {
return 0;
}
} else if (cmp == -1) {
return -2;
} else {
cmp = this.compare(start.row, start.column);
if (cmp == -1) {
return -1;
} else if (cmp == 1) {
return 42;
} else {
return 0;
}
}
}
/** related to: Range.compare
* Range.comparePoint(p) -> Number
* - p (Range): A point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `0` if the two points are exactly equal<br/>
* * `-1` if `p.row` is less then the calling range<br/>
* * `1` if `p.row` is greater than the calling range<br/>
* <br/>
* If the starting row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/>
* * Otherwise, it returns -1<br/>
*<br/>
* If the ending row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/>
* * Otherwise, it returns 1<br/>
*
* Checks the row and column points of `p` with the row and column points of the calling range.
*
*
*
**/
this.comparePoint = function(p) {
return this.compare(p.row, p.column);
}
/** related to: Range.comparePoint
* Range.containsRange(range) -> Boolean
* - range (Range): A range to compare with
*
* Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range.
*
**/
this.containsRange = function(range) {
return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
}
/**
* Range.intersects(range) -> Boolean
* - range (Range): A range to compare with
*
* Returns `true` if passed in `range` intersects with the one calling this method.
*
**/
this.intersects = function(range) {
var cmp = this.compareRange(range);
return (cmp == -1 || cmp == 0 || cmp == 1);
}
/**
* Range.isEnd(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`.
*
**/
this.isEnd = function(row, column) {
return this.end.row == row && this.end.column == column;
}
/**
* Range.isStart(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`.
*
**/
this.isStart = function(row, column) {
return this.start.row == row && this.start.column == column;
}
/**
* Range.setStart(row, column)
* - row (Number): A row point to set
* - column (Number): A column point to set
*
* Sets the starting row and column for the range.
*
**/
this.setStart = function(row, column) {
if (typeof row == "object") {
this.start.column = row.column;
this.start.row = row.row;
} else {
this.start.row = row;
this.start.column = column;
}
}
/**
* Range.setEnd(row, column)
* - row (Number): A row point to set
* - column (Number): A column point to set
*
* Sets the starting row and column for the range.
*
**/
this.setEnd = function(row, column) {
if (typeof row == "object") {
this.end.column = row.column;
this.end.row = row.row;
} else {
this.end.row = row;
this.end.column = column;
}
}
/** related to: Range.compare
* Range.inside(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the `row` and `column` are within the given range.
*
**/
this.inside = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column) || this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
/** related to: Range.compare
* Range.insideStart(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the `row` and `column` are within the given range's starting points.
*
**/
this.insideStart = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
/** related to: Range.compare
* Range.insideEnd(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the `row` and `column` are within the given range's ending points.
*
**/
this.insideEnd = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
/**
* Range.compare(row, column) -> Number
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `0` if the two points are exactly equal <br/>
* * `-1` if `p.row` is less then the calling range <br/>
* * `1` if `p.row` is greater than the calling range <br/>
* <br/>
* If the starting row of the calling range is equal to `p.row`, and: <br/>
* * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/>
* * Otherwise, it returns -1<br/>
* <br/>
* If the ending row of the calling range is equal to `p.row`, and: <br/>
* * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/>
* * Otherwise, it returns 1
*
* Checks the row and column points with the row and column points of the calling range.
*
*
**/
this.compare = function(row, column) {
if (!this.isMultiLine()) {
if (row === this.start.row) {
return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
};
}
if (row < this.start.row)
return -1;
if (row > this.end.row)
return 1;
if (this.start.row === row)
return column >= this.start.column ? 0 : -1;
if (this.end.row === row)
return column <= this.end.column ? 0 : 1;
return 0;
};
this.compareStart = function(row, column) {
if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
/**
* Range.compareEnd(row, column) -> Number
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `0` if the two points are exactly equal<br/>
* * `-1` if `p.row` is less then the calling range<br/>
* * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/>
* <br/>
* If the starting row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/>
* * Otherwise, it returns -1<br/>
*<br/>
* If the ending row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/>
* * Otherwise, it returns 1
*
* Checks the row and column points with the row and column points of the calling range.
*
*
**/
this.compareEnd = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else {
return this.compare(row, column);
}
}
/**
* Range.compareInside(row, column) -> Number
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/>
* * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/>
* <br/>
* Otherwise, it returns the value after calling [[Range.compare `compare()`]].
*
* Checks the row and column points with the row and column points of the calling range.
*
*
*
**/
this.compareInside = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
/**
* Range.clipRows(firstRow, lastRow) -> Range
* - firstRow (Number): The starting row
* - lastRow (Number): The ending row
*
* Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object.
*
**/
this.clipRows = function(firstRow, lastRow) {
if (this.end.row > lastRow) {
var end = {
row: lastRow+1,
column: 0
};
}
if (this.start.row > lastRow) {
var start = {
row: lastRow+1,
column: 0
};
}
if (this.start.row < firstRow) {
var start = {
row: firstRow,
column: 0
};
}
if (this.end.row < firstRow) {
var end = {
row: firstRow,
column: 0
};
}
return Range.fromPoints(start || this.start, end || this.end);
};
this.extend = function(row, column) {
var cmp = this.compare(row, column);
if (cmp == 0)
return this;
else if (cmp == -1)
var start = {row: row, column: column};
else
var end = {row: row, column: column};
return Range.fromPoints(start || this.start, end || this.end);
};
this.isEmpty = function() {
return (this.start.row == this.end.row && this.start.column == this.end.column);
};
this.isMultiLine = function() {
return (this.start.row !== this.end.row);
};
this.clone = function() {
return Range.fromPoints(this.start, this.end);
};
this.collapseRows = function() {
if (this.end.column == 0)
return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
else
return new Range(this.start.row, 0, this.end.row, 0)
};
this.toScreenRange = function(session) {
var screenPosStart =
session.documentToScreenPosition(this.start);
var screenPosEnd =
session.documentToScreenPosition(this.end);
return new Range(
screenPosStart.row, screenPosStart.column,
screenPosEnd.row, screenPosEnd.column
);
};
}).call(Range.prototype);
Range.fromPoints = function(start, end) {
return new Range(start.row, start.column, end.row, end.column);
};
exports.Range = Range;
});
define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) {
var oop = require("./lib/oop");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
/**
* new Anchor(doc, row, column)
* - doc (Document): The document to associate with the anchor
* - row (Number): The starting row position
* - column (Number): The starting column position
*
* Creates a new `Anchor` and associates it with a document.
*
**/
var Anchor = exports.Anchor = function(doc, row, column) {
this.document = doc;
if (typeof column == "undefined")
this.setPosition(row.row, row.column);
else
this.setPosition(row, column);
this.$onChange = this.onChange.bind(this);
doc.on("change", this.$onChange);
};
(function() {
oop.implement(this, EventEmitter);
this.getPosition = function() {
return this.$clipPositionToDocument(this.row, this.column);
};
this.getDocument = function() {
return this.document;
};
this.onChange = function(e) {
var delta = e.data;
var range = delta.range;
if (range.start.row == range.end.row && range.start.row != this.row)
return;
if (range.start.row > this.row)
return;
if (range.start.row == this.row && range.start.column > this.column)
return;
var row = this.row;
var column = this.column;
if (delta.action === "insertText") {
if (range.start.row === row && range.start.column <= column) {
if (range.start.row === range.end.row) {
column += range.end.column - range.start.column;
}
else {
column -= range.start.column;
row += range.end.row - range.start.row;
}
}
else if (range.start.row !== range.end.row && range.start.row < row) {
row += range.end.row - range.start.row;
}
} else if (delta.action === "insertLines") {
if (range.start.row <= row) {
row += range.end.row - range.start.row;
}
}
else if (delta.action == "removeText") {
if (range.start.row == row && range.start.column < column) {
if (range.end.column >= column)
column = range.start.column;
else
column = Math.max(0, column - (range.end.column - range.start.column));
} else if (range.start.row !== range.end.row && range.start.row < row) {
if (range.end.row == row) {
column = Math.max(0, column - range.end.column) + range.start.column;
}
row -= (range.end.row - range.start.row);
}
else if (range.end.row == row) {
row -= range.end.row - range.start.row;
column = Math.max(0, column - range.end.column) + range.start.column;
}
} else if (delta.action == "removeLines") {
if (range.start.row <= row) {
if (range.end.row <= row)
row -= range.end.row - range.start.row;
else {
row = range.start.row;
column = 0;
}
}
}
this.setPosition(row, column, true);
};
this.setPosition = function(row, column, noClip) {
var pos;
if (noClip) {
pos = {
row: row,
column: column
};
}
else {
pos = this.$clipPositionToDocument(row, column);
}
if (this.row == pos.row && this.column == pos.column)
return;
var old = {
row: this.row,
column: this.column
};
this.row = pos.row;
this.column = pos.column;
this._emit("change", {
old: old,
value: pos
});
};
this.detach = function() {
this.document.removeEventListener("change", this.$onChange);
};
this.$clipPositionToDocument = function(row, column) {
var pos = {};
if (row >= this.document.getLength()) {
pos.row = Math.max(0, this.document.getLength() - 1);
pos.column = this.document.getLine(pos.row).length;
}
else if (row < 0) {
pos.row = 0;
pos.column = 0;
}
else {
pos.row = row;
pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
}
if (column < 0)
pos.column = 0;
return pos;
};
}).call(Anchor.prototype);
});
define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.stringReverse = function(string) {
return string.split("").reverse().join("");
};
exports.stringRepeat = function (string, count) {
return new Array(count + 1).join(string);
};
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
exports.stringTrimLeft = function (string) {
return string.replace(trimBeginRegexp, '');
};
exports.stringTrimRight = function (string) {
return string.replace(trimEndRegexp, '');
};
exports.copyObject = function(obj) {
var copy = {};
for (var key in obj) {
copy[key] = obj[key];
}
return copy;
};
exports.copyArray = function(array){
var copy = [];
for (var i=0, l=array.length; i<l; i++) {
if (array[i] && typeof array[i] == "object")
copy[i] = this.copyObject( array[i] );
else
copy[i] = array[i];
}
return copy;
};
exports.deepCopy = function (obj) {
if (typeof obj != "object") {
return obj;
}
var copy = obj.constructor();
for (var key in obj) {
if (typeof obj[key] == "object") {
copy[key] = this.deepCopy(obj[key]);
} else {
copy[key] = obj[key];
}
}
return copy;
};
exports.arrayToMap = function(arr) {
var map = {};
for (var i=0; i<arr.length; i++) {
map[arr[i]] = 1;
}
return map;
};
exports.arrayRemove = function(array, value) {
for (var i = 0; i <= array.length; i++) {
if (value === array[i]) {
array.splice(i, 1);
}
}
};
exports.escapeRegExp = function(str) {
return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
};
exports.getMatchOffsets = function(string, regExp) {
var matches = [];
string.replace(regExp, function(str) {
matches.push({
offset: arguments[arguments.length-2],
length: str.length
});
});
return matches;
};
exports.deferredCall = function(fcn) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var deferred = function(timeout) {
deferred.cancel();
timer = setTimeout(callback, timeout || 0);
return deferred;
};
deferred.schedule = deferred;
deferred.call = function() {
this.cancel();
fcn();
return deferred;
};
deferred.cancel = function() {
clearTimeout(timer);
timer = null;
return deferred;
};
return deferred;
};
});
define('ace/mode/css/csslint', ['require', 'exports', 'module' ], function(require, exports, module) {
/*!
CSSLint
Copyright (c) 2011 Nicole Sullivan and Nicholas C. Zakas. All rights reserved.
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.
*/
/* Build time: 2-March-2012 02:47:11 */
/*!
Parser-Lib
Copyright (c) 2009-2011 Nicholas C. Zakas. All rights reserved.
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.
*/
/* Version v0.1.6, Build time: 2-March-2012 02:44:32 */
var parserlib = {};
(function(){
/**
* A generic base to inherit from for any object
* that needs event handling.
* @class EventTarget
* @constructor
*/
function EventTarget(){
/**
* The array of listeners for various events.
* @type Object
* @property _listeners
* @private
*/
this._listeners = {};
}
EventTarget.prototype = {
//restore constructor
constructor: EventTarget,
/**
* Adds a listener for a given event type.
* @param {String} type The type of event to add a listener for.
* @param {Function} listener The function to call when the event occurs.
* @return {void}
* @method addListener
*/
addListener: function(type, listener){
if (!this._listeners[type]){
this._listeners[type] = [];
}
this._listeners[type].push(listener);
},
/**
* Fires an event based on the passed-in object.
* @param {Object|String} event An object with at least a 'type' attribute
* or a string indicating the event name.
* @return {void}
* @method fire
*/
fire: function(event){
if (typeof event == "string"){
event = { type: event };
}
if (typeof event.target != "undefined"){
event.target = this;
}
if (typeof event.type == "undefined"){
throw new Error("Event object missing 'type' property.");
}
if (this._listeners[event.type]){
//create a copy of the array and use that so listeners can't chane
var listeners = this._listeners[event.type].concat();
for (var i=0, len=listeners.length; i < len; i++){
listeners[i].call(this, event);
}
}
},
/**
* Removes a listener for a given event type.
* @param {String} type The type of event to remove a listener from.
* @param {Function} listener The function to remove from the event.
* @return {void}
* @method removeListener
*/
removeListener: function(type, listener){
if (this._listeners[type]){
var listeners = this._listeners[type];
for (var i=0, len=listeners.length; i < len; i++){
if (listeners[i] === listener){
listeners.splice(i, 1);
break;
}
}
}
}
};
function StringReader(text){
/**
* The input text with line endings normalized.
* @property _input
* @type String
* @private
*/
this._input = text.replace(/\n\r?/g, "\n");
this._line = 1;
this._col = 1;
this._cursor = 0;
}
StringReader.prototype = {
//restore constructor
constructor: StringReader,
//-------------------------------------------------------------------------
// Position info
//-------------------------------------------------------------------------
/**
* Returns the column of the character to be read next.
* @return {int} The column of the character to be read next.
* @method getCol
*/
getCol: function(){
return this._col;
},
/**
* Returns the row of the character to be read next.
* @return {int} The row of the character to be read next.
* @method getLine
*/
getLine: function(){
return this._line ;
},
/**
* Determines if you're at the end of the input.
* @return {Boolean} True if there's no more input, false otherwise.
* @method eof
*/
eof: function(){
return (this._cursor == this._input.length);
},
//-------------------------------------------------------------------------
// Basic reading
//-------------------------------------------------------------------------
/**
* Reads the next character without advancing the cursor.
* @param {int} count How many characters to look ahead (default is 1).
* @return {String} The next character or null if there is no next character.
* @method peek
*/
peek: function(count){
var c = null;
count = (typeof count == "undefined" ? 1 : count);
//if we're not at the end of the input...
if (this._cursor < this._input.length){
//get character and increment cursor and column
c = this._input.charAt(this._cursor + count - 1);
}
return c;
},
/**
* Reads the next character from the input and adjusts the row and column
* accordingly.
* @return {String} The next character or null if there is no next character.
* @method read
*/
read: function(){
var c = null;
//if we're not at the end of the input...
if (this._cursor < this._input.length){
//if the last character was a newline, increment row count
//and reset column count
if (this._input.charAt(this._cursor) == "\n"){
this._line++;
this._col=1;
} else {
this._col++;
}
//get character and increment cursor and column
c = this._input.charAt(this._cursor++);
}
return c;
},
//-------------------------------------------------------------------------
// Misc
//-------------------------------------------------------------------------
/**
* Saves the current location so it can be returned to later.
* @method mark
* @return {void}
*/
mark: function(){
this._bookmark = {
cursor: this._cursor,
line: this._line,
col: this._col
};
},
reset: function(){
if (this._bookmark){
this._cursor = this._bookmark.cursor;
this._line = this._bookmark.line;
this._col = this._bookmark.col;
delete this._bookmark;
}
},
//-------------------------------------------------------------------------
// Advanced reading
//-------------------------------------------------------------------------
/**
* Reads up to and including the given string. Throws an error if that
* string is not found.
* @param {String} pattern The string to read.
* @return {String} The string when it is found.
* @throws Error when the string pattern is not found.
* @method readTo
*/
readTo: function(pattern){
var buffer = "",
c;
while (buffer.length < pattern.length || buffer.lastIndexOf(pattern) != buffer.length - pattern.length){
c = this.read();
if (c){
buffer += c;
} else {
throw new Error("Expected \"" + pattern + "\" at line " + this._line + ", col " + this._col + ".");
}
}
return buffer;
},
/**
* Reads characters while each character causes the given
* filter function to return true. The function is passed
* in each character and either returns true to continue
* reading or false to stop.
* @param {Function} filter The function to read on each character.
* @return {String} The string made up of all characters that passed the
* filter check.
* @method readWhile
*/
readWhile: function(filter){
var buffer = "",
c = this.read();
while(c !== null && filter(c)){
buffer += c;
c = this.read();
}
return buffer;
},
/**
* Reads characters that match either text or a regular expression and
* returns those characters. If a match is found, the row and column
* are adjusted; if no match is found, the reader's state is unchanged.
* reading or false to stop.
* @param {String|RegExp} matchter If a string, then the literal string
* value is searched for. If a regular expression, then any string
* matching the pattern is search for.
* @return {String} The string made up of all characters that matched or
* null if there was no match.
* @method readMatch
*/
readMatch: function(matcher){
var source = this._input.substring(this._cursor),
value = null;
//if it's a string, just do a straight match
if (typeof matcher == "string"){
if (source.indexOf(matcher) === 0){
value = this.readCount(matcher.length);
}
} else if (matcher instanceof RegExp){
if (matcher.test(source)){
value = this.readCount(RegExp.lastMatch.length);
}
}
return value;
},
/**
* Reads a given number of characters. If the end of the input is reached,
* it reads only the remaining characters and does not throw an error.
* @param {int} count The number of characters to read.
* @return {String} The string made up the read characters.
* @method readCount
*/
readCount: function(count){
var buffer = "";
while(count--){
buffer += this.read();
}
return buffer;
}
};
function SyntaxError(message, line, col){
/**
* The column at which the error occurred.
* @type int
* @property col
*/
this.col = col;
this.line = line;
this.message = message;
}
//inherit from Error
SyntaxError.prototype = new Error();
function SyntaxUnit(text, line, col, type){
/**
* The column of text on which the unit resides.
* @type int
* @property col
*/
this.col = col;
this.line = line;
this.text = text;
this.type = type;
}
/**
* Create a new syntax unit based solely on the given token.
* Convenience method for creating a new syntax unit when
* it represents a single token instead of multiple.
* @param {Object} token The token object to represent.
* @return {parserlib.util.SyntaxUnit} The object representing the token.
* @static
* @method fromToken
*/
SyntaxUnit.fromToken = function(token){
return new SyntaxUnit(token.value, token.startLine, token.startCol);
};
SyntaxUnit.prototype = {
//restore constructor
constructor: SyntaxUnit,
/**
* Returns the text representation of the unit.
* @return {String} The text representation of the unit.
* @method valueOf
*/
valueOf: function(){
return this.toString();
},
/**
* Returns the text representation of the unit.
* @return {String} The text representation of the unit.
* @method toString
*/
toString: function(){
return this.text;
}
};
/**
* Generic TokenStream providing base functionality.
* @class TokenStreamBase
* @namespace parserlib.util
* @constructor
* @param {String|StringReader} input The text to tokenize or a reader from
* which to read the input.
*/
function TokenStreamBase(input, tokenData){
/**
* The string reader for easy access to the text.
* @type StringReader
* @property _reader
* @private
*/
this._reader = input ? new StringReader(input.toString()) : null;
this._token = null;
this._tokenData = tokenData;
this._lt = [];
this._ltIndex = 0;
this._ltIndexCache = [];
}
/**
* Accepts an array of token information and outputs
* an array of token data containing key-value mappings
* and matching functions that the TokenStream needs.
* @param {Array} tokens An array of token descriptors.
* @return {Array} An array of processed token data.
* @method createTokenData
* @static
*/
TokenStreamBase.createTokenData = function(tokens){
var nameMap = [],
typeMap = {},
tokenData = tokens.concat([]),
i = 0,
len = tokenData.length+1;
tokenData.UNKNOWN = -1;
tokenData.unshift({name:"EOF"});
for (; i < len; i++){
nameMap.push(tokenData[i].name);
tokenData[tokenData[i].name] = i;
if (tokenData[i].text){
typeMap[tokenData[i].text] = i;
}
}
tokenData.name = function(tt){
return nameMap[tt];
};
tokenData.type = function(c){
return typeMap[c];
};
return tokenData;
};
TokenStreamBase.prototype = {
//restore constructor
constructor: TokenStreamBase,
//-------------------------------------------------------------------------
// Matching methods
//-------------------------------------------------------------------------
/**
* Determines if the next token matches the given token type.
* If so, that token is consumed; if not, the token is placed
* back onto the token stream. You can pass in any number of
* token types and this will return true if any of the token
* types is found.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token might be. If an array is passed,
* it's assumed that the token can be any of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {Boolean} True if the token type matches, false if not.
* @method match
*/
match: function(tokenTypes, channel){
//always convert to an array, makes things easier
if (!(tokenTypes instanceof Array)){
tokenTypes = [tokenTypes];
}
var tt = this.get(channel),
i = 0,
len = tokenTypes.length;
while(i < len){
if (tt == tokenTypes[i++]){
return true;
}
}
//no match found, put the token back
this.unget();
return false;
},
/**
* Determines if the next token matches the given token type.
* If so, that token is consumed; if not, an error is thrown.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token should be. If an array is passed,
* it's assumed that the token must be one of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {void}
* @method mustMatch
*/
mustMatch: function(tokenTypes, channel){
var token;
//always convert to an array, makes things easier
if (!(tokenTypes instanceof Array)){
tokenTypes = [tokenTypes];
}
if (!this.match.apply(this, arguments)){
token = this.LT(1);
throw new SyntaxError("Expected " + this._tokenData[tokenTypes[0]].name +
" at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
}
},
//-------------------------------------------------------------------------
// Consuming methods
//-------------------------------------------------------------------------
/**
* Keeps reading from the token stream until either one of the specified
* token types is found or until the end of the input is reached.
* @param {int|int[]} tokenTypes Either a single token type or an array of
* token types that the next token should be. If an array is passed,
* it's assumed that the token must be one of these.
* @param {variant} channel (Optional) The channel to read from. If not
* provided, reads from the default (unnamed) channel.
* @return {void}
* @method advance
*/
advance: function(tokenTypes, channel){
while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){
this.get();
}
return this.LA(0);
},
/**
* Consumes the next token from the token stream.
* @return {int} The token type of the token that was just consumed.
* @method get
*/
get: function(channel){
var tokenInfo = this._tokenData,
reader = this._reader,
value,
i =0,
len = tokenInfo.length,
found = false,
token,
info;
//check the lookahead buffer first
if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length){
i++;
this._token = this._lt[this._ltIndex++];
info = tokenInfo[this._token.type];
//obey channels logic
while((info.channel !== undefined && channel !== info.channel) &&
this._ltIndex < this._lt.length){
this._token = this._lt[this._ltIndex++];
info = tokenInfo[this._token.type];
i++;
}
//here be dragons
if ((info.channel === undefined || channel === info.channel) &&
this._ltIndex <= this._lt.length){
this._ltIndexCache.push(i);
return this._token.type;
}
}
//call token retriever method
token = this._getToken();
//if it should be hidden, don't save a token
if (token.type > -1 && !tokenInfo[token.type].hide){
//apply token channel
token.channel = tokenInfo[token.type].channel;
//save for later
this._token = token;
this._lt.push(token);
//save space that will be moved (must be done before array is truncated)
this._ltIndexCache.push(this._lt.length - this._ltIndex + i);
//keep the buffer under 5 items
if (this._lt.length > 5){
this._lt.shift();
}
//also keep the shift buffer under 5 items
if (this._ltIndexCache.length > 5){
this._ltIndexCache.shift();
}
//update lookahead index
this._ltIndex = this._lt.length;
}
/*
* Skip to the next token if:
* 1. The token type is marked as hidden.
* 2. The token type has a channel specified and it isn't the current channel.
*/
info = tokenInfo[token.type];
if (info &&
(info.hide ||
(info.channel !== undefined && channel !== info.channel))){
return this.get(channel);
} else {
//return just the type
return token.type;
}
},
/**
* Looks ahead a certain number of tokens and returns the token type at
* that position. This will throw an error if you lookahead past the
* end of input, past the size of the lookahead buffer, or back past
* the first token in the lookahead buffer.
* @param {int} The index of the token type to retrieve. 0 for the
* current token, 1 for the next, -1 for the previous, etc.
* @return {int} The token type of the token in the given position.
* @method LA
*/
LA: function(index){
var total = index,
tt;
if (index > 0){
//TODO: Store 5 somewhere
if (index > 5){
throw new Error("Too much lookahead.");
}
//get all those tokens
while(total){
tt = this.get();
total--;
}
//unget all those tokens
while(total < index){
this.unget();
total++;
}
} else if (index < 0){
if(this._lt[this._ltIndex+index]){
tt = this._lt[this._ltIndex+index].type;
} else {
throw new Error("Too much lookbehind.");
}
} else {
tt = this._token.type;
}
return tt;
},
/**
* Looks ahead a certain number of tokens and returns the token at
* that position. This will throw an error if you lookahead past the
* end of input, past the size of the lookahead buffer, or back past
* the first token in the lookahead buffer.
* @param {int} The index of the token type to retrieve. 0 for the
* current token, 1 for the next, -1 for the previous, etc.
* @return {Object} The token of the token in the given position.
* @method LA
*/
LT: function(index){
//lookahead first to prime the token buffer
this.LA(index);
//now find the token, subtract one because _ltIndex is already at the next index
return this._lt[this._ltIndex+index-1];
},
/**
* Returns the token type for the next token in the stream without
* consuming it.
* @return {int} The token type of the next token in the stream.
* @method peek
*/
peek: function(){
return this.LA(1);
},
/**
* Returns the actual token object for the last consumed token.
* @return {Token} The token object for the last consumed token.
* @method token
*/
token: function(){
return this._token;
},
/**
* Returns the name of the token for the given token type.
* @param {int} tokenType The type of token to get the name of.
* @return {String} The name of the token or "UNKNOWN_TOKEN" for any
* invalid token type.
* @method tokenName
*/
tokenName: function(tokenType){
if (tokenType < 0 || tokenType > this._tokenData.length){
return "UNKNOWN_TOKEN";
} else {
return this._tokenData[tokenType].name;
}
},
/**
* Returns the token type value for the given token name.
* @param {String} tokenName The name of the token whose value should be returned.
* @return {int} The token type value for the given token name or -1
* for an unknown token.
* @method tokenName
*/
tokenType: function(tokenName){
return this._tokenData[tokenName] || -1;
},
/**
* Returns the last consumed token to the token stream.
* @method unget
*/
unget: function(){
//if (this._ltIndex > -1){
if (this._ltIndexCache.length){
this._ltIndex -= this._ltIndexCache.pop();//--;
this._token = this._lt[this._ltIndex - 1];
} else {
throw new Error("Too much lookahead.");
}
}
};
parserlib.util = {
StringReader: StringReader,
SyntaxError : SyntaxError,
SyntaxUnit : SyntaxUnit,
EventTarget : EventTarget,
TokenStreamBase : TokenStreamBase
};
})();
/* Version v0.1.6, Build time: 2-March-2012 02:44:32 */
(function(){
var EventTarget = parserlib.util.EventTarget,
TokenStreamBase = parserlib.util.TokenStreamBase,
StringReader = parserlib.util.StringReader,
SyntaxError = parserlib.util.SyntaxError,
SyntaxUnit = parserlib.util.SyntaxUnit;
var Colors = {
aliceblue :"#f0f8ff",
antiquewhite :"#faebd7",
aqua :"#00ffff",
aquamarine :"#7fffd4",
azure :"#f0ffff",
beige :"#f5f5dc",
bisque :"#ffe4c4",
black :"#000000",
blanchedalmond :"#ffebcd",
blue :"#0000ff",
blueviolet :"#8a2be2",
brown :"#a52a2a",
burlywood :"#deb887",
cadetblue :"#5f9ea0",
chartreuse :"#7fff00",
chocolate :"#d2691e",
coral :"#ff7f50",
cornflowerblue :"#6495ed",
cornsilk :"#fff8dc",
crimson :"#dc143c",
cyan :"#00ffff",
darkblue :"#00008b",
darkcyan :"#008b8b",
darkgoldenrod :"#b8860b",
darkgray :"#a9a9a9",
darkgreen :"#006400",
darkkhaki :"#bdb76b",
darkmagenta :"#8b008b",
darkolivegreen :"#556b2f",
darkorange :"#ff8c00",
darkorchid :"#9932cc",
darkred :"#8b0000",
darksalmon :"#e9967a",
darkseagreen :"#8fbc8f",
darkslateblue :"#483d8b",
darkslategray :"#2f4f4f",
darkturquoise :"#00ced1",
darkviolet :"#9400d3",
deeppink :"#ff1493",
deepskyblue :"#00bfff",
dimgray :"#696969",
dodgerblue :"#1e90ff",
firebrick :"#b22222",
floralwhite :"#fffaf0",
forestgreen :"#228b22",
fuchsia :"#ff00ff",
gainsboro :"#dcdcdc",
ghostwhite :"#f8f8ff",
gold :"#ffd700",
goldenrod :"#daa520",
gray :"#808080",
green :"#008000",
greenyellow :"#adff2f",
honeydew :"#f0fff0",
hotpink :"#ff69b4",
indianred :"#cd5c5c",
indigo :"#4b0082",
ivory :"#fffff0",
khaki :"#f0e68c",
lavender :"#e6e6fa",
lavenderblush :"#fff0f5",
lawngreen :"#7cfc00",
lemonchiffon :"#fffacd",
lightblue :"#add8e6",
lightcoral :"#f08080",
lightcyan :"#e0ffff",
lightgoldenrodyellow :"#fafad2",
lightgray :"#d3d3d3",
lightgreen :"#90ee90",
lightpink :"#ffb6c1",
lightsalmon :"#ffa07a",
lightseagreen :"#20b2aa",
lightskyblue :"#87cefa",
lightslategray :"#778899",
lightsteelblue :"#b0c4de",
lightyellow :"#ffffe0",
lime :"#00ff00",
limegreen :"#32cd32",
linen :"#faf0e6",
magenta :"#ff00ff",
maroon :"#800000",
mediumaquamarine:"#66cdaa",
mediumblue :"#0000cd",
mediumorchid :"#ba55d3",
mediumpurple :"#9370d8",
mediumseagreen :"#3cb371",
mediumslateblue :"#7b68ee",
mediumspringgreen :"#00fa9a",
mediumturquoise :"#48d1cc",
mediumvioletred :"#c71585",
midnightblue :"#191970",
mintcream :"#f5fffa",
mistyrose :"#ffe4e1",
moccasin :"#ffe4b5",
navajowhite :"#ffdead",
navy :"#000080",
oldlace :"#fdf5e6",
olive :"#808000",
olivedrab :"#6b8e23",
orange :"#ffa500",
orangered :"#ff4500",
orchid :"#da70d6",
palegoldenrod :"#eee8aa",
palegreen :"#98fb98",
paleturquoise :"#afeeee",
palevioletred :"#d87093",
papayawhip :"#ffefd5",
peachpuff :"#ffdab9",
peru :"#cd853f",
pink :"#ffc0cb",
plum :"#dda0dd",
powderblue :"#b0e0e6",
purple :"#800080",
red :"#ff0000",
rosybrown :"#bc8f8f",
royalblue :"#4169e1",
saddlebrown :"#8b4513",
salmon :"#fa8072",
sandybrown :"#f4a460",
seagreen :"#2e8b57",
seashell :"#fff5ee",
sienna :"#a0522d",
silver :"#c0c0c0",
skyblue :"#87ceeb",
slateblue :"#6a5acd",
slategray :"#708090",
snow :"#fffafa",
springgreen :"#00ff7f",
steelblue :"#4682b4",
tan :"#d2b48c",
teal :"#008080",
thistle :"#d8bfd8",
tomato :"#ff6347",
turquoise :"#40e0d0",
violet :"#ee82ee",
wheat :"#f5deb3",
white :"#ffffff",
whitesmoke :"#f5f5f5",
yellow :"#ffff00",
yellowgreen :"#9acd32"
};
/**
* Represents a selector combinator (whitespace, +, >).
* @namespace parserlib.css
* @class Combinator
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function Combinator(text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE);
this.type = "unknown";
//pretty simple
if (/^\s+$/.test(text)){
this.type = "descendant";
} else if (text == ">"){
this.type = "child";
} else if (text == "+"){
this.type = "adjacent-sibling";
} else if (text == "~"){
this.type = "sibling";
}
}
Combinator.prototype = new SyntaxUnit();
Combinator.prototype.constructor = Combinator;
/**
* Represents a media feature, such as max-width:500.
* @namespace parserlib.css
* @class MediaFeature
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {SyntaxUnit} name The name of the feature.
* @param {SyntaxUnit} value The value of the feature or null if none.
*/
function MediaFeature(name, value){
SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE);
this.name = name;
this.value = value;
}
MediaFeature.prototype = new SyntaxUnit();
MediaFeature.prototype.constructor = MediaFeature;
/**
* Represents an individual media query.
* @namespace parserlib.css
* @class MediaQuery
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} modifier The modifier "not" or "only" (or null).
* @param {String} mediaType The type of media (i.e., "print").
* @param {Array} parts Array of selectors parts making up this selector.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function MediaQuery(modifier, mediaType, features, line, col){
SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType + " " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE);
this.modifier = modifier;
this.mediaType = mediaType;
this.features = features;
}
MediaQuery.prototype = new SyntaxUnit();
MediaQuery.prototype.constructor = MediaQuery;
/**
* A CSS3 parser.
* @namespace parserlib.css
* @class Parser
* @constructor
* @param {Object} options (Optional) Various options for the parser:
* starHack (true|false) to allow IE6 star hack as valid,
* underscoreHack (true|false) to interpret leading underscores
* as IE6-7 targeting for known properties, ieFilters (true|false)
* to indicate that IE < 8 filters should be accepted and not throw
* syntax errors.
*/
function Parser(options){
//inherit event functionality
EventTarget.call(this);
this.options = options || {};
this._tokenStream = null;
}
//Static constants
Parser.DEFAULT_TYPE = 0;
Parser.COMBINATOR_TYPE = 1;
Parser.MEDIA_FEATURE_TYPE = 2;
Parser.MEDIA_QUERY_TYPE = 3;
Parser.PROPERTY_NAME_TYPE = 4;
Parser.PROPERTY_VALUE_TYPE = 5;
Parser.PROPERTY_VALUE_PART_TYPE = 6;
Parser.SELECTOR_TYPE = 7;
Parser.SELECTOR_PART_TYPE = 8;
Parser.SELECTOR_SUB_PART_TYPE = 9;
Parser.prototype = function(){
var proto = new EventTarget(), //new prototype
prop,
additions = {
//restore constructor
constructor: Parser,
//instance constants - yuck
DEFAULT_TYPE : 0,
COMBINATOR_TYPE : 1,
MEDIA_FEATURE_TYPE : 2,
MEDIA_QUERY_TYPE : 3,
PROPERTY_NAME_TYPE : 4,
PROPERTY_VALUE_TYPE : 5,
PROPERTY_VALUE_PART_TYPE : 6,
SELECTOR_TYPE : 7,
SELECTOR_PART_TYPE : 8,
SELECTOR_SUB_PART_TYPE : 9,
//-----------------------------------------------------------------
// Grammar
//-----------------------------------------------------------------
_stylesheet: function(){
/*
* stylesheet
* : [ CHARSET_SYM S* STRING S* ';' ]?
* [S|CDO|CDC]* [ import [S|CDO|CDC]* ]*
* [ namespace [S|CDO|CDC]* ]*
* [ [ ruleset | media | page | font_face | keyframes ] [S|CDO|CDC]* ]*
* ;
*/
var tokenStream = this._tokenStream,
charset = null,
count,
token,
tt;
this.fire("startstylesheet");
//try to read character set
this._charset();
this._skipCruft();
//try to read imports - may be more than one
while (tokenStream.peek() == Tokens.IMPORT_SYM){
this._import();
this._skipCruft();
}
//try to read namespaces - may be more than one
while (tokenStream.peek() == Tokens.NAMESPACE_SYM){
this._namespace();
this._skipCruft();
}
//get the next token
tt = tokenStream.peek();
//try to read the rest
while(tt > Tokens.EOF){
try {
switch(tt){
case Tokens.MEDIA_SYM:
this._media();
this._skipCruft();
break;
case Tokens.PAGE_SYM:
this._page();
this._skipCruft();
break;
case Tokens.FONT_FACE_SYM:
this._font_face();
this._skipCruft();
break;
case Tokens.KEYFRAMES_SYM:
this._keyframes();
this._skipCruft();
break;
case Tokens.UNKNOWN_SYM: //unknown @ rule
tokenStream.get();
if (!this.options.strict){
//fire error event
this.fire({
type: "error",
error: null,
message: "Unknown @ rule: " + tokenStream.LT(0).value + ".",
line: tokenStream.LT(0).startLine,
col: tokenStream.LT(0).startCol
});
//skip braces
count=0;
while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) == Tokens.LBRACE){
count++; //keep track of nesting depth
}
while(count){
tokenStream.advance([Tokens.RBRACE]);
count--;
}
} else {
//not a syntax error, rethrow it
throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol);
}
break;
case Tokens.S:
this._readWhitespace();
break;
default:
if(!this._ruleset()){
//error handling for known issues
switch(tt){
case Tokens.CHARSET_SYM:
token = tokenStream.LT(1);
this._charset(false);
throw new SyntaxError("@charset not allowed here.", token.startLine, token.startCol);
case Tokens.IMPORT_SYM:
token = tokenStream.LT(1);
this._import(false);
throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
case Tokens.NAMESPACE_SYM:
token = tokenStream.LT(1);
this._namespace(false);
throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
default:
tokenStream.get(); //get the last token
this._unexpectedToken(tokenStream.token());
}
}
}
} catch(ex) {
if (ex instanceof SyntaxError && !this.options.strict){
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
} else {
throw ex;
}
}
tt = tokenStream.peek();
}
if (tt != Tokens.EOF){
this._unexpectedToken(tokenStream.token());
}
this.fire("endstylesheet");
},
_charset: function(emit){
var tokenStream = this._tokenStream,
charset,
token,
line,
col;
if (tokenStream.match(Tokens.CHARSET_SYM)){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
tokenStream.mustMatch(Tokens.STRING);
token = tokenStream.token();
charset = token.value;
this._readWhitespace();
tokenStream.mustMatch(Tokens.SEMICOLON);
if (emit !== false){
this.fire({
type: "charset",
charset:charset,
line: line,
col: col
});
}
}
},
_import: function(emit){
/*
* import
* : IMPORT_SYM S*
* [STRING|URI] S* media_query_list? ';' S*
*/
var tokenStream = this._tokenStream,
tt,
uri,
importToken,
mediaList = [];
//read import symbol
tokenStream.mustMatch(Tokens.IMPORT_SYM);
importToken = tokenStream.token();
this._readWhitespace();
tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
//grab the URI value
uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
this._readWhitespace();
mediaList = this._media_query_list();
//must end with a semicolon
tokenStream.mustMatch(Tokens.SEMICOLON);
this._readWhitespace();
if (emit !== false){
this.fire({
type: "import",
uri: uri,
media: mediaList,
line: importToken.startLine,
col: importToken.startCol
});
}
},
_namespace: function(emit){
/*
* namespace
* : NAMESPACE_SYM S* [namespace_prefix S*]? [STRING|URI] S* ';' S*
*/
var tokenStream = this._tokenStream,
line,
col,
prefix,
uri;
//read import symbol
tokenStream.mustMatch(Tokens.NAMESPACE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
//it's a namespace prefix - no _namespace_prefix() method because it's just an IDENT
if (tokenStream.match(Tokens.IDENT)){
prefix = tokenStream.token().value;
this._readWhitespace();
}
tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
//grab the URI value
uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
this._readWhitespace();
//must end with a semicolon
tokenStream.mustMatch(Tokens.SEMICOLON);
this._readWhitespace();
if (emit !== false){
this.fire({
type: "namespace",
prefix: prefix,
uri: uri,
line: line,
col: col
});
}
},
_media: function(){
/*
* media
* : MEDIA_SYM S* media_query_list S* '{' S* ruleset* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
mediaList;// = [];
//look for @media
tokenStream.mustMatch(Tokens.MEDIA_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
mediaList = this._media_query_list();
tokenStream.mustMatch(Tokens.LBRACE);
this._readWhitespace();
this.fire({
type: "startmedia",
media: mediaList,
line: line,
col: col
});
while(true) {
if (tokenStream.peek() == Tokens.PAGE_SYM){
this._page();
} else if (!this._ruleset()){
break;
}
}
tokenStream.mustMatch(Tokens.RBRACE);
this._readWhitespace();
this.fire({
type: "endmedia",
media: mediaList,
line: line,
col: col
});
},
//CSS3 Media Queries
_media_query_list: function(){
/*
* media_query_list
* : S* [media_query [ ',' S* media_query ]* ]?
* ;
*/
var tokenStream = this._tokenStream,
mediaList = [];
this._readWhitespace();
if (tokenStream.peek() == Tokens.IDENT || tokenStream.peek() == Tokens.LPAREN){
mediaList.push(this._media_query());
}
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
mediaList.push(this._media_query());
}
return mediaList;
},
/*
* Note: "expression" in the grammar maps to the _media_expression
* method.
*/
_media_query: function(){
/*
* media_query
* : [ONLY | NOT]? S* media_type S* [ AND S* expression ]*
* | expression [ AND S* expression ]*
* ;
*/
var tokenStream = this._tokenStream,
type = null,
ident = null,
token = null,
expressions = [];
if (tokenStream.match(Tokens.IDENT)){
ident = tokenStream.token().value.toLowerCase();
//since there's no custom tokens for these, need to manually check
if (ident != "only" && ident != "not"){
tokenStream.unget();
ident = null;
} else {
token = tokenStream.token();
}
}
this._readWhitespace();
if (tokenStream.peek() == Tokens.IDENT){
type = this._media_type();
if (token === null){
token = tokenStream.token();
}
} else if (tokenStream.peek() == Tokens.LPAREN){
if (token === null){
token = tokenStream.LT(1);
}
expressions.push(this._media_expression());
}
if (type === null && expressions.length === 0){
return null;
} else {
this._readWhitespace();
while (tokenStream.match(Tokens.IDENT)){
if (tokenStream.token().value.toLowerCase() != "and"){
this._unexpectedToken(tokenStream.token());
}
this._readWhitespace();
expressions.push(this._media_expression());
}
}
return new MediaQuery(ident, type, expressions, token.startLine, token.startCol);
},
//CSS3 Media Queries
_media_type: function(){
/*
* media_type
* : IDENT
* ;
*/
return this._media_feature();
},
/**
* Note: in CSS3 Media Queries, this is called "expression".
* Renamed here to avoid conflict with CSS3 Selectors
* definition of "expression". Also note that "expr" in the
* grammar now maps to "expression" from CSS3 selectors.
* @method _media_expression
* @private
*/
_media_expression: function(){
/*
* expression
* : '(' S* media_feature S* [ ':' S* expr ]? ')' S*
* ;
*/
var tokenStream = this._tokenStream,
feature = null,
token,
expression = null;
tokenStream.mustMatch(Tokens.LPAREN);
feature = this._media_feature();
this._readWhitespace();
if (tokenStream.match(Tokens.COLON)){
this._readWhitespace();
token = tokenStream.LT(1);
expression = this._expression();
}
tokenStream.mustMatch(Tokens.RPAREN);
this._readWhitespace();
return new MediaFeature(feature, (expression ? new SyntaxUnit(expression, token.startLine, token.startCol) : null));
},
//CSS3 Media Queries
_media_feature: function(){
/*
* media_feature
* : IDENT
* ;
*/
var tokenStream = this._tokenStream;
tokenStream.mustMatch(Tokens.IDENT);
return SyntaxUnit.fromToken(tokenStream.token());
},
//CSS3 Paged Media
_page: function(){
/*
* page:
* PAGE_SYM S* IDENT? pseudo_page? S*
* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
identifier = null,
pseudoPage = null;
//look for @page
tokenStream.mustMatch(Tokens.PAGE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
if (tokenStream.match(Tokens.IDENT)){
identifier = tokenStream.token().value;
//The value 'auto' may not be used as a page name and MUST be treated as a syntax error.
if (identifier.toLowerCase() === "auto"){
this._unexpectedToken(tokenStream.token());
}
}
//see if there's a colon upcoming
if (tokenStream.peek() == Tokens.COLON){
pseudoPage = this._pseudo_page();
}
this._readWhitespace();
this.fire({
type: "startpage",
id: identifier,
pseudo: pseudoPage,
line: line,
col: col
});
this._readDeclarations(true, true);
this.fire({
type: "endpage",
id: identifier,
pseudo: pseudoPage,
line: line,
col: col
});
},
//CSS3 Paged Media
_margin: function(){
/*
* margin :
* margin_sym S* '{' declaration [ ';' S* declaration? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
marginSym = this._margin_sym();
if (marginSym){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this.fire({
type: "startpagemargin",
margin: marginSym,
line: line,
col: col
});
this._readDeclarations(true);
this.fire({
type: "endpagemargin",
margin: marginSym,
line: line,
col: col
});
return true;
} else {
return false;
}
},
//CSS3 Paged Media
_margin_sym: function(){
/*
* margin_sym :
* TOPLEFTCORNER_SYM |
* TOPLEFT_SYM |
* TOPCENTER_SYM |
* TOPRIGHT_SYM |
* TOPRIGHTCORNER_SYM |
* BOTTOMLEFTCORNER_SYM |
* BOTTOMLEFT_SYM |
* BOTTOMCENTER_SYM |
* BOTTOMRIGHT_SYM |
* BOTTOMRIGHTCORNER_SYM |
* LEFTTOP_SYM |
* LEFTMIDDLE_SYM |
* LEFTBOTTOM_SYM |
* RIGHTTOP_SYM |
* RIGHTMIDDLE_SYM |
* RIGHTBOTTOM_SYM
* ;
*/
var tokenStream = this._tokenStream;
if(tokenStream.match([Tokens.TOPLEFTCORNER_SYM, Tokens.TOPLEFT_SYM,
Tokens.TOPCENTER_SYM, Tokens.TOPRIGHT_SYM, Tokens.TOPRIGHTCORNER_SYM,
Tokens.BOTTOMLEFTCORNER_SYM, Tokens.BOTTOMLEFT_SYM,
Tokens.BOTTOMCENTER_SYM, Tokens.BOTTOMRIGHT_SYM,
Tokens.BOTTOMRIGHTCORNER_SYM, Tokens.LEFTTOP_SYM,
Tokens.LEFTMIDDLE_SYM, Tokens.LEFTBOTTOM_SYM, Tokens.RIGHTTOP_SYM,
Tokens.RIGHTMIDDLE_SYM, Tokens.RIGHTBOTTOM_SYM]))
{
return SyntaxUnit.fromToken(tokenStream.token());
} else {
return null;
}
},
_pseudo_page: function(){
/*
* pseudo_page
* : ':' IDENT
* ;
*/
var tokenStream = this._tokenStream;
tokenStream.mustMatch(Tokens.COLON);
tokenStream.mustMatch(Tokens.IDENT);
//TODO: CSS3 Paged Media says only "left", "center", and "right" are allowed
return tokenStream.token().value;
},
_font_face: function(){
/*
* font_face
* : FONT_FACE_SYM S*
* '{' S* declaration [ ';' S* declaration ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
line,
col;
//look for @page
tokenStream.mustMatch(Tokens.FONT_FACE_SYM);
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
this._readWhitespace();
this.fire({
type: "startfontface",
line: line,
col: col
});
this._readDeclarations(true);
this.fire({
type: "endfontface",
line: line,
col: col
});
},
_operator: function(){
/*
* operator
* : '/' S* | ',' S* | /( empty )/
* ;
*/
var tokenStream = this._tokenStream,
token = null;
if (tokenStream.match([Tokens.SLASH, Tokens.COMMA])){
token = tokenStream.token();
this._readWhitespace();
}
return token ? PropertyValuePart.fromToken(token) : null;
},
_combinator: function(){
/*
* combinator
* : PLUS S* | GREATER S* | TILDE S* | S+
* ;
*/
var tokenStream = this._tokenStream,
value = null,
token;
if(tokenStream.match([Tokens.PLUS, Tokens.GREATER, Tokens.TILDE])){
token = tokenStream.token();
value = new Combinator(token.value, token.startLine, token.startCol);
this._readWhitespace();
}
return value;
},
_unary_operator: function(){
/*
* unary_operator
* : '-' | '+'
* ;
*/
var tokenStream = this._tokenStream;
if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])){
return tokenStream.token().value;
} else {
return null;
}
},
_property: function(){
/*
* property
* : IDENT S*
* ;
*/
var tokenStream = this._tokenStream,
value = null,
hack = null,
tokenValue,
token,
line,
col;
//check for star hack - throws error if not allowed
if (tokenStream.peek() == Tokens.STAR && this.options.starHack){
tokenStream.get();
token = tokenStream.token();
hack = token.value;
line = token.startLine;
col = token.startCol;
}
if(tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
tokenValue = token.value;
//check for underscore hack - no error if not allowed because it's valid CSS syntax
if (tokenValue.charAt(0) == "_" && this.options.underscoreHack){
hack = "_";
tokenValue = tokenValue.substring(1);
}
value = new PropertyName(tokenValue, hack, (line||token.startLine), (col||token.startCol));
this._readWhitespace();
}
return value;
},
//Augmented with CSS3 Selectors
_ruleset: function(){
/*
* ruleset
* : selectors_group
* '{' S* declaration? [ ';' S* declaration? ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
tt,
selectors;
try {
selectors = this._selectors_group();
} catch (ex){
if (ex instanceof SyntaxError && !this.options.strict){
//fire error event
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
//skip over everything until closing brace
tt = tokenStream.advance([Tokens.RBRACE]);
if (tt == Tokens.RBRACE){
//if there's a right brace, the rule is finished so don't do anything
} else {
//otherwise, rethrow the error because it wasn't handled properly
throw ex;
}
} else {
//not a syntax error, rethrow it
throw ex;
}
//trigger parser to continue
return true;
}
//if it got here, all selectors parsed
if (selectors){
this.fire({
type: "startrule",
selectors: selectors,
line: selectors[0].line,
col: selectors[0].col
});
this._readDeclarations(true);
this.fire({
type: "endrule",
selectors: selectors,
line: selectors[0].line,
col: selectors[0].col
});
}
return selectors;
},
//CSS3 Selectors
_selectors_group: function(){
/*
* selectors_group
* : selector [ COMMA S* selector ]*
* ;
*/
var tokenStream = this._tokenStream,
selectors = [],
selector;
selector = this._selector();
if (selector !== null){
selectors.push(selector);
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
selector = this._selector();
if (selector !== null){
selectors.push(selector);
} else {
this._unexpectedToken(tokenStream.LT(1));
}
}
}
return selectors.length ? selectors : null;
},
//CSS3 Selectors
_selector: function(){
/*
* selector
* : simple_selector_sequence [ combinator simple_selector_sequence ]*
* ;
*/
var tokenStream = this._tokenStream,
selector = [],
nextSelector = null,
combinator = null,
ws = null;
//if there's no simple selector, then there's no selector
nextSelector = this._simple_selector_sequence();
if (nextSelector === null){
return null;
}
selector.push(nextSelector);
do {
//look for a combinator
combinator = this._combinator();
if (combinator !== null){
selector.push(combinator);
nextSelector = this._simple_selector_sequence();
//there must be a next selector
if (nextSelector === null){
this._unexpectedToken(this.LT(1));
} else {
//nextSelector is an instance of SelectorPart
selector.push(nextSelector);
}
} else {
//if there's not whitespace, we're done
if (this._readWhitespace()){
//add whitespace separator
ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol);
//combinator is not required
combinator = this._combinator();
//selector is required if there's a combinator
nextSelector = this._simple_selector_sequence();
if (nextSelector === null){
if (combinator !== null){
this._unexpectedToken(tokenStream.LT(1));
}
} else {
if (combinator !== null){
selector.push(combinator);
} else {
selector.push(ws);
}
selector.push(nextSelector);
}
} else {
break;
}
}
} while(true);
return new Selector(selector, selector[0].line, selector[0].col);
},
//CSS3 Selectors
_simple_selector_sequence: function(){
/*
* simple_selector_sequence
* : [ type_selector | universal ]
* [ HASH | class | attrib | pseudo | negation ]*
* | [ HASH | class | attrib | pseudo | negation ]+
* ;
*/
var tokenStream = this._tokenStream,
//parts of a simple selector
elementName = null,
modifiers = [],
//complete selector text
selectorText= "",
//the different parts after the element name to search for
components = [
//HASH
function(){
return tokenStream.match(Tokens.HASH) ?
new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
null;
},
this._class,
this._attrib,
this._pseudo,
this._negation
],
i = 0,
len = components.length,
component = null,
found = false,
line,
col;
//get starting line and column for the selector
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
elementName = this._type_selector();
if (!elementName){
elementName = this._universal();
}
if (elementName !== null){
selectorText += elementName;
}
while(true){
//whitespace means we're done
if (tokenStream.peek() === Tokens.S){
break;
}
//check for each component
while(i < len && component === null){
component = components[i++].call(this);
}
if (component === null){
//we don't have a selector
if (selectorText === ""){
return null;
} else {
break;
}
} else {
i = 0;
modifiers.push(component);
selectorText += component.toString();
component = null;
}
}
return selectorText !== "" ?
new SelectorPart(elementName, modifiers, selectorText, line, col) :
null;
},
//CSS3 Selectors
_type_selector: function(){
/*
* type_selector
* : [ namespace_prefix ]? element_name
* ;
*/
var tokenStream = this._tokenStream,
ns = this._namespace_prefix(),
elementName = this._element_name();
if (!elementName){
/*
* Need to back out the namespace that was read due to both
* type_selector and universal reading namespace_prefix
* first. Kind of hacky, but only way I can figure out
* right now how to not change the grammar.
*/
if (ns){
tokenStream.unget();
if (ns.length > 1){
tokenStream.unget();
}
}
return null;
} else {
if (ns){
elementName.text = ns + elementName.text;
elementName.col -= ns.length;
}
return elementName;
}
},
//CSS3 Selectors
_class: function(){
/*
* class
* : '.' IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.DOT)){
tokenStream.mustMatch(Tokens.IDENT);
token = tokenStream.token();
return new SelectorSubPart("." + token.value, "class", token.startLine, token.startCol - 1);
} else {
return null;
}
},
//CSS3 Selectors
_element_name: function(){
/*
* element_name
* : IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
return new SelectorSubPart(token.value, "elementName", token.startLine, token.startCol);
} else {
return null;
}
},
//CSS3 Selectors
_namespace_prefix: function(){
/*
* namespace_prefix
* : [ IDENT | '*' ]? '|'
* ;
*/
var tokenStream = this._tokenStream,
value = "";
//verify that this is a namespace prefix
if (tokenStream.LA(1) === Tokens.PIPE || tokenStream.LA(2) === Tokens.PIPE){
if(tokenStream.match([Tokens.IDENT, Tokens.STAR])){
value += tokenStream.token().value;
}
tokenStream.mustMatch(Tokens.PIPE);
value += "|";
}
return value.length ? value : null;
},
//CSS3 Selectors
_universal: function(){
/*
* universal
* : [ namespace_prefix ]? '*'
* ;
*/
var tokenStream = this._tokenStream,
value = "",
ns;
ns = this._namespace_prefix();
if(ns){
value += ns;
}
if(tokenStream.match(Tokens.STAR)){
value += "*";
}
return value.length ? value : null;
},
//CSS3 Selectors
_attrib: function(){
/*
* attrib
* : '[' S* [ namespace_prefix ]? IDENT S*
* [ [ PREFIXMATCH |
* SUFFIXMATCH |
* SUBSTRINGMATCH |
* '=' |
* INCLUDES |
* DASHMATCH ] S* [ IDENT | STRING ] S*
* ]? ']'
* ;
*/
var tokenStream = this._tokenStream,
value = null,
ns,
token;
if (tokenStream.match(Tokens.LBRACKET)){
token = tokenStream.token();
value = token.value;
value += this._readWhitespace();
ns = this._namespace_prefix();
if (ns){
value += ns;
}
tokenStream.mustMatch(Tokens.IDENT);
value += tokenStream.token().value;
value += this._readWhitespace();
if(tokenStream.match([Tokens.PREFIXMATCH, Tokens.SUFFIXMATCH, Tokens.SUBSTRINGMATCH,
Tokens.EQUALS, Tokens.INCLUDES, Tokens.DASHMATCH])){
value += tokenStream.token().value;
value += this._readWhitespace();
tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
value += tokenStream.token().value;
value += this._readWhitespace();
}
tokenStream.mustMatch(Tokens.RBRACKET);
return new SelectorSubPart(value + "]", "attribute", token.startLine, token.startCol);
} else {
return null;
}
},
//CSS3 Selectors
_pseudo: function(){
/*
* pseudo
* : ':' ':'? [ IDENT | functional_pseudo ]
* ;
*/
var tokenStream = this._tokenStream,
pseudo = null,
colons = ":",
line,
col;
if (tokenStream.match(Tokens.COLON)){
if (tokenStream.match(Tokens.COLON)){
colons += ":";
}
if (tokenStream.match(Tokens.IDENT)){
pseudo = tokenStream.token().value;
line = tokenStream.token().startLine;
col = tokenStream.token().startCol - colons.length;
} else if (tokenStream.peek() == Tokens.FUNCTION){
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol - colons.length;
pseudo = this._functional_pseudo();
}
if (pseudo){
pseudo = new SelectorSubPart(colons + pseudo, "pseudo", line, col);
}
}
return pseudo;
},
//CSS3 Selectors
_functional_pseudo: function(){
/*
* functional_pseudo
* : FUNCTION S* expression ')'
* ;
*/
var tokenStream = this._tokenStream,
value = null;
if(tokenStream.match(Tokens.FUNCTION)){
value = tokenStream.token().value;
value += this._readWhitespace();
value += this._expression();
tokenStream.mustMatch(Tokens.RPAREN);
value += ")";
}
return value;
},
//CSS3 Selectors
_expression: function(){
/*
* expression
* : [ [ PLUS | '-' | DIMENSION | NUMBER | STRING | IDENT ] S* ]+
* ;
*/
var tokenStream = this._tokenStream,
value = "";
while(tokenStream.match([Tokens.PLUS, Tokens.MINUS, Tokens.DIMENSION,
Tokens.NUMBER, Tokens.STRING, Tokens.IDENT, Tokens.LENGTH,
Tokens.FREQ, Tokens.ANGLE, Tokens.TIME,
Tokens.RESOLUTION])){
value += tokenStream.token().value;
value += this._readWhitespace();
}
return value.length ? value : null;
},
//CSS3 Selectors
_negation: function(){
/*
* negation
* : NOT S* negation_arg S* ')'
* ;
*/
var tokenStream = this._tokenStream,
line,
col,
value = "",
arg,
subpart = null;
if (tokenStream.match(Tokens.NOT)){
value = tokenStream.token().value;
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
value += this._readWhitespace();
arg = this._negation_arg();
value += arg;
value += this._readWhitespace();
tokenStream.match(Tokens.RPAREN);
value += tokenStream.token().value;
subpart = new SelectorSubPart(value, "not", line, col);
subpart.args.push(arg);
}
return subpart;
},
//CSS3 Selectors
_negation_arg: function(){
/*
* negation_arg
* : type_selector | universal | HASH | class | attrib | pseudo
* ;
*/
var tokenStream = this._tokenStream,
args = [
this._type_selector,
this._universal,
function(){
return tokenStream.match(Tokens.HASH) ?
new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
null;
},
this._class,
this._attrib,
this._pseudo
],
arg = null,
i = 0,
len = args.length,
elementName,
line,
col,
part;
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
while(i < len && arg === null){
arg = args[i].call(this);
i++;
}
//must be a negation arg
if (arg === null){
this._unexpectedToken(tokenStream.LT(1));
}
//it's an element name
if (arg.type == "elementName"){
part = new SelectorPart(arg, [], arg.toString(), line, col);
} else {
part = new SelectorPart(null, [arg], arg.toString(), line, col);
}
return part;
},
_declaration: function(){
/*
* declaration
* : property ':' S* expr prio?
* | /( empty )/
* ;
*/
var tokenStream = this._tokenStream,
property = null,
expr = null,
prio = null,
error = null,
invalid = null;
property = this._property();
if (property !== null){
tokenStream.mustMatch(Tokens.COLON);
this._readWhitespace();
expr = this._expr();
//if there's no parts for the value, it's an error
if (!expr || expr.length === 0){
this._unexpectedToken(tokenStream.LT(1));
}
prio = this._prio();
try {
this._validateProperty(property, expr);
} catch (ex) {
invalid = ex;
}
this.fire({
type: "property",
property: property,
value: expr,
important: prio,
line: property.line,
col: property.col,
invalid: invalid
});
return true;
} else {
return false;
}
},
_prio: function(){
/*
* prio
* : IMPORTANT_SYM S*
* ;
*/
var tokenStream = this._tokenStream,
result = tokenStream.match(Tokens.IMPORTANT_SYM);
this._readWhitespace();
return result;
},
_expr: function(){
/*
* expr
* : term [ operator term ]*
* ;
*/
var tokenStream = this._tokenStream,
values = [],
//valueParts = [],
value = null,
operator = null;
value = this._term();
if (value !== null){
values.push(value);
do {
operator = this._operator();
//if there's an operator, keep building up the value parts
if (operator){
values.push(operator);
} /*else {
//if there's not an operator, you have a full value
values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
valueParts = [];
}*/
value = this._term();
if (value === null){
break;
} else {
values.push(value);
}
} while(true);
}
//cleanup
/*if (valueParts.length){
values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
}*/
return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null;
},
_term: function(){
/*
* term
* : unary_operator?
* [ NUMBER S* | PERCENTAGE S* | LENGTH S* | ANGLE S* |
* TIME S* | FREQ S* | function | ie_function ]
* | STRING S* | IDENT S* | URI S* | UNICODERANGE S* | hexcolor
* ;
*/
var tokenStream = this._tokenStream,
unary = null,
value = null,
token,
line,
col;
//returns the operator or null
unary = this._unary_operator();
if (unary !== null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
//exception for IE filters
if (tokenStream.peek() == Tokens.IE_FUNCTION && this.options.ieFilters){
value = this._ie_function();
if (unary === null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
//see if there's a simple match
} else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
Tokens.ANGLE, Tokens.TIME,
Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])){
value = tokenStream.token().value;
if (unary === null){
line = tokenStream.token().startLine;
col = tokenStream.token().startCol;
}
this._readWhitespace();
} else {
//see if it's a color
token = this._hexcolor();
if (token === null){
//if there's no unary, get the start of the next token for line/col info
if (unary === null){
line = tokenStream.LT(1).startLine;
col = tokenStream.LT(1).startCol;
}
//has to be a function
if (value === null){
/*
* This checks for alpha(opacity=0) style of IE
* functions. IE_FUNCTION only presents progid: style.
*/
if (tokenStream.LA(3) == Tokens.EQUALS && this.options.ieFilters){
value = this._ie_function();
} else {
value = this._function();
}
}
/*if (value === null){
return null;
//throw new Error("Expected identifier at line " + tokenStream.token().startLine + ", character " + tokenStream.token().startCol + ".");
}*/
} else {
value = token.value;
if (unary === null){
line = token.startLine;
col = token.startCol;
}
}
}
return value !== null ?
new PropertyValuePart(unary !== null ? unary + value : value, line, col) :
null;
},
_function: function(){
/*
* function
* : FUNCTION S* expr ')' S*
* ;
*/
var tokenStream = this._tokenStream,
functionText = null,
expr = null,
lt;
if (tokenStream.match(Tokens.FUNCTION)){
functionText = tokenStream.token().value;
this._readWhitespace();
expr = this._expr();
functionText += expr;
//START: Horrible hack in case it's an IE filter
if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){
do {
if (this._readWhitespace()){
functionText += tokenStream.token().value;
}
//might be second time in the loop
if (tokenStream.LA(0) == Tokens.COMMA){
functionText += tokenStream.token().value;
}
tokenStream.match(Tokens.IDENT);
functionText += tokenStream.token().value;
tokenStream.match(Tokens.EQUALS);
functionText += tokenStream.token().value;
//functionText += this._term();
lt = tokenStream.peek();
while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
tokenStream.get();
functionText += tokenStream.token().value;
lt = tokenStream.peek();
}
} while(tokenStream.match([Tokens.COMMA, Tokens.S]));
}
//END: Horrible Hack
tokenStream.match(Tokens.RPAREN);
functionText += ")";
this._readWhitespace();
}
return functionText;
},
_ie_function: function(){
/* (My own extension)
* ie_function
* : IE_FUNCTION S* IDENT '=' term [S* ','? IDENT '=' term]+ ')' S*
* ;
*/
var tokenStream = this._tokenStream,
functionText = null,
expr = null,
lt;
//IE function can begin like a regular function, too
if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])){
functionText = tokenStream.token().value;
do {
if (this._readWhitespace()){
functionText += tokenStream.token().value;
}
//might be second time in the loop
if (tokenStream.LA(0) == Tokens.COMMA){
functionText += tokenStream.token().value;
}
tokenStream.match(Tokens.IDENT);
functionText += tokenStream.token().value;
tokenStream.match(Tokens.EQUALS);
functionText += tokenStream.token().value;
//functionText += this._term();
lt = tokenStream.peek();
while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
tokenStream.get();
functionText += tokenStream.token().value;
lt = tokenStream.peek();
}
} while(tokenStream.match([Tokens.COMMA, Tokens.S]));
tokenStream.match(Tokens.RPAREN);
functionText += ")";
this._readWhitespace();
}
return functionText;
},
_hexcolor: function(){
/*
* There is a constraint on the color that it must
* have either 3 or 6 hex-digits (i.e., [0-9a-fA-F])
* after the "#"; e.g., "#000" is OK, but "#abcd" is not.
*
* hexcolor
* : HASH S*
* ;
*/
var tokenStream = this._tokenStream,
token = null,
color;
if(tokenStream.match(Tokens.HASH)){
//need to do some validation here
token = tokenStream.token();
color = token.value;
if (!/#[a-f0-9]{3,6}/i.test(color)){
throw new SyntaxError("Expected a hex color but found '" + color + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
}
this._readWhitespace();
}
return token;
},
//-----------------------------------------------------------------
// Animations methods
//-----------------------------------------------------------------
_keyframes: function(){
/*
* keyframes:
* : KEYFRAMES_SYM S* keyframe_name S* '{' S* keyframe_rule* '}' {
* ;
*/
var tokenStream = this._tokenStream,
token,
tt,
name;
tokenStream.mustMatch(Tokens.KEYFRAMES_SYM);
this._readWhitespace();
name = this._keyframe_name();
this._readWhitespace();
tokenStream.mustMatch(Tokens.LBRACE);
this.fire({
type: "startkeyframes",
name: name,
line: name.line,
col: name.col
});
this._readWhitespace();
tt = tokenStream.peek();
//check for key
while(tt == Tokens.IDENT || tt == Tokens.PERCENTAGE) {
this._keyframe_rule();
this._readWhitespace();
tt = tokenStream.peek();
}
this.fire({
type: "endkeyframes",
name: name,
line: name.line,
col: name.col
});
this._readWhitespace();
tokenStream.mustMatch(Tokens.RBRACE);
},
_keyframe_name: function(){
/*
* keyframe_name:
* : IDENT
* | STRING
* ;
*/
var tokenStream = this._tokenStream,
token;
tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
return SyntaxUnit.fromToken(tokenStream.token());
},
_keyframe_rule: function(){
/*
* keyframe_rule:
* : key_list S*
* '{' S* declaration [ ';' S* declaration ]* '}' S*
* ;
*/
var tokenStream = this._tokenStream,
token,
keyList = this._key_list();
this.fire({
type: "startkeyframerule",
keys: keyList,
line: keyList[0].line,
col: keyList[0].col
});
this._readDeclarations(true);
this.fire({
type: "endkeyframerule",
keys: keyList,
line: keyList[0].line,
col: keyList[0].col
});
},
_key_list: function(){
/*
* key_list:
* : key [ S* ',' S* key]*
* ;
*/
var tokenStream = this._tokenStream,
token,
key,
keyList = [];
//must be least one key
keyList.push(this._key());
this._readWhitespace();
while(tokenStream.match(Tokens.COMMA)){
this._readWhitespace();
keyList.push(this._key());
this._readWhitespace();
}
return keyList;
},
_key: function(){
/*
* There is a restriction that IDENT can be only "from" or "to".
*
* key
* : PERCENTAGE
* | IDENT
* ;
*/
var tokenStream = this._tokenStream,
token;
if (tokenStream.match(Tokens.PERCENTAGE)){
return SyntaxUnit.fromToken(tokenStream.token());
} else if (tokenStream.match(Tokens.IDENT)){
token = tokenStream.token();
if (/from|to/i.test(token.value)){
return SyntaxUnit.fromToken(token);
}
tokenStream.unget();
}
//if it gets here, there wasn't a valid token, so time to explode
this._unexpectedToken(tokenStream.LT(1));
},
//-----------------------------------------------------------------
// Helper methods
//-----------------------------------------------------------------
/**
* Not part of CSS grammar, but useful for skipping over
* combination of white space and HTML-style comments.
* @return {void}
* @method _skipCruft
* @private
*/
_skipCruft: function(){
while(this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])){
//noop
}
},
/**
* Not part of CSS grammar, but this pattern occurs frequently
* in the official CSS grammar. Split out here to eliminate
* duplicate code.
* @param {Boolean} checkStart Indicates if the rule should check
* for the left brace at the beginning.
* @param {Boolean} readMargins Indicates if the rule should check
* for margin patterns.
* @return {void}
* @method _readDeclarations
* @private
*/
_readDeclarations: function(checkStart, readMargins){
/*
* Reads the pattern
* S* '{' S* declaration [ ';' S* declaration ]* '}' S*
* or
* S* '{' S* [ declaration | margin ]? [ ';' S* [ declaration | margin ]? ]* '}' S*
* Note that this is how it is described in CSS3 Paged Media, but is actually incorrect.
* A semicolon is only necessary following a delcaration is there's another declaration
* or margin afterwards.
*/
var tokenStream = this._tokenStream,
tt;
this._readWhitespace();
if (checkStart){
tokenStream.mustMatch(Tokens.LBRACE);
}
this._readWhitespace();
try {
while(true){
if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())){
//noop
} else if (this._declaration()){
if (!tokenStream.match(Tokens.SEMICOLON)){
break;
}
} else {
break;
}
//if ((!this._margin() && !this._declaration()) || !tokenStream.match(Tokens.SEMICOLON)){
// break;
//}
this._readWhitespace();
}
tokenStream.mustMatch(Tokens.RBRACE);
this._readWhitespace();
} catch (ex) {
if (ex instanceof SyntaxError && !this.options.strict){
//fire error event
this.fire({
type: "error",
error: ex,
message: ex.message,
line: ex.line,
col: ex.col
});
//see if there's another declaration
tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]);
if (tt == Tokens.SEMICOLON){
//if there's a semicolon, then there might be another declaration
this._readDeclarations(false, readMargins);
} else if (tt != Tokens.RBRACE){
//if there's a right brace, the rule is finished so don't do anything
//otherwise, rethrow the error because it wasn't handled properly
throw ex;
}
} else {
//not a syntax error, rethrow it
throw ex;
}
}
},
/**
* In some cases, you can end up with two white space tokens in a
* row. Instead of making a change in every function that looks for
* white space, this function is used to match as much white space
* as necessary.
* @method _readWhitespace
* @return {String} The white space if found, empty string if not.
* @private
*/
_readWhitespace: function(){
var tokenStream = this._tokenStream,
ws = "";
while(tokenStream.match(Tokens.S)){
ws += tokenStream.token().value;
}
return ws;
},
/**
* Throws an error when an unexpected token is found.
* @param {Object} token The token that was found.
* @method _unexpectedToken
* @return {void}
* @private
*/
_unexpectedToken: function(token){
throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
},
/**
* Helper method used for parsing subparts of a style sheet.
* @return {void}
* @method _verifyEnd
* @private
*/
_verifyEnd: function(){
if (this._tokenStream.LA(1) != Tokens.EOF){
this._unexpectedToken(this._tokenStream.LT(1));
}
},
//-----------------------------------------------------------------
// Validation methods
//-----------------------------------------------------------------
_validateProperty: function(property, value){
Validation.validate(property, value);
},
//-----------------------------------------------------------------
// Parsing methods
//-----------------------------------------------------------------
parse: function(input){
this._tokenStream = new TokenStream(input, Tokens);
this._stylesheet();
},
parseStyleSheet: function(input){
//just passthrough
return this.parse(input);
},
parseMediaQuery: function(input){
this._tokenStream = new TokenStream(input, Tokens);
var result = this._media_query();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a property value (everything after the semicolon).
* @return {parserlib.css.PropertyValue} The property value.
* @throws parserlib.util.SyntaxError If an unexpected token is found.
* @method parserPropertyValue
*/
parsePropertyValue: function(input){
this._tokenStream = new TokenStream(input, Tokens);
this._readWhitespace();
var result = this._expr();
//okay to have a trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a complete CSS rule, including selectors and
* properties.
* @param {String} input The text to parser.
* @return {Boolean} True if the parse completed successfully, false if not.
* @method parseRule
*/
parseRule: function(input){
this._tokenStream = new TokenStream(input, Tokens);
//skip any leading white space
this._readWhitespace();
var result = this._ruleset();
//skip any trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses a single CSS selector (no comma)
* @param {String} input The text to parse as a CSS selector.
* @return {Selector} An object representing the selector.
* @throws parserlib.util.SyntaxError If an unexpected token is found.
* @method parseSelector
*/
parseSelector: function(input){
this._tokenStream = new TokenStream(input, Tokens);
//skip any leading white space
this._readWhitespace();
var result = this._selector();
//skip any trailing white space
this._readWhitespace();
//if there's anything more, then it's an invalid selector
this._verifyEnd();
//otherwise return result
return result;
},
/**
* Parses an HTML style attribute: a set of CSS declarations
* separated by semicolons.
* @param {String} input The text to parse as a style attribute
* @return {void}
* @method parseStyleAttribute
*/
parseStyleAttribute: function(input){
input += "}"; // for error recovery in _readDeclarations()
this._tokenStream = new TokenStream(input, Tokens);
this._readDeclarations();
}
};
//copy over onto prototype
for (prop in additions){
if (additions.hasOwnProperty(prop)){
proto[prop] = additions[prop];
}
}
return proto;
}();
/*global Validation, ValidationTypes, ValidationError*/
var Properties = {
//A
"alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>",
"alignment-baseline" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"animation" : 1,
"animation-delay" : { multi: "<time>", comma: true },
"animation-direction" : { multi: "normal | alternate", comma: true },
"animation-duration" : { multi: "<time>", comma: true },
"animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"animation-name" : { multi: "none | <ident>", comma: true },
"animation-play-state" : { multi: "running | paused", comma: true },
"animation-timing-function" : 1,
//vendor prefixed
"-moz-animation-delay" : { multi: "<time>", comma: true },
"-moz-animation-direction" : { multi: "normal | alternate", comma: true },
"-moz-animation-duration" : { multi: "<time>", comma: true },
"-moz-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-moz-animation-name" : { multi: "none | <ident>", comma: true },
"-moz-animation-play-state" : { multi: "running | paused", comma: true },
"-ms-animation-delay" : { multi: "<time>", comma: true },
"-ms-animation-direction" : { multi: "normal | alternate", comma: true },
"-ms-animation-duration" : { multi: "<time>", comma: true },
"-ms-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-ms-animation-name" : { multi: "none | <ident>", comma: true },
"-ms-animation-play-state" : { multi: "running | paused", comma: true },
"-webkit-animation-delay" : { multi: "<time>", comma: true },
"-webkit-animation-direction" : { multi: "normal | alternate", comma: true },
"-webkit-animation-duration" : { multi: "<time>", comma: true },
"-webkit-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-webkit-animation-name" : { multi: "none | <ident>", comma: true },
"-webkit-animation-play-state" : { multi: "running | paused", comma: true },
"-o-animation-delay" : { multi: "<time>", comma: true },
"-o-animation-direction" : { multi: "normal | alternate", comma: true },
"-o-animation-duration" : { multi: "<time>", comma: true },
"-o-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
"-o-animation-name" : { multi: "none | <ident>", comma: true },
"-o-animation-play-state" : { multi: "running | paused", comma: true },
"appearance" : "icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | inherit",
"azimuth" : function (expression) {
var simple = "<angle> | leftwards | rightwards | inherit",
direction = "left-side | far-left | left | center-left | center | center-right | right | far-right | right-side",
behind = false,
valid = false,
part;
if (!ValidationTypes.isAny(expression, simple)) {
if (ValidationTypes.isAny(expression, "behind")) {
behind = true;
valid = true;
}
if (ValidationTypes.isAny(expression, direction)) {
valid = true;
if (!behind) {
ValidationTypes.isAny(expression, "behind");
}
}
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (<'azimuth'>) but found '" + part + "'.", part.line, part.col);
}
}
},
//B
"backface-visibility" : "visible | hidden",
"background" : 1,
"background-attachment" : { multi: "<attachment>", comma: true },
"background-clip" : { multi: "<box>", comma: true },
"background-color" : "<color> | inherit",
"background-image" : { multi: "<bg-image>", comma: true },
"background-origin" : { multi: "<box>", comma: true },
"background-position" : { multi: "<bg-position>", comma: true },
"background-repeat" : { multi: "<repeat-style>" },
"background-size" : { multi: "<bg-size>", comma: true },
"baseline-shift" : "baseline | sub | super | <percentage> | <length>",
"binding" : 1,
"bleed" : "<length>",
"bookmark-label" : "<content> | <attr> | <string>",
"bookmark-level" : "none | <integer>",
"bookmark-state" : "open | closed",
"bookmark-target" : "none | <uri> | <attr>",
"border" : "<border-width> || <border-style> || <color>",
"border-bottom" : "<border-width> || <border-style> || <color>",
"border-bottom-color" : "<color>",
"border-bottom-left-radius" : "<x-one-radius>",
"border-bottom-right-radius" : "<x-one-radius>",
"border-bottom-style" : "<border-style>",
"border-bottom-width" : "<border-width>",
"border-collapse" : "collapse | separate | inherit",
"border-color" : { multi: "<color> | inherit", max: 4 },
"border-image" : 1,
"border-image-outset" : { multi: "<length> | <number>", max: 4 },
"border-image-repeat" : { multi: "stretch | repeat | round", max: 2 },
"border-image-slice" : function(expression) {
var valid = false,
numeric = "<number> | <percentage>",
fill = false,
count = 0,
max = 4,
part;
if (ValidationTypes.isAny(expression, "fill")) {
fill = true;
valid = true;
}
while (expression.hasNext() && count < max) {
valid = ValidationTypes.isAny(expression, numeric);
if (!valid) {
break;
}
count++;
}
if (!fill) {
ValidationTypes.isAny(expression, "fill");
} else {
valid = true;
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '" + part + "'.", part.line, part.col);
}
}
},
"border-image-source" : "<image> | none",
"border-image-width" : { multi: "<length> | <percentage> | <number> | auto", max: 4 },
"border-left" : "<border-width> || <border-style> || <color>",
"border-left-color" : "<color> | inherit",
"border-left-style" : "<border-style>",
"border-left-width" : "<border-width>",
"border-radius" : function(expression) {
var valid = false,
numeric = "<length> | <percentage>",
slash = false,
fill = false,
count = 0,
max = 8,
part;
while (expression.hasNext() && count < max) {
valid = ValidationTypes.isAny(expression, numeric);
if (!valid) {
if (expression.peek() == "/" && count > 1 && !slash) {
slash = true;
max = count + 5;
expression.next();
} else {
break;
}
}
count++;
}
if (expression.hasNext()) {
part = expression.next();
if (valid) {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (<'border-radius'>) but found '" + part + "'.", part.line, part.col);
}
}
},
"border-right" : "<border-width> || <border-style> || <color>",
"border-right-color" : "<color> | inherit",
"border-right-style" : "<border-style>",
"border-right-width" : "<border-width>",
"border-spacing" : { multi: "<length> | inherit", max: 2 },
"border-style" : { multi: "<border-style>", max: 4 },
"border-top" : "<border-width> || <border-style> || <color>",
"border-top-color" : "<color> | inherit",
"border-top-left-radius" : "<x-one-radius>",
"border-top-right-radius" : "<x-one-radius>",
"border-top-style" : "<border-style>",
"border-top-width" : "<border-width>",
"border-width" : { multi: "<border-width>", max: 4 },
"bottom" : "<margin-width> | inherit",
"box-align" : "start | end | center | baseline | stretch", //http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/
"box-decoration-break" : "slice |clone",
"box-direction" : "normal | reverse | inherit",
"box-flex" : "<number>",
"box-flex-group" : "<integer>",
"box-lines" : "single | multiple",
"box-ordinal-group" : "<integer>",
"box-orient" : "horizontal | vertical | inline-axis | block-axis | inherit",
"box-pack" : "start | end | center | justify",
"box-shadow" : function (expression) {
var result = false,
part;
if (!ValidationTypes.isAny(expression, "none")) {
Validation.multiProperty("<shadow>", expression, true, Infinity);
} else {
if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
}
},
"box-sizing" : "content-box | border-box | inherit",
"break-after" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
"break-before" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
"break-inside" : "auto | avoid | avoid-page | avoid-column",
//C
"caption-side" : "top | bottom | inherit",
"clear" : "none | right | left | both | inherit",
"clip" : 1,
"color" : "<color> | inherit",
"color-profile" : 1,
"column-count" : "<integer> | auto", //http://www.w3.org/TR/css3-multicol/
"column-fill" : "auto | balance",
"column-gap" : "<length> | normal",
"column-rule" : "<border-width> || <border-style> || <color>",
"column-rule-color" : "<color>",
"column-rule-style" : "<border-style>",
"column-rule-width" : "<border-width>",
"column-span" : "none | all",
"column-width" : "<length> | auto",
"columns" : 1,
"content" : 1,
"counter-increment" : 1,
"counter-reset" : 1,
"crop" : "<shape> | auto",
"cue" : "cue-after | cue-before | inherit",
"cue-after" : 1,
"cue-before" : 1,
"cursor" : 1,
//D
"direction" : "ltr | rtl | inherit",
"display" : "inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | box | inline-box | grid | inline-grid | none | inherit",
"dominant-baseline" : 1,
"drop-initial-after-adjust" : "central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>",
"drop-initial-after-align" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"drop-initial-before-adjust" : "before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>",
"drop-initial-before-align" : "caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
"drop-initial-size" : "auto | line | <length> | <percentage>",
"drop-initial-value" : "initial | <integer>",
//E
"elevation" : "<angle> | below | level | above | higher | lower | inherit",
"empty-cells" : "show | hide | inherit",
//F
"filter" : 1,
"fit" : "fill | hidden | meet | slice",
"fit-position" : 1,
"float" : "left | right | none | inherit",
"float-offset" : 1,
"font" : 1,
"font-family" : 1,
"font-size" : "<absolute-size> | <relative-size> | <length> | <percentage> | inherit",
"font-size-adjust" : "<number> | none | inherit",
"font-stretch" : "normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit",
"font-style" : "normal | italic | oblique | inherit",
"font-variant" : "normal | small-caps | inherit",
"font-weight" : "normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit",
//G
"grid-cell-stacking" : "columns | rows | layer",
"grid-column" : 1,
"grid-columns" : 1,
"grid-column-align" : "start | end | center | stretch",
"grid-column-sizing" : 1,
"grid-column-span" : "<integer>",
"grid-flow" : "none | rows | columns",
"grid-layer" : "<integer>",
"grid-row" : 1,
"grid-rows" : 1,
"grid-row-align" : "start | end | center | stretch",
"grid-row-span" : "<integer>",
"grid-row-sizing" : 1,
//H
"hanging-punctuation" : 1,
"height" : "<margin-width> | inherit",
"hyphenate-after" : "<integer> | auto",
"hyphenate-before" : "<integer> | auto",
"hyphenate-character" : "<string> | auto",
"hyphenate-lines" : "no-limit | <integer>",
"hyphenate-resource" : 1,
"hyphens" : "none | manual | auto",
//I
"icon" : 1,
"image-orientation" : "angle | auto",
"image-rendering" : 1,
"image-resolution" : 1,
"inline-box-align" : "initial | last | <integer>",
//L
"left" : "<margin-width> | inherit",
"letter-spacing" : "<length> | normal | inherit",
"line-height" : "<number> | <length> | <percentage> | normal | inherit",
"line-break" : "auto | loose | normal | strict",
"line-stacking" : 1,
"line-stacking-ruby" : "exclude-ruby | include-ruby",
"line-stacking-shift" : "consider-shifts | disregard-shifts",
"line-stacking-strategy" : "inline-line-height | block-line-height | max-height | grid-height",
"list-style" : 1,
"list-style-image" : "<uri> | none | inherit",
"list-style-position" : "inside | outside | inherit",
"list-style-type" : "disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit",
//M
"margin" : { multi: "<margin-width> | inherit", max: 4 },
"margin-bottom" : "<margin-width> | inherit",
"margin-left" : "<margin-width> | inherit",
"margin-right" : "<margin-width> | inherit",
"margin-top" : "<margin-width> | inherit",
"mark" : 1,
"mark-after" : 1,
"mark-before" : 1,
"marks" : 1,
"marquee-direction" : 1,
"marquee-play-count" : 1,
"marquee-speed" : 1,
"marquee-style" : 1,
"max-height" : "<length> | <percentage> | none | inherit",
"max-width" : "<length> | <percentage> | none | inherit",
"min-height" : "<length> | <percentage> | inherit",
"min-width" : "<length> | <percentage> | inherit",
"move-to" : 1,
//N
"nav-down" : 1,
"nav-index" : 1,
"nav-left" : 1,
"nav-right" : 1,
"nav-up" : 1,
//O
"opacity" : "<number> | inherit",
"orphans" : "<integer> | inherit",
"outline" : 1,
"outline-color" : "<color> | invert | inherit",
"outline-offset" : 1,
"outline-style" : "<border-style> | inherit",
"outline-width" : "<border-width> | inherit",
"overflow" : "visible | hidden | scroll | auto | inherit",
"overflow-style" : 1,
"overflow-x" : 1,
"overflow-y" : 1,
//P
"padding" : { multi: "<padding-width> | inherit", max: 4 },
"padding-bottom" : "<padding-width> | inherit",
"padding-left" : "<padding-width> | inherit",
"padding-right" : "<padding-width> | inherit",
"padding-top" : "<padding-width> | inherit",
"page" : 1,
"page-break-after" : "auto | always | avoid | left | right | inherit",
"page-break-before" : "auto | always | avoid | left | right | inherit",
"page-break-inside" : "auto | avoid | inherit",
"page-policy" : 1,
"pause" : 1,
"pause-after" : 1,
"pause-before" : 1,
"perspective" : 1,
"perspective-origin" : 1,
"phonemes" : 1,
"pitch" : 1,
"pitch-range" : 1,
"play-during" : 1,
"position" : "static | relative | absolute | fixed | inherit",
"presentation-level" : 1,
"punctuation-trim" : 1,
//Q
"quotes" : 1,
//R
"rendering-intent" : 1,
"resize" : 1,
"rest" : 1,
"rest-after" : 1,
"rest-before" : 1,
"richness" : 1,
"right" : "<margin-width> | inherit",
"rotation" : 1,
"rotation-point" : 1,
"ruby-align" : 1,
"ruby-overhang" : 1,
"ruby-position" : 1,
"ruby-span" : 1,
//S
"size" : 1,
"speak" : "normal | none | spell-out | inherit",
"speak-header" : "once | always | inherit",
"speak-numeral" : "digits | continuous | inherit",
"speak-punctuation" : "code | none | inherit",
"speech-rate" : 1,
"src" : 1,
"stress" : 1,
"string-set" : 1,
"table-layout" : "auto | fixed | inherit",
"tab-size" : "<integer> | <length>",
"target" : 1,
"target-name" : 1,
"target-new" : 1,
"target-position" : 1,
"text-align" : "left | right | center | justify | inherit" ,
"text-align-last" : 1,
"text-decoration" : 1,
"text-emphasis" : 1,
"text-height" : 1,
"text-indent" : "<length> | <percentage> | inherit",
"text-justify" : "auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida",
"text-outline" : 1,
"text-overflow" : 1,
"text-shadow" : 1,
"text-transform" : "capitalize | uppercase | lowercase | none | inherit",
"text-wrap" : "normal | none | avoid",
"top" : "<margin-width> | inherit",
"transform" : 1,
"transform-origin" : 1,
"transform-style" : 1,
"transition" : 1,
"transition-delay" : 1,
"transition-duration" : 1,
"transition-property" : 1,
"transition-timing-function" : 1,
//U
"unicode-bidi" : "normal | embed | bidi-override | inherit",
"user-modify" : "read-only | read-write | write-only | inherit",
"user-select" : "none | text | toggle | element | elements | all | inherit",
//V
"vertical-align" : "<percentage> | <length> | baseline | sub | super | top | text-top | middle | bottom | text-bottom | inherit",
"visibility" : "visible | hidden | collapse | inherit",
"voice-balance" : 1,
"voice-duration" : 1,
"voice-family" : 1,
"voice-pitch" : 1,
"voice-pitch-range" : 1,
"voice-rate" : 1,
"voice-stress" : 1,
"voice-volume" : 1,
"volume" : 1,
//W
"white-space" : "normal | pre | nowrap | pre-wrap | pre-line | inherit",
"white-space-collapse" : 1,
"widows" : "<integer> | inherit",
"width" : "<length> | <percentage> | auto | inherit" ,
"word-break" : "normal | keep-all | break-all",
"word-spacing" : "<length> | normal | inherit",
"word-wrap" : 1,
//Z
"z-index" : "<integer> | auto | inherit",
"zoom" : "<number> | <percentage> | normal"
};
/**
* Represents a selector combinator (whitespace, +, >).
* @namespace parserlib.css
* @class PropertyName
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {String} hack The type of IE hack applied ("*", "_", or null).
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function PropertyName(text, hack, line, col){
SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE);
this.hack = hack;
}
PropertyName.prototype = new SyntaxUnit();
PropertyName.prototype.constructor = PropertyName;
PropertyName.prototype.toString = function(){
return (this.hack ? this.hack : "") + this.text;
};
/**
* Represents a single part of a CSS property value, meaning that it represents
* just everything single part between ":" and ";". If there are multiple values
* separated by commas, this type represents just one of the values.
* @param {String[]} parts An array of value parts making up this value.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
* @namespace parserlib.css
* @class PropertyValue
* @extends parserlib.util.SyntaxUnit
* @constructor
*/
function PropertyValue(parts, line, col){
SyntaxUnit.call(this, parts.join(" "), line, col, Parser.PROPERTY_VALUE_TYPE);
this.parts = parts;
}
PropertyValue.prototype = new SyntaxUnit();
PropertyValue.prototype.constructor = PropertyValue;
/**
* A utility class that allows for easy iteration over the various parts of a
* property value.
* @param {parserlib.css.PropertyValue} value The property value to iterate over.
* @namespace parserlib.css
* @class PropertyValueIterator
* @constructor
*/
function PropertyValueIterator(value){
/**
* Iterator value
* @type int
* @property _i
* @private
*/
this._i = 0;
this._parts = value.parts;
this._marks = [];
this.value = value;
}
/**
* Returns the total number of parts in the value.
* @return {int} The total number of parts in the value.
* @method count
*/
PropertyValueIterator.prototype.count = function(){
return this._parts.length;
};
PropertyValueIterator.prototype.isFirst = function(){
return this._i === 0;
};
PropertyValueIterator.prototype.hasNext = function(){
return (this._i < this._parts.length);
};
PropertyValueIterator.prototype.mark = function(){
this._marks.push(this._i);
};
PropertyValueIterator.prototype.peek = function(count){
return this.hasNext() ? this._parts[this._i + (count || 0)] : null;
};
PropertyValueIterator.prototype.next = function(){
return this.hasNext() ? this._parts[this._i++] : null;
};
PropertyValueIterator.prototype.previous = function(){
return this._i > 0 ? this._parts[--this._i] : null;
};
PropertyValueIterator.prototype.restore = function(){
if (this._marks.length){
this._i = this._marks.pop();
}
};
/**
* Represents a single part of a CSS property value, meaning that it represents
* just one part of the data between ":" and ";".
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
* @namespace parserlib.css
* @class PropertyValuePart
* @extends parserlib.util.SyntaxUnit
* @constructor
*/
function PropertyValuePart(text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_VALUE_PART_TYPE);
this.type = "unknown";
//figure out what type of data it is
var temp;
//it is a measurement?
if (/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)){ //dimension
this.type = "dimension";
this.value = +RegExp.$1;
this.units = RegExp.$2;
//try to narrow down
switch(this.units.toLowerCase()){
case "em":
case "rem":
case "ex":
case "px":
case "cm":
case "mm":
case "in":
case "pt":
case "pc":
case "ch":
this.type = "length";
break;
case "deg":
case "rad":
case "grad":
this.type = "angle";
break;
case "ms":
case "s":
this.type = "time";
break;
case "hz":
case "khz":
this.type = "frequency";
break;
case "dpi":
case "dpcm":
this.type = "resolution";
break;
//default
}
} else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
this.type = "percentage";
this.value = +RegExp.$1;
} else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
this.type = "percentage";
this.value = +RegExp.$1;
} else if (/^([+\-]?\d+)$/i.test(text)){ //integer
this.type = "integer";
this.value = +RegExp.$1;
} else if (/^([+\-]?[\d\.]+)$/i.test(text)){ //number
this.type = "number";
this.value = +RegExp.$1;
} else if (/^#([a-f0-9]{3,6})/i.test(text)){ //hexcolor
this.type = "color";
temp = RegExp.$1;
if (temp.length == 3){
this.red = parseInt(temp.charAt(0)+temp.charAt(0),16);
this.green = parseInt(temp.charAt(1)+temp.charAt(1),16);
this.blue = parseInt(temp.charAt(2)+temp.charAt(2),16);
} else {
this.red = parseInt(temp.substring(0,2),16);
this.green = parseInt(temp.substring(2,4),16);
this.blue = parseInt(temp.substring(4,6),16);
}
} else if (/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)){ //rgb() color with absolute numbers
this.type = "color";
this.red = +RegExp.$1;
this.green = +RegExp.$2;
this.blue = +RegExp.$3;
} else if (/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //rgb() color with percentages
this.type = "color";
this.red = +RegExp.$1 * 255 / 100;
this.green = +RegExp.$2 * 255 / 100;
this.blue = +RegExp.$3 * 255 / 100;
} else if (/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with absolute numbers
this.type = "color";
this.red = +RegExp.$1;
this.green = +RegExp.$2;
this.blue = +RegExp.$3;
this.alpha = +RegExp.$4;
} else if (/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with percentages
this.type = "color";
this.red = +RegExp.$1 * 255 / 100;
this.green = +RegExp.$2 * 255 / 100;
this.blue = +RegExp.$3 * 255 / 100;
this.alpha = +RegExp.$4;
} else if (/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //hsl()
this.type = "color";
this.hue = +RegExp.$1;
this.saturation = +RegExp.$2 / 100;
this.lightness = +RegExp.$3 / 100;
} else if (/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //hsla() color with percentages
this.type = "color";
this.hue = +RegExp.$1;
this.saturation = +RegExp.$2 / 100;
this.lightness = +RegExp.$3 / 100;
this.alpha = +RegExp.$4;
} else if (/^url\(["']?([^\)"']+)["']?\)/i.test(text)){ //URI
this.type = "uri";
this.uri = RegExp.$1;
} else if (/^([^\(]+)\(/i.test(text)){
this.type = "function";
this.name = RegExp.$1;
this.value = text;
} else if (/^["'][^"']*["']/.test(text)){ //string
this.type = "string";
this.value = eval(text);
} else if (Colors[text.toLowerCase()]){ //named color
this.type = "color";
temp = Colors[text.toLowerCase()].substring(1);
this.red = parseInt(temp.substring(0,2),16);
this.green = parseInt(temp.substring(2,4),16);
this.blue = parseInt(temp.substring(4,6),16);
} else if (/^[\,\/]$/.test(text)){
this.type = "operator";
this.value = text;
} else if (/^[a-z\-\u0080-\uFFFF][a-z0-9\-\u0080-\uFFFF]*$/i.test(text)){
this.type = "identifier";
this.value = text;
}
}
PropertyValuePart.prototype = new SyntaxUnit();
PropertyValuePart.prototype.constructor = PropertyValuePart;
PropertyValuePart.fromToken = function(token){
return new PropertyValuePart(token.value, token.startLine, token.startCol);
};
var Pseudos = {
":first-letter": 1,
":first-line": 1,
":before": 1,
":after": 1
};
Pseudos.ELEMENT = 1;
Pseudos.CLASS = 2;
Pseudos.isElement = function(pseudo){
return pseudo.indexOf("::") === 0 || Pseudos[pseudo.toLowerCase()] == Pseudos.ELEMENT;
};
/**
* Represents an entire single selector, including all parts but not
* including multiple selectors (those separated by commas).
* @namespace parserlib.css
* @class Selector
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {Array} parts Array of selectors parts making up this selector.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function Selector(parts, line, col){
SyntaxUnit.call(this, parts.join(" "), line, col, Parser.SELECTOR_TYPE);
this.parts = parts;
this.specificity = Specificity.calculate(this);
}
Selector.prototype = new SyntaxUnit();
Selector.prototype.constructor = Selector;
/**
* Represents a single part of a selector string, meaning a single set of
* element name and modifiers. This does not include combinators such as
* spaces, +, >, etc.
* @namespace parserlib.css
* @class SelectorPart
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} elementName The element name in the selector or null
* if there is no element name.
* @param {Array} modifiers Array of individual modifiers for the element.
* May be empty if there are none.
* @param {String} text The text representation of the unit.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SelectorPart(elementName, modifiers, text, line, col){
SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_PART_TYPE);
this.elementName = elementName;
this.modifiers = modifiers;
}
SelectorPart.prototype = new SyntaxUnit();
SelectorPart.prototype.constructor = SelectorPart;
/**
* Represents a selector modifier string, meaning a class name, element name,
* element ID, pseudo rule, etc.
* @namespace parserlib.css
* @class SelectorSubPart
* @extends parserlib.util.SyntaxUnit
* @constructor
* @param {String} text The text representation of the unit.
* @param {String} type The type of selector modifier.
* @param {int} line The line of text on which the unit resides.
* @param {int} col The column of text on which the unit resides.
*/
function SelectorSubPart(text, type, line, col){
SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_SUB_PART_TYPE);
this.type = type;
this.args = [];
}
SelectorSubPart.prototype = new SyntaxUnit();
SelectorSubPart.prototype.constructor = SelectorSubPart;
/**
* Represents a selector's specificity.
* @namespace parserlib.css
* @class Specificity
* @constructor
* @param {int} a Should be 1 for inline styles, zero for stylesheet styles
* @param {int} b Number of ID selectors
* @param {int} c Number of classes and pseudo classes
* @param {int} d Number of element names and pseudo elements
*/
function Specificity(a, b, c, d){
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
Specificity.prototype = {
constructor: Specificity,
/**
* Compare this specificity to another.
* @param {Specificity} other The other specificity to compare to.
* @return {int} -1 if the other specificity is larger, 1 if smaller, 0 if equal.
* @method compare
*/
compare: function(other){
var comps = ["a", "b", "c", "d"],
i, len;
for (i=0, len=comps.length; i < len; i++){
if (this[comps[i]] < other[comps[i]]){
return -1;
} else if (this[comps[i]] > other[comps[i]]){
return 1;
}
}
return 0;
},
/**
* Creates a numeric value for the specificity.
* @return {int} The numeric value for the specificity.
* @method valueOf
*/
valueOf: function(){
return (this.a * 1000) + (this.b * 100) + (this.c * 10) + this.d;
},
/**
* Returns a string representation for specificity.
* @return {String} The string representation of specificity.
* @method toString
*/
toString: function(){
return this.a + "," + this.b + "," + this.c + "," + this.d;
}
};
Specificity.calculate = function(selector){
var i, len,
part,
b=0, c=0, d=0;
function updateValues(part){
var i, j, len, num,
elementName = part.elementName ? part.elementName.text : "",
modifier;
if (elementName && elementName.charAt(elementName.length-1) != "*") {
d++;
}
for (i=0, len=part.modifiers.length; i < len; i++){
modifier = part.modifiers[i];
switch(modifier.type){
case "class":
case "attribute":
c++;
break;
case "id":
b++;
break;
case "pseudo":
if (Pseudos.isElement(modifier.text)){
d++;
} else {
c++;
}
break;
case "not":
for (j=0, num=modifier.args.length; j < num; j++){
updateValues(modifier.args[j]);
}
}
}
}
for (i=0, len=selector.parts.length; i < len; i++){
part = selector.parts[i];
if (part instanceof SelectorPart){
updateValues(part);
}
}
return new Specificity(0, b, c, d);
};
var h = /^[0-9a-fA-F]$/,
nonascii = /^[\u0080-\uFFFF]$/,
nl = /\n|\r\n|\r|\f/;
//-----------------------------------------------------------------------------
// Helper functions
//-----------------------------------------------------------------------------
function isHexDigit(c){
return c !== null && h.test(c);
}
function isDigit(c){
return c !== null && /\d/.test(c);
}
function isWhitespace(c){
return c !== null && /\s/.test(c);
}
function isNewLine(c){
return c !== null && nl.test(c);
}
function isNameStart(c){
return c !== null && (/[a-z_\u0080-\uFFFF\\]/i.test(c));
}
function isNameChar(c){
return c !== null && (isNameStart(c) || /[0-9\-\\]/.test(c));
}
function isIdentStart(c){
return c !== null && (isNameStart(c) || /\-\\/.test(c));
}
function mix(receiver, supplier){
for (var prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return receiver;
}
//-----------------------------------------------------------------------------
// CSS Token Stream
//-----------------------------------------------------------------------------
/**
* A token stream that produces CSS tokens.
* @param {String|Reader} input The source of text to tokenize.
* @constructor
* @class TokenStream
* @namespace parserlib.css
*/
function TokenStream(input){
TokenStreamBase.call(this, input, Tokens);
}
TokenStream.prototype = mix(new TokenStreamBase(), {
/**
* Overrides the TokenStreamBase method of the same name
* to produce CSS tokens.
* @param {variant} channel The name of the channel to use
* for the next token.
* @return {Object} A token object representing the next token.
* @method _getToken
* @private
*/
_getToken: function(channel){
var c,
reader = this._reader,
token = null,
startLine = reader.getLine(),
startCol = reader.getCol();
c = reader.read();
while(c){
switch(c){
/*
* Potential tokens:
* - COMMENT
* - SLASH
* - CHAR
*/
case "/":
if(reader.peek() == "*"){
token = this.commentToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
case "|":
case "~":
case "^":
case "$":
case "*":
if(reader.peek() == "="){
token = this.comparisonToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
case "\"":
case "'":
token = this.stringToken(c, startLine, startCol);
break;
case "#":
if (isNameChar(reader.peek())){
token = this.hashToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
case ".":
if (isDigit(reader.peek())){
token = this.numberToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
case "-":
if (reader.peek() == "-"){ //could be closing HTML-style comment
token = this.htmlCommentEndToken(c, startLine, startCol);
} else if (isNameStart(reader.peek())){
token = this.identOrFunctionToken(c, startLine, startCol);
} else {
token = this.charToken(c, startLine, startCol);
}
break;
case "!":
token = this.importantToken(c, startLine, startCol);
break;
case "@":
token = this.atRuleToken(c, startLine, startCol);
break;
case ":":
token = this.notToken(c, startLine, startCol);
break;
case "<":
token = this.htmlCommentStartToken(c, startLine, startCol);
break;
case "U":
case "u":
if (reader.peek() == "+"){
token = this.unicodeRangeToken(c, startLine, startCol);
break;
}
/* falls through */
default:
/*
* Potential tokens:
* - NUMBER
* - DIMENSION
* - LENGTH
* - FREQ
* - TIME
* - EMS
* - EXS
* - ANGLE
*/
if (isDigit(c)){
token = this.numberToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - S
*/
if (isWhitespace(c)){
token = this.whitespaceToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - IDENT
*/
if (isIdentStart(c)){
token = this.identOrFunctionToken(c, startLine, startCol);
} else
/*
* Potential tokens:
* - CHAR
* - PLUS
*/
{
token = this.charToken(c, startLine, startCol);
}
}
//make sure this token is wanted
//TODO: check channel
break;
}
if (!token && c === null){
token = this.createToken(Tokens.EOF,null,startLine,startCol);
}
return token;
},
//-------------------------------------------------------------------------
// Methods to create tokens
//-------------------------------------------------------------------------
/**
* Produces a token based on available data and the current
* reader position information. This method is called by other
* private methods to create tokens and is never called directly.
* @param {int} tt The token type.
* @param {String} value The text value of the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @param {Object} options (Optional) Specifies a channel property
* to indicate that a different channel should be scanned
* and/or a hide property indicating that the token should
* be hidden.
* @return {Object} A token object.
* @method createToken
*/
createToken: function(tt, value, startLine, startCol, options){
var reader = this._reader;
options = options || {};
return {
value: value,
type: tt,
channel: options.channel,
hide: options.hide || false,
startLine: startLine,
startCol: startCol,
endLine: reader.getLine(),
endCol: reader.getCol()
};
},
//-------------------------------------------------------------------------
// Methods to create specific tokens
//-------------------------------------------------------------------------
/**
* Produces a token for any at-rule. If the at-rule is unknown, then
* the token is for a single "@" character.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method atRuleToken
*/
atRuleToken: function(first, startLine, startCol){
var rule = first,
reader = this._reader,
tt = Tokens.CHAR,
valid = false,
ident,
c;
reader.mark();
//try to find the at-keyword
ident = this.readName();
rule = first + ident;
tt = Tokens.type(rule.toLowerCase());
//if it's not valid, use the first character only and reset the reader
if (tt == Tokens.CHAR || tt == Tokens.UNKNOWN){
if (rule.length > 1){
tt = Tokens.UNKNOWN_SYM;
} else {
tt = Tokens.CHAR;
rule = first;
reader.reset();
}
}
return this.createToken(tt, rule, startLine, startCol);
},
/**
* Produces a character token based on the given character
* and location in the stream. If there's a special (non-standard)
* token name, this is used; otherwise CHAR is used.
* @param {String} c The character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method charToken
*/
charToken: function(c, startLine, startCol){
var tt = Tokens.type(c);
if (tt == -1){
tt = Tokens.CHAR;
}
return this.createToken(tt, c, startLine, startCol);
},
/**
* Produces a character token based on the given character
* and location in the stream. If there's a special (non-standard)
* token name, this is used; otherwise CHAR is used.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method commentToken
*/
commentToken: function(first, startLine, startCol){
var reader = this._reader,
comment = this.readComment(first);
return this.createToken(Tokens.COMMENT, comment, startLine, startCol);
},
/**
* Produces a comparison token based on the given character
* and location in the stream. The next character must be
* read and is already known to be an equals sign.
* @param {String} c The character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method comparisonToken
*/
comparisonToken: function(c, startLine, startCol){
var reader = this._reader,
comparison = c + reader.read(),
tt = Tokens.type(comparison) || Tokens.CHAR;
return this.createToken(tt, comparison, startLine, startCol);
},
/**
* Produces a hash token based on the specified information. The
* first character provided is the pound sign (#) and then this
* method reads a name afterward.
* @param {String} first The first character (#) in the hash name.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method hashToken
*/
hashToken: function(first, startLine, startCol){
var reader = this._reader,
name = this.readName(first);
return this.createToken(Tokens.HASH, name, startLine, startCol);
},
/**
* Produces a CDO or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method htmlCommentStartToken
*/
htmlCommentStartToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(3);
if (text == "<!--"){
return this.createToken(Tokens.CDO, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces a CDC or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method htmlCommentEndToken
*/
htmlCommentEndToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(2);
if (text == "-->"){
return this.createToken(Tokens.CDC, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces an IDENT or FUNCTION token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the identifier.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method identOrFunctionToken
*/
identOrFunctionToken: function(first, startLine, startCol){
var reader = this._reader,
ident = this.readName(first),
tt = Tokens.IDENT;
//if there's a left paren immediately after, it's a URI or function
if (reader.peek() == "("){
ident += reader.read();
if (ident.toLowerCase() == "url("){
tt = Tokens.URI;
ident = this.readURI(ident);
//didn't find a valid URL or there's no closing paren
if (ident.toLowerCase() == "url("){
tt = Tokens.FUNCTION;
}
} else {
tt = Tokens.FUNCTION;
}
} else if (reader.peek() == ":"){ //might be an IE function
//IE-specific functions always being with progid:
if (ident.toLowerCase() == "progid"){
ident += reader.readTo("(");
tt = Tokens.IE_FUNCTION;
}
}
return this.createToken(tt, ident, startLine, startCol);
},
/**
* Produces an IMPORTANT_SYM or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method importantToken
*/
importantToken: function(first, startLine, startCol){
var reader = this._reader,
important = first,
tt = Tokens.CHAR,
temp,
c;
reader.mark();
c = reader.read();
while(c){
//there can be a comment in here
if (c == "/"){
//if the next character isn't a star, then this isn't a valid !important token
if (reader.peek() != "*"){
break;
} else {
temp = this.readComment(c);
if (temp === ""){ //broken!
break;
}
}
} else if (isWhitespace(c)){
important += c + this.readWhitespace();
} else if (/i/i.test(c)){
temp = reader.readCount(8);
if (/mportant/i.test(temp)){
important += c + temp;
tt = Tokens.IMPORTANT_SYM;
}
break; //we're done
} else {
break;
}
c = reader.read();
}
if (tt == Tokens.CHAR){
reader.reset();
return this.charToken(first, startLine, startCol);
} else {
return this.createToken(tt, important, startLine, startCol);
}
},
/**
* Produces a NOT or CHAR token based on the specified information. The
* first character is provided and the rest is read by the function to determine
* the correct token to create.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method notToken
*/
notToken: function(first, startLine, startCol){
var reader = this._reader,
text = first;
reader.mark();
text += reader.readCount(4);
if (text.toLowerCase() == ":not("){
return this.createToken(Tokens.NOT, text, startLine, startCol);
} else {
reader.reset();
return this.charToken(first, startLine, startCol);
}
},
/**
* Produces a number token based on the given character
* and location in the stream. This may return a token of
* NUMBER, EMS, EXS, LENGTH, ANGLE, TIME, FREQ, DIMENSION,
* or PERCENTAGE.
* @param {String} first The first character for the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method numberToken
*/
numberToken: function(first, startLine, startCol){
var reader = this._reader,
value = this.readNumber(first),
ident,
tt = Tokens.NUMBER,
c = reader.peek();
if (isIdentStart(c)){
ident = this.readName(reader.read());
value += ident;
if (/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vm$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(ident)){
tt = Tokens.LENGTH;
} else if (/^deg|^rad$|^grad$/i.test(ident)){
tt = Tokens.ANGLE;
} else if (/^ms$|^s$/i.test(ident)){
tt = Tokens.TIME;
} else if (/^hz$|^khz$/i.test(ident)){
tt = Tokens.FREQ;
} else if (/^dpi$|^dpcm$/i.test(ident)){
tt = Tokens.RESOLUTION;
} else {
tt = Tokens.DIMENSION;
}
} else if (c == "%"){
value += reader.read();
tt = Tokens.PERCENTAGE;
}
return this.createToken(tt, value, startLine, startCol);
},
/**
* Produces a string token based on the given character
* and location in the stream. Since strings may be indicated
* by single or double quotes, a failure to match starting
* and ending quotes results in an INVALID token being generated.
* The first character in the string is passed in and then
* the rest are read up to and including the final quotation mark.
* @param {String} first The first character in the string.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method stringToken
*/
stringToken: function(first, startLine, startCol){
var delim = first,
string = first,
reader = this._reader,
prev = first,
tt = Tokens.STRING,
c = reader.read();
while(c){
string += c;
//if the delimiter is found with an escapement, we're done.
if (c == delim && prev != "\\"){
break;
}
//if there's a newline without an escapement, it's an invalid string
if (isNewLine(reader.peek()) && c != "\\"){
tt = Tokens.INVALID;
break;
}
//save previous and get next
prev = c;
c = reader.read();
}
//if c is null, that means we're out of input and the string was never closed
if (c === null){
tt = Tokens.INVALID;
}
return this.createToken(tt, string, startLine, startCol);
},
unicodeRangeToken: function(first, startLine, startCol){
var reader = this._reader,
value = first,
temp,
tt = Tokens.CHAR;
//then it should be a unicode range
if (reader.peek() == "+"){
reader.mark();
value += reader.read();
value += this.readUnicodeRangePart(true);
//ensure there's an actual unicode range here
if (value.length == 2){
reader.reset();
} else {
tt = Tokens.UNICODE_RANGE;
//if there's a ? in the first part, there can't be a second part
if (value.indexOf("?") == -1){
if (reader.peek() == "-"){
reader.mark();
temp = reader.read();
temp += this.readUnicodeRangePart(false);
//if there's not another value, back up and just take the first
if (temp.length == 1){
reader.reset();
} else {
value += temp;
}
}
}
}
}
return this.createToken(tt, value, startLine, startCol);
},
/**
* Produces a S token based on the specified information. Since whitespace
* may have multiple characters, this consumes all whitespace characters
* into a single token.
* @param {String} first The first character in the token.
* @param {int} startLine The beginning line for the character.
* @param {int} startCol The beginning column for the character.
* @return {Object} A token object.
* @method whitespaceToken
*/
whitespaceToken: function(first, startLine, startCol){
var reader = this._reader,
value = first + this.readWhitespace();
return this.createToken(Tokens.S, value, startLine, startCol);
},
//-------------------------------------------------------------------------
// Methods to read values from the string stream
//-------------------------------------------------------------------------
readUnicodeRangePart: function(allowQuestionMark){
var reader = this._reader,
part = "",
c = reader.peek();
//first read hex digits
while(isHexDigit(c) && part.length < 6){
reader.read();
part += c;
c = reader.peek();
}
//then read question marks if allowed
if (allowQuestionMark){
while(c == "?" && part.length < 6){
reader.read();
part += c;
c = reader.peek();
}
}
//there can't be any other characters after this point
return part;
},
readWhitespace: function(){
var reader = this._reader,
whitespace = "",
c = reader.peek();
while(isWhitespace(c)){
reader.read();
whitespace += c;
c = reader.peek();
}
return whitespace;
},
readNumber: function(first){
var reader = this._reader,
number = first,
hasDot = (first == "."),
c = reader.peek();
while(c){
if (isDigit(c)){
number += reader.read();
} else if (c == "."){
if (hasDot){
break;
} else {
hasDot = true;
number += reader.read();
}
} else {
break;
}
c = reader.peek();
}
return number;
},
readString: function(){
var reader = this._reader,
delim = reader.read(),
string = delim,
prev = delim,
c = reader.peek();
while(c){
c = reader.read();
string += c;
//if the delimiter is found with an escapement, we're done.
if (c == delim && prev != "\\"){
break;
}
//if there's a newline without an escapement, it's an invalid string
if (isNewLine(reader.peek()) && c != "\\"){
string = "";
break;
}
//save previous and get next
prev = c;
c = reader.peek();
}
//if c is null, that means we're out of input and the string was never closed
if (c === null){
string = "";
}
return string;
},
readURI: function(first){
var reader = this._reader,
uri = first,
inner = "",
c = reader.peek();
reader.mark();
//skip whitespace before
while(c && isWhitespace(c)){
reader.read();
c = reader.peek();
}
//it's a string
if (c == "'" || c == "\""){
inner = this.readString();
} else {
inner = this.readURL();
}
c = reader.peek();
//skip whitespace after
while(c && isWhitespace(c)){
reader.read();
c = reader.peek();
}
//if there was no inner value or the next character isn't closing paren, it's not a URI
if (inner === "" || c != ")"){
uri = first;
reader.reset();
} else {
uri += inner + reader.read();
}
return uri;
},
readURL: function(){
var reader = this._reader,
url = "",
c = reader.peek();
//TODO: Check for escape and nonascii
while (/^[!#$%&\\*-~]$/.test(c)){
url += reader.read();
c = reader.peek();
}
return url;
},
readName: function(first){
var reader = this._reader,
ident = first || "",
c = reader.peek();
while(true){
if (c == "\\"){
ident += this.readEscape(reader.read());
c = reader.peek();
} else if(c && isNameChar(c)){
ident += reader.read();
c = reader.peek();
} else {
break;
}
}
return ident;
},
readEscape: function(first){
var reader = this._reader,
cssEscape = first || "",
i = 0,
c = reader.peek();
if (isHexDigit(c)){
do {
cssEscape += reader.read();
c = reader.peek();
} while(c && isHexDigit(c) && ++i < 6);
}
if (cssEscape.length == 3 && /\s/.test(c) ||
cssEscape.length == 7 || cssEscape.length == 1){
reader.read();
} else {
c = "";
}
return cssEscape + c;
},
readComment: function(first){
var reader = this._reader,
comment = first || "",
c = reader.read();
if (c == "*"){
while(c){
comment += c;
//look for end of comment
if (comment.length > 2 && c == "*" && reader.peek() == "/"){
comment += reader.read();
break;
}
c = reader.read();
}
return comment;
} else {
return "";
}
}
});
var Tokens = [
/*
* The following token names are defined in CSS3 Grammar: http://www.w3.org/TR/css3-syntax/#lexical
*/
//HTML-style comments
{ name: "CDO"},
{ name: "CDC"},
//ignorables
{ name: "S", whitespace: true/*, channel: "ws"*/},
{ name: "COMMENT", comment: true, hide: true, channel: "comment" },
//attribute equality
{ name: "INCLUDES", text: "~="},
{ name: "DASHMATCH", text: "|="},
{ name: "PREFIXMATCH", text: "^="},
{ name: "SUFFIXMATCH", text: "$="},
{ name: "SUBSTRINGMATCH", text: "*="},
//identifier types
{ name: "STRING"},
{ name: "IDENT"},
{ name: "HASH"},
//at-keywords
{ name: "IMPORT_SYM", text: "@import"},
{ name: "PAGE_SYM", text: "@page"},
{ name: "MEDIA_SYM", text: "@media"},
{ name: "FONT_FACE_SYM", text: "@font-face"},
{ name: "CHARSET_SYM", text: "@charset"},
{ name: "NAMESPACE_SYM", text: "@namespace"},
{ name: "UNKNOWN_SYM" },
//{ name: "ATKEYWORD"},
//CSS3 animations
{ name: "KEYFRAMES_SYM", text: [ "@keyframes", "@-webkit-keyframes", "@-moz-keyframes", "@-ms-keyframes" ] },
//important symbol
{ name: "IMPORTANT_SYM"},
//measurements
{ name: "LENGTH"},
{ name: "ANGLE"},
{ name: "TIME"},
{ name: "FREQ"},
{ name: "DIMENSION"},
{ name: "PERCENTAGE"},
{ name: "NUMBER"},
//functions
{ name: "URI"},
{ name: "FUNCTION"},
//Unicode ranges
{ name: "UNICODE_RANGE"},
/*
* The following token names are defined in CSS3 Selectors: http://www.w3.org/TR/css3-selectors/#selector-syntax
*/
//invalid string
{ name: "INVALID"},
//combinators
{ name: "PLUS", text: "+" },
{ name: "GREATER", text: ">"},
{ name: "COMMA", text: ","},
{ name: "TILDE", text: "~"},
//modifier
{ name: "NOT"},
/*
* Defined in CSS3 Paged Media
*/
{ name: "TOPLEFTCORNER_SYM", text: "@top-left-corner"},
{ name: "TOPLEFT_SYM", text: "@top-left"},
{ name: "TOPCENTER_SYM", text: "@top-center"},
{ name: "TOPRIGHT_SYM", text: "@top-right"},
{ name: "TOPRIGHTCORNER_SYM", text: "@top-right-corner"},
{ name: "BOTTOMLEFTCORNER_SYM", text: "@bottom-left-corner"},
{ name: "BOTTOMLEFT_SYM", text: "@bottom-left"},
{ name: "BOTTOMCENTER_SYM", text: "@bottom-center"},
{ name: "BOTTOMRIGHT_SYM", text: "@bottom-right"},
{ name: "BOTTOMRIGHTCORNER_SYM", text: "@bottom-right-corner"},
{ name: "LEFTTOP_SYM", text: "@left-top"},
{ name: "LEFTMIDDLE_SYM", text: "@left-middle"},
{ name: "LEFTBOTTOM_SYM", text: "@left-bottom"},
{ name: "RIGHTTOP_SYM", text: "@right-top"},
{ name: "RIGHTMIDDLE_SYM", text: "@right-middle"},
{ name: "RIGHTBOTTOM_SYM", text: "@right-bottom"},
/*
* The following token names are defined in CSS3 Media Queries: http://www.w3.org/TR/css3-mediaqueries/#syntax
*/
/*{ name: "MEDIA_ONLY", state: "media"},
{ name: "MEDIA_NOT", state: "media"},
{ name: "MEDIA_AND", state: "media"},*/
{ name: "RESOLUTION", state: "media"},
/*
* The following token names are not defined in any CSS specification but are used by the lexer.
*/
//not a real token, but useful for stupid IE filters
{ name: "IE_FUNCTION" },
//part of CSS3 grammar but not the Flex code
{ name: "CHAR" },
//TODO: Needed?
//Not defined as tokens, but might as well be
{
name: "PIPE",
text: "|"
},
{
name: "SLASH",
text: "/"
},
{
name: "MINUS",
text: "-"
},
{
name: "STAR",
text: "*"
},
{
name: "LBRACE",
text: "{"
},
{
name: "RBRACE",
text: "}"
},
{
name: "LBRACKET",
text: "["
},
{
name: "RBRACKET",
text: "]"
},
{
name: "EQUALS",
text: "="
},
{
name: "COLON",
text: ":"
},
{
name: "SEMICOLON",
text: ";"
},
{
name: "LPAREN",
text: "("
},
{
name: "RPAREN",
text: ")"
},
{
name: "DOT",
text: "."
}
];
(function(){
var nameMap = [],
typeMap = {};
Tokens.UNKNOWN = -1;
Tokens.unshift({name:"EOF"});
for (var i=0, len = Tokens.length; i < len; i++){
nameMap.push(Tokens[i].name);
Tokens[Tokens[i].name] = i;
if (Tokens[i].text){
if (Tokens[i].text instanceof Array){
for (var j=0; j < Tokens[i].text.length; j++){
typeMap[Tokens[i].text[j]] = i;
}
} else {
typeMap[Tokens[i].text] = i;
}
}
}
Tokens.name = function(tt){
return nameMap[tt];
};
Tokens.type = function(c){
return typeMap[c] || -1;
};
})();
//This file will likely change a lot! Very experimental!
/*global Properties, ValidationTypes, ValidationError, PropertyValueIterator */
var Validation = {
validate: function(property, value){
//normalize name
var name = property.toString().toLowerCase(),
parts = value.parts,
expression = new PropertyValueIterator(value),
spec = Properties[name],
part,
valid,
j, count,
msg,
types,
last,
literals,
max, multi, group;
if (!spec) {
if (name.indexOf("-") !== 0){ //vendor prefixed are ok
throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col);
}
} else if (typeof spec != "number"){
//initialization
if (typeof spec == "string"){
if (spec.indexOf("||") > -1) {
this.groupProperty(spec, expression);
} else {
this.singleProperty(spec, expression, 1);
}
} else if (spec.multi) {
this.multiProperty(spec.multi, expression, spec.comma, spec.max || Infinity);
} else if (typeof spec == "function") {
spec(expression);
}
}
},
singleProperty: function(types, expression, max, partial) {
var result = false,
value = expression.value,
count = 0,
part;
while (expression.hasNext() && count < max) {
result = ValidationTypes.isAny(expression, types);
if (!result) {
break;
}
count++;
}
if (!result) {
if (expression.hasNext() && !expression.isFirst()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
},
multiProperty: function (types, expression, comma, max) {
var result = false,
value = expression.value,
count = 0,
sep = false,
part;
while(expression.hasNext() && !result && count < max) {
if (ValidationTypes.isAny(expression, types)) {
count++;
if (!expression.hasNext()) {
result = true;
} else if (comma) {
if (expression.peek() == ",") {
part = expression.next();
} else {
break;
}
}
} else {
break;
}
}
if (!result) {
if (expression.hasNext() && !expression.isFirst()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
part = expression.previous();
if (comma && part == ",") {
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
},
groupProperty: function (types, expression, comma) {
var result = false,
value = expression.value,
typeCount = types.split("||").length,
groups = { count: 0 },
partial = false,
name,
part;
while(expression.hasNext() && !result) {
name = ValidationTypes.isAnyOfGroup(expression, types);
if (name) {
//no dupes
if (groups[name]) {
break;
} else {
groups[name] = 1;
groups.count++;
partial = true;
if (groups.count == typeCount || !expression.hasNext()) {
result = true;
}
}
} else {
break;
}
}
if (!result) {
if (partial && expression.hasNext()) {
part = expression.peek();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
} else {
throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
}
} else if (expression.hasNext()) {
part = expression.next();
throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
}
}
};
function ValidationError(message, line, col){
/**
* The column at which the error occurred.
* @type int
* @property col
*/
this.col = col;
this.line = line;
this.message = message;
}
//inherit from Error
ValidationError.prototype = new Error();
//This file will likely change a lot! Very experimental!
/*global Properties, Validation, ValidationError, PropertyValueIterator, console*/
var ValidationTypes = {
isLiteral: function (part, literals) {
var text = part.text.toString().toLowerCase(),
args = literals.split(" | "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found; i++){
if (text == args[i]){
found = true;
}
}
return found;
},
isSimple: function(type) {
return !!this.simple[type];
},
isComplex: function(type) {
return !!this.complex[type];
},
/**
* Determines if the next part(s) of the given expression
* are any of the given types.
*/
isAny: function (expression, types) {
var args = types.split(" | "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found && expression.hasNext(); i++){
found = this.isType(expression, args[i]);
}
return found;
},
/**
* Determines if the next part(s) of the given expresion
* are one of a group.
*/
isAnyOfGroup: function(expression, types) {
var args = types.split(" || "),
i, len, found = false;
for (i=0,len=args.length; i < len && !found; i++){
found = this.isType(expression, args[i]);
}
return found ? args[i-1] : false;
},
/**
* Determines if the next part(s) of the given expression
* are of a given type.
*/
isType: function (expression, type) {
var part = expression.peek(),
result = false;
if (type.charAt(0) != "<") {
result = this.isLiteral(part, type);
if (result) {
expression.next();
}
} else if (this.simple[type]) {
result = this.simple[type](part);
if (result) {
expression.next();
}
} else {
result = this.complex[type](expression);
}
return result;
},
simple: {
"<absolute-size>": function(part){
return ValidationTypes.isLiteral(part, "xx-small | x-small | small | medium | large | x-large | xx-large");
},
"<attachment>": function(part){
return ValidationTypes.isLiteral(part, "scroll | fixed | local");
},
"<attr>": function(part){
return part.type == "function" && part.name == "attr";
},
"<bg-image>": function(part){
return this["<image>"](part) || this["<gradient>"](part) || part == "none";
},
"<gradient>": function(part) {
return part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial|linear)\-gradient/i.test(part);
},
"<box>": function(part){
return ValidationTypes.isLiteral(part, "padding-box | border-box | content-box");
},
"<content>": function(part){
return part.type == "function" && part.name == "content";
},
"<relative-size>": function(part){
return ValidationTypes.isLiteral(part, "smaller | larger");
},
//any identifier
"<ident>": function(part){
return part.type == "identifier";
},
"<length>": function(part){
return part.type == "length" || part.type == "number" || part.type == "integer" || part == "0";
},
"<color>": function(part){
return part.type == "color" || part == "transparent";
},
"<number>": function(part){
return part.type == "number" || this["<integer>"](part);
},
"<integer>": function(part){
return part.type == "integer";
},
"<line>": function(part){
return part.type == "integer";
},
"<angle>": function(part){
return part.type == "angle";
},
"<uri>": function(part){
return part.type == "uri";
},
"<image>": function(part){
return this["<uri>"](part);
},
"<percentage>": function(part){
return part.type == "percentage" || part == "0";
},
"<border-width>": function(part){
return this["<length>"](part) || ValidationTypes.isLiteral(part, "thin | medium | thick");
},
"<border-style>": function(part){
return ValidationTypes.isLiteral(part, "none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset");
},
"<margin-width>": function(part){
return this["<length>"](part) || this["<percentage>"](part) || ValidationTypes.isLiteral(part, "auto");
},
"<padding-width>": function(part){
return this["<length>"](part) || this["<percentage>"](part);
},
"<shape>": function(part){
return part.type == "function" && (part.name == "rect" || part.name == "inset-rect");
},
"<time>": function(part) {
return part.type == "time";
}
},
complex: {
"<bg-position>": function(expression){
var types = this,
result = false,
numeric = "<percentage> | <length>",
xDir = "left | center | right",
yDir = "top | center | bottom",
part,
i, len;
if (ValidationTypes.isAny(expression, "top | bottom")) {
result = true;
} else {
//must be two-part
if (ValidationTypes.isAny(expression, numeric)){
if (expression.hasNext()){
result = ValidationTypes.isAny(expression, numeric + " | " + yDir);
}
} else if (ValidationTypes.isAny(expression, xDir)){
if (expression.hasNext()){
//two- or three-part
if (ValidationTypes.isAny(expression, yDir)){
result = true;
ValidationTypes.isAny(expression, numeric);
} else if (ValidationTypes.isAny(expression, numeric)){
//could also be two-part, so check the next part
if (ValidationTypes.isAny(expression, yDir)){
ValidationTypes.isAny(expression, numeric);
}
result = true;
}
}
}
}
return result;
},
"<bg-size>": function(expression){
//<bg-size> = [ <length> | <percentage> | auto ]{1,2} | cover | contain
var types = this,
result = false,
numeric = "<percentage> | <length> | auto",
part,
i, len;
if (ValidationTypes.isAny(expression, "cover | contain")) {
result = true;
} else if (ValidationTypes.isAny(expression, numeric)) {
result = true;
ValidationTypes.isAny(expression, numeric);
}
return result;
},
"<repeat-style>": function(expression){
//repeat-x | repeat-y | [repeat | space | round | no-repeat]{1,2}
var result = false,
values = "repeat | space | round | no-repeat",
part;
if (expression.hasNext()){
part = expression.next();
if (ValidationTypes.isLiteral(part, "repeat-x | repeat-y")) {
result = true;
} else if (ValidationTypes.isLiteral(part, values)) {
result = true;
if (expression.hasNext() && ValidationTypes.isLiteral(expression.peek(), values)) {
expression.next();
}
}
}
return result;
},
"<shadow>": function(expression) {
//inset? && [ <length>{2,4} && <color>? ]
var result = false,
count = 0,
inset = false,
color = false,
part;
if (expression.hasNext()) {
if (ValidationTypes.isAny(expression, "inset")){
inset = true;
}
if (ValidationTypes.isAny(expression, "<color>")) {
color = true;
}
while (ValidationTypes.isAny(expression, "<length>") && count < 4) {
count++;
}
if (expression.hasNext()) {
if (!color) {
ValidationTypes.isAny(expression, "<color>");
}
if (!inset) {
ValidationTypes.isAny(expression, "inset");
}
}
result = (count >= 2 && count <= 4);
}
return result;
},
"<x-one-radius>": function(expression) {
//[ <length> | <percentage> ] [ <length> | <percentage> ]?
var result = false,
count = 0,
numeric = "<length> | <percentage>",
part;
if (ValidationTypes.isAny(expression, numeric)){
result = true;
ValidationTypes.isAny(expression, numeric);
}
return result;
}
}
};
parserlib.css = {
Colors :Colors,
Combinator :Combinator,
Parser :Parser,
PropertyName :PropertyName,
PropertyValue :PropertyValue,
PropertyValuePart :PropertyValuePart,
MediaFeature :MediaFeature,
MediaQuery :MediaQuery,
Selector :Selector,
SelectorPart :SelectorPart,
SelectorSubPart :SelectorSubPart,
Specificity :Specificity,
TokenStream :TokenStream,
Tokens :Tokens,
ValidationError :ValidationError
};
})();
/*global parserlib, Reporter*/
var CSSLint = (function(){
var rules = [],
formatters = [],
api = new parserlib.util.EventTarget();
api.version = "0.9.7";
//-------------------------------------------------------------------------
// Rule Management
//-------------------------------------------------------------------------
/**
* Adds a new rule to the engine.
* @param {Object} rule The rule to add.
* @method addRule
*/
api.addRule = function(rule){
rules.push(rule);
rules[rule.id] = rule;
};
api.clearRules = function(){
rules = [];
};
api.getRules = function(){
return [].concat(rules).sort(function(a,b){
return a.id > b.id ? 1 : 0;
});
};
//-------------------------------------------------------------------------
// Formatters
//-------------------------------------------------------------------------
/**
* Adds a new formatter to the engine.
* @param {Object} formatter The formatter to add.
* @method addFormatter
*/
api.addFormatter = function(formatter) {
// formatters.push(formatter);
formatters[formatter.id] = formatter;
};
api.getFormatter = function(formatId){
return formatters[formatId];
};
api.format = function(results, filename, formatId, options) {
var formatter = this.getFormatter(formatId),
result = null;
if (formatter){
result = formatter.startFormat();
result += formatter.formatResults(results, filename, options || {});
result += formatter.endFormat();
}
return result;
};
api.hasFormat = function(formatId){
return formatters.hasOwnProperty(formatId);
};
//-------------------------------------------------------------------------
// Verification
//-------------------------------------------------------------------------
/**
* Starts the verification process for the given CSS text.
* @param {String} text The CSS text to verify.
* @param {Object} ruleset (Optional) List of rules to apply. If null, then
* all rules are used. If a rule has a value of 1 then it's a warning,
* a value of 2 means it's an error.
* @return {Object} Results of the verification.
* @method verify
*/
api.verify = function(text, ruleset){
var i = 0,
len = rules.length,
reporter,
lines,
report,
parser = new parserlib.css.Parser({ starHack: true, ieFilters: true,
underscoreHack: true, strict: false });
lines = text.replace(/\n\r?/g, "$split$").split('$split$');
if (!ruleset){
ruleset = {};
while (i < len){
ruleset[rules[i++].id] = 1; //by default, everything is a warning
}
}
reporter = new Reporter(lines, ruleset);
ruleset.errors = 2; //always report parsing errors as errors
for (i in ruleset){
if(ruleset.hasOwnProperty(i)){
if (rules[i]){
rules[i].init(parser, reporter);
}
}
}
//capture most horrible error type
try {
parser.parse(text);
} catch (ex) {
reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {});
}
report = {
messages : reporter.messages,
stats : reporter.stats
};
//sort by line numbers, rollups at the bottom
report.messages.sort(function (a, b){
if (a.rollup && !b.rollup){
return 1;
} else if (!a.rollup && b.rollup){
return -1;
} else {
return a.line - b.line;
}
});
return report;
};
//-------------------------------------------------------------------------
// Publish the API
//-------------------------------------------------------------------------
return api;
})();
/**
* An instance of Report is used to report results of the
* verification back to the main API.
* @class Reporter
* @constructor
* @param {String[]} lines The text lines of the source.
* @param {Object} ruleset The set of rules to work with, including if
* they are errors or warnings.
*/
function Reporter(lines, ruleset){
/**
* List of messages being reported.
* @property messages
* @type String[]
*/
this.messages = [];
this.stats = [];
this.lines = lines;
this.ruleset = ruleset;
}
Reporter.prototype = {
//restore constructor
constructor: Reporter,
/**
* Report an error.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method error
*/
error: function(message, line, col, rule){
this.messages.push({
type : "error",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule || {}
});
},
/**
* Report an warning.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method warn
* @deprecated Use report instead.
*/
warn: function(message, line, col, rule){
this.report(message, line, col, rule);
},
/**
* Report an issue.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method report
*/
report: function(message, line, col, rule){
this.messages.push({
type : this.ruleset[rule.id] == 2 ? "error" : "warning",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some informational text.
* @param {String} message The message to store.
* @param {int} line The line number.
* @param {int} col The column number.
* @param {Object} rule The rule this message relates to.
* @method info
*/
info: function(message, line, col, rule){
this.messages.push({
type : "info",
line : line,
col : col,
message : message,
evidence: this.lines[line-1],
rule : rule
});
},
/**
* Report some rollup error information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupError
*/
rollupError: function(message, rule){
this.messages.push({
type : "error",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report some rollup warning information.
* @param {String} message The message to store.
* @param {Object} rule The rule this message relates to.
* @method rollupWarn
*/
rollupWarn: function(message, rule){
this.messages.push({
type : "warning",
rollup : true,
message : message,
rule : rule
});
},
/**
* Report a statistic.
* @param {String} name The name of the stat to store.
* @param {Variant} value The value of the stat.
* @method stat
*/
stat: function(name, value){
this.stats[name] = value;
}
};
//expose for testing purposes
CSSLint._Reporter = Reporter;
/*
* Utility functions that make life easier.
*/
CSSLint.Util = {
/*
* Adds all properties from supplier onto receiver,
* overwriting if the same name already exists on
* reciever.
* @param {Object} The object to receive the properties.
* @param {Object} The object to provide the properties.
* @return {Object} The receiver
*/
mix: function(receiver, supplier){
var prop;
for (prop in supplier){
if (supplier.hasOwnProperty(prop)){
receiver[prop] = supplier[prop];
}
}
return prop;
},
/*
* Polyfill for array indexOf() method.
* @param {Array} values The array to search.
* @param {Variant} value The value to search for.
* @return {int} The index of the value if found, -1 if not.
*/
indexOf: function(values, value){
if (values.indexOf){
return values.indexOf(value);
} else {
for (var i=0, len=values.length; i < len; i++){
if (values[i] === value){
return i;
}
}
return -1;
}
},
/*
* Polyfill for array forEach() method.
* @param {Array} values The array to operate on.
* @param {Function} func The function to call on each item.
* @return {void}
*/
forEach: function(values, func) {
if (values.forEach){
return values.forEach(func);
} else {
for (var i=0, len=values.length; i < len; i++){
func(values[i], i, values);
}
}
}
};
/*
* Rule: Don't use adjoining classes (.foo.bar).
*/
CSSLint.addRule({
//rule information
id: "adjoining-classes",
name: "Disallow adjoining classes",
desc: "Don't use adjoining classes.",
browsers: "IE6",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
classCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
classCount = 0;
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "class"){
classCount++;
}
if (classCount > 1){
reporter.report("Don't use adjoining classes.", part.line, part.col, rule);
}
}
}
}
}
});
}
});
/*
* Rule: Don't use width or height when using padding or border.
*/
CSSLint.addRule({
//rule information
id: "box-model",
name: "Beware of broken box size",
desc: "Don't use width or height when using padding or border.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
widthProperties = {
border: 1,
"border-left": 1,
"border-right": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1
},
heightProperties = {
border: 1,
"border-bottom": 1,
"border-top": 1,
padding: 1,
"padding-bottom": 1,
"padding-top": 1
},
properties;
function startRule(){
properties = {};
}
function endRule(){
var prop;
if (properties.height){
for (prop in heightProperties){
if (heightProperties.hasOwnProperty(prop) && properties[prop]){
//special case for padding
if (!(prop == "padding" && properties[prop].value.parts.length === 2 && properties[prop].value.parts[0].value === 0)){
reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
if (properties.width){
for (prop in widthProperties){
if (widthProperties.hasOwnProperty(prop) && properties[prop]){
if (!(prop == "padding" && properties[prop].value.parts.length === 2 && properties[prop].value.parts[1].value === 0)){
reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
}
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (heightProperties[name] || widthProperties[name]){
if (!/^0\S*$/.test(event.value) && !(name == "border" && event.value == "none")){
properties[name] = { line: event.property.line, col: event.property.col, value: event.value };
}
} else {
if (name == "width" || name == "height"){
properties[name] = 1;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*
* Rule: box-sizing doesn't work in IE6 and IE7.
*/
CSSLint.addRule({
//rule information
id: "box-sizing",
name: "Disallow use of box-sizing",
desc: "The box-sizing properties isn't supported in IE6 and IE7.",
browsers: "IE6, IE7",
tags: ["Compatibility"],
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (name == "box-sizing"){
reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "compatible-vendor-prefixes",
name: "Require compatible vendor prefixes",
desc: "Include all compatible vendor prefixes to reach a wider range of users.",
browsers: "All",
//initialization
init: function (parser, reporter) {
var rule = this,
compatiblePrefixes,
properties,
prop,
variations,
prefixed,
i,
len,
arrayPush = Array.prototype.push,
applyTo = [];
// See http://peter.sh/experiments/vendor-prefixed-css-property-overview/ for details
compatiblePrefixes = {
"animation" : "webkit moz ms",
"animation-delay" : "webkit moz ms",
"animation-direction" : "webkit moz ms",
"animation-duration" : "webkit moz ms",
"animation-fill-mode" : "webkit moz ms",
"animation-iteration-count" : "webkit moz ms",
"animation-name" : "webkit moz ms",
"animation-play-state" : "webkit moz ms",
"animation-timing-function" : "webkit moz ms",
"appearance" : "webkit moz",
"border-end" : "webkit moz",
"border-end-color" : "webkit moz",
"border-end-style" : "webkit moz",
"border-end-width" : "webkit moz",
"border-image" : "webkit moz o",
"border-radius" : "webkit moz",
"border-start" : "webkit moz",
"border-start-color" : "webkit moz",
"border-start-style" : "webkit moz",
"border-start-width" : "webkit moz",
"box-align" : "webkit moz ms",
"box-direction" : "webkit moz ms",
"box-flex" : "webkit moz ms",
"box-lines" : "webkit ms",
"box-ordinal-group" : "webkit moz ms",
"box-orient" : "webkit moz ms",
"box-pack" : "webkit moz ms",
"box-sizing" : "webkit moz",
"box-shadow" : "webkit moz",
"column-count" : "webkit moz ms",
"column-gap" : "webkit moz ms",
"column-rule" : "webkit moz ms",
"column-rule-color" : "webkit moz ms",
"column-rule-style" : "webkit moz ms",
"column-rule-width" : "webkit moz ms",
"column-width" : "webkit moz ms",
"hyphens" : "epub moz",
"line-break" : "webkit ms",
"margin-end" : "webkit moz",
"margin-start" : "webkit moz",
"marquee-speed" : "webkit wap",
"marquee-style" : "webkit wap",
"padding-end" : "webkit moz",
"padding-start" : "webkit moz",
"tab-size" : "moz o",
"text-size-adjust" : "webkit ms",
"transform" : "webkit moz ms o",
"transform-origin" : "webkit moz ms o",
"transition" : "webkit moz o ms",
"transition-delay" : "webkit moz o ms",
"transition-duration" : "webkit moz o ms",
"transition-property" : "webkit moz o ms",
"transition-timing-function" : "webkit moz o ms",
"user-modify" : "webkit moz",
"user-select" : "webkit moz ms",
"word-break" : "epub ms",
"writing-mode" : "epub ms"
};
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = [];
prefixed = compatiblePrefixes[prop].split(' ');
for (i = 0, len = prefixed.length; i < len; i++) {
variations.push('-' + prefixed[i] + '-' + prop);
}
compatiblePrefixes[prop] = variations;
arrayPush.apply(applyTo, variations);
}
}
parser.addListener("startrule", function () {
properties = [];
});
parser.addListener("property", function (event) {
var name = event.property;
if (CSSLint.Util.indexOf(applyTo, name.text) > -1) {
properties.push(name);
}
});
parser.addListener("endrule", function (event) {
if (!properties.length) {
return;
}
var propertyGroups = {},
i,
len,
name,
prop,
variations,
value,
full,
actual,
item,
propertiesSpecified;
for (i = 0, len = properties.length; i < len; i++) {
name = properties[i];
for (prop in compatiblePrefixes) {
if (compatiblePrefixes.hasOwnProperty(prop)) {
variations = compatiblePrefixes[prop];
if (CSSLint.Util.indexOf(variations, name.text) > -1) {
if (!propertyGroups[prop]) {
propertyGroups[prop] = {
full : variations.slice(0),
actual : [],
actualNodes: []
};
}
if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) {
propertyGroups[prop].actual.push(name.text);
propertyGroups[prop].actualNodes.push(name);
}
}
}
}
}
for (prop in propertyGroups) {
if (propertyGroups.hasOwnProperty(prop)) {
value = propertyGroups[prop];
full = value.full;
actual = value.actual;
if (full.length > actual.length) {
for (i = 0, len = full.length; i < len; i++) {
item = full[i];
if (CSSLint.Util.indexOf(actual, item) === -1) {
propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length == 2) ? actual.join(" and ") : actual.join(", ");
reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule);
}
}
}
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "display-property-grouping",
name: "Require properties appropriate for display",
desc: "Certain properties shouldn't be used with certain display property values.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var propertiesToCheck = {
display: 1,
"float": "none",
height: 1,
width: 1,
margin: 1,
"margin-left": 1,
"margin-right": 1,
"margin-bottom": 1,
"margin-top": 1,
padding: 1,
"padding-left": 1,
"padding-right": 1,
"padding-bottom": 1,
"padding-top": 1,
"vertical-align": 1
},
properties;
function reportProperty(name, display, msg){
if (properties[name]){
if (typeof propertiesToCheck[name] != "string" || properties[name].value.toLowerCase() != propertiesToCheck[name]){
reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule);
}
}
}
function startRule(){
properties = {};
}
function endRule(){
var display = properties.display ? properties.display.value : null;
if (display){
switch(display){
case "inline":
//height, width, margin-top, margin-bottom, float should not be used with inline
reportProperty("height", display);
reportProperty("width", display);
reportProperty("margin", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");
break;
case "block":
//vertical-align should not be used with block
reportProperty("vertical-align", display);
break;
case "inline-block":
//float should not be used with inline-block
reportProperty("float", display);
break;
default:
//margin, float should not be used with table
if (display.indexOf("table-") === 0){
reportProperty("margin", display);
reportProperty("margin-left", display);
reportProperty("margin-right", display);
reportProperty("margin-top", display);
reportProperty("margin-bottom", display);
reportProperty("float", display);
}
//otherwise do nothing
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startpage", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (propertiesToCheck[name]){
properties[name] = { value: event.value.text, line: event.property.line, col: event.property.col };
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endkeyframerule", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endpage", endRule);
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "duplicate-background-images",
name: "Disallow duplicate background images",
desc: "Every background-image should be unique. Use a common class for e.g. sprites.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
stack = {};
parser.addListener("property", function(event){
var name = event.property.text,
value = event.value,
i, len;
if (name.match(/background/i)) {
for (i=0, len=value.parts.length; i < len; i++) {
if (value.parts[i].type == 'uri') {
if (typeof stack[value.parts[i].uri] === 'undefined') {
stack[value.parts[i].uri] = event;
}
else {
reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule);
}
}
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "duplicate-properties",
name: "Disallow duplicate properties",
desc: "Duplicate properties must appear one after the other.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
properties,
lastProperty;
function startRule(event){
properties = {};
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase();
if (properties[name] && (lastProperty != name || properties[name] == event.value.text)){
reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule);
}
properties[name] = event.value.text;
lastProperty = name;
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "empty-rules",
name: "Disallow empty rules",
desc: "Rules without any properties specified should be removed.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
parser.addListener("startrule", function(){
count=0;
});
parser.addListener("property", function(){
count++;
});
parser.addListener("endrule", function(event){
var selectors = event.selectors;
if (count === 0){
reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "errors",
name: "Parsing Errors",
desc: "This rule looks for recoverable syntax errors.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("error", function(event){
reporter.error(event.message, event.line, event.col, rule);
});
}
});
CSSLint.addRule({
//rule information
id: "fallback-colors",
name: "Require fallback colors",
desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",
browsers: "IE6,IE7,IE8",
//initialization
init: function(parser, reporter){
var rule = this,
lastProperty,
propertiesToCheck = {
color: 1,
background: 1,
"background-color": 1
},
properties;
function startRule(event){
properties = {};
lastProperty = null;
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var property = event.property,
name = property.text.toLowerCase(),
parts = event.value.parts,
i = 0,
colorType = "",
len = parts.length;
if(propertiesToCheck[name]){
while(i < len){
if (parts[i].type == "color"){
if ("alpha" in parts[i] || "hue" in parts[i]){
if (/([^\)]+)\(/.test(parts[i])){
colorType = RegExp.$1.toUpperCase();
}
if (!lastProperty || (lastProperty.property.text.toLowerCase() != name || lastProperty.colorType != "compat")){
reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule);
}
} else {
event.colorType = "compat";
}
}
i++;
}
}
lastProperty = event;
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "floats",
name: "Disallow too many floats",
desc: "This rule tests if the float property is used too many times",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var count = 0;
//count how many times "float" is used
parser.addListener("property", function(event){
if (event.property.text.toLowerCase() == "float" &&
event.value.text.toLowerCase() != "none"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("floats", count);
if (count >= 10){
reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "font-faces",
name: "Don't use too many web fonts",
desc: "Too many different web fonts in the same stylesheet.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
parser.addListener("startfontface", function(){
count++;
});
parser.addListener("endstylesheet", function(){
if (count > 5){
reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "font-sizes",
name: "Disallow too many font sizes",
desc: "Checks the number of font-size declarations.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//check for use of "font-size"
parser.addListener("property", function(event){
if (event.property == "font-size"){
count++;
}
});
//report the results
parser.addListener("endstylesheet", function(){
reporter.stat("font-sizes", count);
if (count >= 10){
reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "gradients",
name: "Require all gradient definitions",
desc: "When using a vendor-prefixed gradient, make sure to use them all.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
gradients;
parser.addListener("startrule", function(){
gradients = {
moz: 0,
webkit: 0,
oldWebkit: 0,
ms: 0,
o: 0
};
});
parser.addListener("property", function(event){
if (/\-(moz|ms|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)){
gradients[RegExp.$1] = 1;
} else if (/\-webkit\-gradient/i.test(event.value)){
gradients.oldWebkit = 1;
}
});
parser.addListener("endrule", function(event){
var missing = [];
if (!gradients.moz){
missing.push("Firefox 3.6+");
}
if (!gradients.webkit){
missing.push("Webkit (Safari 5+, Chrome)");
}
if (!gradients.oldWebkit){
missing.push("Old Webkit (Safari 4+, Chrome)");
}
if (!gradients.ms){
missing.push("Internet Explorer 10+");
}
if (!gradients.o){
missing.push("Opera 11.1+");
}
if (missing.length && missing.length < 5){
reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "ids",
name: "Disallow IDs in selectors",
desc: "Selectors should not contain IDs.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
idCount,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
idCount = 0;
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "id"){
idCount++;
}
}
}
}
if (idCount == 1){
reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule);
} else if (idCount > 1){
reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule);
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "import",
name: "Disallow @import",
desc: "Don't use @import, use <link> instead.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("import", function(event){
reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule);
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "important",
name: "Disallow !important",
desc: "Be careful when using !important declaration",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//warn that important is used and increment the declaration counter
parser.addListener("property", function(event){
if (event.important === true){
count++;
reporter.report("Use of !important", event.line, event.col, rule);
}
});
//if there are more than 10, show an error
parser.addListener("endstylesheet", function(){
reporter.stat("important", count);
if (count >= 10){
reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specifity issues.", rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "known-properties",
name: "Require use of known properties",
desc: "Properties should be known (listed in CSS specification) or be a vendor-prefixed property.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
properties = {
"alignment-adjust": 1,
"alignment-baseline": 1,
"animation": 1,
"animation-delay": 1,
"animation-direction": 1,
"animation-duration": 1,
"animation-fill-mode": 1,
"animation-iteration-count": 1,
"animation-name": 1,
"animation-play-state": 1,
"animation-timing-function": 1,
"appearance": 1,
"azimuth": 1,
"backface-visibility": 1,
"background": 1,
"background-attachment": 1,
"background-break": 1,
"background-clip": 1,
"background-color": 1,
"background-image": 1,
"background-origin": 1,
"background-position": 1,
"background-repeat": 1,
"background-size": 1,
"baseline-shift": 1,
"binding": 1,
"bleed": 1,
"bookmark-label": 1,
"bookmark-level": 1,
"bookmark-state": 1,
"bookmark-target": 1,
"border": 1,
"border-bottom": 1,
"border-bottom-color": 1,
"border-bottom-left-radius": 1,
"border-bottom-right-radius": 1,
"border-bottom-style": 1,
"border-bottom-width": 1,
"border-collapse": 1,
"border-color": 1,
"border-image": 1,
"border-image-outset": 1,
"border-image-repeat": 1,
"border-image-slice": 1,
"border-image-source": 1,
"border-image-width": 1,
"border-left": 1,
"border-left-color": 1,
"border-left-style": 1,
"border-left-width": 1,
"border-radius": 1,
"border-right": 1,
"border-right-color": 1,
"border-right-style": 1,
"border-right-width": 1,
"border-spacing": 1,
"border-style": 1,
"border-top": 1,
"border-top-color": 1,
"border-top-left-radius": 1,
"border-top-right-radius": 1,
"border-top-style": 1,
"border-top-width": 1,
"border-width": 1,
"bottom": 1,
"box-align": 1,
"box-decoration-break": 1,
"box-direction": 1,
"box-flex": 1,
"box-flex-group": 1,
"box-lines": 1,
"box-ordinal-group": 1,
"box-orient": 1,
"box-pack": 1,
"box-shadow": 1,
"box-sizing": 1,
"break-after": 1,
"break-before": 1,
"break-inside": 1,
"caption-side": 1,
"clear": 1,
"clip": 1,
"color": 1,
"color-profile": 1,
"column-count": 1,
"column-fill": 1,
"column-gap": 1,
"column-rule": 1,
"column-rule-color": 1,
"column-rule-style": 1,
"column-rule-width": 1,
"column-span": 1,
"column-width": 1,
"columns": 1,
"content": 1,
"counter-increment": 1,
"counter-reset": 1,
"crop": 1,
"cue": 1,
"cue-after": 1,
"cue-before": 1,
"cursor": 1,
"direction": 1,
"display": 1,
"dominant-baseline": 1,
"drop-initial-after-adjust": 1,
"drop-initial-after-align": 1,
"drop-initial-before-adjust": 1,
"drop-initial-before-align": 1,
"drop-initial-size": 1,
"drop-initial-value": 1,
"elevation": 1,
"empty-cells": 1,
"fit": 1,
"fit-position": 1,
"float": 1,
"float-offset": 1,
"font": 1,
"font-family": 1,
"font-size": 1,
"font-size-adjust": 1,
"font-stretch": 1,
"font-style": 1,
"font-variant": 1,
"font-weight": 1,
"grid-columns": 1,
"grid-rows": 1,
"hanging-punctuation": 1,
"height": 1,
"hyphenate-after": 1,
"hyphenate-before": 1,
"hyphenate-character": 1,
"hyphenate-lines": 1,
"hyphenate-resource": 1,
"hyphens": 1,
"icon": 1,
"image-orientation": 1,
"image-rendering": 1,
"image-resolution": 1,
"inline-box-align": 1,
"left": 1,
"letter-spacing": 1,
"line-height": 1,
"line-stacking": 1,
"line-stacking-ruby": 1,
"line-stacking-shift": 1,
"line-stacking-strategy": 1,
"list-style": 1,
"list-style-image": 1,
"list-style-position": 1,
"list-style-type": 1,
"margin": 1,
"margin-bottom": 1,
"margin-left": 1,
"margin-right": 1,
"margin-top": 1,
"mark": 1,
"mark-after": 1,
"mark-before": 1,
"marks": 1,
"marquee-direction": 1,
"marquee-play-count": 1,
"marquee-speed": 1,
"marquee-style": 1,
"max-height": 1,
"max-width": 1,
"min-height": 1,
"min-width": 1,
"move-to": 1,
"nav-down": 1,
"nav-index": 1,
"nav-left": 1,
"nav-right": 1,
"nav-up": 1,
"opacity": 1,
"orphans": 1,
"outline": 1,
"outline-color": 1,
"outline-offset": 1,
"outline-style": 1,
"outline-width": 1,
"overflow": 1,
"overflow-style": 1,
"overflow-x": 1,
"overflow-y": 1,
"padding": 1,
"padding-bottom": 1,
"padding-left": 1,
"padding-right": 1,
"padding-top": 1,
"page": 1,
"page-break-after": 1,
"page-break-before": 1,
"page-break-inside": 1,
"page-policy": 1,
"pause": 1,
"pause-after": 1,
"pause-before": 1,
"perspective": 1,
"perspective-origin": 1,
"phonemes": 1,
"pitch": 1,
"pitch-range": 1,
"play-during": 1,
"position": 1,
"presentation-level": 1,
"punctuation-trim": 1,
"quotes": 1,
"rendering-intent": 1,
"resize": 1,
"rest": 1,
"rest-after": 1,
"rest-before": 1,
"richness": 1,
"right": 1,
"rotation": 1,
"rotation-point": 1,
"ruby-align": 1,
"ruby-overhang": 1,
"ruby-position": 1,
"ruby-span": 1,
"size": 1,
"speak": 1,
"speak-header": 1,
"speak-numeral": 1,
"speak-punctuation": 1,
"speech-rate": 1,
"stress": 1,
"string-set": 1,
"table-layout": 1,
"target": 1,
"target-name": 1,
"target-new": 1,
"target-position": 1,
"text-align": 1,
"text-align-last": 1,
"text-decoration": 1,
"text-emphasis": 1,
"text-height": 1,
"text-indent": 1,
"text-justify": 1,
"text-outline": 1,
"text-shadow": 1,
"text-transform": 1,
"text-wrap": 1,
"top": 1,
"transform": 1,
"transform-origin": 1,
"transform-style": 1,
"transition": 1,
"transition-delay": 1,
"transition-duration": 1,
"transition-property": 1,
"transition-timing-function": 1,
"unicode-bidi": 1,
"user-modify": 1,
"user-select": 1,
"vertical-align": 1,
"visibility": 1,
"voice-balance": 1,
"voice-duration": 1,
"voice-family": 1,
"voice-pitch": 1,
"voice-pitch-range": 1,
"voice-rate": 1,
"voice-stress": 1,
"voice-volume": 1,
"volume": 1,
"white-space": 1,
"white-space-collapse": 1,
"widows": 1,
"width": 1,
"word-break": 1,
"word-spacing": 1,
"word-wrap": 1,
"z-index": 1,
//IE
"filter": 1,
"zoom": 1,
//@font-face
"src": 1
};
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (event.invalid) {
reporter.report(event.invalid.message, event.line, event.col, rule);
}
//if (!properties[name] && name.charAt(0) != "-"){
// reporter.error("Unknown property '" + event.property + "'.", event.line, event.col, rule);
//}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "outline-none",
name: "Disallow outline: none",
desc: "Use of outline: none or outline: 0 should be limited to :focus rules.",
browsers: "All",
tags: ["Accessibility"],
//initialization
init: function(parser, reporter){
var rule = this,
lastRule;
function startRule(event){
if (event.selectors){
lastRule = {
line: event.line,
col: event.col,
selectors: event.selectors,
propCount: 0,
outline: false
};
} else {
lastRule = null;
}
}
function endRule(event){
if (lastRule){
if (lastRule.outline){
if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") == -1){
reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule);
} else if (lastRule.propCount == 1) {
reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase(),
value = event.value;
if (lastRule){
lastRule.propCount++;
if (name == "outline" && (value == "none" || value == "0")){
lastRule.outline = true;
}
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "overqualified-elements",
name: "Disallow overqualified elements",
desc: "Don't use classes or IDs with elements (a.foo or a#foo).",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
classes = {};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (part.elementName && modifier.type == "id"){
reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule);
} else if (modifier.type == "class"){
if (!classes[modifier]){
classes[modifier] = [];
}
classes[modifier].push({ modifier: modifier, part: part });
}
}
}
}
}
});
parser.addListener("endstylesheet", function(){
var prop;
for (prop in classes){
if (classes.hasOwnProperty(prop)){
//one use means that this is overqualified
if (classes[prop].length == 1 && classes[prop][0].part.elementName){
reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule);
}
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "qualified-headings",
name: "Disallow qualified headings",
desc: "Headings should not be qualified (namespaced).",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0){
reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule);
}
}
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "regex-selectors",
name: "Disallow selectors that look like regexs",
desc: "Selectors that look like regular expressions are slow and should be avoided.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
for (j=0; j < selector.parts.length; j++){
part = selector.parts[j];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "attribute"){
if (/([\~\|\^\$\*]=)/.test(modifier)){
reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule);
}
}
}
}
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "rules-count",
name: "Rules Count",
desc: "Track how many rules there are.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
count = 0;
//count each rule
parser.addListener("startrule", function(){
count++;
});
parser.addListener("endstylesheet", function(){
reporter.stat("rule-count", count);
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "shorthand",
name: "Require shorthand properties",
desc: "Use shorthand properties where possible.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
prop, i, len,
propertiesToCheck = {},
properties,
mapping = {
"margin": [
"margin-top",
"margin-bottom",
"margin-left",
"margin-right"
],
"padding": [
"padding-top",
"padding-bottom",
"padding-left",
"padding-right"
]
};
//initialize propertiesToCheck
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
for (i=0, len=mapping[prop].length; i < len; i++){
propertiesToCheck[mapping[prop][i]] = prop;
}
}
}
function startRule(event){
properties = {};
}
//event handler for end of rules
function endRule(event){
var prop, i, len, total;
//check which properties this rule has
for (prop in mapping){
if (mapping.hasOwnProperty(prop)){
total=0;
for (i=0, len=mapping[prop].length; i < len; i++){
total += properties[mapping[prop][i]] ? 1 : 0;
}
if (total == mapping[prop].length){
reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase(),
value = event.value.parts[0].value;
if (propertiesToCheck[name]){
properties[name] = 1;
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "text-indent",
name: "Disallow negative text-indent",
desc: "Checks for text indent less than -99px",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
textIndent = false;
function startRule(event){
textIndent = false;
}
//event handler for end of rules
function endRule(event){
if (textIndent){
reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule);
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
//check for use of "font-size"
parser.addListener("property", function(event){
var name = event.property.toString().toLowerCase(),
value = event.value;
if (name == "text-indent" && value.parts[0].value < -99){
textIndent = event.property;
} else if (name == "direction" && value == "ltr"){
textIndent = false;
}
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "unique-headings",
name: "Headings should only be defined once",
desc: "Headings should be defined only once.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
var headings = {
h1: 0,
h2: 0,
h3: 0,
h4: 0,
h5: 0,
h6: 0
};
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
pseudo,
i, j;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())){
for (j=0; j < part.modifiers.length; j++){
if (part.modifiers[j].type == "pseudo"){
pseudo = true;
break;
}
}
if (!pseudo){
headings[RegExp.$1]++;
if (headings[RegExp.$1] > 1) {
reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule);
}
}
}
}
});
parser.addListener("endstylesheet", function(event){
var prop,
messages = [];
for (prop in headings){
if (headings.hasOwnProperty(prop)){
if (headings[prop] > 1){
messages.push(headings[prop] + " " + prop + "s");
}
}
}
if (messages.length){
reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule);
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "universal-selector",
name: "Disallow universal selector",
desc: "The universal selector (*) is known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.elementName == "*"){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "unqualified-attributes",
name: "Disallow unqualified attribute selectors",
desc: "Unqualified attribute selectors are known to be slow.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
parser.addListener("startrule", function(event){
var selectors = event.selectors,
selector,
part,
modifier,
i, j, k;
for (i=0; i < selectors.length; i++){
selector = selectors[i];
part = selector.parts[selector.parts.length-1];
if (part.type == parser.SELECTOR_PART_TYPE){
for (k=0; k < part.modifiers.length; k++){
modifier = part.modifiers[k];
if (modifier.type == "attribute" && (!part.elementName || part.elementName == "*")){
reporter.report(rule.desc, part.line, part.col, rule);
}
}
}
}
});
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "vendor-prefix",
name: "Require standard property with vendor prefix",
desc: "When using a vendor-prefixed property, make sure to include the standard one.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this,
properties,
num,
propertiesToCheck = {
"-webkit-border-radius": "border-radius",
"-webkit-border-top-left-radius": "border-top-left-radius",
"-webkit-border-top-right-radius": "border-top-right-radius",
"-webkit-border-bottom-left-radius": "border-bottom-left-radius",
"-webkit-border-bottom-right-radius": "border-bottom-right-radius",
"-o-border-radius": "border-radius",
"-o-border-top-left-radius": "border-top-left-radius",
"-o-border-top-right-radius": "border-top-right-radius",
"-o-border-bottom-left-radius": "border-bottom-left-radius",
"-o-border-bottom-right-radius": "border-bottom-right-radius",
"-moz-border-radius": "border-radius",
"-moz-border-radius-topleft": "border-top-left-radius",
"-moz-border-radius-topright": "border-top-right-radius",
"-moz-border-radius-bottomleft": "border-bottom-left-radius",
"-moz-border-radius-bottomright": "border-bottom-right-radius",
"-moz-column-count": "column-count",
"-webkit-column-count": "column-count",
"-moz-column-gap": "column-gap",
"-webkit-column-gap": "column-gap",
"-moz-column-rule": "column-rule",
"-webkit-column-rule": "column-rule",
"-moz-column-rule-style": "column-rule-style",
"-webkit-column-rule-style": "column-rule-style",
"-moz-column-rule-color": "column-rule-color",
"-webkit-column-rule-color": "column-rule-color",
"-moz-column-rule-width": "column-rule-width",
"-webkit-column-rule-width": "column-rule-width",
"-moz-column-width": "column-width",
"-webkit-column-width": "column-width",
"-webkit-column-span": "column-span",
"-webkit-columns": "columns",
"-moz-box-shadow": "box-shadow",
"-webkit-box-shadow": "box-shadow",
"-moz-transform" : "transform",
"-webkit-transform" : "transform",
"-o-transform" : "transform",
"-ms-transform" : "transform",
"-moz-transform-origin" : "transform-origin",
"-webkit-transform-origin" : "transform-origin",
"-o-transform-origin" : "transform-origin",
"-ms-transform-origin" : "transform-origin",
"-moz-box-sizing" : "box-sizing",
"-webkit-box-sizing" : "box-sizing",
"-moz-user-select" : "user-select",
"-khtml-user-select" : "user-select",
"-webkit-user-select" : "user-select"
};
//event handler for beginning of rules
function startRule(){
properties = {};
num=1;
}
//event handler for end of rules
function endRule(event){
var prop,
i, len,
standard,
needed,
actual,
needsStandard = [];
for (prop in properties){
if (propertiesToCheck[prop]){
needsStandard.push({ actual: prop, needed: propertiesToCheck[prop]});
}
}
for (i=0, len=needsStandard.length; i < len; i++){
needed = needsStandard[i].needed;
actual = needsStandard[i].actual;
if (!properties[needed]){
reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
} else {
//make sure standard property is last
if (properties[needed][0].pos < properties[actual][0].pos){
reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
}
}
}
}
parser.addListener("startrule", startRule);
parser.addListener("startfontface", startRule);
parser.addListener("startpage", startRule);
parser.addListener("startpagemargin", startRule);
parser.addListener("startkeyframerule", startRule);
parser.addListener("property", function(event){
var name = event.property.text.toLowerCase();
if (!properties[name]){
properties[name] = [];
}
properties[name].push({ name: event.property, value : event.value, pos:num++ });
});
parser.addListener("endrule", endRule);
parser.addListener("endfontface", endRule);
parser.addListener("endpage", endRule);
parser.addListener("endpagemargin", endRule);
parser.addListener("endkeyframerule", endRule);
}
});
/*global CSSLint*/
CSSLint.addRule({
//rule information
id: "zero-units",
name: "Disallow units for 0 values",
desc: "You don't need to specify units when a value is 0.",
browsers: "All",
//initialization
init: function(parser, reporter){
var rule = this;
//count how many times "float" is used
parser.addListener("property", function(event){
var parts = event.value.parts,
i = 0,
len = parts.length;
while(i < len){
if ((parts[i].units || parts[i].type == "percentage") && parts[i].value === 0 && parts[i].type != "time"){
reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule);
}
i++;
}
});
}
});
CSSLint.addFormatter({
//format information
id: "checkstyle-xml",
name: "Checkstyle XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</checkstyle>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
var generateSource = function(rule) {
if (!rule || !('name' in rule)) {
return "";
}
return 'net.csslint.' + rule.name.replace(/\s/g,'');
};
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
//ignore rollups for now
if (!message.rollup) {
output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" message=\"" + escapeSpecialCharacters(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
CSSLint.addFormatter({
//format information
id: "compact",
name: "Compact, 'porcelain' format",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = "";
options = options || {};
var capitalize = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
if (messages.length === 0) {
return options.quiet ? "" : filename + ": Lint Free!";
}
CSSLint.Util.forEach(messages, function(message, i) {
if (message.rollup) {
output += filename + ": " + capitalize(message.type) + " - " + message.message + "\n";
} else {
output += filename + ": " + "line " + message.line +
", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + "\n";
}
});
return output;
}
});
CSSLint.addFormatter({
//format information
id: "csslint-xml",
name: "CSSLint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</csslint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
CSSLint.addFormatter({
//format information
id: "lint-xml",
name: "Lint XML format",
/**
* Return opening root XML tag.
* @return {String} to prepend before all results
*/
startFormat: function(){
return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>";
},
/**
* Return closing root XML tag.
* @return {String} to append after all results
*/
endFormat: function(){
return "</lint>";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (UNUSED for now) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = [];
var escapeSpecialCharacters = function(str) {
if (!str || str.constructor !== String) {
return "";
}
return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">");
};
if (messages.length > 0) {
output.push("<file name=\""+filename+"\">");
CSSLint.Util.forEach(messages, function (message, i) {
if (message.rollup) {
output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
} else {
output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
}
});
output.push("</file>");
}
return output.join("");
}
});
CSSLint.addFormatter({
//format information
id: "text",
name: "Plain Text",
/**
* Return content to be printed before all file results.
* @return {String} to prepend before all results
*/
startFormat: function() {
return "";
},
/**
* Return content to be printed after all file results.
* @return {String} to append after all results
*/
endFormat: function() {
return "";
},
/**
* Given CSS Lint results for a file, return output for this format.
* @param results {Object} with error and warning messages
* @param filename {String} relative file path
* @param options {Object} (Optional) specifies special handling of output
* @return {String} output for results
*/
formatResults: function(results, filename, options) {
var messages = results.messages,
output = "";
options = options || {};
if (messages.length === 0) {
return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + ".";
}
output = "\n\ncsslint: There are " + messages.length + " problems in " + filename + ".";
var pos = filename.lastIndexOf("/"),
shortFilename = filename;
if (pos === -1){
pos = filename.lastIndexOf("\\");
}
if (pos > -1){
shortFilename = filename.substring(pos+1);
}
CSSLint.Util.forEach(messages, function (message, i) {
output = output + "\n\n" + shortFilename;
if (message.rollup) {
output += "\n" + (i+1) + ": " + message.type;
output += "\n" + message.message;
} else {
output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col;
output += "\n" + message.message;
output += "\n" + message.evidence;
}
});
return output;
}
});
exports.CSSLint = CSSLint;
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* John Roepke <john AT justjohn DOT us>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/less', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/less_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var LessHighlightRules = require("./less_highlight_rules").LessHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new LessHighlightRules().getRules(), "i");
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
// ignore braces in comments
var tokens = this.$tokenizer.getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/less_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var LessHighlightRules = function() {
var properties = lang.arrayToMap( (function () {
var browserPrefix = ("-webkit-|-moz-|-o-|-ms-|-svg-|-pie-|-khtml-").split("|");
var prefixProperties = ("appearance|background-clip|background-inline-policy|background-origin|" +
"background-size|binding|border-bottom-colors|border-left-colors|" +
"border-right-colors|border-top-colors|border-end|border-end-color|" +
"border-end-style|border-end-width|border-image|border-start|" +
"border-start-color|border-start-style|border-start-width|box-align|" +
"box-direction|box-flex|box-flexgroup|box-ordinal-group|box-orient|" +
"box-pack|box-sizing|column-count|column-gap|column-width|column-rule|" +
"column-rule-width|column-rule-style|column-rule-color|float-edge|" +
"font-feature-settings|font-language-override|force-broken-image-icon|" +
"image-region|margin-end|margin-start|opacity|outline|outline-color|" +
"outline-offset|outline-radius|outline-radius-bottomleft|" +
"outline-radius-bottomright|outline-radius-topleft|outline-radius-topright|" +
"outline-style|outline-width|padding-end|padding-start|stack-sizing|" +
"tab-size|text-blink|text-decoration-color|text-decoration-line|" +
"text-decoration-style|transform|transform-origin|transition|" +
"transition-delay|transition-duration|transition-property|" +
"transition-timing-function|user-focus|user-input|user-modify|user-select|" +
"window-shadow|border-radius").split("|");
var properties = ("azimuth|background-attachment|background-color|background-image|" +
"background-position|background-repeat|background|border-bottom-color|" +
"border-bottom-style|border-bottom-width|border-bottom|border-collapse|" +
"border-color|border-left-color|border-left-style|border-left-width|" +
"border-left|border-right-color|border-right-style|border-right-width|" +
"border-right|border-spacing|border-style|border-top-color|" +
"border-top-style|border-top-width|border-top|border-width|border|" +
"bottom|box-sizing|caption-side|clear|clip|color|content|counter-increment|" +
"counter-reset|cue-after|cue-before|cue|cursor|direction|display|" +
"elevation|empty-cells|float|font-family|font-size-adjust|font-size|" +
"font-stretch|font-style|font-variant|font-weight|font|height|left|" +
"letter-spacing|line-height|list-style-image|list-style-position|" +
"list-style-type|list-style|margin-bottom|margin-left|margin-right|" +
"margin-top|marker-offset|margin|marks|max-height|max-width|min-height|" +
"min-width|opacity|orphans|outline-color|" +
"outline-style|outline-width|outline|overflow|overflow-x|overflow-y|padding-bottom|" +
"padding-left|padding-right|padding-top|padding|page-break-after|" +
"page-break-before|page-break-inside|page|pause-after|pause-before|" +
"pause|pitch-range|pitch|play-during|position|quotes|richness|right|" +
"size|speak-header|speak-numeral|speak-punctuation|speech-rate|speak|" +
"stress|table-layout|text-align|text-decoration|text-indent|" +
"text-shadow|text-transform|top|unicode-bidi|vertical-align|" +
"visibility|voice-family|volume|white-space|widows|width|word-spacing|" +
"z-index").split("|");
//The return array
var ret = [];
//All prefixProperties will get the browserPrefix in
//the begning by join the prefixProperties array with the value of browserPrefix
for (var i=0, ln=browserPrefix.length; i<ln; i++) {
Array.prototype.push.apply(
ret,
(( browserPrefix[i] + prefixProperties.join("|" + browserPrefix[i]) ).split("|"))
);
}
//Add also prefixProperties and properties without any browser prefix
Array.prototype.push.apply(ret, prefixProperties);
Array.prototype.push.apply(ret, properties);
return ret;
})() );
var functions = lang.arrayToMap(
("hsl|hsla|rgb|rgba|url|attr|counter|counters|lighten|darken|saturate|" +
"desaturate|fadein|fadeout|fade|spin|mix|hue|saturation|lightness|" +
"alpha|round|ceil|floor|percentage|color|iscolor|isnumber|isstring|" +
"iskeyword|isurl|ispixel|ispercentage|isem").split("|")
);
var constants = lang.arrayToMap(
("absolute|all-scroll|always|armenian|auto|baseline|below|bidi-override|" +
"block|bold|bolder|border-box|both|bottom|break-all|break-word|capitalize|center|" +
"char|circle|cjk-ideographic|col-resize|collapse|content-box|crosshair|dashed|" +
"decimal-leading-zero|decimal|default|disabled|disc|" +
"distribute-all-lines|distribute-letter|distribute-space|" +
"distribute|dotted|double|e-resize|ellipsis|fixed|georgian|groove|" +
"hand|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|" +
"ideograph-alpha|ideograph-numeric|ideograph-parenthesis|" +
"ideograph-space|inactive|inherit|inline-block|inline|inset|inside|" +
"inter-ideograph|inter-word|italic|justify|katakana-iroha|katakana|" +
"keep-all|left|lighter|line-edge|line-through|line|list-item|loose|" +
"lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|" +
"medium|middle|move|n-resize|ne-resize|newspaper|no-drop|no-repeat|" +
"nw-resize|none|normal|not-allowed|nowrap|oblique|outset|outside|" +
"overline|pointer|progress|relative|repeat-x|repeat-y|repeat|right|" +
"ridge|row-resize|rtl|s-resize|scroll|se-resize|separate|small-caps|" +
"solid|square|static|strict|super|sw-resize|table-footer-group|" +
"table-header-group|tb-rl|text-bottom|text-top|text|thick|thin|top|" +
"transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|" +
"vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|" +
"zero").split("|")
);
var colors = lang.arrayToMap(
("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" +
"purple|red|silver|teal|white|yellow").split("|")
);
var keywords = lang.arrayToMap(
("@mixin|@extend|@include|@import|@media|@debug|@warn|@if|@for|@each|" +
"@while|@else|@font-face|@-webkit-keyframes|if|and|!default|module|" +
"def|end|declare|when|not|and").split("|")
);
var tags = lang.arrayToMap(
("a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdo|" +
"big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|" +
"command|datalist|dd|del|details|dfn|dir|div|dl|dt|em|embed|fieldset|" +
"figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|" +
"header|hgroup|hr|html|i|iframe|img|input|ins|keygen|kbd|label|legend|li|" +
"link|map|mark|menu|meta|meter|nav|noframes|noscript|object|ol|optgroup|" +
"option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|" +
"small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|" +
"textarea|tfoot|th|thead|time|title|tr|tt|u|ul|var|video|wbr|xmp").split("|")
);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "comment",
regex : "\\/\\/.*$"
},
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "constant.numeric",
regex : numRe + "(?:em|ex|px|cm|mm|in|pt|pc|deg|rad|grad|ms|s|hz|khz|%)"
}, {
token : "constant.numeric", // hex6 color
regex : "#[a-f0-9]{6}"
}, {
token : "constant.numeric", // hex3 color
regex : "#[a-f0-9]{3}"
}, {
token : "constant.numeric",
regex : numRe
}, {
token : function(value) {
if (keywords.hasOwnProperty(value))
return "keyword";
else
return "variable";
},
regex : "@[a-z0-9_\\-@]*\\b"
}, {
token : function(value) {
if (properties.hasOwnProperty(value.toLowerCase()))
return "support.type";
else if (keywords.hasOwnProperty(value))
return "keyword";
else if (constants.hasOwnProperty(value))
return "constant.language";
else if (functions.hasOwnProperty(value))
return "support.function";
else if (colors.hasOwnProperty(value.toLowerCase()))
return "support.constant.color";
else if (tags.hasOwnProperty(value.toLowerCase()))
return "variable.language";
else
return "text";
},
regex : "\\-?[@a-z_][@a-z0-9_\\-]*"
}, {
token: "variable.language",
regex: "#[a-z0-9-_]+"
}, {
token: "variable.language",
regex: "\\.[a-z0-9-_]+"
}, {
token: "variable.language",
regex: ":[a-z0-9-_]+"
}, {
token: "constant",
regex: "[a-z0-9-_]+"
}, {
token : "keyword.operator",
regex : "<|>|<=|>=|==|!=|-|%|#|\\+|\\$|\\+|\\*"
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
]
};
};
oop.inherits(LessHighlightRules, TextHighlightRules);
exports.LessHighlightRules = LessHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i");
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.foldingRules = "cStyle";
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
// ignore braces in comments
var tokens = this.$tokenizer.getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("csslint", function(e) {
var errors = [];
e.data.forEach(function(message) {
errors.push({
row: message.line - 1,
column: message.col - 1,
text: message.message,
type: message.type,
lint: message
});
});
session.setAnnotations(errors);
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var CssHighlightRules = function() {
var properties = lang.arrayToMap(
("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|")
);
var functions = lang.arrayToMap(
("rgb|rgba|url|attr|counter|counters").split("|")
);
var constants = lang.arrayToMap(
("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|")
);
var colors = lang.arrayToMap(
("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" +
"purple|red|silver|teal|white|yellow").split("|")
);
var fonts = lang.arrayToMap(
("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" +
"symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" +
"serif|monospace").split("|")
);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b";
var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b";
var base_ruleset = [
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "ruleset_comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : ["constant.numeric", "keyword"],
regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"
}, {
token : ["constant.numeric"],
regex : "([0-9]+)"
}, {
token : "constant.numeric", // hex6 color
regex : "#[a-f0-9]{6}"
}, {
token : "constant.numeric", // hex3 color
regex : "#[a-f0-9]{3}"
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"],
regex : pseudoElements
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"],
regex : pseudoClasses
}, {
token : function(value) {
if (properties.hasOwnProperty(value.toLowerCase())) {
return "support.type";
}
else if (functions.hasOwnProperty(value.toLowerCase())) {
return "support.function";
}
else if (constants.hasOwnProperty(value.toLowerCase())) {
return "support.constant";
}
else if (colors.hasOwnProperty(value.toLowerCase())) {
return "support.constant.color";
}
else if (fonts.hasOwnProperty(value.toLowerCase())) {
return "support.constant.fonts";
}
else {
return "text";
}
},
regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"
}
];
var ruleset = lang.copyArray(base_ruleset);
ruleset.unshift({
token : "paren.rparen",
regex : "\\}",
next: "start"
});
var media_ruleset = lang.copyArray( base_ruleset );
media_ruleset.unshift({
token : "paren.rparen",
regex : "\\}",
next: "media"
});
var base_comment = [{
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}];
var comment = lang.copyArray(base_comment);
comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
});
var media_comment = lang.copyArray(base_comment);
media_comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "media"
});
var ruleset_comment = lang.copyArray(base_comment);
ruleset_comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "ruleset"
});
this.$rules = {
"start" : [{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment"
}, {
token: "paren.lparen",
regex: "\\{",
next: "ruleset"
}, {
token: "string",
regex: "@.*?{",
next: "media"
},{
token: "keyword",
regex: "#[a-z0-9-_]+"
},{
token: "variable",
regex: "\\.[a-z0-9-_]+"
},{
token: "string",
regex: ":[a-z0-9-_]+"
},{
token: "constant",
regex: "[a-z0-9-_]+"
}],
"media" : [ {
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "media_comment"
}, {
token: "paren.lparen",
regex: "\\{",
next: "media_ruleset"
},{
token: "string",
regex: "\\}",
next: "start"
},{
token: "keyword",
regex: "#[a-z0-9-_]+"
},{
token: "variable",
regex: "\\.[a-z0-9-_]+"
},{
token: "string",
regex: ":[a-z0-9-_]+"
},{
token: "constant",
regex: "[a-z0-9-_]+"
}],
"comment" : comment,
"ruleset" : ruleset,
"ruleset_comment" : ruleset_comment,
"media_ruleset" : media_ruleset,
"media_comment" : media_comment
};
};
oop.inherits(CssHighlightRules, TextHighlightRules);
exports.CssHighlightRules = CssHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/tomorrow', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = false;
exports.cssClass = "ace-tomorrow";
exports.cssText = "\
.ace-tomorrow .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-tomorrow .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-tomorrow .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-tomorrow .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-tomorrow .ace_scroller {\
background-color: #FFFFFF;\
}\
\
.ace-tomorrow .ace_text-layer {\
cursor: text;\
color: #4D4D4C;\
}\
\
.ace-tomorrow .ace_cursor {\
border-left: 2px solid #AEAFAD;\
}\
\
.ace-tomorrow .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #AEAFAD;\
}\
\
.ace-tomorrow .ace_marker-layer .ace_selection {\
background: #D6D6D6;\
}\
\
.ace-tomorrow.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #FFFFFF;\
border-radius: 2px;\
}\
\
.ace-tomorrow .ace_marker-layer .ace_step {\
background: rgb(255, 255, 0);\
}\
\
.ace-tomorrow .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #D1D1D1;\
}\
\
.ace-tomorrow .ace_marker-layer .ace_active_line {\
background: #EFEFEF;\
}\
\
.ace-tomorrow .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-tomorrow .ace_marker-layer .ace_selected_word {\
border: 1px solid #D6D6D6;\
}\
\
.ace-tomorrow .ace_invisible {\
color: #D1D1D1;\
}\
\
.ace-tomorrow .ace_keyword, .ace-tomorrow .ace_meta {\
color:#8959A8;\
}\
\
.ace-tomorrow .ace_keyword.ace_operator {\
color:#3E999F;\
}\
\
.ace-tomorrow .ace_constant.ace_language {\
color:#F5871F;\
}\
\
.ace-tomorrow .ace_constant.ace_numeric {\
color:#F5871F;\
}\
\
.ace-tomorrow .ace_constant.ace_other {\
color:#666969;\
}\
\
.ace-tomorrow .ace_invalid {\
color:#FFFFFF;\
background-color:#C82829;\
}\
\
.ace-tomorrow .ace_invalid.ace_deprecated {\
color:#FFFFFF;\
background-color:#8959A8;\
}\
\
.ace-tomorrow .ace_support.ace_constant {\
color:#F5871F;\
}\
\
.ace-tomorrow .ace_fold {\
background-color: #4271AE;\
border-color: #4D4D4C;\
}\
\
.ace-tomorrow .ace_support.ace_function {\
color:#4271AE;\
}\
\
.ace-tomorrow .ace_storage {\
color:#8959A8;\
}\
\
.ace-tomorrow .ace_storage.ace_type, .ace-tomorrow .ace_support.ace_type{\
color:#8959A8;\
}\
\
.ace-tomorrow .ace_variable {\
color:#4271AE;\
}\
\
.ace-tomorrow .ace_variable.ace_parameter {\
color:#F5871F;\
}\
\
.ace-tomorrow .ace_string {\
color:#718C00;\
}\
\
.ace-tomorrow .ace_string.ace_regexp {\
color:#C82829;\
}\
\
.ace-tomorrow .ace_comment {\
color:#8E908C;\
}\
\
.ace-tomorrow .ace_variable {\
color:#C82829;\
}\
\
.ace-tomorrow .ace_meta.ace_tag {\
color:#C82829;\
}\
\
.ace-tomorrow .ace_entity.ace_other.ace_attribute-name {\
color:#C82829;\
}\
\
.ace-tomorrow .ace_entity.ace_name.ace_function {\
color:#4271AE;\
}\
\
.ace-tomorrow .ace_markup.ace_underline {\
text-decoration:underline;\
}\
\
.ace-tomorrow .ace_markup.ace_heading {\
color:#718C00;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
JavaScript
|
"no use strict";
var console = {
log: function(msg) {
postMessage({type: "log", data: msg});
}
};
var window = {
console: console
};
var normalizeModule = function(parentId, moduleName) {
// normalize plugin requires
if (moduleName.indexOf("!") !== -1) {
var chunks = moduleName.split("!");
return normalizeModule(parentId, chunks[0]) + "!" + normalizeModule(parentId, chunks[1]);
}
// normalize relative requires
if (moduleName.charAt(0) == ".") {
var base = parentId.split("/").slice(0, -1).join("/");
var moduleName = base + "/" + moduleName;
while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
var previous = moduleName;
var moduleName = moduleName.replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
}
}
return moduleName;
};
var require = function(parentId, id) {
var id = normalizeModule(parentId, id);
var module = require.modules[id];
if (module) {
if (!module.initialized) {
module.exports = module.factory().exports;
module.initialized = true;
}
return module.exports;
}
var chunks = id.split("/");
chunks[0] = require.tlns[chunks[0]] || chunks[0];
var path = chunks.join("/") + ".js";
require.id = id;
importScripts(path);
return require(parentId, id);
};
require.modules = {};
require.tlns = {};
var define = function(id, deps, factory) {
if (arguments.length == 2) {
factory = deps;
} else if (arguments.length == 1) {
factory = id;
id = require.id;
}
if (id.indexOf("text!") === 0)
return;
var req = function(deps, factory) {
return require(id, deps, factory);
};
require.modules[id] = {
factory: function() {
var module = {
exports: {}
};
var returnExports = factory(req, module.exports, module);
if (returnExports)
module.exports = returnExports;
return module;
}
};
};
function initBaseUrls(topLevelNamespaces) {
require.tlns = topLevelNamespaces;
}
function initSender() {
var EventEmitter = require(null, "ace/lib/event_emitter").EventEmitter;
var oop = require(null, "ace/lib/oop");
var Sender = function() {};
(function() {
oop.implement(this, EventEmitter);
this.callback = function(data, callbackId) {
postMessage({
type: "call",
id: callbackId,
data: data
});
};
this.emit = function(name, data) {
postMessage({
type: "event",
name: name,
data: data
});
};
}).call(Sender.prototype);
return new Sender();
}
var main;
var sender;
onmessage = function(e) {
var msg = e.data;
if (msg.command) {
main[msg.command].apply(main, msg.args);
}
else if (msg.init) {
initBaseUrls(msg.tlns);
require(null, "ace/lib/fixoldbrowsers");
sender = initSender();
var clazz = require(null, msg.module)[msg.classname];
main = new clazz(sender);
}
else if (msg.event && sender) {
sender._emit(msg.event, msg.data);
}
};
// vim:set ts=4 sts=4 sw=4 st:
// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project)
// -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified
// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
// -- Irakli Gozalishvili Copyright (C) 2010 MIT License
/*!
Copyright (c) 2009, 280 North Inc. http://280north.com/
MIT License. http://github.com/280north/narwhal/blob/master/README.md
*/
define('ace/lib/fixoldbrowsers', ['require', 'exports', 'module' , 'ace/lib/regexp', 'ace/lib/es5-shim'], function(require, exports, module) {
require("./regexp");
require("./es5-shim");
});
define('ace/lib/regexp', ['require', 'exports', 'module' ], function(require, exports, module) {
//---------------------------------
// Private variables
//---------------------------------
var real = {
exec: RegExp.prototype.exec,
test: RegExp.prototype.test,
match: String.prototype.match,
replace: String.prototype.replace,
split: String.prototype.split
},
compliantExecNpcg = real.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups
compliantLastIndexIncrement = function () {
var x = /^/g;
real.test.call(x, "");
return !x.lastIndex;
}();
if (compliantLastIndexIncrement && compliantExecNpcg)
return;
//---------------------------------
// Overriden native methods
//---------------------------------
// Adds named capture support (with backreferences returned as `result.name`), and fixes two
// cross-browser issues per ES3:
// - Captured values for nonparticipating capturing groups should be returned as `undefined`,
// rather than the empty string.
// - `lastIndex` should not be incremented after zero-length matches.
RegExp.prototype.exec = function (str) {
var match = real.exec.apply(this, arguments),
name, r2;
if ( typeof(str) == 'string' && match) {
// Fix browsers whose `exec` methods don't consistently return `undefined` for
// nonparticipating capturing groups
if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) {
r2 = RegExp(this.source, real.replace.call(getNativeFlags(this), "g", ""));
// Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed
// matching due to characters outside the match
real.replace.call(str.slice(match.index), r2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined)
match[i] = undefined;
}
});
}
// Attach named capture properties
if (this._xregexp && this._xregexp.captureNames) {
for (var i = 1; i < match.length; i++) {
name = this._xregexp.captureNames[i - 1];
if (name)
match[name] = match[i];
}
}
// Fix browsers that increment `lastIndex` after zero-length matches
if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
}
return match;
};
// Don't override `test` if it won't change anything
if (!compliantLastIndexIncrement) {
// Fix browser bug in native method
RegExp.prototype.test = function (str) {
// Use the native `exec` to skip some processing overhead, even though the overriden
// `exec` would take care of the `lastIndex` fix
var match = real.exec.call(this, str);
// Fix browsers that increment `lastIndex` after zero-length matches
if (match && this.global && !match[0].length && (this.lastIndex > match.index))
this.lastIndex--;
return !!match;
};
}
//---------------------------------
// Private helper functions
//---------------------------------
function getNativeFlags (regex) {
return (regex.global ? "g" : "") +
(regex.ignoreCase ? "i" : "") +
(regex.multiline ? "m" : "") +
(regex.extended ? "x" : "") + // Proposed for ES4; included in AS3
(regex.sticky ? "y" : "");
};
function indexOf (array, item, from) {
if (Array.prototype.indexOf) // Use the native array method if available
return array.indexOf(item, from);
for (var i = from || 0; i < array.length; i++) {
if (array[i] === item)
return i;
}
return -1;
};
});
// vim: ts=4 sts=4 sw=4 expandtab
// -- kriskowal Kris Kowal Copyright (C) 2009-2011 MIT License
// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project)
// -- dantman Daniel Friesen Copyright (C) 2010 XXX TODO License or CLA
// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
// -- Gozala Irakli Gozalishvili Copyright (C) 2010 MIT License
// -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License
// -- kossnocorp Sasha Koss XXX TODO License or CLA
// -- bryanforbes Bryan Forbes XXX TODO License or CLA
// -- killdream Quildreen Motta Copyright (C) 2011 MIT Licence
// -- michaelficarra Michael Ficarra Copyright (C) 2011 3-clause BSD License
// -- sharkbrainguy Gerard Paapu Copyright (C) 2011 MIT License
// -- bbqsrc Brendan Molloy (C) 2011 Creative Commons Zero (public domain)
// -- iwyg XXX TODO License or CLA
// -- DomenicDenicola Domenic Denicola Copyright (C) 2011 MIT License
// -- xavierm02 Montillet Xavier XXX TODO License or CLA
// -- Raynos Raynos XXX TODO License or CLA
// -- samsonjs Sami Samhuri Copyright (C) 2010 MIT License
// -- rwldrn Rick Waldron Copyright (C) 2011 MIT License
// -- lexer Alexey Zakharov XXX TODO License or CLA
/*!
Copyright (c) 2009, 280 North Inc. http://280north.com/
MIT License. http://github.com/280north/narwhal/blob/master/README.md
*/
define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) {
/*
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* Annotated ES5: http://es5.github.com/ (specific links below)
* ES5 Spec: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
*
* @module
*/
/*whatsupdoc*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://es5.github.com/#x15.3.4.5
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
if (typeof target != "function")
throw new TypeError(); // TODO message
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 11. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 12. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 13. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 14. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
var bound = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs, the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Construct]] internal
// method of target providing args as the arguments.
var F = function(){};
F.prototype = target.prototype;
var self = new F;
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (result !== null && Object(result) === result)
return result;
return self;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs, the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
// 5. Return the result of calling the [[Call]] internal method
// of target providing boundThis as the this value and
// providing args as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
// XXX bound.length is never writable, so don't even try
//
// 15. If the [[Class]] internal property of Target is "Function", then
// a. Let L be the length property of Target minus the length of A.
// b. Set the length own property of F to either 0 or L, whichever is
// larger.
// 16. Else set the length own property of F to 0.
// 17. Set the attributes of the length own property of F to the values
// specified in 15.3.5.1.
// TODO
// 18. Set the [[Extensible]] internal property of F to true.
// TODO
// 19. Let thrower be the [[ThrowTypeError]] function Object (13.2.3).
// 20. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Get]]: thrower, [[Set]]:
// thrower, [[Enumerable]]: false, [[Configurable]]: false}, and
// false.
// 21. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Get]]: thrower,
// [[Set]]: thrower, [[Enumerable]]: false, [[Configurable]]: false},
// and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property or the [[Code]], [[FormalParameters]], and
// [[Scope]] internal properties.
// XXX can't delete prototype in pure-js.
// 22. Return F.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var slice = prototypeOfArray.slice;
var toString = call.bind(prototypeOfObject.toString);
var owns = call.bind(prototypeOfObject.hasOwnProperty);
// If JS engine supports accessors creating shortcuts.
var defineGetter;
var defineSetter;
var lookupGetter;
var lookupSetter;
var supportsAccessors;
if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.3.2
// http://es5.github.com/#x15.4.3.2
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return toString(obj) == "[object Array]";
};
}
// The IsCallable() check in the Array functions
// has been replaced with a strict check on the
// internal class of the object to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions.
// ES5 15.4.4.18
// http://es5.github.com/#x15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/forEach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var self = toObject(this),
thisp = arguments[1],
i = 0,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
while (i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object context
fun.call(thisp, self[i], i, self);
}
i++;
}
};
}
// ES5 15.4.4.19
// http://es5.github.com/#x15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var self = toObject(this),
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, self);
}
return result;
};
}
// ES5 15.4.4.20
// http://es5.github.com/#x15.4.4.20
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
result = [],
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, self))
result.push(self[i]);
}
return result;
};
}
// ES5 15.4.4.16
// http://es5.github.com/#x15.4.4.16
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/every
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, self))
return false;
}
return true;
};
}
// ES5 15.4.4.17
// http://es5.github.com/#x15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
var self = toObject(this),
length = self.length >>> 0,
thisp = arguments[1];
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, self))
return true;
}
return false;
};
}
// ES5 15.4.4.21
// http://es5.github.com/#x15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var self = toObject(this),
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
// no value to return if no initial value and an empty array
if (!length && arguments.length == 1)
throw new TypeError(); // TODO message
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length)
throw new TypeError(); // TODO message
} while (true);
}
for (; i < length; i++) {
if (i in self)
result = fun.call(void 0, result, self[i], i, self);
}
return result;
};
}
// ES5 15.4.4.22
// http://es5.github.com/#x15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var self = toObject(this),
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (toString(fun) != "[object Function]") {
throw new TypeError(); // TODO message
}
// no value to return if no initial value, empty array
if (!length && arguments.length == 1)
throw new TypeError(); // TODO message
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError(); // TODO message
} while (true);
}
do {
if (i in this)
result = fun.call(void 0, result, self[i], i, self);
} while (i--);
return result;
};
}
// ES5 15.4.4.14
// http://es5.github.com/#x15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
var self = toObject(this),
length = self.length >>> 0;
if (!length)
return -1;
var i = 0;
if (arguments.length > 1)
i = toInteger(arguments[1]);
// handle negative indices
i = i >= 0 ? i : Math.max(0, length + i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
};
}
// ES5 15.4.4.15
// http://es5.github.com/#x15.4.4.15
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
var self = toObject(this),
length = self.length >>> 0;
if (!length)
return -1;
var i = length - 1;
if (arguments.length > 1)
i = Math.min(i, toInteger(arguments[1]));
// handle negative indices
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i])
return i;
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.2
// http://es5.github.com/#x15.2.3.2
if (!Object.getPrototypeOf) {
// https://github.com/kriskowal/es5-shim/issues#issue/2
// http://ejohn.org/blog/objectgetprototypeof/
// recommended by fschaefer on github
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || (
object.constructor ?
object.constructor.prototype :
prototypeOfObject
);
};
}
// ES5 15.2.3.3
// http://es5.github.com/#x15.2.3.3
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
"non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT + object);
// If object does not owns property return undefined immediately.
if (!owns(object, property))
return;
var descriptor, getter, setter;
// If object has a property then it's for sure both `enumerable` and
// `configurable`.
descriptor = { enumerable: true, configurable: true };
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it's owned by an object.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
// Once we have getter and setter we can put values back.
object.__proto__ = prototype;
if (getter || setter) {
if (getter) descriptor.get = getter;
if (setter) descriptor.set = setter;
// If it was accessor property we're done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
return descriptor;
};
}
// ES5 15.2.3.4
// http://es5.github.com/#x15.2.3.4
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
// ES5 15.2.3.5
// http://es5.github.com/#x15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype != "object")
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (properties !== void 0)
Object.defineProperties(object, properties);
return object;
};
}
// ES5 15.2.3.6
// http://es5.github.com/#x15.2.3.6
// Patch for WebKit and IE8 standard mode
// Designed by hax <hax.github.com>
// related issue: https://github.com/kriskowal/es5-shim/issues#issue/5
// IE8 Reference:
// http://msdn.microsoft.com/en-us/library/dd282900.aspx
// http://msdn.microsoft.com/en-us/library/dd229916.aspx
// WebKit Bugs:
// https://bugs.webkit.org/show_bug.cgi?id=36423
function doesDefinePropertyWork(object) {
try {
Object.defineProperty(object, "sentinel", {});
return "sentinel" in object;
} catch (exception) {
// returns falsy
}
}
// check whether defineProperty works if it's given. Otherwise,
// shim partially.
if (Object.defineProperty) {
var definePropertyWorksOnObject = doesDefinePropertyWork({});
var definePropertyWorksOnDom = typeof document == "undefined" ||
doesDefinePropertyWork(document.createElement("div"));
if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
var definePropertyFallback = Object.defineProperty;
}
}
if (!Object.defineProperty || definePropertyFallback) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
// make a valiant attempt to use the real defineProperty
// for I8's DOM elements.
if (definePropertyFallback) {
try {
return definePropertyFallback.call(Object, object, property, descriptor);
} catch (exception) {
// try the shim if the real one doesn't work
}
}
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors)
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get"))
defineGetter(object, property, descriptor.get);
if (owns(descriptor, "set"))
defineSetter(object, property, descriptor.set);
}
return object;
};
}
// ES5 15.2.3.7
// http://es5.github.com/#x15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
// ES5 15.2.3.8
// http://es5.github.com/#x15.2.3.8
if (!Object.seal) {
Object.seal = function seal(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.9
// http://es5.github.com/#x15.2.3.9
if (!Object.freeze) {
Object.freeze = function freeze(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// detect a Rhino bug and patch it
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object == "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
// ES5 15.2.3.10
// http://es5.github.com/#x15.2.3.10
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.11
// http://es5.github.com/#x15.2.3.11
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
// ES5 15.2.3.12
// http://es5.github.com/#x15.2.3.12
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
// ES5 15.2.3.13
// http://es5.github.com/#x15.2.3.13
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
// 1. If Type(O) is not Object throw a TypeError exception.
if (Object(object) === object) {
throw new TypeError(); // TODO message
}
// 2. Return the Boolean value of the [[Extensible]] internal property of O.
var name = '';
while (owns(object, name)) {
name += '?';
}
object[name] = true;
var returnValue = owns(object, name);
delete object[name];
return returnValue;
};
}
// ES5 15.2.3.14
// http://es5.github.com/#x15.2.3.14
if (!Object.keys) {
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
var hasDontEnumBug = true,
dontEnums = [
"toString",
"toLocaleString",
"valueOf",
"hasOwnProperty",
"isPrototypeOf",
"propertyIsEnumerable",
"constructor"
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null})
hasDontEnumBug = false;
Object.keys = function keys(object) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError("Object.keys called on a non-object");
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// http://es5.github.com/#x15.9.5.43
// This function returns a String value represent the instance in time
// represented by this Date object. The format of the String is the Date Time
// string format defined in 15.9.1.15. All fields are present in the String.
// The time zone is always UTC, denoted by the suffix Z. If the time value of
// this object is not a finite Number a RangeError exception is thrown.
if (!Date.prototype.toISOString || (new Date(-62198755200000).toISOString().indexOf('-000001') === -1)) {
Date.prototype.toISOString = function toISOString() {
var result, length, value, year;
if (!isFinite(this))
throw new RangeError;
// the date time string format is specified in 15.9.1.15.
result = [this.getUTCMonth() + 1, this.getUTCDate(),
this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
year = this.getUTCFullYear();
year = (year < 0 ? '-' : (year > 9999 ? '+' : '')) + ('00000' + Math.abs(year)).slice(0 <= year && year <= 9999 ? -4 : -6);
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two digits.
if (value < 10)
result[length] = "0" + value;
}
// pad milliseconds to have three digits.
return year + "-" + result.slice(0, 2).join("-") + "T" + result.slice(2).join(":") + "." +
("000" + this.getUTCMilliseconds()).slice(-3) + "Z";
}
}
// ES5 15.9.4.4
// http://es5.github.com/#x15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
// ES5 15.9.5.44
// http://es5.github.com/#x15.9.5.44
// This function provides a String representation of a Date object for use by
// JSON.stringify (15.12.3).
if (!Date.prototype.toJSON) {
Date.prototype.toJSON = function toJSON(key) {
// When the toJSON method is called with argument key, the following
// steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ToPrimitive(O, hint Number).
// 3. If tv is a Number and is not finite, return null.
// XXX
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
if (typeof this.toISOString != "function")
throw new TypeError(); // TODO message
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return this.toISOString();
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// ES5 15.9.4.2
// http://es5.github.com/#x15.9.4.2
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (Date.parse("+275760-09-13T00:00:00.000Z") !== 8.64e15) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
var Date = function Date(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length == 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format.
var isoDateExpression = new RegExp("^" +
"(\\d{4}|[\+\-]\\d{6})" + // four-digit year capture or sign + 6-digit extended year
"(?:-(\\d{2})" + // optional month capture
"(?:-(\\d{2})" + // optional day capture
"(?:" + // capture hours:minutes:seconds.milliseconds
"T(\\d{2})" + // hours capture
":(\\d{2})" + // minutes capture
"(?:" + // optional :seconds.milliseconds
":(\\d{2})" + // seconds capture
"(?:\\.(\\d{3}))?" + // milliseconds capture
")?" +
"(?:" + // capture UTC offset component
"Z|" + // UTC capture
"(?:" + // offset specifier +/-hours:minutes
"([-+])" + // sign capture
"(\\d{2})" + // hours offset capture
":(\\d{2})" + // minutes offset capture
")" +
")?)?)?)?" +
"$");
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate)
Date[key] = NativeDate[key];
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle simplified ISO 8601 strings
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
match.shift(); // kill match[0], the full match
// parse months, days, hours, minutes, seconds, and milliseconds
for (var i = 1; i < 7; i++) {
// provide default values if necessary
match[i] = +(match[i] || (i < 3 ? 1 : 0));
// match[1] is the month. Months are 0-11 in JavaScript
// `Date` objects, but 1-12 in ISO notation, so we
// decrement.
if (i == 1)
match[i]--;
}
// parse the UTC offset component
var minuteOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop();
// compute the explicit time zone offset if specified
var offset = 0;
if (sign) {
// detect invalid offsets and return early
if (hourOffset > 23 || minuteOffset > 59)
return NaN;
// express the provided time zone offset in minutes. The offset is
// negative for time zones west of UTC; positive otherwise.
offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1);
}
// Date.UTC for years between 0 and 99 converts year to 1900 + year
// The Gregorian calendar has a 400-year cycle, so
// to Date.UTC(year + 400, .... ) - 12622780800000 == Date.UTC(year, ...),
// where 12622780800000 - number of milliseconds in Gregorian calendar 400 years
var year = +match[0];
if (0 <= year && year <= 99) {
match[0] = year + 400;
return NativeDate.UTC.apply(this, match) + offset - 12622780800000;
}
// compute a new UTC date value, accounting for the optional offset
return NativeDate.UTC.apply(this, match) + offset;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
//
// String
// ======
//
// ES5 15.5.4.20
// http://es5.github.com/#x15.5.4.20
var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
"\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
"\u2029\uFEFF";
if (!String.prototype.trim || ws.trim()) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
ws = "[" + ws + "]";
var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
trimEndRegexp = new RegExp(ws + ws + "*$");
String.prototype.trim = function trim() {
return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
};
}
//
// Util
// ======
//
// ES5 9.4
// http://es5.github.com/#x9.4
// http://jsperf.com/to-integer
var toInteger = function (n) {
n = +n;
if (n !== n) // isNaN
n = 0;
else if (n !== 0 && n !== (1/0) && n !== -(1/0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
return n;
};
var prepareString = "a"[0] != "a",
// ES5 9.9
// http://es5.github.com/#x9.9
toObject = function (o) {
if (o == null) { // this matches both null and undefined
throw new TypeError(); // TODO message
}
// If the implementation doesn't support by-index access of
// string characters (ex. IE < 7), split the string
if (prepareString && typeof o == "string" && o) {
return o.split("");
}
return Object(o);
};
});
define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) {
var EventEmitter = {};
EventEmitter._emit =
EventEmitter._dispatchEvent = function(eventName, e) {
this._eventRegistry = this._eventRegistry || {};
this._defaultHandlers = this._defaultHandlers || {};
var listeners = this._eventRegistry[eventName] || [];
var defaultHandler = this._defaultHandlers[eventName];
if (!listeners.length && !defaultHandler)
return;
e = e || {};
e.type = eventName;
if (!e.stopPropagation) {
e.stopPropagation = function() {
this.propagationStopped = true;
};
}
if (!e.preventDefault) {
e.preventDefault = function() {
this.defaultPrevented = true;
};
}
for (var i=0; i<listeners.length; i++) {
listeners[i](e);
if (e.propagationStopped)
break;
}
if (defaultHandler && !e.defaultPrevented)
return defaultHandler(e);
};
EventEmitter.setDefaultHandler = function(eventName, callback) {
this._defaultHandlers = this._defaultHandlers || {};
if (this._defaultHandlers[eventName])
throw new Error("The default handler for '" + eventName + "' is already set");
this._defaultHandlers[eventName] = callback;
};
EventEmitter.on =
EventEmitter.addEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
var listeners = this._eventRegistry[eventName] = [];
if (listeners.indexOf(callback) == -1)
listeners.push(callback);
};
EventEmitter.removeListener =
EventEmitter.removeEventListener = function(eventName, callback) {
this._eventRegistry = this._eventRegistry || {};
var listeners = this._eventRegistry[eventName];
if (!listeners)
return;
var index = listeners.indexOf(callback);
if (index !== -1)
listeners.splice(index, 1);
};
EventEmitter.removeAllListeners = function(eventName) {
if (this._eventRegistry) this._eventRegistry[eventName] = [];
};
exports.EventEmitter = EventEmitter;
});
define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.inherits = (function() {
var tempCtor = function() {};
return function(ctor, superCtor) {
tempCtor.prototype = superCtor.prototype;
ctor.super_ = superCtor.prototype;
ctor.prototype = new tempCtor();
ctor.prototype.constructor = ctor;
};
}());
exports.mixin = function(obj, mixin) {
for (var key in mixin) {
obj[key] = mixin[key];
}
};
exports.implement = function(proto, mixin) {
exports.mixin(proto, mixin);
};
});
define('ace/mode/coffee_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/worker/mirror', 'ace/mode/coffee/coffee-script'], function(require, exports, module) {
var oop = require("../lib/oop");
var Mirror = require("../worker/mirror").Mirror;
var coffee = require("../mode/coffee/coffee-script");
window.addEventListener = function() {};
var Worker = exports.Worker = function(sender) {
Mirror.call(this, sender);
this.setTimeout(200);
};
oop.inherits(Worker, Mirror);
(function() {
this.onUpdate = function() {
var value = this.doc.getValue();
try {
coffee.parse(value);
} catch(e) {
var m = e.message.match(/Parse error on line (\d+): (.*)/);
if (m) {
this.sender.emit("error", {
row: parseInt(m[1], 10) - 1,
column: null,
text: m[2],
type: "error"
});
return;
}
if (e instanceof SyntaxError) {
var m = e.message.match(/ on line (\d+)/);
if (m) {
this.sender.emit("error", {
row: parseInt(m[1], 10) - 1,
column: null,
text: e.message.replace(m[0], ""),
type: "error"
});
}
}
return;
}
this.sender.emit("ok");
};
}).call(Worker.prototype);
});
define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) {
var Document = require("../document").Document;
var lang = require("../lib/lang");
var Mirror = exports.Mirror = function(sender) {
this.sender = sender;
var doc = this.doc = new Document("");
var deferredUpdate = this.deferredUpdate = lang.deferredCall(this.onUpdate.bind(this));
var _self = this;
sender.on("change", function(e) {
doc.applyDeltas([e.data]);
deferredUpdate.schedule(_self.$timeout);
});
};
(function() {
this.$timeout = 500;
this.setTimeout = function(timeout) {
this.$timeout = timeout;
};
this.setValue = function(value) {
this.doc.setValue(value);
this.deferredUpdate.schedule(this.$timeout);
};
this.getValue = function(callbackId) {
this.sender.callback(this.doc.getValue(), callbackId);
};
this.onUpdate = function() {
// abstract method
};
}).call(Mirror.prototype);
});
define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) {
var oop = require("./lib/oop");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var Range = require("./range").Range;
var Anchor = require("./anchor").Anchor;
/**
* new Document([text])
* - text (String | Array): The starting text
*
* Creates a new `Document`. If `text` is included, the `Document` contains those strings; otherwise, it's empty.
*
**/
var Document = function(text) {
this.$lines = [];
// There has to be one line at least in the document. If you pass an empty
// string to the insert function, nothing will happen. Workaround.
if (text.length == 0) {
this.$lines = [""];
} else if (Array.isArray(text)) {
this.insertLines(0, text);
} else {
this.insert({row: 0, column:0}, text);
}
};
(function() {
oop.implement(this, EventEmitter);
this.setValue = function(text) {
var len = this.getLength();
this.remove(new Range(0, 0, len, this.getLine(len-1).length));
this.insert({row: 0, column:0}, text);
};
this.getValue = function() {
return this.getAllLines().join(this.getNewLineCharacter());
};
this.createAnchor = function(row, column) {
return new Anchor(this, row, column);
};
// check for IE split bug
if ("aaa".split(/a/).length == 0)
this.$split = function(text) {
return text.replace(/\r\n|\r/g, "\n").split("\n");
}
else
this.$split = function(text) {
return text.split(/\r\n|\r|\n/);
};
this.$detectNewLine = function(text) {
var match = text.match(/^.*?(\r\n|\r|\n)/m);
if (match) {
this.$autoNewLine = match[1];
} else {
this.$autoNewLine = "\n";
}
};
this.getNewLineCharacter = function() {
switch (this.$newLineMode) {
case "windows":
return "\r\n";
case "unix":
return "\n";
case "auto":
return this.$autoNewLine;
}
};
this.$autoNewLine = "\n";
this.$newLineMode = "auto";
this.setNewLineMode = function(newLineMode) {
if (this.$newLineMode === newLineMode)
return;
this.$newLineMode = newLineMode;
};
this.getNewLineMode = function() {
return this.$newLineMode;
};
this.isNewLine = function(text) {
return (text == "\r\n" || text == "\r" || text == "\n");
};
this.getLine = function(row) {
return this.$lines[row] || "";
};
this.getLines = function(firstRow, lastRow) {
return this.$lines.slice(firstRow, lastRow + 1);
};
this.getAllLines = function() {
return this.getLines(0, this.getLength());
};
this.getLength = function() {
return this.$lines.length;
};
this.getTextRange = function(range) {
if (range.start.row == range.end.row) {
return this.$lines[range.start.row].substring(range.start.column,
range.end.column);
}
else {
var lines = this.getLines(range.start.row+1, range.end.row-1);
lines.unshift((this.$lines[range.start.row] || "").substring(range.start.column));
lines.push((this.$lines[range.end.row] || "").substring(0, range.end.column));
return lines.join(this.getNewLineCharacter());
}
};
this.$clipPosition = function(position) {
var length = this.getLength();
if (position.row >= length) {
position.row = Math.max(0, length - 1);
position.column = this.getLine(length-1).length;
}
return position;
};
this.insert = function(position, text) {
if (!text || text.length === 0)
return position;
position = this.$clipPosition(position);
// only detect new lines if the document has no line break yet
if (this.getLength() <= 1)
this.$detectNewLine(text);
var lines = this.$split(text);
var firstLine = lines.splice(0, 1)[0];
var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0];
position = this.insertInLine(position, firstLine);
if (lastLine !== null) {
position = this.insertNewLine(position); // terminate first line
position = this.insertLines(position.row, lines);
position = this.insertInLine(position, lastLine || "");
}
return position;
};
this.insertLines = function(row, lines) {
if (lines.length == 0)
return {row: row, column: 0};
// apply doesn't work for big arrays (smallest threshold is on safari 0xFFFF)
// to circumvent that we have to break huge inserts into smaller chunks here
if (lines.length > 0xFFFF) {
var end = this.insertLines(row, lines.slice(0xFFFF));
lines = lines.slice(0, 0xFFFF);
}
var args = [row, 0];
args.push.apply(args, lines);
this.$lines.splice.apply(this.$lines, args);
var range = new Range(row, 0, row + lines.length, 0);
var delta = {
action: "insertLines",
range: range,
lines: lines
};
this._emit("change", { data: delta });
return end || range.end;
};
this.insertNewLine = function(position) {
position = this.$clipPosition(position);
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column);
this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length));
var end = {
row : position.row + 1,
column : 0
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: this.getNewLineCharacter()
};
this._emit("change", { data: delta });
return end;
};
this.insertInLine = function(position, text) {
if (text.length == 0)
return position;
var line = this.$lines[position.row] || "";
this.$lines[position.row] = line.substring(0, position.column) + text
+ line.substring(position.column);
var end = {
row : position.row,
column : position.column + text.length
};
var delta = {
action: "insertText",
range: Range.fromPoints(position, end),
text: text
};
this._emit("change", { data: delta });
return end;
};
this.remove = function(range) {
// clip to document
range.start = this.$clipPosition(range.start);
range.end = this.$clipPosition(range.end);
if (range.isEmpty())
return range.start;
var firstRow = range.start.row;
var lastRow = range.end.row;
if (range.isMultiLine()) {
var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1;
var lastFullRow = lastRow - 1;
if (range.end.column > 0)
this.removeInLine(lastRow, 0, range.end.column);
if (lastFullRow >= firstFullRow)
this.removeLines(firstFullRow, lastFullRow);
if (firstFullRow != firstRow) {
this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length);
this.removeNewLine(range.start.row);
}
}
else {
this.removeInLine(firstRow, range.start.column, range.end.column);
}
return range.start;
};
this.removeInLine = function(row, startColumn, endColumn) {
if (startColumn == endColumn)
return;
var range = new Range(row, startColumn, row, endColumn);
var line = this.getLine(row);
var removed = line.substring(startColumn, endColumn);
var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length);
this.$lines.splice(row, 1, newLine);
var delta = {
action: "removeText",
range: range,
text: removed
};
this._emit("change", { data: delta });
return range.start;
};
this.removeLines = function(firstRow, lastRow) {
var range = new Range(firstRow, 0, lastRow + 1, 0);
var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1);
var delta = {
action: "removeLines",
range: range,
nl: this.getNewLineCharacter(),
lines: removed
};
this._emit("change", { data: delta });
return removed;
};
this.removeNewLine = function(row) {
var firstLine = this.getLine(row);
var secondLine = this.getLine(row+1);
var range = new Range(row, firstLine.length, row+1, 0);
var line = firstLine + secondLine;
this.$lines.splice(row, 2, line);
var delta = {
action: "removeText",
range: range,
text: this.getNewLineCharacter()
};
this._emit("change", { data: delta });
};
this.replace = function(range, text) {
if (text.length == 0 && range.isEmpty())
return range.start;
// Shortcut: If the text we want to insert is the same as it is already
// in the document, we don't have to replace anything.
if (text == this.getTextRange(range))
return range.end;
this.remove(range);
if (text) {
var end = this.insert(range.start, text);
}
else {
end = range.start;
}
return end;
};
this.applyDeltas = function(deltas) {
for (var i=0; i<deltas.length; i++) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.insertLines(range.start.row, delta.lines);
else if (delta.action == "insertText")
this.insert(range.start, delta.text);
else if (delta.action == "removeLines")
this.removeLines(range.start.row, range.end.row - 1);
else if (delta.action == "removeText")
this.remove(range);
}
};
this.revertDeltas = function(deltas) {
for (var i=deltas.length-1; i>=0; i--) {
var delta = deltas[i];
var range = Range.fromPoints(delta.range.start, delta.range.end);
if (delta.action == "insertLines")
this.removeLines(range.start.row, range.end.row - 1);
else if (delta.action == "insertText")
this.remove(range);
else if (delta.action == "removeLines")
this.insertLines(range.start.row, delta.lines);
else if (delta.action == "removeText")
this.insert(range.start, delta.text);
}
};
}).call(Document.prototype);
exports.Document = Document;
});
define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) {
/**
* class Range
*
* This object is used in various places to indicate a region within the editor. To better visualize how this works, imagine a rectangle. Each quadrant of the rectangle is analogus to a range, as ranges contain a starting row and starting column, and an ending row, and ending column.
*
**/
/**
* new Range(startRow, startColumn, endRow, endColumn)
* - startRow (Number): The starting row
* - startColumn (Number): The starting column
* - endRow (Number): The ending row
* - endColumn (Number): The ending column
*
* Creates a new `Range` object with the given starting and ending row and column points.
*
**/
var Range = function(startRow, startColumn, endRow, endColumn) {
this.start = {
row: startRow,
column: startColumn
};
this.end = {
row: endRow,
column: endColumn
};
};
(function() {
/**
* Range.isEqual(range) -> Boolean
* - range (Range): A range to check against
*
* Returns `true` if and only if the starting row and column, and ending tow and column, are equivalent to those given by `range`.
*
**/
this.isEqual = function(range) {
return this.start.row == range.start.row &&
this.end.row == range.end.row &&
this.start.column == range.start.column &&
this.end.column == range.end.column
};
this.toString = function() {
return ("Range: [" + this.start.row + "/" + this.start.column +
"] -> [" + this.end.row + "/" + this.end.column + "]");
};
this.contains = function(row, column) {
return this.compare(row, column) == 0;
};
this.compareRange = function(range) {
var cmp,
end = range.end,
start = range.start;
cmp = this.compare(end.row, end.column);
if (cmp == 1) {
cmp = this.compare(start.row, start.column);
if (cmp == 1) {
return 2;
} else if (cmp == 0) {
return 1;
} else {
return 0;
}
} else if (cmp == -1) {
return -2;
} else {
cmp = this.compare(start.row, start.column);
if (cmp == -1) {
return -1;
} else if (cmp == 1) {
return 42;
} else {
return 0;
}
}
}
/** related to: Range.compare
* Range.comparePoint(p) -> Number
* - p (Range): A point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `0` if the two points are exactly equal<br/>
* * `-1` if `p.row` is less then the calling range<br/>
* * `1` if `p.row` is greater than the calling range<br/>
* <br/>
* If the starting row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/>
* * Otherwise, it returns -1<br/>
*<br/>
* If the ending row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/>
* * Otherwise, it returns 1<br/>
*
* Checks the row and column points of `p` with the row and column points of the calling range.
*
*
*
**/
this.comparePoint = function(p) {
return this.compare(p.row, p.column);
}
/** related to: Range.comparePoint
* Range.containsRange(range) -> Boolean
* - range (Range): A range to compare with
*
* Checks the start and end points of `range` and compares them to the calling range. Returns `true` if the `range` is contained within the caller's range.
*
**/
this.containsRange = function(range) {
return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
}
/**
* Range.intersects(range) -> Boolean
* - range (Range): A range to compare with
*
* Returns `true` if passed in `range` intersects with the one calling this method.
*
**/
this.intersects = function(range) {
var cmp = this.compareRange(range);
return (cmp == -1 || cmp == 0 || cmp == 1);
}
/**
* Range.isEnd(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the caller's ending row point is the same as `row`, and if the caller's ending column is the same as `column`.
*
**/
this.isEnd = function(row, column) {
return this.end.row == row && this.end.column == column;
}
/**
* Range.isStart(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the caller's starting row point is the same as `row`, and if the caller's starting column is the same as `column`.
*
**/
this.isStart = function(row, column) {
return this.start.row == row && this.start.column == column;
}
/**
* Range.setStart(row, column)
* - row (Number): A row point to set
* - column (Number): A column point to set
*
* Sets the starting row and column for the range.
*
**/
this.setStart = function(row, column) {
if (typeof row == "object") {
this.start.column = row.column;
this.start.row = row.row;
} else {
this.start.row = row;
this.start.column = column;
}
}
/**
* Range.setEnd(row, column)
* - row (Number): A row point to set
* - column (Number): A column point to set
*
* Sets the starting row and column for the range.
*
**/
this.setEnd = function(row, column) {
if (typeof row == "object") {
this.end.column = row.column;
this.end.row = row.row;
} else {
this.end.row = row;
this.end.column = column;
}
}
/** related to: Range.compare
* Range.inside(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the `row` and `column` are within the given range.
*
**/
this.inside = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column) || this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
/** related to: Range.compare
* Range.insideStart(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the `row` and `column` are within the given range's starting points.
*
**/
this.insideStart = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isEnd(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
/** related to: Range.compare
* Range.insideEnd(row, column) -> Boolean
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
*
* Returns `true` if the `row` and `column` are within the given range's ending points.
*
**/
this.insideEnd = function(row, column) {
if (this.compare(row, column) == 0) {
if (this.isStart(row, column)) {
return false;
} else {
return true;
}
}
return false;
}
/**
* Range.compare(row, column) -> Number
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `0` if the two points are exactly equal <br/>
* * `-1` if `p.row` is less then the calling range <br/>
* * `1` if `p.row` is greater than the calling range <br/>
* <br/>
* If the starting row of the calling range is equal to `p.row`, and: <br/>
* * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/>
* * Otherwise, it returns -1<br/>
* <br/>
* If the ending row of the calling range is equal to `p.row`, and: <br/>
* * `p.column` is less than or equal to the calling range's ending column, this returns `0` <br/>
* * Otherwise, it returns 1
*
* Checks the row and column points with the row and column points of the calling range.
*
*
**/
this.compare = function(row, column) {
if (!this.isMultiLine()) {
if (row === this.start.row) {
return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
};
}
if (row < this.start.row)
return -1;
if (row > this.end.row)
return 1;
if (this.start.row === row)
return column >= this.start.column ? 0 : -1;
if (this.end.row === row)
return column <= this.end.column ? 0 : 1;
return 0;
};
this.compareStart = function(row, column) {
if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
/**
* Range.compareEnd(row, column) -> Number
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `0` if the two points are exactly equal<br/>
* * `-1` if `p.row` is less then the calling range<br/>
* * `1` if `p.row` is greater than the calling range, or if `isEnd` is `true.<br/>
* <br/>
* If the starting row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is greater than or equal to the calling range's starting column, this returns `0`<br/>
* * Otherwise, it returns -1<br/>
*<br/>
* If the ending row of the calling range is equal to `p.row`, and:<br/>
* * `p.column` is less than or equal to the calling range's ending column, this returns `0`<br/>
* * Otherwise, it returns 1
*
* Checks the row and column points with the row and column points of the calling range.
*
*
**/
this.compareEnd = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else {
return this.compare(row, column);
}
}
/**
* Range.compareInside(row, column) -> Number
* - row (Number): A row point to compare with
* - column (Number): A column point to compare with
* + (Number): This method returns one of the following numbers:<br/>
* * `1` if the ending row of the calling range is equal to `row`, and the ending column of the calling range is equal to `column`<br/>
* * `-1` if the starting row of the calling range is equal to `row`, and the starting column of the calling range is equal to `column`<br/>
* <br/>
* Otherwise, it returns the value after calling [[Range.compare `compare()`]].
*
* Checks the row and column points with the row and column points of the calling range.
*
*
*
**/
this.compareInside = function(row, column) {
if (this.end.row == row && this.end.column == column) {
return 1;
} else if (this.start.row == row && this.start.column == column) {
return -1;
} else {
return this.compare(row, column);
}
}
/**
* Range.clipRows(firstRow, lastRow) -> Range
* - firstRow (Number): The starting row
* - lastRow (Number): The ending row
*
* Returns the part of the current `Range` that occurs within the boundaries of `firstRow` and `lastRow` as a new `Range` object.
*
**/
this.clipRows = function(firstRow, lastRow) {
if (this.end.row > lastRow) {
var end = {
row: lastRow+1,
column: 0
};
}
if (this.start.row > lastRow) {
var start = {
row: lastRow+1,
column: 0
};
}
if (this.start.row < firstRow) {
var start = {
row: firstRow,
column: 0
};
}
if (this.end.row < firstRow) {
var end = {
row: firstRow,
column: 0
};
}
return Range.fromPoints(start || this.start, end || this.end);
};
this.extend = function(row, column) {
var cmp = this.compare(row, column);
if (cmp == 0)
return this;
else if (cmp == -1)
var start = {row: row, column: column};
else
var end = {row: row, column: column};
return Range.fromPoints(start || this.start, end || this.end);
};
this.isEmpty = function() {
return (this.start.row == this.end.row && this.start.column == this.end.column);
};
this.isMultiLine = function() {
return (this.start.row !== this.end.row);
};
this.clone = function() {
return Range.fromPoints(this.start, this.end);
};
this.collapseRows = function() {
if (this.end.column == 0)
return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
else
return new Range(this.start.row, 0, this.end.row, 0)
};
this.toScreenRange = function(session) {
var screenPosStart =
session.documentToScreenPosition(this.start);
var screenPosEnd =
session.documentToScreenPosition(this.end);
return new Range(
screenPosStart.row, screenPosStart.column,
screenPosEnd.row, screenPosEnd.column
);
};
}).call(Range.prototype);
Range.fromPoints = function(start, end) {
return new Range(start.row, start.column, end.row, end.column);
};
exports.Range = Range;
});
define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) {
var oop = require("./lib/oop");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
/**
* new Anchor(doc, row, column)
* - doc (Document): The document to associate with the anchor
* - row (Number): The starting row position
* - column (Number): The starting column position
*
* Creates a new `Anchor` and associates it with a document.
*
**/
var Anchor = exports.Anchor = function(doc, row, column) {
this.document = doc;
if (typeof column == "undefined")
this.setPosition(row.row, row.column);
else
this.setPosition(row, column);
this.$onChange = this.onChange.bind(this);
doc.on("change", this.$onChange);
};
(function() {
oop.implement(this, EventEmitter);
this.getPosition = function() {
return this.$clipPositionToDocument(this.row, this.column);
};
this.getDocument = function() {
return this.document;
};
this.onChange = function(e) {
var delta = e.data;
var range = delta.range;
if (range.start.row == range.end.row && range.start.row != this.row)
return;
if (range.start.row > this.row)
return;
if (range.start.row == this.row && range.start.column > this.column)
return;
var row = this.row;
var column = this.column;
if (delta.action === "insertText") {
if (range.start.row === row && range.start.column <= column) {
if (range.start.row === range.end.row) {
column += range.end.column - range.start.column;
}
else {
column -= range.start.column;
row += range.end.row - range.start.row;
}
}
else if (range.start.row !== range.end.row && range.start.row < row) {
row += range.end.row - range.start.row;
}
} else if (delta.action === "insertLines") {
if (range.start.row <= row) {
row += range.end.row - range.start.row;
}
}
else if (delta.action == "removeText") {
if (range.start.row == row && range.start.column < column) {
if (range.end.column >= column)
column = range.start.column;
else
column = Math.max(0, column - (range.end.column - range.start.column));
} else if (range.start.row !== range.end.row && range.start.row < row) {
if (range.end.row == row) {
column = Math.max(0, column - range.end.column) + range.start.column;
}
row -= (range.end.row - range.start.row);
}
else if (range.end.row == row) {
row -= range.end.row - range.start.row;
column = Math.max(0, column - range.end.column) + range.start.column;
}
} else if (delta.action == "removeLines") {
if (range.start.row <= row) {
if (range.end.row <= row)
row -= range.end.row - range.start.row;
else {
row = range.start.row;
column = 0;
}
}
}
this.setPosition(row, column, true);
};
this.setPosition = function(row, column, noClip) {
var pos;
if (noClip) {
pos = {
row: row,
column: column
};
}
else {
pos = this.$clipPositionToDocument(row, column);
}
if (this.row == pos.row && this.column == pos.column)
return;
var old = {
row: this.row,
column: this.column
};
this.row = pos.row;
this.column = pos.column;
this._emit("change", {
old: old,
value: pos
});
};
this.detach = function() {
this.document.removeEventListener("change", this.$onChange);
};
this.$clipPositionToDocument = function(row, column) {
var pos = {};
if (row >= this.document.getLength()) {
pos.row = Math.max(0, this.document.getLength() - 1);
pos.column = this.document.getLine(pos.row).length;
}
else if (row < 0) {
pos.row = 0;
pos.column = 0;
}
else {
pos.row = row;
pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
}
if (column < 0)
pos.column = 0;
return pos;
};
}).call(Anchor.prototype);
});
define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) {
exports.stringReverse = function(string) {
return string.split("").reverse().join("");
};
exports.stringRepeat = function (string, count) {
return new Array(count + 1).join(string);
};
var trimBeginRegexp = /^\s\s*/;
var trimEndRegexp = /\s\s*$/;
exports.stringTrimLeft = function (string) {
return string.replace(trimBeginRegexp, '');
};
exports.stringTrimRight = function (string) {
return string.replace(trimEndRegexp, '');
};
exports.copyObject = function(obj) {
var copy = {};
for (var key in obj) {
copy[key] = obj[key];
}
return copy;
};
exports.copyArray = function(array){
var copy = [];
for (var i=0, l=array.length; i<l; i++) {
if (array[i] && typeof array[i] == "object")
copy[i] = this.copyObject( array[i] );
else
copy[i] = array[i];
}
return copy;
};
exports.deepCopy = function (obj) {
if (typeof obj != "object") {
return obj;
}
var copy = obj.constructor();
for (var key in obj) {
if (typeof obj[key] == "object") {
copy[key] = this.deepCopy(obj[key]);
} else {
copy[key] = obj[key];
}
}
return copy;
};
exports.arrayToMap = function(arr) {
var map = {};
for (var i=0; i<arr.length; i++) {
map[arr[i]] = 1;
}
return map;
};
exports.arrayRemove = function(array, value) {
for (var i = 0; i <= array.length; i++) {
if (value === array[i]) {
array.splice(i, 1);
}
}
};
exports.escapeRegExp = function(str) {
return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
};
exports.getMatchOffsets = function(string, regExp) {
var matches = [];
string.replace(regExp, function(str) {
matches.push({
offset: arguments[arguments.length-2],
length: str.length
});
});
return matches;
};
exports.deferredCall = function(fcn) {
var timer = null;
var callback = function() {
timer = null;
fcn();
};
var deferred = function(timeout) {
deferred.cancel();
timer = setTimeout(callback, timeout || 0);
return deferred;
};
deferred.schedule = deferred;
deferred.call = function() {
this.cancel();
fcn();
return deferred;
};
deferred.cancel = function() {
clearTimeout(timer);
timer = null;
return deferred;
};
return deferred;
};
});
define('ace/mode/coffee/coffee-script', ['require', 'exports', 'module' , 'ace/mode/coffee/lexer', 'ace/mode/coffee/parser', 'ace/mode/coffee/nodes'], function(require, exports, module) {
var Lexer = require("./lexer").Lexer;
var parser = require("./parser");
var lexer = new Lexer();
parser.lexer = {
lex: function() {
var tag, _ref2;
_ref2 = this.tokens[this.pos++] || [''], tag = _ref2[0], this.yytext = _ref2[1], this.yylineno = _ref2[2];
return tag;
},
setInput: function(tokens) {
this.tokens = tokens;
return this.pos = 0;
},
upcomingInput: function() {
return "";
}
};
parser.yy = require('./nodes');
exports.parse = function(code) {
return parser.parse(lexer.tokenize(code));
};
});
define('ace/mode/coffee/lexer', ['require', 'exports', 'module' , 'ace/mode/coffee/rewriter', 'ace/mode/coffee/helpers'], function(require, exports, module) {
// Generated by CoffeeScript 1.2.1-pre
var BOOL, CALLABLE, CODE, COFFEE_ALIASES, COFFEE_ALIAS_MAP, COFFEE_KEYWORDS, COMMENT, COMPARE, COMPOUND_ASSIGN, HEREDOC, HEREDOC_ILLEGAL, HEREDOC_INDENT, HEREGEX, HEREGEX_OMIT, IDENTIFIER, INDEXABLE, INVERSES, JSTOKEN, JS_FORBIDDEN, JS_KEYWORDS, LINE_BREAK, LINE_CONTINUER, LOGIC, Lexer, MATH, MULTILINER, MULTI_DENT, NOT_REGEX, NOT_SPACED_REGEX, NUMBER, OPERATOR, REGEX, RELATION, RESERVED, Rewriter, SHIFT, SIMPLESTR, STRICT_PROSCRIBED, TRAILING_SPACES, UNARY, WHITESPACE, compact, count, key, last, starts, _ref, _ref1,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
_ref = require('./rewriter'), Rewriter = _ref.Rewriter, INVERSES = _ref.INVERSES;
_ref1 = require('./helpers'), count = _ref1.count, starts = _ref1.starts, compact = _ref1.compact, last = _ref1.last;
exports.Lexer = Lexer = (function() {
Lexer.name = 'Lexer';
function Lexer() {}
Lexer.prototype.tokenize = function(code, opts) {
var i, tag;
if (opts == null) opts = {};
if (WHITESPACE.test(code)) code = "\n" + code;
code = code.replace(/\r/g, '').replace(TRAILING_SPACES, '');
this.code = code;
this.line = opts.line || 0;
this.indent = 0;
this.indebt = 0;
this.outdebt = 0;
this.indents = [];
this.ends = [];
this.tokens = [];
i = 0;
while (this.chunk = code.slice(i)) {
i += this.identifierToken() || this.commentToken() || this.whitespaceToken() || this.lineToken() || this.heredocToken() || this.stringToken() || this.numberToken() || this.regexToken() || this.jsToken() || this.literalToken();
}
this.closeIndentation();
if (tag = this.ends.pop()) this.error("missing " + tag);
if (opts.rewrite === false) return this.tokens;
return (new Rewriter).rewrite(this.tokens);
};
Lexer.prototype.identifierToken = function() {
var colon, forcedIdentifier, id, input, match, prev, tag, _ref2, _ref3;
if (!(match = IDENTIFIER.exec(this.chunk))) return 0;
input = match[0], id = match[1], colon = match[2];
if (id === 'own' && this.tag() === 'FOR') {
this.token('OWN', id);
return id.length;
}
forcedIdentifier = colon || (prev = last(this.tokens)) && (((_ref2 = prev[0]) === '.' || _ref2 === '?.' || _ref2 === '::') || !prev.spaced && prev[0] === '@');
tag = 'IDENTIFIER';
if (!forcedIdentifier && (__indexOf.call(JS_KEYWORDS, id) >= 0 || __indexOf.call(COFFEE_KEYWORDS, id) >= 0)) {
tag = id.toUpperCase();
if (tag === 'WHEN' && (_ref3 = this.tag(), __indexOf.call(LINE_BREAK, _ref3) >= 0)) {
tag = 'LEADING_WHEN';
} else if (tag === 'FOR') {
this.seenFor = true;
} else if (tag === 'UNLESS') {
tag = 'IF';
} else if (__indexOf.call(UNARY, tag) >= 0) {
tag = 'UNARY';
} else if (__indexOf.call(RELATION, tag) >= 0) {
if (tag !== 'INSTANCEOF' && this.seenFor) {
tag = 'FOR' + tag;
this.seenFor = false;
} else {
tag = 'RELATION';
if (this.value() === '!') {
this.tokens.pop();
id = '!' + id;
}
}
}
}
if (__indexOf.call(JS_FORBIDDEN, id) >= 0) {
if (forcedIdentifier) {
tag = 'IDENTIFIER';
id = new String(id);
id.reserved = true;
} else if (__indexOf.call(RESERVED, id) >= 0) {
this.error("reserved word \"" + id + "\"");
}
}
if (!forcedIdentifier) {
if (__indexOf.call(COFFEE_ALIASES, id) >= 0) id = COFFEE_ALIAS_MAP[id];
tag = (function() {
switch (id) {
case '!':
return 'UNARY';
case '==':
case '!=':
return 'COMPARE';
case '&&':
case '||':
return 'LOGIC';
case 'true':
case 'false':
case 'null':
case 'undefined':
return 'BOOL';
case 'break':
case 'continue':
return 'STATEMENT';
default:
return tag;
}
})();
}
this.token(tag, id);
if (colon) this.token(':', ':');
return input.length;
};
Lexer.prototype.numberToken = function() {
var binaryLiteral, lexedLength, match, number, octalLiteral;
if (!(match = NUMBER.exec(this.chunk))) return 0;
number = match[0];
if (/E/.test(number)) {
this.error("exponential notation '" + number + "' must be indicated with a lowercase 'e'");
} else if (/[BOX]/.test(number)) {
this.error("radix prefix '" + number + "' must be lowercase");
} else if (/^0[89]/.test(number)) {
this.error("decimal literal '" + number + "' must not be prefixed with '0'");
} else if (/^0[0-7]/.test(number)) {
this.error("octal literal '" + number + "' must be prefixed with '0o'");
}
lexedLength = number.length;
if (octalLiteral = /0o([0-7]+)/.exec(number)) {
number = (parseInt(octalLiteral[1], 8)).toString();
}
if (binaryLiteral = /0b([01]+)/.exec(number)) {
number = (parseInt(binaryLiteral[1], 2)).toString();
}
this.token('NUMBER', number);
return lexedLength;
};
Lexer.prototype.stringToken = function() {
var match, octalEsc, string;
switch (this.chunk.charAt(0)) {
case "'":
if (!(match = SIMPLESTR.exec(this.chunk))) return 0;
this.token('STRING', (string = match[0]).replace(MULTILINER, '\\\n'));
break;
case '"':
if (!(string = this.balancedString(this.chunk, '"'))) return 0;
if (0 < string.indexOf('#{', 1)) {
this.interpolateString(string.slice(1, -1));
} else {
this.token('STRING', this.escapeLines(string));
}
break;
default:
return 0;
}
if (octalEsc = /^(?:\\.|[^\\])*\\[0-7]/.test(string)) {
this.error("octal escape sequences " + string + " are not allowed");
}
this.line += count(string, '\n');
return string.length;
};
Lexer.prototype.heredocToken = function() {
var doc, heredoc, match, quote;
if (!(match = HEREDOC.exec(this.chunk))) return 0;
heredoc = match[0];
quote = heredoc.charAt(0);
doc = this.sanitizeHeredoc(match[2], {
quote: quote,
indent: null
});
if (quote === '"' && 0 <= doc.indexOf('#{')) {
this.interpolateString(doc, {
heredoc: true
});
} else {
this.token('STRING', this.makeString(doc, quote, true));
}
this.line += count(heredoc, '\n');
return heredoc.length;
};
Lexer.prototype.commentToken = function() {
var comment, here, match;
if (!(match = this.chunk.match(COMMENT))) return 0;
comment = match[0], here = match[1];
if (here) {
this.token('HERECOMMENT', this.sanitizeHeredoc(here, {
herecomment: true,
indent: Array(this.indent + 1).join(' ')
}));
}
this.line += count(comment, '\n');
return comment.length;
};
Lexer.prototype.jsToken = function() {
var match, script;
if (!(this.chunk.charAt(0) === '`' && (match = JSTOKEN.exec(this.chunk)))) {
return 0;
}
this.token('JS', (script = match[0]).slice(1, -1));
return script.length;
};
Lexer.prototype.regexToken = function() {
var flags, length, match, prev, regex, _ref2, _ref3;
if (this.chunk.charAt(0) !== '/') return 0;
if (match = HEREGEX.exec(this.chunk)) {
length = this.heregexToken(match);
this.line += count(match[0], '\n');
return length;
}
prev = last(this.tokens);
if (prev && (_ref2 = prev[0], __indexOf.call((prev.spaced ? NOT_REGEX : NOT_SPACED_REGEX), _ref2) >= 0)) {
return 0;
}
if (!(match = REGEX.exec(this.chunk))) return 0;
_ref3 = match, match = _ref3[0], regex = _ref3[1], flags = _ref3[2];
if (regex.slice(0, 2) === '/*') {
this.error('regular expressions cannot begin with `*`');
}
if (regex === '//') regex = '/(?:)/';
this.token('REGEX', "" + regex + flags);
return match.length;
};
Lexer.prototype.heregexToken = function(match) {
var body, flags, heregex, re, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4, _ref5;
heregex = match[0], body = match[1], flags = match[2];
if (0 > body.indexOf('#{')) {
re = body.replace(HEREGEX_OMIT, '').replace(/\//g, '\\/');
if (re.match(/^\*/)) {
this.error('regular expressions cannot begin with `*`');
}
this.token('REGEX', "/" + (re || '(?:)') + "/" + flags);
return heregex.length;
}
this.token('IDENTIFIER', 'RegExp');
this.tokens.push(['CALL_START', '(']);
tokens = [];
_ref2 = this.interpolateString(body, {
regex: true
});
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
_ref3 = _ref2[_i], tag = _ref3[0], value = _ref3[1];
if (tag === 'TOKENS') {
tokens.push.apply(tokens, value);
} else {
if (!(value = value.replace(HEREGEX_OMIT, ''))) continue;
value = value.replace(/\\/g, '\\\\');
tokens.push(['STRING', this.makeString(value, '"', true)]);
}
tokens.push(['+', '+']);
}
tokens.pop();
if (((_ref4 = tokens[0]) != null ? _ref4[0] : void 0) !== 'STRING') {
this.tokens.push(['STRING', '""'], ['+', '+']);
}
(_ref5 = this.tokens).push.apply(_ref5, tokens);
if (flags) this.tokens.push([',', ','], ['STRING', '"' + flags + '"']);
this.token(')', ')');
return heregex.length;
};
Lexer.prototype.lineToken = function() {
var diff, indent, match, noNewlines, prev, size;
if (!(match = MULTI_DENT.exec(this.chunk))) return 0;
indent = match[0];
this.line += count(indent, '\n');
this.seenFor = false;
prev = last(this.tokens, 1);
size = indent.length - 1 - indent.lastIndexOf('\n');
noNewlines = this.unfinished();
if (size - this.indebt === this.indent) {
if (noNewlines) {
this.suppressNewlines();
} else {
this.newlineToken();
}
return indent.length;
}
if (size > this.indent) {
if (noNewlines) {
this.indebt = size - this.indent;
this.suppressNewlines();
return indent.length;
}
diff = size - this.indent + this.outdebt;
this.token('INDENT', diff);
this.indents.push(diff);
this.ends.push('OUTDENT');
this.outdebt = this.indebt = 0;
} else {
this.indebt = 0;
this.outdentToken(this.indent - size, noNewlines);
}
this.indent = size;
return indent.length;
};
Lexer.prototype.outdentToken = function(moveOut, noNewlines) {
var dent, len;
while (moveOut > 0) {
len = this.indents.length - 1;
if (this.indents[len] === void 0) {
moveOut = 0;
} else if (this.indents[len] === this.outdebt) {
moveOut -= this.outdebt;
this.outdebt = 0;
} else if (this.indents[len] < this.outdebt) {
this.outdebt -= this.indents[len];
moveOut -= this.indents[len];
} else {
dent = this.indents.pop() - this.outdebt;
moveOut -= dent;
this.outdebt = 0;
this.pair('OUTDENT');
this.token('OUTDENT', dent);
}
}
if (dent) this.outdebt -= moveOut;
while (this.value() === ';') {
this.tokens.pop();
}
if (!(this.tag() === 'TERMINATOR' || noNewlines)) {
this.token('TERMINATOR', '\n');
}
return this;
};
Lexer.prototype.whitespaceToken = function() {
var match, nline, prev;
if (!((match = WHITESPACE.exec(this.chunk)) || (nline = this.chunk.charAt(0) === '\n'))) {
return 0;
}
prev = last(this.tokens);
if (prev) prev[match ? 'spaced' : 'newLine'] = true;
if (match) {
return match[0].length;
} else {
return 0;
}
};
Lexer.prototype.newlineToken = function() {
while (this.value() === ';') {
this.tokens.pop();
}
if (this.tag() !== 'TERMINATOR') this.token('TERMINATOR', '\n');
return this;
};
Lexer.prototype.suppressNewlines = function() {
if (this.value() === '\\') this.tokens.pop();
return this;
};
Lexer.prototype.literalToken = function() {
var match, prev, tag, value, _ref2, _ref3, _ref4, _ref5;
if (match = OPERATOR.exec(this.chunk)) {
value = match[0];
if (CODE.test(value)) this.tagParameters();
} else {
value = this.chunk.charAt(0);
}
tag = value;
prev = last(this.tokens);
if (value === '=' && prev) {
if (!prev[1].reserved && (_ref2 = prev[1], __indexOf.call(JS_FORBIDDEN, _ref2) >= 0)) {
this.error("reserved word \"" + (this.value()) + "\" can't be assigned");
}
if ((_ref3 = prev[1]) === '||' || _ref3 === '&&') {
prev[0] = 'COMPOUND_ASSIGN';
prev[1] += '=';
return value.length;
}
}
if (value === ';') {
this.seenFor = false;
tag = 'TERMINATOR';
} else if (__indexOf.call(MATH, value) >= 0) {
tag = 'MATH';
} else if (__indexOf.call(COMPARE, value) >= 0) {
tag = 'COMPARE';
} else if (__indexOf.call(COMPOUND_ASSIGN, value) >= 0) {
tag = 'COMPOUND_ASSIGN';
} else if (__indexOf.call(UNARY, value) >= 0) {
tag = 'UNARY';
} else if (__indexOf.call(SHIFT, value) >= 0) {
tag = 'SHIFT';
} else if (__indexOf.call(LOGIC, value) >= 0 || value === '?' && (prev != null ? prev.spaced : void 0)) {
tag = 'LOGIC';
} else if (prev && !prev.spaced) {
if (value === '(' && (_ref4 = prev[0], __indexOf.call(CALLABLE, _ref4) >= 0)) {
if (prev[0] === '?') prev[0] = 'FUNC_EXIST';
tag = 'CALL_START';
} else if (value === '[' && (_ref5 = prev[0], __indexOf.call(INDEXABLE, _ref5) >= 0)) {
tag = 'INDEX_START';
switch (prev[0]) {
case '?':
prev[0] = 'INDEX_SOAK';
}
}
}
switch (value) {
case '(':
case '{':
case '[':
this.ends.push(INVERSES[value]);
break;
case ')':
case '}':
case ']':
this.pair(value);
}
this.token(tag, value);
return value.length;
};
Lexer.prototype.sanitizeHeredoc = function(doc, options) {
var attempt, herecomment, indent, match, _ref2;
indent = options.indent, herecomment = options.herecomment;
if (herecomment) {
if (HEREDOC_ILLEGAL.test(doc)) {
this.error("block comment cannot contain \"*/\", starting");
}
if (doc.indexOf('\n') <= 0) return doc;
} else {
while (match = HEREDOC_INDENT.exec(doc)) {
attempt = match[1];
if (indent === null || (0 < (_ref2 = attempt.length) && _ref2 < indent.length)) {
indent = attempt;
}
}
}
if (indent) doc = doc.replace(RegExp("\\n" + indent, "g"), '\n');
if (!herecomment) doc = doc.replace(/^\n/, '');
return doc;
};
Lexer.prototype.tagParameters = function() {
var i, stack, tok, tokens;
if (this.tag() !== ')') return this;
stack = [];
tokens = this.tokens;
i = tokens.length;
tokens[--i][0] = 'PARAM_END';
while (tok = tokens[--i]) {
switch (tok[0]) {
case ')':
stack.push(tok);
break;
case '(':
case 'CALL_START':
if (stack.length) {
stack.pop();
} else if (tok[0] === '(') {
tok[0] = 'PARAM_START';
return this;
} else {
return this;
}
}
}
return this;
};
Lexer.prototype.closeIndentation = function() {
return this.outdentToken(this.indent);
};
Lexer.prototype.balancedString = function(str, end) {
var continueCount, i, letter, match, prev, stack, _i, _ref2;
continueCount = 0;
stack = [end];
for (i = _i = 1, _ref2 = str.length; 1 <= _ref2 ? _i < _ref2 : _i > _ref2; i = 1 <= _ref2 ? ++_i : --_i) {
if (continueCount) {
--continueCount;
continue;
}
switch (letter = str.charAt(i)) {
case '\\':
++continueCount;
continue;
case end:
stack.pop();
if (!stack.length) return str.slice(0, i + 1 || 9e9);
end = stack[stack.length - 1];
continue;
}
if (end === '}' && (letter === '"' || letter === "'")) {
stack.push(end = letter);
} else if (end === '}' && letter === '/' && (match = HEREGEX.exec(str.slice(i)) || REGEX.exec(str.slice(i)))) {
continueCount += match[0].length - 1;
} else if (end === '}' && letter === '{') {
stack.push(end = '}');
} else if (end === '"' && prev === '#' && letter === '{') {
stack.push(end = '}');
}
prev = letter;
}
return this.error("missing " + (stack.pop()) + ", starting");
};
Lexer.prototype.interpolateString = function(str, options) {
var expr, heredoc, i, inner, interpolated, len, letter, nested, pi, regex, tag, tokens, value, _i, _len, _ref2, _ref3, _ref4;
if (options == null) options = {};
heredoc = options.heredoc, regex = options.regex;
tokens = [];
pi = 0;
i = -1;
while (letter = str.charAt(i += 1)) {
if (letter === '\\') {
i += 1;
continue;
}
if (!(letter === '#' && str.charAt(i + 1) === '{' && (expr = this.balancedString(str.slice(i + 1), '}')))) {
continue;
}
if (pi < i) tokens.push(['NEOSTRING', str.slice(pi, i)]);
inner = expr.slice(1, -1);
if (inner.length) {
nested = new Lexer().tokenize(inner, {
line: this.line,
rewrite: false
});
nested.pop();
if (((_ref2 = nested[0]) != null ? _ref2[0] : void 0) === 'TERMINATOR') {
nested.shift();
}
if (len = nested.length) {
if (len > 1) {
nested.unshift(['(', '(', this.line]);
nested.push([')', ')', this.line]);
}
tokens.push(['TOKENS', nested]);
}
}
i += expr.length;
pi = i + 1;
}
if ((i > pi && pi < str.length)) tokens.push(['NEOSTRING', str.slice(pi)]);
if (regex) return tokens;
if (!tokens.length) return this.token('STRING', '""');
if (tokens[0][0] !== 'NEOSTRING') tokens.unshift(['', '']);
if (interpolated = tokens.length > 1) this.token('(', '(');
for (i = _i = 0, _len = tokens.length; _i < _len; i = ++_i) {
_ref3 = tokens[i], tag = _ref3[0], value = _ref3[1];
if (i) this.token('+', '+');
if (tag === 'TOKENS') {
(_ref4 = this.tokens).push.apply(_ref4, value);
} else {
this.token('STRING', this.makeString(value, '"', heredoc));
}
}
if (interpolated) this.token(')', ')');
return tokens;
};
Lexer.prototype.pair = function(tag) {
var size, wanted;
if (tag !== (wanted = last(this.ends))) {
if ('OUTDENT' !== wanted) this.error("unmatched " + tag);
this.indent -= size = last(this.indents);
this.outdentToken(size, true);
return this.pair(tag);
}
return this.ends.pop();
};
Lexer.prototype.token = function(tag, value) {
return this.tokens.push([tag, value, this.line]);
};
Lexer.prototype.tag = function(index, tag) {
var tok;
return (tok = last(this.tokens, index)) && (tag ? tok[0] = tag : tok[0]);
};
Lexer.prototype.value = function(index, val) {
var tok;
return (tok = last(this.tokens, index)) && (val ? tok[1] = val : tok[1]);
};
Lexer.prototype.unfinished = function() {
var _ref2;
return LINE_CONTINUER.test(this.chunk) || ((_ref2 = this.tag()) === '\\' || _ref2 === '.' || _ref2 === '?.' || _ref2 === 'UNARY' || _ref2 === 'MATH' || _ref2 === '+' || _ref2 === '-' || _ref2 === 'SHIFT' || _ref2 === 'RELATION' || _ref2 === 'COMPARE' || _ref2 === 'LOGIC' || _ref2 === 'THROW' || _ref2 === 'EXTENDS');
};
Lexer.prototype.escapeLines = function(str, heredoc) {
return str.replace(MULTILINER, heredoc ? '\\n' : '');
};
Lexer.prototype.makeString = function(body, quote, heredoc) {
if (!body) return quote + quote;
body = body.replace(/\\([\s\S])/g, function(match, contents) {
if (contents === '\n' || contents === quote) {
return contents;
} else {
return match;
}
});
body = body.replace(RegExp("" + quote, "g"), '\\$&');
return quote + this.escapeLines(body, heredoc) + quote;
};
Lexer.prototype.error = function(message) {
throw SyntaxError("" + message + " on line " + (this.line + 1));
};
return Lexer;
})();
JS_KEYWORDS = ['true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super'];
COFFEE_KEYWORDS = ['undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when'];
COFFEE_ALIAS_MAP = {
and: '&&',
or: '||',
is: '==',
isnt: '!=',
not: '!',
yes: 'true',
no: 'false',
on: 'true',
off: 'false'
};
COFFEE_ALIASES = (function() {
var _results;
_results = [];
for (key in COFFEE_ALIAS_MAP) {
_results.push(key);
}
return _results;
})();
COFFEE_KEYWORDS = COFFEE_KEYWORDS.concat(COFFEE_ALIASES);
RESERVED = ['case', 'default', 'function', 'var', 'void', 'with', 'const', 'let', 'enum', 'export', 'import', 'native', '__hasProp', '__extends', '__slice', '__bind', '__indexOf', 'implements', 'interface', 'let', 'package', 'private', 'protected', 'public', 'static', 'yield'];
STRICT_PROSCRIBED = ['arguments', 'eval'];
JS_FORBIDDEN = JS_KEYWORDS.concat(RESERVED).concat(STRICT_PROSCRIBED);
exports.RESERVED = RESERVED.concat(JS_KEYWORDS).concat(COFFEE_KEYWORDS).concat(STRICT_PROSCRIBED);
exports.STRICT_PROSCRIBED = STRICT_PROSCRIBED;
IDENTIFIER = /^([$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)([^\n\S]*:(?!:))?/;
NUMBER = /^0b[01]+|^0o[0-7]+|^0x[\da-f]+|^\d*\.?\d+(?:e[+-]?\d+)?/i;
HEREDOC = /^("""|''')([\s\S]*?)(?:\n[^\n\S]*)?\1/;
OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;
WHITESPACE = /^[^\n\S]+/;
COMMENT = /^###([^#][\s\S]*?)(?:###[^\n\S]*|(?:###)?$)|^(?:\s*#(?!##[^#]).*)+/;
CODE = /^[-=]>/;
MULTI_DENT = /^(?:\n[^\n\S]*)+/;
SIMPLESTR = /^'[^\\']*(?:\\.[^\\']*)*'/;
JSTOKEN = /^`[^\\`]*(?:\\.[^\\`]*)*`/;
REGEX = /^(\/(?![\s=])[^[\/\n\\]*(?:(?:\\[\s\S]|\[[^\]\n\\]*(?:\\[\s\S][^\]\n\\]*)*])[^[\/\n\\]*)*\/)([imgy]{0,4})(?!\w)/;
HEREGEX = /^\/{3}([\s\S]+?)\/{3}([imgy]{0,4})(?!\w)/;
HEREGEX_OMIT = /\s+(?:#.*)?/g;
MULTILINER = /\n/g;
HEREDOC_INDENT = /\n+([^\n\S]*)/g;
HEREDOC_ILLEGAL = /\*\//;
LINE_CONTINUER = /^\s*(?:,|\??\.(?![.\d])|::)/;
TRAILING_SPACES = /\s+$/;
COMPOUND_ASSIGN = ['-=', '+=', '/=', '*=', '%=', '||=', '&&=', '?=', '<<=', '>>=', '>>>=', '&=', '^=', '|='];
UNARY = ['!', '~', 'NEW', 'TYPEOF', 'DELETE', 'DO'];
LOGIC = ['&&', '||', '&', '|', '^'];
SHIFT = ['<<', '>>', '>>>'];
COMPARE = ['==', '!=', '<', '>', '<=', '>='];
MATH = ['*', '/', '%'];
RELATION = ['IN', 'OF', 'INSTANCEOF'];
BOOL = ['TRUE', 'FALSE', 'NULL', 'UNDEFINED'];
NOT_REGEX = ['NUMBER', 'REGEX', 'BOOL', '++', '--', ']'];
NOT_SPACED_REGEX = NOT_REGEX.concat(')', '}', 'THIS', 'IDENTIFIER', 'STRING');
CALLABLE = ['IDENTIFIER', 'STRING', 'REGEX', ')', ']', '}', '?', '::', '@', 'THIS', 'SUPER'];
INDEXABLE = CALLABLE.concat('NUMBER', 'BOOL');
LINE_BREAK = ['INDENT', 'OUTDENT', 'TERMINATOR'];
});
define('ace/mode/coffee/rewriter', ['require', 'exports', 'module' ], function(require, exports, module) {
// Generated by CoffeeScript 1.2.1-pre
var BALANCED_PAIRS, EXPRESSION_CLOSE, EXPRESSION_END, EXPRESSION_START, IMPLICIT_BLOCK, IMPLICIT_CALL, IMPLICIT_END, IMPLICIT_FUNC, IMPLICIT_UNSPACED_CALL, INVERSES, LINEBREAKS, SINGLE_CLOSERS, SINGLE_LINERS, left, rite, _i, _len, _ref,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__slice = [].slice;
exports.Rewriter = (function() {
Rewriter.name = 'Rewriter';
function Rewriter() {}
Rewriter.prototype.rewrite = function(tokens) {
this.tokens = tokens;
this.removeLeadingNewlines();
this.removeMidExpressionNewlines();
this.closeOpenCalls();
this.closeOpenIndexes();
this.addImplicitIndentation();
this.tagPostfixConditionals();
this.addImplicitBraces();
this.addImplicitParentheses();
return this.tokens;
};
Rewriter.prototype.scanTokens = function(block) {
var i, token, tokens;
tokens = this.tokens;
i = 0;
while (token = tokens[i]) {
i += block.call(this, token, i, tokens);
}
return true;
};
Rewriter.prototype.detectEnd = function(i, condition, action) {
var levels, token, tokens, _ref, _ref1;
tokens = this.tokens;
levels = 0;
while (token = tokens[i]) {
if (levels === 0 && condition.call(this, token, i)) {
return action.call(this, token, i);
}
if (!token || levels < 0) return action.call(this, token, i - 1);
if (_ref = token[0], __indexOf.call(EXPRESSION_START, _ref) >= 0) {
levels += 1;
} else if (_ref1 = token[0], __indexOf.call(EXPRESSION_END, _ref1) >= 0) {
levels -= 1;
}
i += 1;
}
return i - 1;
};
Rewriter.prototype.removeLeadingNewlines = function() {
var i, tag, _i, _len, _ref;
_ref = this.tokens;
for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
tag = _ref[i][0];
if (tag !== 'TERMINATOR') break;
}
if (i) return this.tokens.splice(0, i);
};
Rewriter.prototype.removeMidExpressionNewlines = function() {
return this.scanTokens(function(token, i, tokens) {
var _ref;
if (!(token[0] === 'TERMINATOR' && (_ref = this.tag(i + 1), __indexOf.call(EXPRESSION_CLOSE, _ref) >= 0))) {
return 1;
}
tokens.splice(i, 1);
return 0;
});
};
Rewriter.prototype.closeOpenCalls = function() {
var action, condition;
condition = function(token, i) {
var _ref;
return ((_ref = token[0]) === ')' || _ref === 'CALL_END') || token[0] === 'OUTDENT' && this.tag(i - 1) === ')';
};
action = function(token, i) {
return this.tokens[token[0] === 'OUTDENT' ? i - 1 : i][0] = 'CALL_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'CALL_START') this.detectEnd(i + 1, condition, action);
return 1;
});
};
Rewriter.prototype.closeOpenIndexes = function() {
var action, condition;
condition = function(token, i) {
var _ref;
return (_ref = token[0]) === ']' || _ref === 'INDEX_END';
};
action = function(token, i) {
return token[0] = 'INDEX_END';
};
return this.scanTokens(function(token, i) {
if (token[0] === 'INDEX_START') this.detectEnd(i + 1, condition, action);
return 1;
});
};
Rewriter.prototype.addImplicitBraces = function() {
var action, condition, sameLine, stack, start, startIndent, startsLine;
stack = [];
start = null;
startsLine = null;
sameLine = true;
startIndent = 0;
condition = function(token, i) {
var one, tag, three, two, _ref, _ref1;
_ref = this.tokens.slice(i + 1, (i + 3) + 1 || 9e9), one = _ref[0], two = _ref[1], three = _ref[2];
if ('HERECOMMENT' === (one != null ? one[0] : void 0)) return false;
tag = token[0];
if (__indexOf.call(LINEBREAKS, tag) >= 0) sameLine = false;
return (((tag === 'TERMINATOR' || tag === 'OUTDENT') || (__indexOf.call(IMPLICIT_END, tag) >= 0 && sameLine)) && ((!startsLine && this.tag(i - 1) !== ',') || !((two != null ? two[0] : void 0) === ':' || (one != null ? one[0] : void 0) === '@' && (three != null ? three[0] : void 0) === ':'))) || (tag === ',' && one && ((_ref1 = one[0]) !== 'IDENTIFIER' && _ref1 !== 'NUMBER' && _ref1 !== 'STRING' && _ref1 !== '@' && _ref1 !== 'TERMINATOR' && _ref1 !== 'OUTDENT'));
};
action = function(token, i) {
var tok;
tok = this.generate('}', '}', token[2]);
return this.tokens.splice(i, 0, tok);
};
return this.scanTokens(function(token, i, tokens) {
var ago, idx, prevTag, tag, tok, value, _ref, _ref1;
if (_ref = (tag = token[0]), __indexOf.call(EXPRESSION_START, _ref) >= 0) {
stack.push([(tag === 'INDENT' && this.tag(i - 1) === '{' ? '{' : tag), i]);
return 1;
}
if (__indexOf.call(EXPRESSION_END, tag) >= 0) {
start = stack.pop();
return 1;
}
if (!(tag === ':' && ((ago = this.tag(i - 2)) === ':' || ((_ref1 = stack[stack.length - 1]) != null ? _ref1[0] : void 0) !== '{'))) {
return 1;
}
sameLine = true;
stack.push(['{']);
idx = ago === '@' ? i - 2 : i - 1;
while (this.tag(idx - 2) === 'HERECOMMENT') {
idx -= 2;
}
prevTag = this.tag(idx - 1);
startsLine = !prevTag || (__indexOf.call(LINEBREAKS, prevTag) >= 0);
value = new String('{');
value.generated = true;
tok = this.generate('{', value, token[2]);
tokens.splice(idx, 0, tok);
this.detectEnd(i + 2, condition, action);
return 2;
});
};
Rewriter.prototype.addImplicitParentheses = function() {
var action, condition, noCall, seenControl, seenSingle;
noCall = seenSingle = seenControl = false;
condition = function(token, i) {
var post, tag, _ref, _ref1;
tag = token[0];
if (!seenSingle && token.fromThen) return true;
if (tag === 'IF' || tag === 'ELSE' || tag === 'CATCH' || tag === '->' || tag === '=>' || tag === 'CLASS') {
seenSingle = true;
}
if (tag === 'IF' || tag === 'ELSE' || tag === 'SWITCH' || tag === 'TRY' || tag === '=') {
seenControl = true;
}
if ((tag === '.' || tag === '?.' || tag === '::') && this.tag(i - 1) === 'OUTDENT') {
return true;
}
return !token.generated && this.tag(i - 1) !== ',' && (__indexOf.call(IMPLICIT_END, tag) >= 0 || (tag === 'INDENT' && !seenControl)) && (tag !== 'INDENT' || (((_ref = this.tag(i - 2)) !== 'CLASS' && _ref !== 'EXTENDS') && (_ref1 = this.tag(i - 1), __indexOf.call(IMPLICIT_BLOCK, _ref1) < 0) && !((post = this.tokens[i + 1]) && post.generated && post[0] === '{')));
};
action = function(token, i) {
return this.tokens.splice(i, 0, this.generate('CALL_END', ')', token[2]));
};
return this.scanTokens(function(token, i, tokens) {
var callObject, current, next, prev, tag, _ref, _ref1, _ref2;
tag = token[0];
if (tag === 'CLASS' || tag === 'IF' || tag === 'FOR' || tag === 'WHILE') {
noCall = true;
}
_ref = tokens.slice(i - 1, (i + 1) + 1 || 9e9), prev = _ref[0], current = _ref[1], next = _ref[2];
callObject = !noCall && tag === 'INDENT' && next && next.generated && next[0] === '{' && prev && (_ref1 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref1) >= 0);
seenSingle = false;
seenControl = false;
if (__indexOf.call(LINEBREAKS, tag) >= 0) noCall = false;
if (prev && !prev.spaced && tag === '?') token.call = true;
if (token.fromThen) return 1;
if (!(callObject || (prev != null ? prev.spaced : void 0) && (prev.call || (_ref2 = prev[0], __indexOf.call(IMPLICIT_FUNC, _ref2) >= 0)) && (__indexOf.call(IMPLICIT_CALL, tag) >= 0 || !(token.spaced || token.newLine) && __indexOf.call(IMPLICIT_UNSPACED_CALL, tag) >= 0))) {
return 1;
}
tokens.splice(i, 0, this.generate('CALL_START', '(', token[2]));
this.detectEnd(i + 1, condition, action);
if (prev[0] === '?') prev[0] = 'FUNC_EXIST';
return 2;
});
};
Rewriter.prototype.addImplicitIndentation = function() {
var action, condition, indent, outdent, starter;
starter = indent = outdent = null;
condition = function(token, i) {
var _ref;
return token[1] !== ';' && (_ref = token[0], __indexOf.call(SINGLE_CLOSERS, _ref) >= 0) && !(token[0] === 'ELSE' && (starter !== 'IF' && starter !== 'THEN'));
};
action = function(token, i) {
return this.tokens.splice((this.tag(i - 1) === ',' ? i - 1 : i), 0, outdent);
};
return this.scanTokens(function(token, i, tokens) {
var tag, _ref, _ref1;
tag = token[0];
if (tag === 'TERMINATOR' && this.tag(i + 1) === 'THEN') {
tokens.splice(i, 1);
return 0;
}
if (tag === 'ELSE' && this.tag(i - 1) !== 'OUTDENT') {
tokens.splice.apply(tokens, [i, 0].concat(__slice.call(this.indentation(token))));
return 2;
}
if (tag === 'CATCH' && ((_ref = this.tag(i + 2)) === 'OUTDENT' || _ref === 'TERMINATOR' || _ref === 'FINALLY')) {
tokens.splice.apply(tokens, [i + 2, 0].concat(__slice.call(this.indentation(token))));
return 4;
}
if (__indexOf.call(SINGLE_LINERS, tag) >= 0 && this.tag(i + 1) !== 'INDENT' && !(tag === 'ELSE' && this.tag(i + 1) === 'IF')) {
starter = tag;
_ref1 = this.indentation(token, true), indent = _ref1[0], outdent = _ref1[1];
if (starter === 'THEN') indent.fromThen = true;
tokens.splice(i + 1, 0, indent);
this.detectEnd(i + 2, condition, action);
if (tag === 'THEN') tokens.splice(i, 1);
return 1;
}
return 1;
});
};
Rewriter.prototype.tagPostfixConditionals = function() {
var action, condition, original;
original = null;
condition = function(token, i) {
var _ref;
return (_ref = token[0]) === 'TERMINATOR' || _ref === 'INDENT';
};
action = function(token, i) {
if (token[0] !== 'INDENT' || (token.generated && !token.fromThen)) {
return original[0] = 'POST_' + original[0];
}
};
return this.scanTokens(function(token, i) {
if (token[0] !== 'IF') return 1;
original = token;
this.detectEnd(i + 1, condition, action);
return 1;
});
};
Rewriter.prototype.indentation = function(token, implicit) {
var indent, outdent;
if (implicit == null) implicit = false;
indent = ['INDENT', 2, token[2]];
outdent = ['OUTDENT', 2, token[2]];
if (implicit) indent.generated = outdent.generated = true;
return [indent, outdent];
};
Rewriter.prototype.generate = function(tag, value, line) {
var tok;
tok = [tag, value, line];
tok.generated = true;
return tok;
};
Rewriter.prototype.tag = function(i) {
var _ref;
return (_ref = this.tokens[i]) != null ? _ref[0] : void 0;
};
return Rewriter;
})();
BALANCED_PAIRS = [['(', ')'], ['[', ']'], ['{', '}'], ['INDENT', 'OUTDENT'], ['CALL_START', 'CALL_END'], ['PARAM_START', 'PARAM_END'], ['INDEX_START', 'INDEX_END']];
exports.INVERSES = INVERSES = {};
EXPRESSION_START = [];
EXPRESSION_END = [];
for (_i = 0, _len = BALANCED_PAIRS.length; _i < _len; _i++) {
_ref = BALANCED_PAIRS[_i], left = _ref[0], rite = _ref[1];
EXPRESSION_START.push(INVERSES[rite] = left);
EXPRESSION_END.push(INVERSES[left] = rite);
}
EXPRESSION_CLOSE = ['CATCH', 'WHEN', 'ELSE', 'FINALLY'].concat(EXPRESSION_END);
IMPLICIT_FUNC = ['IDENTIFIER', 'SUPER', ')', 'CALL_END', ']', 'INDEX_END', '@', 'THIS'];
IMPLICIT_CALL = ['IDENTIFIER', 'NUMBER', 'STRING', 'JS', 'REGEX', 'NEW', 'PARAM_START', 'CLASS', 'IF', 'TRY', 'SWITCH', 'THIS', 'BOOL', 'UNARY', 'SUPER', '@', '->', '=>', '[', '(', '{', '--', '++'];
IMPLICIT_UNSPACED_CALL = ['+', '-'];
IMPLICIT_BLOCK = ['->', '=>', '{', '[', ','];
IMPLICIT_END = ['POST_IF', 'FOR', 'WHILE', 'UNTIL', 'WHEN', 'BY', 'LOOP', 'TERMINATOR'];
SINGLE_LINERS = ['ELSE', '->', '=>', 'TRY', 'FINALLY', 'THEN'];
SINGLE_CLOSERS = ['TERMINATOR', 'CATCH', 'FINALLY', 'ELSE', 'OUTDENT', 'LEADING_WHEN'];
LINEBREAKS = ['TERMINATOR', 'INDENT', 'OUTDENT'];
});
define('ace/mode/coffee/helpers', ['require', 'exports', 'module' ], function(require, exports, module) {
// Generated by CoffeeScript 1.2.1-pre
var extend, flatten;
exports.starts = function(string, literal, start) {
return literal === string.substr(start, literal.length);
};
exports.ends = function(string, literal, back) {
var len;
len = literal.length;
return literal === string.substr(string.length - len - (back || 0), len);
};
exports.compact = function(array) {
var item, _i, _len, _results;
_results = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
item = array[_i];
if (item) _results.push(item);
}
return _results;
};
exports.count = function(string, substr) {
var num, pos;
num = pos = 0;
if (!substr.length) return 1 / 0;
while (pos = 1 + string.indexOf(substr, pos)) {
num++;
}
return num;
};
exports.merge = function(options, overrides) {
return extend(extend({}, options), overrides);
};
extend = exports.extend = function(object, properties) {
var key, val;
for (key in properties) {
val = properties[key];
object[key] = val;
}
return object;
};
exports.flatten = flatten = function(array) {
var element, flattened, _i, _len;
flattened = [];
for (_i = 0, _len = array.length; _i < _len; _i++) {
element = array[_i];
if (element instanceof Array) {
flattened = flattened.concat(flatten(element));
} else {
flattened.push(element);
}
}
return flattened;
};
exports.del = function(obj, key) {
var val;
val = obj[key];
delete obj[key];
return val;
};
exports.last = function(array, back) {
return array[array.length - (back || 0) - 1];
};
});
define('ace/mode/coffee/parser', ['require', 'exports', 'module' ], function(require, exports, module) {
/* Jison generated parser */
undefined
var parser = {trace: function trace() { },
yy: {},
symbols_: {"error":2,"Root":3,"Body":4,"Block":5,"TERMINATOR":6,"Line":7,"Expression":8,"Statement":9,"Return":10,"Comment":11,"STATEMENT":12,"Value":13,"Invocation":14,"Code":15,"Operation":16,"Assign":17,"If":18,"Try":19,"While":20,"For":21,"Switch":22,"Class":23,"Throw":24,"INDENT":25,"OUTDENT":26,"Identifier":27,"IDENTIFIER":28,"AlphaNumeric":29,"NUMBER":30,"STRING":31,"Literal":32,"JS":33,"REGEX":34,"DEBUGGER":35,"BOOL":36,"Assignable":37,"=":38,"AssignObj":39,"ObjAssignable":40,":":41,"ThisProperty":42,"RETURN":43,"HERECOMMENT":44,"PARAM_START":45,"ParamList":46,"PARAM_END":47,"FuncGlyph":48,"->":49,"=>":50,"OptComma":51,",":52,"Param":53,"ParamVar":54,"...":55,"Array":56,"Object":57,"Splat":58,"SimpleAssignable":59,"Accessor":60,"Parenthetical":61,"Range":62,"This":63,".":64,"?.":65,"::":66,"Index":67,"INDEX_START":68,"IndexValue":69,"INDEX_END":70,"INDEX_SOAK":71,"Slice":72,"{":73,"AssignList":74,"}":75,"CLASS":76,"EXTENDS":77,"OptFuncExist":78,"Arguments":79,"SUPER":80,"FUNC_EXIST":81,"CALL_START":82,"CALL_END":83,"ArgList":84,"THIS":85,"@":86,"[":87,"]":88,"RangeDots":89,"..":90,"Arg":91,"SimpleArgs":92,"TRY":93,"Catch":94,"FINALLY":95,"CATCH":96,"THROW":97,"(":98,")":99,"WhileSource":100,"WHILE":101,"WHEN":102,"UNTIL":103,"Loop":104,"LOOP":105,"ForBody":106,"FOR":107,"ForStart":108,"ForSource":109,"ForVariables":110,"OWN":111,"ForValue":112,"FORIN":113,"FOROF":114,"BY":115,"SWITCH":116,"Whens":117,"ELSE":118,"When":119,"LEADING_WHEN":120,"IfBlock":121,"IF":122,"POST_IF":123,"UNARY":124,"-":125,"+":126,"--":127,"++":128,"?":129,"MATH":130,"SHIFT":131,"COMPARE":132,"LOGIC":133,"RELATION":134,"COMPOUND_ASSIGN":135,"$accept":0,"$end":1},
terminals_: {2:"error",6:"TERMINATOR",12:"STATEMENT",25:"INDENT",26:"OUTDENT",28:"IDENTIFIER",30:"NUMBER",31:"STRING",33:"JS",34:"REGEX",35:"DEBUGGER",36:"BOOL",38:"=",41:":",43:"RETURN",44:"HERECOMMENT",45:"PARAM_START",47:"PARAM_END",49:"->",50:"=>",52:",",55:"...",64:".",65:"?.",66:"::",68:"INDEX_START",70:"INDEX_END",71:"INDEX_SOAK",73:"{",75:"}",76:"CLASS",77:"EXTENDS",80:"SUPER",81:"FUNC_EXIST",82:"CALL_START",83:"CALL_END",85:"THIS",86:"@",87:"[",88:"]",90:"..",93:"TRY",95:"FINALLY",96:"CATCH",97:"THROW",98:"(",99:")",101:"WHILE",102:"WHEN",103:"UNTIL",105:"LOOP",107:"FOR",111:"OWN",113:"FORIN",114:"FOROF",115:"BY",116:"SWITCH",118:"ELSE",120:"LEADING_WHEN",122:"IF",123:"POST_IF",124:"UNARY",125:"-",126:"+",127:"--",128:"++",129:"?",130:"MATH",131:"SHIFT",132:"COMPARE",133:"LOGIC",134:"RELATION",135:"COMPOUND_ASSIGN"},
productions_: [0,[3,0],[3,1],[3,2],[4,1],[4,3],[4,2],[7,1],[7,1],[9,1],[9,1],[9,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[8,1],[5,2],[5,3],[27,1],[29,1],[29,1],[32,1],[32,1],[32,1],[32,1],[32,1],[17,3],[17,4],[17,5],[39,1],[39,3],[39,5],[39,1],[40,1],[40,1],[40,1],[10,2],[10,1],[11,1],[15,5],[15,2],[48,1],[48,1],[51,0],[51,1],[46,0],[46,1],[46,3],[53,1],[53,2],[53,3],[54,1],[54,1],[54,1],[54,1],[58,2],[59,1],[59,2],[59,2],[59,1],[37,1],[37,1],[37,1],[13,1],[13,1],[13,1],[13,1],[13,1],[60,2],[60,2],[60,2],[60,1],[60,1],[67,3],[67,2],[69,1],[69,1],[57,4],[74,0],[74,1],[74,3],[74,4],[74,6],[23,1],[23,2],[23,3],[23,4],[23,2],[23,3],[23,4],[23,5],[14,3],[14,3],[14,1],[14,2],[78,0],[78,1],[79,2],[79,4],[63,1],[63,1],[42,2],[56,2],[56,4],[89,1],[89,1],[62,5],[72,3],[72,2],[72,2],[72,1],[84,1],[84,3],[84,4],[84,4],[84,6],[91,1],[91,1],[92,1],[92,3],[19,2],[19,3],[19,4],[19,5],[94,3],[24,2],[61,3],[61,5],[100,2],[100,4],[100,2],[100,4],[20,2],[20,2],[20,2],[20,1],[104,2],[104,2],[21,2],[21,2],[21,2],[106,2],[106,2],[108,2],[108,3],[112,1],[112,1],[112,1],[110,1],[110,3],[109,2],[109,2],[109,4],[109,4],[109,4],[109,6],[109,6],[22,5],[22,7],[22,4],[22,6],[117,1],[117,2],[119,3],[119,4],[121,3],[121,5],[18,1],[18,3],[18,3],[18,3],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,2],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,3],[16,5],[16,3]],
performAction: function anonymous(yytext,yyleng,yylineno,yy,yystate,$$,_$) {
var $0 = $$.length - 1;
switch (yystate) {
case 1:return this.$ = new yy.Block;
break;
case 2:return this.$ = $$[$0];
break;
case 3:return this.$ = $$[$0-1];
break;
case 4:this.$ = yy.Block.wrap([$$[$0]]);
break;
case 5:this.$ = $$[$0-2].push($$[$0]);
break;
case 6:this.$ = $$[$0-1];
break;
case 7:this.$ = $$[$0];
break;
case 8:this.$ = $$[$0];
break;
case 9:this.$ = $$[$0];
break;
case 10:this.$ = $$[$0];
break;
case 11:this.$ = new yy.Literal($$[$0]);
break;
case 12:this.$ = $$[$0];
break;
case 13:this.$ = $$[$0];
break;
case 14:this.$ = $$[$0];
break;
case 15:this.$ = $$[$0];
break;
case 16:this.$ = $$[$0];
break;
case 17:this.$ = $$[$0];
break;
case 18:this.$ = $$[$0];
break;
case 19:this.$ = $$[$0];
break;
case 20:this.$ = $$[$0];
break;
case 21:this.$ = $$[$0];
break;
case 22:this.$ = $$[$0];
break;
case 23:this.$ = $$[$0];
break;
case 24:this.$ = new yy.Block;
break;
case 25:this.$ = $$[$0-1];
break;
case 26:this.$ = new yy.Literal($$[$0]);
break;
case 27:this.$ = new yy.Literal($$[$0]);
break;
case 28:this.$ = new yy.Literal($$[$0]);
break;
case 29:this.$ = $$[$0];
break;
case 30:this.$ = new yy.Literal($$[$0]);
break;
case 31:this.$ = new yy.Literal($$[$0]);
break;
case 32:this.$ = new yy.Literal($$[$0]);
break;
case 33:this.$ = (function () {
var val;
val = new yy.Literal($$[$0]);
if ($$[$0] === 'undefined') val.isUndefined = true;
return val;
}());
break;
case 34:this.$ = new yy.Assign($$[$0-2], $$[$0]);
break;
case 35:this.$ = new yy.Assign($$[$0-3], $$[$0]);
break;
case 36:this.$ = new yy.Assign($$[$0-4], $$[$0-1]);
break;
case 37:this.$ = new yy.Value($$[$0]);
break;
case 38:this.$ = new yy.Assign(new yy.Value($$[$0-2]), $$[$0], 'object');
break;
case 39:this.$ = new yy.Assign(new yy.Value($$[$0-4]), $$[$0-1], 'object');
break;
case 40:this.$ = $$[$0];
break;
case 41:this.$ = $$[$0];
break;
case 42:this.$ = $$[$0];
break;
case 43:this.$ = $$[$0];
break;
case 44:this.$ = new yy.Return($$[$0]);
break;
case 45:this.$ = new yy.Return;
break;
case 46:this.$ = new yy.Comment($$[$0]);
break;
case 47:this.$ = new yy.Code($$[$0-3], $$[$0], $$[$0-1]);
break;
case 48:this.$ = new yy.Code([], $$[$0], $$[$0-1]);
break;
case 49:this.$ = 'func';
break;
case 50:this.$ = 'boundfunc';
break;
case 51:this.$ = $$[$0];
break;
case 52:this.$ = $$[$0];
break;
case 53:this.$ = [];
break;
case 54:this.$ = [$$[$0]];
break;
case 55:this.$ = $$[$0-2].concat($$[$0]);
break;
case 56:this.$ = new yy.Param($$[$0]);
break;
case 57:this.$ = new yy.Param($$[$0-1], null, true);
break;
case 58:this.$ = new yy.Param($$[$0-2], $$[$0]);
break;
case 59:this.$ = $$[$0];
break;
case 60:this.$ = $$[$0];
break;
case 61:this.$ = $$[$0];
break;
case 62:this.$ = $$[$0];
break;
case 63:this.$ = new yy.Splat($$[$0-1]);
break;
case 64:this.$ = new yy.Value($$[$0]);
break;
case 65:this.$ = $$[$0-1].add($$[$0]);
break;
case 66:this.$ = new yy.Value($$[$0-1], [].concat($$[$0]));
break;
case 67:this.$ = $$[$0];
break;
case 68:this.$ = $$[$0];
break;
case 69:this.$ = new yy.Value($$[$0]);
break;
case 70:this.$ = new yy.Value($$[$0]);
break;
case 71:this.$ = $$[$0];
break;
case 72:this.$ = new yy.Value($$[$0]);
break;
case 73:this.$ = new yy.Value($$[$0]);
break;
case 74:this.$ = new yy.Value($$[$0]);
break;
case 75:this.$ = $$[$0];
break;
case 76:this.$ = new yy.Access($$[$0]);
break;
case 77:this.$ = new yy.Access($$[$0], 'soak');
break;
case 78:this.$ = [new yy.Access(new yy.Literal('prototype')), new yy.Access($$[$0])];
break;
case 79:this.$ = new yy.Access(new yy.Literal('prototype'));
break;
case 80:this.$ = $$[$0];
break;
case 81:this.$ = $$[$0-1];
break;
case 82:this.$ = yy.extend($$[$0], {
soak: true
});
break;
case 83:this.$ = new yy.Index($$[$0]);
break;
case 84:this.$ = new yy.Slice($$[$0]);
break;
case 85:this.$ = new yy.Obj($$[$0-2], $$[$0-3].generated);
break;
case 86:this.$ = [];
break;
case 87:this.$ = [$$[$0]];
break;
case 88:this.$ = $$[$0-2].concat($$[$0]);
break;
case 89:this.$ = $$[$0-3].concat($$[$0]);
break;
case 90:this.$ = $$[$0-5].concat($$[$0-2]);
break;
case 91:this.$ = new yy.Class;
break;
case 92:this.$ = new yy.Class(null, null, $$[$0]);
break;
case 93:this.$ = new yy.Class(null, $$[$0]);
break;
case 94:this.$ = new yy.Class(null, $$[$0-1], $$[$0]);
break;
case 95:this.$ = new yy.Class($$[$0]);
break;
case 96:this.$ = new yy.Class($$[$0-1], null, $$[$0]);
break;
case 97:this.$ = new yy.Class($$[$0-2], $$[$0]);
break;
case 98:this.$ = new yy.Class($$[$0-3], $$[$0-1], $$[$0]);
break;
case 99:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]);
break;
case 100:this.$ = new yy.Call($$[$0-2], $$[$0], $$[$0-1]);
break;
case 101:this.$ = new yy.Call('super', [new yy.Splat(new yy.Literal('arguments'))]);
break;
case 102:this.$ = new yy.Call('super', $$[$0]);
break;
case 103:this.$ = false;
break;
case 104:this.$ = true;
break;
case 105:this.$ = [];
break;
case 106:this.$ = $$[$0-2];
break;
case 107:this.$ = new yy.Value(new yy.Literal('this'));
break;
case 108:this.$ = new yy.Value(new yy.Literal('this'));
break;
case 109:this.$ = new yy.Value(new yy.Literal('this'), [new yy.Access($$[$0])], 'this');
break;
case 110:this.$ = new yy.Arr([]);
break;
case 111:this.$ = new yy.Arr($$[$0-2]);
break;
case 112:this.$ = 'inclusive';
break;
case 113:this.$ = 'exclusive';
break;
case 114:this.$ = new yy.Range($$[$0-3], $$[$0-1], $$[$0-2]);
break;
case 115:this.$ = new yy.Range($$[$0-2], $$[$0], $$[$0-1]);
break;
case 116:this.$ = new yy.Range($$[$0-1], null, $$[$0]);
break;
case 117:this.$ = new yy.Range(null, $$[$0], $$[$0-1]);
break;
case 118:this.$ = new yy.Range(null, null, $$[$0]);
break;
case 119:this.$ = [$$[$0]];
break;
case 120:this.$ = $$[$0-2].concat($$[$0]);
break;
case 121:this.$ = $$[$0-3].concat($$[$0]);
break;
case 122:this.$ = $$[$0-2];
break;
case 123:this.$ = $$[$0-5].concat($$[$0-2]);
break;
case 124:this.$ = $$[$0];
break;
case 125:this.$ = $$[$0];
break;
case 126:this.$ = $$[$0];
break;
case 127:this.$ = [].concat($$[$0-2], $$[$0]);
break;
case 128:this.$ = new yy.Try($$[$0]);
break;
case 129:this.$ = new yy.Try($$[$0-1], $$[$0][0], $$[$0][1]);
break;
case 130:this.$ = new yy.Try($$[$0-2], null, null, $$[$0]);
break;
case 131:this.$ = new yy.Try($$[$0-3], $$[$0-2][0], $$[$0-2][1], $$[$0]);
break;
case 132:this.$ = [$$[$0-1], $$[$0]];
break;
case 133:this.$ = new yy.Throw($$[$0]);
break;
case 134:this.$ = new yy.Parens($$[$0-1]);
break;
case 135:this.$ = new yy.Parens($$[$0-2]);
break;
case 136:this.$ = new yy.While($$[$0]);
break;
case 137:this.$ = new yy.While($$[$0-2], {
guard: $$[$0]
});
break;
case 138:this.$ = new yy.While($$[$0], {
invert: true
});
break;
case 139:this.$ = new yy.While($$[$0-2], {
invert: true,
guard: $$[$0]
});
break;
case 140:this.$ = $$[$0-1].addBody($$[$0]);
break;
case 141:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]]));
break;
case 142:this.$ = $$[$0].addBody(yy.Block.wrap([$$[$0-1]]));
break;
case 143:this.$ = $$[$0];
break;
case 144:this.$ = new yy.While(new yy.Literal('true')).addBody($$[$0]);
break;
case 145:this.$ = new yy.While(new yy.Literal('true')).addBody(yy.Block.wrap([$$[$0]]));
break;
case 146:this.$ = new yy.For($$[$0-1], $$[$0]);
break;
case 147:this.$ = new yy.For($$[$0-1], $$[$0]);
break;
case 148:this.$ = new yy.For($$[$0], $$[$0-1]);
break;
case 149:this.$ = {
source: new yy.Value($$[$0])
};
break;
case 150:this.$ = (function () {
$$[$0].own = $$[$0-1].own;
$$[$0].name = $$[$0-1][0];
$$[$0].index = $$[$0-1][1];
return $$[$0];
}());
break;
case 151:this.$ = $$[$0];
break;
case 152:this.$ = (function () {
$$[$0].own = true;
return $$[$0];
}());
break;
case 153:this.$ = $$[$0];
break;
case 154:this.$ = new yy.Value($$[$0]);
break;
case 155:this.$ = new yy.Value($$[$0]);
break;
case 156:this.$ = [$$[$0]];
break;
case 157:this.$ = [$$[$0-2], $$[$0]];
break;
case 158:this.$ = {
source: $$[$0]
};
break;
case 159:this.$ = {
source: $$[$0],
object: true
};
break;
case 160:this.$ = {
source: $$[$0-2],
guard: $$[$0]
};
break;
case 161:this.$ = {
source: $$[$0-2],
guard: $$[$0],
object: true
};
break;
case 162:this.$ = {
source: $$[$0-2],
step: $$[$0]
};
break;
case 163:this.$ = {
source: $$[$0-4],
guard: $$[$0-2],
step: $$[$0]
};
break;
case 164:this.$ = {
source: $$[$0-4],
step: $$[$0-2],
guard: $$[$0]
};
break;
case 165:this.$ = new yy.Switch($$[$0-3], $$[$0-1]);
break;
case 166:this.$ = new yy.Switch($$[$0-5], $$[$0-3], $$[$0-1]);
break;
case 167:this.$ = new yy.Switch(null, $$[$0-1]);
break;
case 168:this.$ = new yy.Switch(null, $$[$0-3], $$[$0-1]);
break;
case 169:this.$ = $$[$0];
break;
case 170:this.$ = $$[$0-1].concat($$[$0]);
break;
case 171:this.$ = [[$$[$0-1], $$[$0]]];
break;
case 172:this.$ = [[$$[$0-2], $$[$0-1]]];
break;
case 173:this.$ = new yy.If($$[$0-1], $$[$0], {
type: $$[$0-2]
});
break;
case 174:this.$ = $$[$0-4].addElse(new yy.If($$[$0-1], $$[$0], {
type: $$[$0-2]
}));
break;
case 175:this.$ = $$[$0];
break;
case 176:this.$ = $$[$0-2].addElse($$[$0]);
break;
case 177:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), {
type: $$[$0-1],
statement: true
});
break;
case 178:this.$ = new yy.If($$[$0], yy.Block.wrap([$$[$0-2]]), {
type: $$[$0-1],
statement: true
});
break;
case 179:this.$ = new yy.Op($$[$0-1], $$[$0]);
break;
case 180:this.$ = new yy.Op('-', $$[$0]);
break;
case 181:this.$ = new yy.Op('+', $$[$0]);
break;
case 182:this.$ = new yy.Op('--', $$[$0]);
break;
case 183:this.$ = new yy.Op('++', $$[$0]);
break;
case 184:this.$ = new yy.Op('--', $$[$0-1], null, true);
break;
case 185:this.$ = new yy.Op('++', $$[$0-1], null, true);
break;
case 186:this.$ = new yy.Existence($$[$0-1]);
break;
case 187:this.$ = new yy.Op('+', $$[$0-2], $$[$0]);
break;
case 188:this.$ = new yy.Op('-', $$[$0-2], $$[$0]);
break;
case 189:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
break;
case 190:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
break;
case 191:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
break;
case 192:this.$ = new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
break;
case 193:this.$ = (function () {
if ($$[$0-1].charAt(0) === '!') {
return new yy.Op($$[$0-1].slice(1), $$[$0-2], $$[$0]).invert();
} else {
return new yy.Op($$[$0-1], $$[$0-2], $$[$0]);
}
}());
break;
case 194:this.$ = new yy.Assign($$[$0-2], $$[$0], $$[$0-1]);
break;
case 195:this.$ = new yy.Assign($$[$0-4], $$[$0-1], $$[$0-3]);
break;
case 196:this.$ = new yy.Extends($$[$0-2], $$[$0]);
break;
}
},
table: [{1:[2,1],3:1,4:2,5:3,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[3]},{1:[2,2],6:[1,72]},{6:[1,73]},{1:[2,4],6:[2,4],26:[2,4],99:[2,4]},{4:75,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[1,74],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,7],6:[2,7],26:[2,7],99:[2,7],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,8],6:[2,8],26:[2,8],99:[2,8],100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,12],6:[2,12],25:[2,12],26:[2,12],47:[2,12],52:[2,12],55:[2,12],60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,12],71:[1,98],75:[2,12],78:90,81:[1,92],82:[2,103],83:[2,12],88:[2,12],90:[2,12],99:[2,12],101:[2,12],102:[2,12],103:[2,12],107:[2,12],115:[2,12],123:[2,12],125:[2,12],126:[2,12],129:[2,12],130:[2,12],131:[2,12],132:[2,12],133:[2,12],134:[2,12]},{1:[2,13],6:[2,13],25:[2,13],26:[2,13],47:[2,13],52:[2,13],55:[2,13],60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],70:[2,13],71:[1,98],75:[2,13],78:99,81:[1,92],82:[2,103],83:[2,13],88:[2,13],90:[2,13],99:[2,13],101:[2,13],102:[2,13],103:[2,13],107:[2,13],115:[2,13],123:[2,13],125:[2,13],126:[2,13],129:[2,13],130:[2,13],131:[2,13],132:[2,13],133:[2,13],134:[2,13]},{1:[2,14],6:[2,14],25:[2,14],26:[2,14],47:[2,14],52:[2,14],55:[2,14],70:[2,14],75:[2,14],83:[2,14],88:[2,14],90:[2,14],99:[2,14],101:[2,14],102:[2,14],103:[2,14],107:[2,14],115:[2,14],123:[2,14],125:[2,14],126:[2,14],129:[2,14],130:[2,14],131:[2,14],132:[2,14],133:[2,14],134:[2,14]},{1:[2,15],6:[2,15],25:[2,15],26:[2,15],47:[2,15],52:[2,15],55:[2,15],70:[2,15],75:[2,15],83:[2,15],88:[2,15],90:[2,15],99:[2,15],101:[2,15],102:[2,15],103:[2,15],107:[2,15],115:[2,15],123:[2,15],125:[2,15],126:[2,15],129:[2,15],130:[2,15],131:[2,15],132:[2,15],133:[2,15],134:[2,15]},{1:[2,16],6:[2,16],25:[2,16],26:[2,16],47:[2,16],52:[2,16],55:[2,16],70:[2,16],75:[2,16],83:[2,16],88:[2,16],90:[2,16],99:[2,16],101:[2,16],102:[2,16],103:[2,16],107:[2,16],115:[2,16],123:[2,16],125:[2,16],126:[2,16],129:[2,16],130:[2,16],131:[2,16],132:[2,16],133:[2,16],134:[2,16]},{1:[2,17],6:[2,17],25:[2,17],26:[2,17],47:[2,17],52:[2,17],55:[2,17],70:[2,17],75:[2,17],83:[2,17],88:[2,17],90:[2,17],99:[2,17],101:[2,17],102:[2,17],103:[2,17],107:[2,17],115:[2,17],123:[2,17],125:[2,17],126:[2,17],129:[2,17],130:[2,17],131:[2,17],132:[2,17],133:[2,17],134:[2,17]},{1:[2,18],6:[2,18],25:[2,18],26:[2,18],47:[2,18],52:[2,18],55:[2,18],70:[2,18],75:[2,18],83:[2,18],88:[2,18],90:[2,18],99:[2,18],101:[2,18],102:[2,18],103:[2,18],107:[2,18],115:[2,18],123:[2,18],125:[2,18],126:[2,18],129:[2,18],130:[2,18],131:[2,18],132:[2,18],133:[2,18],134:[2,18]},{1:[2,19],6:[2,19],25:[2,19],26:[2,19],47:[2,19],52:[2,19],55:[2,19],70:[2,19],75:[2,19],83:[2,19],88:[2,19],90:[2,19],99:[2,19],101:[2,19],102:[2,19],103:[2,19],107:[2,19],115:[2,19],123:[2,19],125:[2,19],126:[2,19],129:[2,19],130:[2,19],131:[2,19],132:[2,19],133:[2,19],134:[2,19]},{1:[2,20],6:[2,20],25:[2,20],26:[2,20],47:[2,20],52:[2,20],55:[2,20],70:[2,20],75:[2,20],83:[2,20],88:[2,20],90:[2,20],99:[2,20],101:[2,20],102:[2,20],103:[2,20],107:[2,20],115:[2,20],123:[2,20],125:[2,20],126:[2,20],129:[2,20],130:[2,20],131:[2,20],132:[2,20],133:[2,20],134:[2,20]},{1:[2,21],6:[2,21],25:[2,21],26:[2,21],47:[2,21],52:[2,21],55:[2,21],70:[2,21],75:[2,21],83:[2,21],88:[2,21],90:[2,21],99:[2,21],101:[2,21],102:[2,21],103:[2,21],107:[2,21],115:[2,21],123:[2,21],125:[2,21],126:[2,21],129:[2,21],130:[2,21],131:[2,21],132:[2,21],133:[2,21],134:[2,21]},{1:[2,22],6:[2,22],25:[2,22],26:[2,22],47:[2,22],52:[2,22],55:[2,22],70:[2,22],75:[2,22],83:[2,22],88:[2,22],90:[2,22],99:[2,22],101:[2,22],102:[2,22],103:[2,22],107:[2,22],115:[2,22],123:[2,22],125:[2,22],126:[2,22],129:[2,22],130:[2,22],131:[2,22],132:[2,22],133:[2,22],134:[2,22]},{1:[2,23],6:[2,23],25:[2,23],26:[2,23],47:[2,23],52:[2,23],55:[2,23],70:[2,23],75:[2,23],83:[2,23],88:[2,23],90:[2,23],99:[2,23],101:[2,23],102:[2,23],103:[2,23],107:[2,23],115:[2,23],123:[2,23],125:[2,23],126:[2,23],129:[2,23],130:[2,23],131:[2,23],132:[2,23],133:[2,23],134:[2,23]},{1:[2,9],6:[2,9],26:[2,9],99:[2,9],101:[2,9],103:[2,9],107:[2,9],123:[2,9]},{1:[2,10],6:[2,10],26:[2,10],99:[2,10],101:[2,10],103:[2,10],107:[2,10],123:[2,10]},{1:[2,11],6:[2,11],26:[2,11],99:[2,11],101:[2,11],103:[2,11],107:[2,11],123:[2,11]},{1:[2,71],6:[2,71],25:[2,71],26:[2,71],38:[1,101],47:[2,71],52:[2,71],55:[2,71],64:[2,71],65:[2,71],66:[2,71],68:[2,71],70:[2,71],71:[2,71],75:[2,71],81:[2,71],82:[2,71],83:[2,71],88:[2,71],90:[2,71],99:[2,71],101:[2,71],102:[2,71],103:[2,71],107:[2,71],115:[2,71],123:[2,71],125:[2,71],126:[2,71],129:[2,71],130:[2,71],131:[2,71],132:[2,71],133:[2,71],134:[2,71]},{1:[2,72],6:[2,72],25:[2,72],26:[2,72],47:[2,72],52:[2,72],55:[2,72],64:[2,72],65:[2,72],66:[2,72],68:[2,72],70:[2,72],71:[2,72],75:[2,72],81:[2,72],82:[2,72],83:[2,72],88:[2,72],90:[2,72],99:[2,72],101:[2,72],102:[2,72],103:[2,72],107:[2,72],115:[2,72],123:[2,72],125:[2,72],126:[2,72],129:[2,72],130:[2,72],131:[2,72],132:[2,72],133:[2,72],134:[2,72]},{1:[2,73],6:[2,73],25:[2,73],26:[2,73],47:[2,73],52:[2,73],55:[2,73],64:[2,73],65:[2,73],66:[2,73],68:[2,73],70:[2,73],71:[2,73],75:[2,73],81:[2,73],82:[2,73],83:[2,73],88:[2,73],90:[2,73],99:[2,73],101:[2,73],102:[2,73],103:[2,73],107:[2,73],115:[2,73],123:[2,73],125:[2,73],126:[2,73],129:[2,73],130:[2,73],131:[2,73],132:[2,73],133:[2,73],134:[2,73]},{1:[2,74],6:[2,74],25:[2,74],26:[2,74],47:[2,74],52:[2,74],55:[2,74],64:[2,74],65:[2,74],66:[2,74],68:[2,74],70:[2,74],71:[2,74],75:[2,74],81:[2,74],82:[2,74],83:[2,74],88:[2,74],90:[2,74],99:[2,74],101:[2,74],102:[2,74],103:[2,74],107:[2,74],115:[2,74],123:[2,74],125:[2,74],126:[2,74],129:[2,74],130:[2,74],131:[2,74],132:[2,74],133:[2,74],134:[2,74]},{1:[2,75],6:[2,75],25:[2,75],26:[2,75],47:[2,75],52:[2,75],55:[2,75],64:[2,75],65:[2,75],66:[2,75],68:[2,75],70:[2,75],71:[2,75],75:[2,75],81:[2,75],82:[2,75],83:[2,75],88:[2,75],90:[2,75],99:[2,75],101:[2,75],102:[2,75],103:[2,75],107:[2,75],115:[2,75],123:[2,75],125:[2,75],126:[2,75],129:[2,75],130:[2,75],131:[2,75],132:[2,75],133:[2,75],134:[2,75]},{1:[2,101],6:[2,101],25:[2,101],26:[2,101],47:[2,101],52:[2,101],55:[2,101],64:[2,101],65:[2,101],66:[2,101],68:[2,101],70:[2,101],71:[2,101],75:[2,101],79:102,81:[2,101],82:[1,103],83:[2,101],88:[2,101],90:[2,101],99:[2,101],101:[2,101],102:[2,101],103:[2,101],107:[2,101],115:[2,101],123:[2,101],125:[2,101],126:[2,101],129:[2,101],130:[2,101],131:[2,101],132:[2,101],133:[2,101],134:[2,101]},{27:107,28:[1,71],42:108,46:104,47:[2,53],52:[2,53],53:105,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{5:113,25:[1,5]},{8:114,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:116,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:117,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:118,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{13:119,14:120,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,56:47,57:48,59:122,61:25,62:26,63:27,73:[1,68],80:[1,28],85:[1,56],86:[1,57],87:[1,55],98:[1,54]},{1:[2,68],6:[2,68],25:[2,68],26:[2,68],38:[2,68],47:[2,68],52:[2,68],55:[2,68],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,68],71:[2,68],75:[2,68],77:[1,126],81:[2,68],82:[2,68],83:[2,68],88:[2,68],90:[2,68],99:[2,68],101:[2,68],102:[2,68],103:[2,68],107:[2,68],115:[2,68],123:[2,68],125:[2,68],126:[2,68],127:[1,123],128:[1,124],129:[2,68],130:[2,68],131:[2,68],132:[2,68],133:[2,68],134:[2,68],135:[1,125]},{1:[2,175],6:[2,175],25:[2,175],26:[2,175],47:[2,175],52:[2,175],55:[2,175],70:[2,175],75:[2,175],83:[2,175],88:[2,175],90:[2,175],99:[2,175],101:[2,175],102:[2,175],103:[2,175],107:[2,175],115:[2,175],118:[1,127],123:[2,175],125:[2,175],126:[2,175],129:[2,175],130:[2,175],131:[2,175],132:[2,175],133:[2,175],134:[2,175]},{5:128,25:[1,5]},{5:129,25:[1,5]},{1:[2,143],6:[2,143],25:[2,143],26:[2,143],47:[2,143],52:[2,143],55:[2,143],70:[2,143],75:[2,143],83:[2,143],88:[2,143],90:[2,143],99:[2,143],101:[2,143],102:[2,143],103:[2,143],107:[2,143],115:[2,143],123:[2,143],125:[2,143],126:[2,143],129:[2,143],130:[2,143],131:[2,143],132:[2,143],133:[2,143],134:[2,143]},{5:130,25:[1,5]},{8:131,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,132],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,91],5:133,6:[2,91],13:119,14:120,25:[1,5],26:[2,91],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:121,42:61,47:[2,91],52:[2,91],55:[2,91],56:47,57:48,59:135,61:25,62:26,63:27,70:[2,91],73:[1,68],75:[2,91],77:[1,134],80:[1,28],83:[2,91],85:[1,56],86:[1,57],87:[1,55],88:[2,91],90:[2,91],98:[1,54],99:[2,91],101:[2,91],102:[2,91],103:[2,91],107:[2,91],115:[2,91],123:[2,91],125:[2,91],126:[2,91],129:[2,91],130:[2,91],131:[2,91],132:[2,91],133:[2,91],134:[2,91]},{8:136,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,45],6:[2,45],8:137,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,45],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,45],100:39,101:[2,45],103:[2,45],104:40,105:[1,65],106:41,107:[2,45],108:67,116:[1,42],121:37,122:[1,62],123:[2,45],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,46],6:[2,46],25:[2,46],26:[2,46],52:[2,46],75:[2,46],99:[2,46],101:[2,46],103:[2,46],107:[2,46],123:[2,46]},{1:[2,69],6:[2,69],25:[2,69],26:[2,69],38:[2,69],47:[2,69],52:[2,69],55:[2,69],64:[2,69],65:[2,69],66:[2,69],68:[2,69],70:[2,69],71:[2,69],75:[2,69],81:[2,69],82:[2,69],83:[2,69],88:[2,69],90:[2,69],99:[2,69],101:[2,69],102:[2,69],103:[2,69],107:[2,69],115:[2,69],123:[2,69],125:[2,69],126:[2,69],129:[2,69],130:[2,69],131:[2,69],132:[2,69],133:[2,69],134:[2,69]},{1:[2,70],6:[2,70],25:[2,70],26:[2,70],38:[2,70],47:[2,70],52:[2,70],55:[2,70],64:[2,70],65:[2,70],66:[2,70],68:[2,70],70:[2,70],71:[2,70],75:[2,70],81:[2,70],82:[2,70],83:[2,70],88:[2,70],90:[2,70],99:[2,70],101:[2,70],102:[2,70],103:[2,70],107:[2,70],115:[2,70],123:[2,70],125:[2,70],126:[2,70],129:[2,70],130:[2,70],131:[2,70],132:[2,70],133:[2,70],134:[2,70]},{1:[2,29],6:[2,29],25:[2,29],26:[2,29],47:[2,29],52:[2,29],55:[2,29],64:[2,29],65:[2,29],66:[2,29],68:[2,29],70:[2,29],71:[2,29],75:[2,29],81:[2,29],82:[2,29],83:[2,29],88:[2,29],90:[2,29],99:[2,29],101:[2,29],102:[2,29],103:[2,29],107:[2,29],115:[2,29],123:[2,29],125:[2,29],126:[2,29],129:[2,29],130:[2,29],131:[2,29],132:[2,29],133:[2,29],134:[2,29]},{1:[2,30],6:[2,30],25:[2,30],26:[2,30],47:[2,30],52:[2,30],55:[2,30],64:[2,30],65:[2,30],66:[2,30],68:[2,30],70:[2,30],71:[2,30],75:[2,30],81:[2,30],82:[2,30],83:[2,30],88:[2,30],90:[2,30],99:[2,30],101:[2,30],102:[2,30],103:[2,30],107:[2,30],115:[2,30],123:[2,30],125:[2,30],126:[2,30],129:[2,30],130:[2,30],131:[2,30],132:[2,30],133:[2,30],134:[2,30]},{1:[2,31],6:[2,31],25:[2,31],26:[2,31],47:[2,31],52:[2,31],55:[2,31],64:[2,31],65:[2,31],66:[2,31],68:[2,31],70:[2,31],71:[2,31],75:[2,31],81:[2,31],82:[2,31],83:[2,31],88:[2,31],90:[2,31],99:[2,31],101:[2,31],102:[2,31],103:[2,31],107:[2,31],115:[2,31],123:[2,31],125:[2,31],126:[2,31],129:[2,31],130:[2,31],131:[2,31],132:[2,31],133:[2,31],134:[2,31]},{1:[2,32],6:[2,32],25:[2,32],26:[2,32],47:[2,32],52:[2,32],55:[2,32],64:[2,32],65:[2,32],66:[2,32],68:[2,32],70:[2,32],71:[2,32],75:[2,32],81:[2,32],82:[2,32],83:[2,32],88:[2,32],90:[2,32],99:[2,32],101:[2,32],102:[2,32],103:[2,32],107:[2,32],115:[2,32],123:[2,32],125:[2,32],126:[2,32],129:[2,32],130:[2,32],131:[2,32],132:[2,32],133:[2,32],134:[2,32]},{1:[2,33],6:[2,33],25:[2,33],26:[2,33],47:[2,33],52:[2,33],55:[2,33],64:[2,33],65:[2,33],66:[2,33],68:[2,33],70:[2,33],71:[2,33],75:[2,33],81:[2,33],82:[2,33],83:[2,33],88:[2,33],90:[2,33],99:[2,33],101:[2,33],102:[2,33],103:[2,33],107:[2,33],115:[2,33],123:[2,33],125:[2,33],126:[2,33],129:[2,33],130:[2,33],131:[2,33],132:[2,33],133:[2,33],134:[2,33]},{4:138,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,139],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:140,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,107],6:[2,107],25:[2,107],26:[2,107],47:[2,107],52:[2,107],55:[2,107],64:[2,107],65:[2,107],66:[2,107],68:[2,107],70:[2,107],71:[2,107],75:[2,107],81:[2,107],82:[2,107],83:[2,107],88:[2,107],90:[2,107],99:[2,107],101:[2,107],102:[2,107],103:[2,107],107:[2,107],115:[2,107],123:[2,107],125:[2,107],126:[2,107],129:[2,107],130:[2,107],131:[2,107],132:[2,107],133:[2,107],134:[2,107]},{1:[2,108],6:[2,108],25:[2,108],26:[2,108],27:146,28:[1,71],47:[2,108],52:[2,108],55:[2,108],64:[2,108],65:[2,108],66:[2,108],68:[2,108],70:[2,108],71:[2,108],75:[2,108],81:[2,108],82:[2,108],83:[2,108],88:[2,108],90:[2,108],99:[2,108],101:[2,108],102:[2,108],103:[2,108],107:[2,108],115:[2,108],123:[2,108],125:[2,108],126:[2,108],129:[2,108],130:[2,108],131:[2,108],132:[2,108],133:[2,108],134:[2,108]},{25:[2,49]},{25:[2,50]},{1:[2,64],6:[2,64],25:[2,64],26:[2,64],38:[2,64],47:[2,64],52:[2,64],55:[2,64],64:[2,64],65:[2,64],66:[2,64],68:[2,64],70:[2,64],71:[2,64],75:[2,64],77:[2,64],81:[2,64],82:[2,64],83:[2,64],88:[2,64],90:[2,64],99:[2,64],101:[2,64],102:[2,64],103:[2,64],107:[2,64],115:[2,64],123:[2,64],125:[2,64],126:[2,64],127:[2,64],128:[2,64],129:[2,64],130:[2,64],131:[2,64],132:[2,64],133:[2,64],134:[2,64],135:[2,64]},{1:[2,67],6:[2,67],25:[2,67],26:[2,67],38:[2,67],47:[2,67],52:[2,67],55:[2,67],64:[2,67],65:[2,67],66:[2,67],68:[2,67],70:[2,67],71:[2,67],75:[2,67],77:[2,67],81:[2,67],82:[2,67],83:[2,67],88:[2,67],90:[2,67],99:[2,67],101:[2,67],102:[2,67],103:[2,67],107:[2,67],115:[2,67],123:[2,67],125:[2,67],126:[2,67],127:[2,67],128:[2,67],129:[2,67],130:[2,67],131:[2,67],132:[2,67],133:[2,67],134:[2,67],135:[2,67]},{8:147,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:148,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:149,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:150,8:151,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,5],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{27:156,28:[1,71],56:157,57:158,62:152,73:[1,68],87:[1,55],110:153,111:[1,154],112:155},{109:159,113:[1,160],114:[1,161]},{6:[2,86],11:165,25:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:162,75:[2,86],86:[1,111]},{1:[2,27],6:[2,27],25:[2,27],26:[2,27],41:[2,27],47:[2,27],52:[2,27],55:[2,27],64:[2,27],65:[2,27],66:[2,27],68:[2,27],70:[2,27],71:[2,27],75:[2,27],81:[2,27],82:[2,27],83:[2,27],88:[2,27],90:[2,27],99:[2,27],101:[2,27],102:[2,27],103:[2,27],107:[2,27],115:[2,27],123:[2,27],125:[2,27],126:[2,27],129:[2,27],130:[2,27],131:[2,27],132:[2,27],133:[2,27],134:[2,27]},{1:[2,28],6:[2,28],25:[2,28],26:[2,28],41:[2,28],47:[2,28],52:[2,28],55:[2,28],64:[2,28],65:[2,28],66:[2,28],68:[2,28],70:[2,28],71:[2,28],75:[2,28],81:[2,28],82:[2,28],83:[2,28],88:[2,28],90:[2,28],99:[2,28],101:[2,28],102:[2,28],103:[2,28],107:[2,28],115:[2,28],123:[2,28],125:[2,28],126:[2,28],129:[2,28],130:[2,28],131:[2,28],132:[2,28],133:[2,28],134:[2,28]},{1:[2,26],6:[2,26],25:[2,26],26:[2,26],38:[2,26],41:[2,26],47:[2,26],52:[2,26],55:[2,26],64:[2,26],65:[2,26],66:[2,26],68:[2,26],70:[2,26],71:[2,26],75:[2,26],77:[2,26],81:[2,26],82:[2,26],83:[2,26],88:[2,26],90:[2,26],99:[2,26],101:[2,26],102:[2,26],103:[2,26],107:[2,26],113:[2,26],114:[2,26],115:[2,26],123:[2,26],125:[2,26],126:[2,26],127:[2,26],128:[2,26],129:[2,26],130:[2,26],131:[2,26],132:[2,26],133:[2,26],134:[2,26],135:[2,26]},{1:[2,6],6:[2,6],7:169,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,26:[2,6],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],99:[2,6],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,3]},{1:[2,24],6:[2,24],25:[2,24],26:[2,24],47:[2,24],52:[2,24],55:[2,24],70:[2,24],75:[2,24],83:[2,24],88:[2,24],90:[2,24],95:[2,24],96:[2,24],99:[2,24],101:[2,24],102:[2,24],103:[2,24],107:[2,24],115:[2,24],118:[2,24],120:[2,24],123:[2,24],125:[2,24],126:[2,24],129:[2,24],130:[2,24],131:[2,24],132:[2,24],133:[2,24],134:[2,24]},{6:[1,72],26:[1,170]},{1:[2,186],6:[2,186],25:[2,186],26:[2,186],47:[2,186],52:[2,186],55:[2,186],70:[2,186],75:[2,186],83:[2,186],88:[2,186],90:[2,186],99:[2,186],101:[2,186],102:[2,186],103:[2,186],107:[2,186],115:[2,186],123:[2,186],125:[2,186],126:[2,186],129:[2,186],130:[2,186],131:[2,186],132:[2,186],133:[2,186],134:[2,186]},{8:171,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:172,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:173,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:174,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:175,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:176,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:177,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:178,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,142],6:[2,142],25:[2,142],26:[2,142],47:[2,142],52:[2,142],55:[2,142],70:[2,142],75:[2,142],83:[2,142],88:[2,142],90:[2,142],99:[2,142],101:[2,142],102:[2,142],103:[2,142],107:[2,142],115:[2,142],123:[2,142],125:[2,142],126:[2,142],129:[2,142],130:[2,142],131:[2,142],132:[2,142],133:[2,142],134:[2,142]},{1:[2,147],6:[2,147],25:[2,147],26:[2,147],47:[2,147],52:[2,147],55:[2,147],70:[2,147],75:[2,147],83:[2,147],88:[2,147],90:[2,147],99:[2,147],101:[2,147],102:[2,147],103:[2,147],107:[2,147],115:[2,147],123:[2,147],125:[2,147],126:[2,147],129:[2,147],130:[2,147],131:[2,147],132:[2,147],133:[2,147],134:[2,147]},{8:179,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,141],6:[2,141],25:[2,141],26:[2,141],47:[2,141],52:[2,141],55:[2,141],70:[2,141],75:[2,141],83:[2,141],88:[2,141],90:[2,141],99:[2,141],101:[2,141],102:[2,141],103:[2,141],107:[2,141],115:[2,141],123:[2,141],125:[2,141],126:[2,141],129:[2,141],130:[2,141],131:[2,141],132:[2,141],133:[2,141],134:[2,141]},{1:[2,146],6:[2,146],25:[2,146],26:[2,146],47:[2,146],52:[2,146],55:[2,146],70:[2,146],75:[2,146],83:[2,146],88:[2,146],90:[2,146],99:[2,146],101:[2,146],102:[2,146],103:[2,146],107:[2,146],115:[2,146],123:[2,146],125:[2,146],126:[2,146],129:[2,146],130:[2,146],131:[2,146],132:[2,146],133:[2,146],134:[2,146]},{79:180,82:[1,103]},{1:[2,65],6:[2,65],25:[2,65],26:[2,65],38:[2,65],47:[2,65],52:[2,65],55:[2,65],64:[2,65],65:[2,65],66:[2,65],68:[2,65],70:[2,65],71:[2,65],75:[2,65],77:[2,65],81:[2,65],82:[2,65],83:[2,65],88:[2,65],90:[2,65],99:[2,65],101:[2,65],102:[2,65],103:[2,65],107:[2,65],115:[2,65],123:[2,65],125:[2,65],126:[2,65],127:[2,65],128:[2,65],129:[2,65],130:[2,65],131:[2,65],132:[2,65],133:[2,65],134:[2,65],135:[2,65]},{82:[2,104]},{27:181,28:[1,71]},{27:182,28:[1,71]},{1:[2,79],6:[2,79],25:[2,79],26:[2,79],27:183,28:[1,71],38:[2,79],47:[2,79],52:[2,79],55:[2,79],64:[2,79],65:[2,79],66:[2,79],68:[2,79],70:[2,79],71:[2,79],75:[2,79],77:[2,79],81:[2,79],82:[2,79],83:[2,79],88:[2,79],90:[2,79],99:[2,79],101:[2,79],102:[2,79],103:[2,79],107:[2,79],115:[2,79],123:[2,79],125:[2,79],126:[2,79],127:[2,79],128:[2,79],129:[2,79],130:[2,79],131:[2,79],132:[2,79],133:[2,79],134:[2,79],135:[2,79]},{1:[2,80],6:[2,80],25:[2,80],26:[2,80],38:[2,80],47:[2,80],52:[2,80],55:[2,80],64:[2,80],65:[2,80],66:[2,80],68:[2,80],70:[2,80],71:[2,80],75:[2,80],77:[2,80],81:[2,80],82:[2,80],83:[2,80],88:[2,80],90:[2,80],99:[2,80],101:[2,80],102:[2,80],103:[2,80],107:[2,80],115:[2,80],123:[2,80],125:[2,80],126:[2,80],127:[2,80],128:[2,80],129:[2,80],130:[2,80],131:[2,80],132:[2,80],133:[2,80],134:[2,80],135:[2,80]},{8:185,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],55:[1,189],56:47,57:48,59:36,61:25,62:26,63:27,69:184,72:186,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],89:187,90:[1,188],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{67:190,68:[1,97],71:[1,98]},{79:191,82:[1,103]},{1:[2,66],6:[2,66],25:[2,66],26:[2,66],38:[2,66],47:[2,66],52:[2,66],55:[2,66],64:[2,66],65:[2,66],66:[2,66],68:[2,66],70:[2,66],71:[2,66],75:[2,66],77:[2,66],81:[2,66],82:[2,66],83:[2,66],88:[2,66],90:[2,66],99:[2,66],101:[2,66],102:[2,66],103:[2,66],107:[2,66],115:[2,66],123:[2,66],125:[2,66],126:[2,66],127:[2,66],128:[2,66],129:[2,66],130:[2,66],131:[2,66],132:[2,66],133:[2,66],134:[2,66],135:[2,66]},{6:[1,193],8:192,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,194],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,102],6:[2,102],25:[2,102],26:[2,102],47:[2,102],52:[2,102],55:[2,102],64:[2,102],65:[2,102],66:[2,102],68:[2,102],70:[2,102],71:[2,102],75:[2,102],81:[2,102],82:[2,102],83:[2,102],88:[2,102],90:[2,102],99:[2,102],101:[2,102],102:[2,102],103:[2,102],107:[2,102],115:[2,102],123:[2,102],125:[2,102],126:[2,102],129:[2,102],130:[2,102],131:[2,102],132:[2,102],133:[2,102],134:[2,102]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[1,195],84:196,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{47:[1,198],52:[1,199]},{47:[2,54],52:[2,54]},{38:[1,201],47:[2,56],52:[2,56],55:[1,200]},{38:[2,59],47:[2,59],52:[2,59],55:[2,59]},{38:[2,60],47:[2,60],52:[2,60],55:[2,60]},{38:[2,61],47:[2,61],52:[2,61],55:[2,61]},{38:[2,62],47:[2,62],52:[2,62],55:[2,62]},{27:146,28:[1,71]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:142,85:[1,56],86:[1,57],87:[1,55],88:[1,141],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,48],6:[2,48],25:[2,48],26:[2,48],47:[2,48],52:[2,48],55:[2,48],70:[2,48],75:[2,48],83:[2,48],88:[2,48],90:[2,48],99:[2,48],101:[2,48],102:[2,48],103:[2,48],107:[2,48],115:[2,48],123:[2,48],125:[2,48],126:[2,48],129:[2,48],130:[2,48],131:[2,48],132:[2,48],133:[2,48],134:[2,48]},{1:[2,179],6:[2,179],25:[2,179],26:[2,179],47:[2,179],52:[2,179],55:[2,179],70:[2,179],75:[2,179],83:[2,179],88:[2,179],90:[2,179],99:[2,179],100:85,101:[2,179],102:[2,179],103:[2,179],106:86,107:[2,179],108:67,115:[2,179],123:[2,179],125:[2,179],126:[2,179],129:[1,76],130:[2,179],131:[2,179],132:[2,179],133:[2,179],134:[2,179]},{100:88,101:[1,63],103:[1,64],106:89,107:[1,66],108:67,123:[1,87]},{1:[2,180],6:[2,180],25:[2,180],26:[2,180],47:[2,180],52:[2,180],55:[2,180],70:[2,180],75:[2,180],83:[2,180],88:[2,180],90:[2,180],99:[2,180],100:85,101:[2,180],102:[2,180],103:[2,180],106:86,107:[2,180],108:67,115:[2,180],123:[2,180],125:[2,180],126:[2,180],129:[1,76],130:[2,180],131:[2,180],132:[2,180],133:[2,180],134:[2,180]},{1:[2,181],6:[2,181],25:[2,181],26:[2,181],47:[2,181],52:[2,181],55:[2,181],70:[2,181],75:[2,181],83:[2,181],88:[2,181],90:[2,181],99:[2,181],100:85,101:[2,181],102:[2,181],103:[2,181],106:86,107:[2,181],108:67,115:[2,181],123:[2,181],125:[2,181],126:[2,181],129:[1,76],130:[2,181],131:[2,181],132:[2,181],133:[2,181],134:[2,181]},{1:[2,182],6:[2,182],25:[2,182],26:[2,182],47:[2,182],52:[2,182],55:[2,182],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,182],71:[2,68],75:[2,182],81:[2,68],82:[2,68],83:[2,182],88:[2,182],90:[2,182],99:[2,182],101:[2,182],102:[2,182],103:[2,182],107:[2,182],115:[2,182],123:[2,182],125:[2,182],126:[2,182],129:[2,182],130:[2,182],131:[2,182],132:[2,182],133:[2,182],134:[2,182]},{60:91,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:90,81:[1,92],82:[2,103]},{60:100,64:[1,93],65:[1,94],66:[1,95],67:96,68:[1,97],71:[1,98],78:99,81:[1,92],82:[2,103]},{64:[2,71],65:[2,71],66:[2,71],68:[2,71],71:[2,71],81:[2,71],82:[2,71]},{1:[2,183],6:[2,183],25:[2,183],26:[2,183],47:[2,183],52:[2,183],55:[2,183],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,183],71:[2,68],75:[2,183],81:[2,68],82:[2,68],83:[2,183],88:[2,183],90:[2,183],99:[2,183],101:[2,183],102:[2,183],103:[2,183],107:[2,183],115:[2,183],123:[2,183],125:[2,183],126:[2,183],129:[2,183],130:[2,183],131:[2,183],132:[2,183],133:[2,183],134:[2,183]},{1:[2,184],6:[2,184],25:[2,184],26:[2,184],47:[2,184],52:[2,184],55:[2,184],70:[2,184],75:[2,184],83:[2,184],88:[2,184],90:[2,184],99:[2,184],101:[2,184],102:[2,184],103:[2,184],107:[2,184],115:[2,184],123:[2,184],125:[2,184],126:[2,184],129:[2,184],130:[2,184],131:[2,184],132:[2,184],133:[2,184],134:[2,184]},{1:[2,185],6:[2,185],25:[2,185],26:[2,185],47:[2,185],52:[2,185],55:[2,185],70:[2,185],75:[2,185],83:[2,185],88:[2,185],90:[2,185],99:[2,185],101:[2,185],102:[2,185],103:[2,185],107:[2,185],115:[2,185],123:[2,185],125:[2,185],126:[2,185],129:[2,185],130:[2,185],131:[2,185],132:[2,185],133:[2,185],134:[2,185]},{8:202,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,203],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:204,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{5:205,25:[1,5],122:[1,206]},{1:[2,128],6:[2,128],25:[2,128],26:[2,128],47:[2,128],52:[2,128],55:[2,128],70:[2,128],75:[2,128],83:[2,128],88:[2,128],90:[2,128],94:207,95:[1,208],96:[1,209],99:[2,128],101:[2,128],102:[2,128],103:[2,128],107:[2,128],115:[2,128],123:[2,128],125:[2,128],126:[2,128],129:[2,128],130:[2,128],131:[2,128],132:[2,128],133:[2,128],134:[2,128]},{1:[2,140],6:[2,140],25:[2,140],26:[2,140],47:[2,140],52:[2,140],55:[2,140],70:[2,140],75:[2,140],83:[2,140],88:[2,140],90:[2,140],99:[2,140],101:[2,140],102:[2,140],103:[2,140],107:[2,140],115:[2,140],123:[2,140],125:[2,140],126:[2,140],129:[2,140],130:[2,140],131:[2,140],132:[2,140],133:[2,140],134:[2,140]},{1:[2,148],6:[2,148],25:[2,148],26:[2,148],47:[2,148],52:[2,148],55:[2,148],70:[2,148],75:[2,148],83:[2,148],88:[2,148],90:[2,148],99:[2,148],101:[2,148],102:[2,148],103:[2,148],107:[2,148],115:[2,148],123:[2,148],125:[2,148],126:[2,148],129:[2,148],130:[2,148],131:[2,148],132:[2,148],133:[2,148],134:[2,148]},{25:[1,210],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{117:211,119:212,120:[1,213]},{1:[2,92],6:[2,92],25:[2,92],26:[2,92],47:[2,92],52:[2,92],55:[2,92],70:[2,92],75:[2,92],83:[2,92],88:[2,92],90:[2,92],99:[2,92],101:[2,92],102:[2,92],103:[2,92],107:[2,92],115:[2,92],123:[2,92],125:[2,92],126:[2,92],129:[2,92],130:[2,92],131:[2,92],132:[2,92],133:[2,92],134:[2,92]},{8:214,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,95],5:215,6:[2,95],25:[1,5],26:[2,95],47:[2,95],52:[2,95],55:[2,95],64:[2,68],65:[2,68],66:[2,68],68:[2,68],70:[2,95],71:[2,68],75:[2,95],77:[1,216],81:[2,68],82:[2,68],83:[2,95],88:[2,95],90:[2,95],99:[2,95],101:[2,95],102:[2,95],103:[2,95],107:[2,95],115:[2,95],123:[2,95],125:[2,95],126:[2,95],129:[2,95],130:[2,95],131:[2,95],132:[2,95],133:[2,95],134:[2,95]},{1:[2,133],6:[2,133],25:[2,133],26:[2,133],47:[2,133],52:[2,133],55:[2,133],70:[2,133],75:[2,133],83:[2,133],88:[2,133],90:[2,133],99:[2,133],100:85,101:[2,133],102:[2,133],103:[2,133],106:86,107:[2,133],108:67,115:[2,133],123:[2,133],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,44],6:[2,44],26:[2,44],99:[2,44],100:85,101:[2,44],103:[2,44],106:86,107:[2,44],108:67,123:[2,44],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,72],99:[1,217]},{4:218,7:4,8:6,9:7,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,124],25:[2,124],52:[2,124],55:[1,220],88:[2,124],89:219,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,110],6:[2,110],25:[2,110],26:[2,110],38:[2,110],47:[2,110],52:[2,110],55:[2,110],64:[2,110],65:[2,110],66:[2,110],68:[2,110],70:[2,110],71:[2,110],75:[2,110],81:[2,110],82:[2,110],83:[2,110],88:[2,110],90:[2,110],99:[2,110],101:[2,110],102:[2,110],103:[2,110],107:[2,110],113:[2,110],114:[2,110],115:[2,110],123:[2,110],125:[2,110],126:[2,110],129:[2,110],130:[2,110],131:[2,110],132:[2,110],133:[2,110],134:[2,110]},{6:[2,51],25:[2,51],51:221,52:[1,222],88:[2,51]},{6:[2,119],25:[2,119],26:[2,119],52:[2,119],83:[2,119],88:[2,119]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:223,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,125],25:[2,125],26:[2,125],52:[2,125],83:[2,125],88:[2,125]},{1:[2,109],6:[2,109],25:[2,109],26:[2,109],38:[2,109],41:[2,109],47:[2,109],52:[2,109],55:[2,109],64:[2,109],65:[2,109],66:[2,109],68:[2,109],70:[2,109],71:[2,109],75:[2,109],77:[2,109],81:[2,109],82:[2,109],83:[2,109],88:[2,109],90:[2,109],99:[2,109],101:[2,109],102:[2,109],103:[2,109],107:[2,109],115:[2,109],123:[2,109],125:[2,109],126:[2,109],127:[2,109],128:[2,109],129:[2,109],130:[2,109],131:[2,109],132:[2,109],133:[2,109],134:[2,109],135:[2,109]},{5:224,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,136],6:[2,136],25:[2,136],26:[2,136],47:[2,136],52:[2,136],55:[2,136],70:[2,136],75:[2,136],83:[2,136],88:[2,136],90:[2,136],99:[2,136],100:85,101:[1,63],102:[1,225],103:[1,64],106:86,107:[1,66],108:67,115:[2,136],123:[2,136],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,138],6:[2,138],25:[2,138],26:[2,138],47:[2,138],52:[2,138],55:[2,138],70:[2,138],75:[2,138],83:[2,138],88:[2,138],90:[2,138],99:[2,138],100:85,101:[1,63],102:[1,226],103:[1,64],106:86,107:[1,66],108:67,115:[2,138],123:[2,138],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,144],6:[2,144],25:[2,144],26:[2,144],47:[2,144],52:[2,144],55:[2,144],70:[2,144],75:[2,144],83:[2,144],88:[2,144],90:[2,144],99:[2,144],101:[2,144],102:[2,144],103:[2,144],107:[2,144],115:[2,144],123:[2,144],125:[2,144],126:[2,144],129:[2,144],130:[2,144],131:[2,144],132:[2,144],133:[2,144],134:[2,144]},{1:[2,145],6:[2,145],25:[2,145],26:[2,145],47:[2,145],52:[2,145],55:[2,145],70:[2,145],75:[2,145],83:[2,145],88:[2,145],90:[2,145],99:[2,145],100:85,101:[1,63],102:[2,145],103:[1,64],106:86,107:[1,66],108:67,115:[2,145],123:[2,145],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,149],6:[2,149],25:[2,149],26:[2,149],47:[2,149],52:[2,149],55:[2,149],70:[2,149],75:[2,149],83:[2,149],88:[2,149],90:[2,149],99:[2,149],101:[2,149],102:[2,149],103:[2,149],107:[2,149],115:[2,149],123:[2,149],125:[2,149],126:[2,149],129:[2,149],130:[2,149],131:[2,149],132:[2,149],133:[2,149],134:[2,149]},{113:[2,151],114:[2,151]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],110:227,112:155},{52:[1,228],113:[2,156],114:[2,156]},{52:[2,153],113:[2,153],114:[2,153]},{52:[2,154],113:[2,154],114:[2,154]},{52:[2,155],113:[2,155],114:[2,155]},{1:[2,150],6:[2,150],25:[2,150],26:[2,150],47:[2,150],52:[2,150],55:[2,150],70:[2,150],75:[2,150],83:[2,150],88:[2,150],90:[2,150],99:[2,150],101:[2,150],102:[2,150],103:[2,150],107:[2,150],115:[2,150],123:[2,150],125:[2,150],126:[2,150],129:[2,150],130:[2,150],131:[2,150],132:[2,150],133:[2,150],134:[2,150]},{8:229,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:230,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],51:231,52:[1,232],75:[2,51]},{6:[2,87],25:[2,87],26:[2,87],52:[2,87],75:[2,87]},{6:[2,37],25:[2,37],26:[2,37],41:[1,233],52:[2,37],75:[2,37]},{6:[2,40],25:[2,40],26:[2,40],52:[2,40],75:[2,40]},{6:[2,41],25:[2,41],26:[2,41],41:[2,41],52:[2,41],75:[2,41]},{6:[2,42],25:[2,42],26:[2,42],41:[2,42],52:[2,42],75:[2,42]},{6:[2,43],25:[2,43],26:[2,43],41:[2,43],52:[2,43],75:[2,43]},{1:[2,5],6:[2,5],26:[2,5],99:[2,5]},{1:[2,25],6:[2,25],25:[2,25],26:[2,25],47:[2,25],52:[2,25],55:[2,25],70:[2,25],75:[2,25],83:[2,25],88:[2,25],90:[2,25],95:[2,25],96:[2,25],99:[2,25],101:[2,25],102:[2,25],103:[2,25],107:[2,25],115:[2,25],118:[2,25],120:[2,25],123:[2,25],125:[2,25],126:[2,25],129:[2,25],130:[2,25],131:[2,25],132:[2,25],133:[2,25],134:[2,25]},{1:[2,187],6:[2,187],25:[2,187],26:[2,187],47:[2,187],52:[2,187],55:[2,187],70:[2,187],75:[2,187],83:[2,187],88:[2,187],90:[2,187],99:[2,187],100:85,101:[2,187],102:[2,187],103:[2,187],106:86,107:[2,187],108:67,115:[2,187],123:[2,187],125:[2,187],126:[2,187],129:[1,76],130:[1,79],131:[2,187],132:[2,187],133:[2,187],134:[2,187]},{1:[2,188],6:[2,188],25:[2,188],26:[2,188],47:[2,188],52:[2,188],55:[2,188],70:[2,188],75:[2,188],83:[2,188],88:[2,188],90:[2,188],99:[2,188],100:85,101:[2,188],102:[2,188],103:[2,188],106:86,107:[2,188],108:67,115:[2,188],123:[2,188],125:[2,188],126:[2,188],129:[1,76],130:[1,79],131:[2,188],132:[2,188],133:[2,188],134:[2,188]},{1:[2,189],6:[2,189],25:[2,189],26:[2,189],47:[2,189],52:[2,189],55:[2,189],70:[2,189],75:[2,189],83:[2,189],88:[2,189],90:[2,189],99:[2,189],100:85,101:[2,189],102:[2,189],103:[2,189],106:86,107:[2,189],108:67,115:[2,189],123:[2,189],125:[2,189],126:[2,189],129:[1,76],130:[2,189],131:[2,189],132:[2,189],133:[2,189],134:[2,189]},{1:[2,190],6:[2,190],25:[2,190],26:[2,190],47:[2,190],52:[2,190],55:[2,190],70:[2,190],75:[2,190],83:[2,190],88:[2,190],90:[2,190],99:[2,190],100:85,101:[2,190],102:[2,190],103:[2,190],106:86,107:[2,190],108:67,115:[2,190],123:[2,190],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[2,190],132:[2,190],133:[2,190],134:[2,190]},{1:[2,191],6:[2,191],25:[2,191],26:[2,191],47:[2,191],52:[2,191],55:[2,191],70:[2,191],75:[2,191],83:[2,191],88:[2,191],90:[2,191],99:[2,191],100:85,101:[2,191],102:[2,191],103:[2,191],106:86,107:[2,191],108:67,115:[2,191],123:[2,191],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,191],133:[2,191],134:[1,83]},{1:[2,192],6:[2,192],25:[2,192],26:[2,192],47:[2,192],52:[2,192],55:[2,192],70:[2,192],75:[2,192],83:[2,192],88:[2,192],90:[2,192],99:[2,192],100:85,101:[2,192],102:[2,192],103:[2,192],106:86,107:[2,192],108:67,115:[2,192],123:[2,192],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[2,192],134:[1,83]},{1:[2,193],6:[2,193],25:[2,193],26:[2,193],47:[2,193],52:[2,193],55:[2,193],70:[2,193],75:[2,193],83:[2,193],88:[2,193],90:[2,193],99:[2,193],100:85,101:[2,193],102:[2,193],103:[2,193],106:86,107:[2,193],108:67,115:[2,193],123:[2,193],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[2,193],133:[2,193],134:[2,193]},{1:[2,178],6:[2,178],25:[2,178],26:[2,178],47:[2,178],52:[2,178],55:[2,178],70:[2,178],75:[2,178],83:[2,178],88:[2,178],90:[2,178],99:[2,178],100:85,101:[1,63],102:[2,178],103:[1,64],106:86,107:[1,66],108:67,115:[2,178],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,177],6:[2,177],25:[2,177],26:[2,177],47:[2,177],52:[2,177],55:[2,177],70:[2,177],75:[2,177],83:[2,177],88:[2,177],90:[2,177],99:[2,177],100:85,101:[1,63],102:[2,177],103:[1,64],106:86,107:[1,66],108:67,115:[2,177],123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,99],6:[2,99],25:[2,99],26:[2,99],47:[2,99],52:[2,99],55:[2,99],64:[2,99],65:[2,99],66:[2,99],68:[2,99],70:[2,99],71:[2,99],75:[2,99],81:[2,99],82:[2,99],83:[2,99],88:[2,99],90:[2,99],99:[2,99],101:[2,99],102:[2,99],103:[2,99],107:[2,99],115:[2,99],123:[2,99],125:[2,99],126:[2,99],129:[2,99],130:[2,99],131:[2,99],132:[2,99],133:[2,99],134:[2,99]},{1:[2,76],6:[2,76],25:[2,76],26:[2,76],38:[2,76],47:[2,76],52:[2,76],55:[2,76],64:[2,76],65:[2,76],66:[2,76],68:[2,76],70:[2,76],71:[2,76],75:[2,76],77:[2,76],81:[2,76],82:[2,76],83:[2,76],88:[2,76],90:[2,76],99:[2,76],101:[2,76],102:[2,76],103:[2,76],107:[2,76],115:[2,76],123:[2,76],125:[2,76],126:[2,76],127:[2,76],128:[2,76],129:[2,76],130:[2,76],131:[2,76],132:[2,76],133:[2,76],134:[2,76],135:[2,76]},{1:[2,77],6:[2,77],25:[2,77],26:[2,77],38:[2,77],47:[2,77],52:[2,77],55:[2,77],64:[2,77],65:[2,77],66:[2,77],68:[2,77],70:[2,77],71:[2,77],75:[2,77],77:[2,77],81:[2,77],82:[2,77],83:[2,77],88:[2,77],90:[2,77],99:[2,77],101:[2,77],102:[2,77],103:[2,77],107:[2,77],115:[2,77],123:[2,77],125:[2,77],126:[2,77],127:[2,77],128:[2,77],129:[2,77],130:[2,77],131:[2,77],132:[2,77],133:[2,77],134:[2,77],135:[2,77]},{1:[2,78],6:[2,78],25:[2,78],26:[2,78],38:[2,78],47:[2,78],52:[2,78],55:[2,78],64:[2,78],65:[2,78],66:[2,78],68:[2,78],70:[2,78],71:[2,78],75:[2,78],77:[2,78],81:[2,78],82:[2,78],83:[2,78],88:[2,78],90:[2,78],99:[2,78],101:[2,78],102:[2,78],103:[2,78],107:[2,78],115:[2,78],123:[2,78],125:[2,78],126:[2,78],127:[2,78],128:[2,78],129:[2,78],130:[2,78],131:[2,78],132:[2,78],133:[2,78],134:[2,78],135:[2,78]},{70:[1,234]},{55:[1,189],70:[2,83],89:235,90:[1,188],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{70:[2,84]},{8:236,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,118],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{12:[2,112],28:[2,112],30:[2,112],31:[2,112],33:[2,112],34:[2,112],35:[2,112],36:[2,112],43:[2,112],44:[2,112],45:[2,112],49:[2,112],50:[2,112],70:[2,112],73:[2,112],76:[2,112],80:[2,112],85:[2,112],86:[2,112],87:[2,112],93:[2,112],97:[2,112],98:[2,112],101:[2,112],103:[2,112],105:[2,112],107:[2,112],116:[2,112],122:[2,112],124:[2,112],125:[2,112],126:[2,112],127:[2,112],128:[2,112]},{12:[2,113],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],70:[2,113],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{1:[2,82],6:[2,82],25:[2,82],26:[2,82],38:[2,82],47:[2,82],52:[2,82],55:[2,82],64:[2,82],65:[2,82],66:[2,82],68:[2,82],70:[2,82],71:[2,82],75:[2,82],77:[2,82],81:[2,82],82:[2,82],83:[2,82],88:[2,82],90:[2,82],99:[2,82],101:[2,82],102:[2,82],103:[2,82],107:[2,82],115:[2,82],123:[2,82],125:[2,82],126:[2,82],127:[2,82],128:[2,82],129:[2,82],130:[2,82],131:[2,82],132:[2,82],133:[2,82],134:[2,82],135:[2,82]},{1:[2,100],6:[2,100],25:[2,100],26:[2,100],47:[2,100],52:[2,100],55:[2,100],64:[2,100],65:[2,100],66:[2,100],68:[2,100],70:[2,100],71:[2,100],75:[2,100],81:[2,100],82:[2,100],83:[2,100],88:[2,100],90:[2,100],99:[2,100],101:[2,100],102:[2,100],103:[2,100],107:[2,100],115:[2,100],123:[2,100],125:[2,100],126:[2,100],129:[2,100],130:[2,100],131:[2,100],132:[2,100],133:[2,100],134:[2,100]},{1:[2,34],6:[2,34],25:[2,34],26:[2,34],47:[2,34],52:[2,34],55:[2,34],70:[2,34],75:[2,34],83:[2,34],88:[2,34],90:[2,34],99:[2,34],100:85,101:[2,34],102:[2,34],103:[2,34],106:86,107:[2,34],108:67,115:[2,34],123:[2,34],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:237,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:238,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,105],6:[2,105],25:[2,105],26:[2,105],47:[2,105],52:[2,105],55:[2,105],64:[2,105],65:[2,105],66:[2,105],68:[2,105],70:[2,105],71:[2,105],75:[2,105],81:[2,105],82:[2,105],83:[2,105],88:[2,105],90:[2,105],99:[2,105],101:[2,105],102:[2,105],103:[2,105],107:[2,105],115:[2,105],123:[2,105],125:[2,105],126:[2,105],129:[2,105],130:[2,105],131:[2,105],132:[2,105],133:[2,105],134:[2,105]},{6:[2,51],25:[2,51],51:239,52:[1,222],83:[2,51]},{6:[2,124],25:[2,124],26:[2,124],52:[2,124],55:[1,240],83:[2,124],88:[2,124],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{48:241,49:[1,58],50:[1,59]},{27:107,28:[1,71],42:108,53:242,54:106,56:109,57:110,73:[1,68],86:[1,111],87:[1,112]},{47:[2,57],52:[2,57]},{8:243,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,194],6:[2,194],25:[2,194],26:[2,194],47:[2,194],52:[2,194],55:[2,194],70:[2,194],75:[2,194],83:[2,194],88:[2,194],90:[2,194],99:[2,194],100:85,101:[2,194],102:[2,194],103:[2,194],106:86,107:[2,194],108:67,115:[2,194],123:[2,194],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:244,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,196],6:[2,196],25:[2,196],26:[2,196],47:[2,196],52:[2,196],55:[2,196],70:[2,196],75:[2,196],83:[2,196],88:[2,196],90:[2,196],99:[2,196],100:85,101:[2,196],102:[2,196],103:[2,196],106:86,107:[2,196],108:67,115:[2,196],123:[2,196],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,176],6:[2,176],25:[2,176],26:[2,176],47:[2,176],52:[2,176],55:[2,176],70:[2,176],75:[2,176],83:[2,176],88:[2,176],90:[2,176],99:[2,176],101:[2,176],102:[2,176],103:[2,176],107:[2,176],115:[2,176],123:[2,176],125:[2,176],126:[2,176],129:[2,176],130:[2,176],131:[2,176],132:[2,176],133:[2,176],134:[2,176]},{8:245,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,129],6:[2,129],25:[2,129],26:[2,129],47:[2,129],52:[2,129],55:[2,129],70:[2,129],75:[2,129],83:[2,129],88:[2,129],90:[2,129],95:[1,246],99:[2,129],101:[2,129],102:[2,129],103:[2,129],107:[2,129],115:[2,129],123:[2,129],125:[2,129],126:[2,129],129:[2,129],130:[2,129],131:[2,129],132:[2,129],133:[2,129],134:[2,129]},{5:247,25:[1,5]},{27:248,28:[1,71]},{117:249,119:212,120:[1,213]},{26:[1,250],118:[1,251],119:252,120:[1,213]},{26:[2,169],118:[2,169],120:[2,169]},{8:254,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],92:253,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,93],5:255,6:[2,93],25:[1,5],26:[2,93],47:[2,93],52:[2,93],55:[2,93],70:[2,93],75:[2,93],83:[2,93],88:[2,93],90:[2,93],99:[2,93],100:85,101:[1,63],102:[2,93],103:[1,64],106:86,107:[1,66],108:67,115:[2,93],123:[2,93],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,96],6:[2,96],25:[2,96],26:[2,96],47:[2,96],52:[2,96],55:[2,96],70:[2,96],75:[2,96],83:[2,96],88:[2,96],90:[2,96],99:[2,96],101:[2,96],102:[2,96],103:[2,96],107:[2,96],115:[2,96],123:[2,96],125:[2,96],126:[2,96],129:[2,96],130:[2,96],131:[2,96],132:[2,96],133:[2,96],134:[2,96]},{8:256,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,134],6:[2,134],25:[2,134],26:[2,134],47:[2,134],52:[2,134],55:[2,134],64:[2,134],65:[2,134],66:[2,134],68:[2,134],70:[2,134],71:[2,134],75:[2,134],81:[2,134],82:[2,134],83:[2,134],88:[2,134],90:[2,134],99:[2,134],101:[2,134],102:[2,134],103:[2,134],107:[2,134],115:[2,134],123:[2,134],125:[2,134],126:[2,134],129:[2,134],130:[2,134],131:[2,134],132:[2,134],133:[2,134],134:[2,134]},{6:[1,72],26:[1,257]},{8:258,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,63],12:[2,113],25:[2,63],28:[2,113],30:[2,113],31:[2,113],33:[2,113],34:[2,113],35:[2,113],36:[2,113],43:[2,113],44:[2,113],45:[2,113],49:[2,113],50:[2,113],52:[2,63],73:[2,113],76:[2,113],80:[2,113],85:[2,113],86:[2,113],87:[2,113],88:[2,63],93:[2,113],97:[2,113],98:[2,113],101:[2,113],103:[2,113],105:[2,113],107:[2,113],116:[2,113],122:[2,113],124:[2,113],125:[2,113],126:[2,113],127:[2,113],128:[2,113]},{6:[1,260],25:[1,261],88:[1,259]},{6:[2,52],8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[2,52],26:[2,52],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],83:[2,52],85:[1,56],86:[1,57],87:[1,55],88:[2,52],91:262,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,51],25:[2,51],26:[2,51],51:263,52:[1,222]},{1:[2,173],6:[2,173],25:[2,173],26:[2,173],47:[2,173],52:[2,173],55:[2,173],70:[2,173],75:[2,173],83:[2,173],88:[2,173],90:[2,173],99:[2,173],101:[2,173],102:[2,173],103:[2,173],107:[2,173],115:[2,173],118:[2,173],123:[2,173],125:[2,173],126:[2,173],129:[2,173],130:[2,173],131:[2,173],132:[2,173],133:[2,173],134:[2,173]},{8:264,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:265,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{113:[2,152],114:[2,152]},{27:156,28:[1,71],56:157,57:158,73:[1,68],87:[1,112],112:266},{1:[2,158],6:[2,158],25:[2,158],26:[2,158],47:[2,158],52:[2,158],55:[2,158],70:[2,158],75:[2,158],83:[2,158],88:[2,158],90:[2,158],99:[2,158],100:85,101:[2,158],102:[1,267],103:[2,158],106:86,107:[2,158],108:67,115:[1,268],123:[2,158],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,159],6:[2,159],25:[2,159],26:[2,159],47:[2,159],52:[2,159],55:[2,159],70:[2,159],75:[2,159],83:[2,159],88:[2,159],90:[2,159],99:[2,159],100:85,101:[2,159],102:[1,269],103:[2,159],106:86,107:[2,159],108:67,115:[2,159],123:[2,159],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,271],25:[1,272],75:[1,270]},{6:[2,52],11:165,25:[2,52],26:[2,52],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:273,40:164,42:168,44:[1,46],75:[2,52],86:[1,111]},{8:274,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,275],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,81],6:[2,81],25:[2,81],26:[2,81],38:[2,81],47:[2,81],52:[2,81],55:[2,81],64:[2,81],65:[2,81],66:[2,81],68:[2,81],70:[2,81],71:[2,81],75:[2,81],77:[2,81],81:[2,81],82:[2,81],83:[2,81],88:[2,81],90:[2,81],99:[2,81],101:[2,81],102:[2,81],103:[2,81],107:[2,81],115:[2,81],123:[2,81],125:[2,81],126:[2,81],127:[2,81],128:[2,81],129:[2,81],130:[2,81],131:[2,81],132:[2,81],133:[2,81],134:[2,81],135:[2,81]},{8:276,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,70:[2,116],73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,117],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,35],6:[2,35],25:[2,35],26:[2,35],47:[2,35],52:[2,35],55:[2,35],70:[2,35],75:[2,35],83:[2,35],88:[2,35],90:[2,35],99:[2,35],100:85,101:[2,35],102:[2,35],103:[2,35],106:86,107:[2,35],108:67,115:[2,35],123:[2,35],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,277],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],83:[1,278]},{6:[2,63],25:[2,63],26:[2,63],52:[2,63],83:[2,63],88:[2,63]},{5:279,25:[1,5]},{47:[2,55],52:[2,55]},{47:[2,58],52:[2,58],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,280],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:281,25:[1,5],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{5:282,25:[1,5]},{1:[2,130],6:[2,130],25:[2,130],26:[2,130],47:[2,130],52:[2,130],55:[2,130],70:[2,130],75:[2,130],83:[2,130],88:[2,130],90:[2,130],99:[2,130],101:[2,130],102:[2,130],103:[2,130],107:[2,130],115:[2,130],123:[2,130],125:[2,130],126:[2,130],129:[2,130],130:[2,130],131:[2,130],132:[2,130],133:[2,130],134:[2,130]},{5:283,25:[1,5]},{26:[1,284],118:[1,285],119:252,120:[1,213]},{1:[2,167],6:[2,167],25:[2,167],26:[2,167],47:[2,167],52:[2,167],55:[2,167],70:[2,167],75:[2,167],83:[2,167],88:[2,167],90:[2,167],99:[2,167],101:[2,167],102:[2,167],103:[2,167],107:[2,167],115:[2,167],123:[2,167],125:[2,167],126:[2,167],129:[2,167],130:[2,167],131:[2,167],132:[2,167],133:[2,167],134:[2,167]},{5:286,25:[1,5]},{26:[2,170],118:[2,170],120:[2,170]},{5:287,25:[1,5],52:[1,288]},{25:[2,126],52:[2,126],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,94],6:[2,94],25:[2,94],26:[2,94],47:[2,94],52:[2,94],55:[2,94],70:[2,94],75:[2,94],83:[2,94],88:[2,94],90:[2,94],99:[2,94],101:[2,94],102:[2,94],103:[2,94],107:[2,94],115:[2,94],123:[2,94],125:[2,94],126:[2,94],129:[2,94],130:[2,94],131:[2,94],132:[2,94],133:[2,94],134:[2,94]},{1:[2,97],5:289,6:[2,97],25:[1,5],26:[2,97],47:[2,97],52:[2,97],55:[2,97],70:[2,97],75:[2,97],83:[2,97],88:[2,97],90:[2,97],99:[2,97],100:85,101:[1,63],102:[2,97],103:[1,64],106:86,107:[1,66],108:67,115:[2,97],123:[2,97],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{99:[1,290]},{88:[1,291],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,111],6:[2,111],25:[2,111],26:[2,111],38:[2,111],47:[2,111],52:[2,111],55:[2,111],64:[2,111],65:[2,111],66:[2,111],68:[2,111],70:[2,111],71:[2,111],75:[2,111],81:[2,111],82:[2,111],83:[2,111],88:[2,111],90:[2,111],99:[2,111],101:[2,111],102:[2,111],103:[2,111],107:[2,111],113:[2,111],114:[2,111],115:[2,111],123:[2,111],125:[2,111],126:[2,111],129:[2,111],130:[2,111],131:[2,111],132:[2,111],133:[2,111],134:[2,111]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],91:292,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:197,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,25:[1,144],27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,58:145,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],84:293,85:[1,56],86:[1,57],87:[1,55],91:143,93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[2,120],25:[2,120],26:[2,120],52:[2,120],83:[2,120],88:[2,120]},{6:[1,260],25:[1,261],26:[1,294]},{1:[2,137],6:[2,137],25:[2,137],26:[2,137],47:[2,137],52:[2,137],55:[2,137],70:[2,137],75:[2,137],83:[2,137],88:[2,137],90:[2,137],99:[2,137],100:85,101:[1,63],102:[2,137],103:[1,64],106:86,107:[1,66],108:67,115:[2,137],123:[2,137],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,139],6:[2,139],25:[2,139],26:[2,139],47:[2,139],52:[2,139],55:[2,139],70:[2,139],75:[2,139],83:[2,139],88:[2,139],90:[2,139],99:[2,139],100:85,101:[1,63],102:[2,139],103:[1,64],106:86,107:[1,66],108:67,115:[2,139],123:[2,139],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{113:[2,157],114:[2,157]},{8:295,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:296,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:297,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,85],6:[2,85],25:[2,85],26:[2,85],38:[2,85],47:[2,85],52:[2,85],55:[2,85],64:[2,85],65:[2,85],66:[2,85],68:[2,85],70:[2,85],71:[2,85],75:[2,85],81:[2,85],82:[2,85],83:[2,85],88:[2,85],90:[2,85],99:[2,85],101:[2,85],102:[2,85],103:[2,85],107:[2,85],113:[2,85],114:[2,85],115:[2,85],123:[2,85],125:[2,85],126:[2,85],129:[2,85],130:[2,85],131:[2,85],132:[2,85],133:[2,85],134:[2,85]},{11:165,27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:298,40:164,42:168,44:[1,46],86:[1,111]},{6:[2,86],11:165,25:[2,86],26:[2,86],27:166,28:[1,71],29:167,30:[1,69],31:[1,70],39:163,40:164,42:168,44:[1,46],52:[2,86],74:299,86:[1,111]},{6:[2,88],25:[2,88],26:[2,88],52:[2,88],75:[2,88]},{6:[2,38],25:[2,38],26:[2,38],52:[2,38],75:[2,38],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{8:300,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{70:[2,115],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,36],6:[2,36],25:[2,36],26:[2,36],47:[2,36],52:[2,36],55:[2,36],70:[2,36],75:[2,36],83:[2,36],88:[2,36],90:[2,36],99:[2,36],101:[2,36],102:[2,36],103:[2,36],107:[2,36],115:[2,36],123:[2,36],125:[2,36],126:[2,36],129:[2,36],130:[2,36],131:[2,36],132:[2,36],133:[2,36],134:[2,36]},{1:[2,106],6:[2,106],25:[2,106],26:[2,106],47:[2,106],52:[2,106],55:[2,106],64:[2,106],65:[2,106],66:[2,106],68:[2,106],70:[2,106],71:[2,106],75:[2,106],81:[2,106],82:[2,106],83:[2,106],88:[2,106],90:[2,106],99:[2,106],101:[2,106],102:[2,106],103:[2,106],107:[2,106],115:[2,106],123:[2,106],125:[2,106],126:[2,106],129:[2,106],130:[2,106],131:[2,106],132:[2,106],133:[2,106],134:[2,106]},{1:[2,47],6:[2,47],25:[2,47],26:[2,47],47:[2,47],52:[2,47],55:[2,47],70:[2,47],75:[2,47],83:[2,47],88:[2,47],90:[2,47],99:[2,47],101:[2,47],102:[2,47],103:[2,47],107:[2,47],115:[2,47],123:[2,47],125:[2,47],126:[2,47],129:[2,47],130:[2,47],131:[2,47],132:[2,47],133:[2,47],134:[2,47]},{1:[2,195],6:[2,195],25:[2,195],26:[2,195],47:[2,195],52:[2,195],55:[2,195],70:[2,195],75:[2,195],83:[2,195],88:[2,195],90:[2,195],99:[2,195],101:[2,195],102:[2,195],103:[2,195],107:[2,195],115:[2,195],123:[2,195],125:[2,195],126:[2,195],129:[2,195],130:[2,195],131:[2,195],132:[2,195],133:[2,195],134:[2,195]},{1:[2,174],6:[2,174],25:[2,174],26:[2,174],47:[2,174],52:[2,174],55:[2,174],70:[2,174],75:[2,174],83:[2,174],88:[2,174],90:[2,174],99:[2,174],101:[2,174],102:[2,174],103:[2,174],107:[2,174],115:[2,174],118:[2,174],123:[2,174],125:[2,174],126:[2,174],129:[2,174],130:[2,174],131:[2,174],132:[2,174],133:[2,174],134:[2,174]},{1:[2,131],6:[2,131],25:[2,131],26:[2,131],47:[2,131],52:[2,131],55:[2,131],70:[2,131],75:[2,131],83:[2,131],88:[2,131],90:[2,131],99:[2,131],101:[2,131],102:[2,131],103:[2,131],107:[2,131],115:[2,131],123:[2,131],125:[2,131],126:[2,131],129:[2,131],130:[2,131],131:[2,131],132:[2,131],133:[2,131],134:[2,131]},{1:[2,132],6:[2,132],25:[2,132],26:[2,132],47:[2,132],52:[2,132],55:[2,132],70:[2,132],75:[2,132],83:[2,132],88:[2,132],90:[2,132],95:[2,132],99:[2,132],101:[2,132],102:[2,132],103:[2,132],107:[2,132],115:[2,132],123:[2,132],125:[2,132],126:[2,132],129:[2,132],130:[2,132],131:[2,132],132:[2,132],133:[2,132],134:[2,132]},{1:[2,165],6:[2,165],25:[2,165],26:[2,165],47:[2,165],52:[2,165],55:[2,165],70:[2,165],75:[2,165],83:[2,165],88:[2,165],90:[2,165],99:[2,165],101:[2,165],102:[2,165],103:[2,165],107:[2,165],115:[2,165],123:[2,165],125:[2,165],126:[2,165],129:[2,165],130:[2,165],131:[2,165],132:[2,165],133:[2,165],134:[2,165]},{5:301,25:[1,5]},{26:[1,302]},{6:[1,303],26:[2,171],118:[2,171],120:[2,171]},{8:304,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{1:[2,98],6:[2,98],25:[2,98],26:[2,98],47:[2,98],52:[2,98],55:[2,98],70:[2,98],75:[2,98],83:[2,98],88:[2,98],90:[2,98],99:[2,98],101:[2,98],102:[2,98],103:[2,98],107:[2,98],115:[2,98],123:[2,98],125:[2,98],126:[2,98],129:[2,98],130:[2,98],131:[2,98],132:[2,98],133:[2,98],134:[2,98]},{1:[2,135],6:[2,135],25:[2,135],26:[2,135],47:[2,135],52:[2,135],55:[2,135],64:[2,135],65:[2,135],66:[2,135],68:[2,135],70:[2,135],71:[2,135],75:[2,135],81:[2,135],82:[2,135],83:[2,135],88:[2,135],90:[2,135],99:[2,135],101:[2,135],102:[2,135],103:[2,135],107:[2,135],115:[2,135],123:[2,135],125:[2,135],126:[2,135],129:[2,135],130:[2,135],131:[2,135],132:[2,135],133:[2,135],134:[2,135]},{1:[2,114],6:[2,114],25:[2,114],26:[2,114],47:[2,114],52:[2,114],55:[2,114],64:[2,114],65:[2,114],66:[2,114],68:[2,114],70:[2,114],71:[2,114],75:[2,114],81:[2,114],82:[2,114],83:[2,114],88:[2,114],90:[2,114],99:[2,114],101:[2,114],102:[2,114],103:[2,114],107:[2,114],115:[2,114],123:[2,114],125:[2,114],126:[2,114],129:[2,114],130:[2,114],131:[2,114],132:[2,114],133:[2,114],134:[2,114]},{6:[2,121],25:[2,121],26:[2,121],52:[2,121],83:[2,121],88:[2,121]},{6:[2,51],25:[2,51],26:[2,51],51:305,52:[1,222]},{6:[2,122],25:[2,122],26:[2,122],52:[2,122],83:[2,122],88:[2,122]},{1:[2,160],6:[2,160],25:[2,160],26:[2,160],47:[2,160],52:[2,160],55:[2,160],70:[2,160],75:[2,160],83:[2,160],88:[2,160],90:[2,160],99:[2,160],100:85,101:[2,160],102:[2,160],103:[2,160],106:86,107:[2,160],108:67,115:[1,306],123:[2,160],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,162],6:[2,162],25:[2,162],26:[2,162],47:[2,162],52:[2,162],55:[2,162],70:[2,162],75:[2,162],83:[2,162],88:[2,162],90:[2,162],99:[2,162],100:85,101:[2,162],102:[1,307],103:[2,162],106:86,107:[2,162],108:67,115:[2,162],123:[2,162],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,161],6:[2,161],25:[2,161],26:[2,161],47:[2,161],52:[2,161],55:[2,161],70:[2,161],75:[2,161],83:[2,161],88:[2,161],90:[2,161],99:[2,161],100:85,101:[2,161],102:[2,161],103:[2,161],106:86,107:[2,161],108:67,115:[2,161],123:[2,161],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,89],25:[2,89],26:[2,89],52:[2,89],75:[2,89]},{6:[2,51],25:[2,51],26:[2,51],51:308,52:[1,232]},{26:[1,309],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{26:[1,310]},{1:[2,168],6:[2,168],25:[2,168],26:[2,168],47:[2,168],52:[2,168],55:[2,168],70:[2,168],75:[2,168],83:[2,168],88:[2,168],90:[2,168],99:[2,168],101:[2,168],102:[2,168],103:[2,168],107:[2,168],115:[2,168],123:[2,168],125:[2,168],126:[2,168],129:[2,168],130:[2,168],131:[2,168],132:[2,168],133:[2,168],134:[2,168]},{26:[2,172],118:[2,172],120:[2,172]},{25:[2,127],52:[2,127],100:85,101:[1,63],103:[1,64],106:86,107:[1,66],108:67,123:[1,84],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[1,260],25:[1,261],26:[1,311]},{8:312,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{8:313,9:115,10:20,11:21,12:[1,22],13:8,14:9,15:10,16:11,17:12,18:13,19:14,20:15,21:16,22:17,23:18,24:19,27:60,28:[1,71],29:49,30:[1,69],31:[1,70],32:24,33:[1,50],34:[1,51],35:[1,52],36:[1,53],37:23,42:61,43:[1,45],44:[1,46],45:[1,29],48:30,49:[1,58],50:[1,59],56:47,57:48,59:36,61:25,62:26,63:27,73:[1,68],76:[1,43],80:[1,28],85:[1,56],86:[1,57],87:[1,55],93:[1,38],97:[1,44],98:[1,54],100:39,101:[1,63],103:[1,64],104:40,105:[1,65],106:41,107:[1,66],108:67,116:[1,42],121:37,122:[1,62],124:[1,31],125:[1,32],126:[1,33],127:[1,34],128:[1,35]},{6:[1,271],25:[1,272],26:[1,314]},{6:[2,39],25:[2,39],26:[2,39],52:[2,39],75:[2,39]},{1:[2,166],6:[2,166],25:[2,166],26:[2,166],47:[2,166],52:[2,166],55:[2,166],70:[2,166],75:[2,166],83:[2,166],88:[2,166],90:[2,166],99:[2,166],101:[2,166],102:[2,166],103:[2,166],107:[2,166],115:[2,166],123:[2,166],125:[2,166],126:[2,166],129:[2,166],130:[2,166],131:[2,166],132:[2,166],133:[2,166],134:[2,166]},{6:[2,123],25:[2,123],26:[2,123],52:[2,123],83:[2,123],88:[2,123]},{1:[2,163],6:[2,163],25:[2,163],26:[2,163],47:[2,163],52:[2,163],55:[2,163],70:[2,163],75:[2,163],83:[2,163],88:[2,163],90:[2,163],99:[2,163],100:85,101:[2,163],102:[2,163],103:[2,163],106:86,107:[2,163],108:67,115:[2,163],123:[2,163],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{1:[2,164],6:[2,164],25:[2,164],26:[2,164],47:[2,164],52:[2,164],55:[2,164],70:[2,164],75:[2,164],83:[2,164],88:[2,164],90:[2,164],99:[2,164],100:85,101:[2,164],102:[2,164],103:[2,164],106:86,107:[2,164],108:67,115:[2,164],123:[2,164],125:[1,78],126:[1,77],129:[1,76],130:[1,79],131:[1,80],132:[1,81],133:[1,82],134:[1,83]},{6:[2,90],25:[2,90],26:[2,90],52:[2,90],75:[2,90]}],
defaultActions: {58:[2,49],59:[2,50],73:[2,3],92:[2,104],186:[2,84]},
parseError: function parseError(str, hash) {
throw new Error(str);
},
parse: function parse(input) {
var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1;
this.lexer.setInput(input);
this.lexer.yy = this.yy;
this.yy.lexer = this.lexer;
if (typeof this.lexer.yylloc == "undefined")
this.lexer.yylloc = {};
var yyloc = this.lexer.yylloc;
lstack.push(yyloc);
if (typeof this.yy.parseError === "function")
this.parseError = this.yy.parseError;
function popStack(n) {
stack.length = stack.length - 2 * n;
vstack.length = vstack.length - n;
lstack.length = lstack.length - n;
}
function lex() {
var token;
token = self.lexer.lex() || 1;
if (typeof token !== "number") {
token = self.symbols_[token] || token;
}
return token;
}
var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
while (true) {
state = stack[stack.length - 1];
if (this.defaultActions[state]) {
action = this.defaultActions[state];
} else {
if (symbol == null)
symbol = lex();
action = table[state] && table[state][symbol];
}
if (typeof action === "undefined" || !action.length || !action[0]) {
if (!recovering) {
expected = [];
for (p in table[state])
if (this.terminals_[p] && p > 2) {
expected.push("'" + this.terminals_[p] + "'");
}
var errStr = "";
if (this.lexer.showPosition) {
errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + this.terminals_[symbol] + "'";
} else {
errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1?"end of input":"'" + (this.terminals_[symbol] || symbol) + "'");
}
this.parseError(errStr, {text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected});
}
}
if (action[0] instanceof Array && action.length > 1) {
throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
}
switch (action[0]) {
case 1:
stack.push(symbol);
vstack.push(this.lexer.yytext);
lstack.push(this.lexer.yylloc);
stack.push(action[1]);
symbol = null;
if (!preErrorSymbol) {
yyleng = this.lexer.yyleng;
yytext = this.lexer.yytext;
yylineno = this.lexer.yylineno;
yyloc = this.lexer.yylloc;
if (recovering > 0)
recovering--;
} else {
symbol = preErrorSymbol;
preErrorSymbol = null;
}
break;
case 2:
len = this.productions_[action[1]][1];
yyval.$ = vstack[vstack.length - len];
yyval._$ = {first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column};
r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
if (typeof r !== "undefined") {
return r;
}
if (len) {
stack = stack.slice(0, -1 * len * 2);
vstack = vstack.slice(0, -1 * len);
lstack = lstack.slice(0, -1 * len);
}
stack.push(this.productions_[action[1]][0]);
vstack.push(yyval.$);
lstack.push(yyval._$);
newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
stack.push(newState);
break;
case 3:
return true;
}
}
return true;
}
};
module.exports = parser;
});
define('ace/mode/coffee/nodes', ['require', 'exports', 'module' , 'ace/mode/coffee/scope', 'ace/mode/coffee/lexer', 'ace/mode/coffee/helpers'], function(require, exports, module) {
// Generated by CoffeeScript 1.2.1-pre
var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, starts, unfoldSoak, utility, _ref, _ref1,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; },
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
Scope = require('./scope').Scope;
_ref = require('./lexer'), RESERVED = _ref.RESERVED, STRICT_PROSCRIBED = _ref.STRICT_PROSCRIBED;
_ref1 = require('./helpers'), compact = _ref1.compact, flatten = _ref1.flatten, extend = _ref1.extend, merge = _ref1.merge, del = _ref1.del, starts = _ref1.starts, ends = _ref1.ends, last = _ref1.last;
exports.extend = extend;
YES = function() {
return true;
};
NO = function() {
return false;
};
THIS = function() {
return this;
};
NEGATE = function() {
this.negated = !this.negated;
return this;
};
exports.Base = Base = (function() {
Base.name = 'Base';
function Base() {}
Base.prototype.compile = function(o, lvl) {
var node;
o = extend({}, o);
if (lvl) o.level = lvl;
node = this.unfoldSoak(o) || this;
node.tab = o.indent;
if (o.level === LEVEL_TOP || !node.isStatement(o)) {
return node.compileNode(o);
} else {
return node.compileClosure(o);
}
};
Base.prototype.compileClosure = function(o) {
if (this.jumps()) {
throw SyntaxError('cannot use a pure statement in an expression.');
}
o.sharedScope = true;
return Closure.wrap(this).compileNode(o);
};
Base.prototype.cache = function(o, level, reused) {
var ref, sub;
if (!this.isComplex()) {
ref = level ? this.compile(o, level) : this;
return [ref, ref];
} else {
ref = new Literal(reused || o.scope.freeVariable('ref'));
sub = new Assign(ref, this);
if (level) {
return [sub.compile(o, level), ref.value];
} else {
return [sub, ref];
}
}
};
Base.prototype.compileLoopReference = function(o, name) {
var src, tmp;
src = tmp = this.compile(o, LEVEL_LIST);
if (!((-Infinity < +src && +src < Infinity) || IDENTIFIER.test(src) && o.scope.check(src, true))) {
src = "" + (tmp = o.scope.freeVariable(name)) + " = " + src;
}
return [src, tmp];
};
Base.prototype.makeReturn = function(res) {
var me;
me = this.unwrapAll();
if (res) {
return new Call(new Literal("" + res + ".push"), [me]);
} else {
return new Return(me);
}
};
Base.prototype.contains = function(pred) {
var contains;
contains = false;
this.traverseChildren(false, function(node) {
if (pred(node)) {
contains = true;
return false;
}
});
return contains;
};
Base.prototype.containsType = function(type) {
return this instanceof type || this.contains(function(node) {
return node instanceof type;
});
};
Base.prototype.lastNonComment = function(list) {
var i;
i = list.length;
while (i--) {
if (!(list[i] instanceof Comment)) return list[i];
}
return null;
};
Base.prototype.toString = function(idt, name) {
var tree;
if (idt == null) idt = '';
if (name == null) name = this.constructor.name;
tree = '\n' + idt + name;
if (this.soak) tree += '?';
this.eachChild(function(node) {
return tree += node.toString(idt + TAB);
});
return tree;
};
Base.prototype.eachChild = function(func) {
var attr, child, _i, _j, _len, _len1, _ref2, _ref3;
if (!this.children) return this;
_ref2 = this.children;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
attr = _ref2[_i];
if (this[attr]) {
_ref3 = flatten([this[attr]]);
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
child = _ref3[_j];
if (func(child) === false) return this;
}
}
}
return this;
};
Base.prototype.traverseChildren = function(crossScope, func) {
return this.eachChild(function(child) {
if (func(child) === false) return false;
return child.traverseChildren(crossScope, func);
});
};
Base.prototype.invert = function() {
return new Op('!', this);
};
Base.prototype.unwrapAll = function() {
var node;
node = this;
while (node !== (node = node.unwrap())) {
continue;
}
return node;
};
Base.prototype.children = [];
Base.prototype.isStatement = NO;
Base.prototype.jumps = NO;
Base.prototype.isComplex = YES;
Base.prototype.isChainable = NO;
Base.prototype.isAssignable = NO;
Base.prototype.unwrap = THIS;
Base.prototype.unfoldSoak = NO;
Base.prototype.assigns = NO;
return Base;
})();
exports.Block = Block = (function(_super) {
__extends(Block, _super);
Block.name = 'Block';
function Block(nodes) {
this.expressions = compact(flatten(nodes || []));
}
Block.prototype.children = ['expressions'];
Block.prototype.push = function(node) {
this.expressions.push(node);
return this;
};
Block.prototype.pop = function() {
return this.expressions.pop();
};
Block.prototype.unshift = function(node) {
this.expressions.unshift(node);
return this;
};
Block.prototype.unwrap = function() {
if (this.expressions.length === 1) {
return this.expressions[0];
} else {
return this;
}
};
Block.prototype.isEmpty = function() {
return !this.expressions.length;
};
Block.prototype.isStatement = function(o) {
var exp, _i, _len, _ref2;
_ref2 = this.expressions;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
exp = _ref2[_i];
if (exp.isStatement(o)) return true;
}
return false;
};
Block.prototype.jumps = function(o) {
var exp, _i, _len, _ref2;
_ref2 = this.expressions;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
exp = _ref2[_i];
if (exp.jumps(o)) return exp;
}
};
Block.prototype.makeReturn = function(res) {
var expr, len;
len = this.expressions.length;
while (len--) {
expr = this.expressions[len];
if (!(expr instanceof Comment)) {
this.expressions[len] = expr.makeReturn(res);
if (expr instanceof Return && !expr.expression) {
this.expressions.splice(len, 1);
}
break;
}
}
return this;
};
Block.prototype.compile = function(o, level) {
if (o == null) o = {};
if (o.scope) {
return Block.__super__.compile.call(this, o, level);
} else {
return this.compileRoot(o);
}
};
Block.prototype.compileNode = function(o) {
var code, codes, node, top, _i, _len, _ref2;
this.tab = o.indent;
top = o.level === LEVEL_TOP;
codes = [];
_ref2 = this.expressions;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
node = _ref2[_i];
node = node.unwrapAll();
node = node.unfoldSoak(o) || node;
if (node instanceof Block) {
codes.push(node.compileNode(o));
} else if (top) {
node.front = true;
code = node.compile(o);
if (!node.isStatement(o)) {
code = "" + this.tab + code + ";";
if (node instanceof Literal) code = "" + code + "\n";
}
codes.push(code);
} else {
codes.push(node.compile(o, LEVEL_LIST));
}
}
if (top) {
if (this.spaced) {
return "\n" + (codes.join('\n\n')) + "\n";
} else {
return codes.join('\n');
}
}
code = codes.join(', ') || 'void 0';
if (codes.length > 1 && o.level >= LEVEL_LIST) {
return "(" + code + ")";
} else {
return code;
}
};
Block.prototype.compileRoot = function(o) {
var code, exp, i, prelude, preludeExps, rest;
o.indent = o.bare ? '' : TAB;
o.scope = new Scope(null, this, null);
o.level = LEVEL_TOP;
this.spaced = true;
prelude = "";
if (!o.bare) {
preludeExps = (function() {
var _i, _len, _ref2, _results;
_ref2 = this.expressions;
_results = [];
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
exp = _ref2[i];
if (!(exp.unwrap() instanceof Comment)) break;
_results.push(exp);
}
return _results;
}).call(this);
rest = this.expressions.slice(preludeExps.length);
this.expressions = preludeExps;
if (preludeExps.length) {
prelude = "" + (this.compileNode(merge(o, {
indent: ''
}))) + "\n";
}
this.expressions = rest;
}
code = this.compileWithDeclarations(o);
if (o.bare) return code;
return "" + prelude + "(function() {\n" + code + "\n}).call(this);\n";
};
Block.prototype.compileWithDeclarations = function(o) {
var assigns, code, declars, exp, i, post, rest, scope, spaced, _i, _len, _ref2, _ref3, _ref4;
code = post = '';
_ref2 = this.expressions;
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
exp = _ref2[i];
exp = exp.unwrap();
if (!(exp instanceof Comment || exp instanceof Literal)) break;
}
o = merge(o, {
level: LEVEL_TOP
});
if (i) {
rest = this.expressions.splice(i, 9e9);
_ref3 = [this.spaced, false], spaced = _ref3[0], this.spaced = _ref3[1];
_ref4 = [this.compileNode(o), spaced], code = _ref4[0], this.spaced = _ref4[1];
this.expressions = rest;
}
post = this.compileNode(o);
scope = o.scope;
if (scope.expressions === this) {
declars = o.scope.hasDeclarations();
assigns = scope.hasAssignments;
if (declars || assigns) {
if (i) code += '\n';
code += "" + this.tab + "var ";
if (declars) code += scope.declaredVariables().join(', ');
if (assigns) {
if (declars) code += ",\n" + (this.tab + TAB);
code += scope.assignedVariables().join(",\n" + (this.tab + TAB));
}
code += ';\n';
}
}
return code + post;
};
Block.wrap = function(nodes) {
if (nodes.length === 1 && nodes[0] instanceof Block) return nodes[0];
return new Block(nodes);
};
return Block;
})(Base);
exports.Literal = Literal = (function(_super) {
__extends(Literal, _super);
Literal.name = 'Literal';
function Literal(value) {
this.value = value;
}
Literal.prototype.makeReturn = function() {
if (this.isStatement()) {
return this;
} else {
return Literal.__super__.makeReturn.apply(this, arguments);
}
};
Literal.prototype.isAssignable = function() {
return IDENTIFIER.test(this.value);
};
Literal.prototype.isStatement = function() {
var _ref2;
return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger';
};
Literal.prototype.isComplex = NO;
Literal.prototype.assigns = function(name) {
return name === this.value;
};
Literal.prototype.jumps = function(o) {
if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) {
return this;
}
if (this.value === 'continue' && !(o != null ? o.loop : void 0)) return this;
};
Literal.prototype.compileNode = function(o) {
var code, _ref2;
code = this.isUndefined ? o.level >= LEVEL_ACCESS ? '(void 0)' : 'void 0' : this.value === 'this' ? ((_ref2 = o.scope.method) != null ? _ref2.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value;
if (this.isStatement()) {
return "" + this.tab + code + ";";
} else {
return code;
}
};
Literal.prototype.toString = function() {
return ' "' + this.value + '"';
};
return Literal;
})(Base);
exports.Return = Return = (function(_super) {
__extends(Return, _super);
Return.name = 'Return';
function Return(expr) {
if (expr && !expr.unwrap().isUndefined) this.expression = expr;
}
Return.prototype.children = ['expression'];
Return.prototype.isStatement = YES;
Return.prototype.makeReturn = THIS;
Return.prototype.jumps = THIS;
Return.prototype.compile = function(o, level) {
var expr, _ref2;
expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0;
if (expr && !(expr instanceof Return)) {
return expr.compile(o, level);
} else {
return Return.__super__.compile.call(this, o, level);
}
};
Return.prototype.compileNode = function(o) {
return this.tab + ("return" + [this.expression ? " " + (this.expression.compile(o, LEVEL_PAREN)) : void 0] + ";");
};
return Return;
})(Base);
exports.Value = Value = (function(_super) {
__extends(Value, _super);
Value.name = 'Value';
function Value(base, props, tag) {
if (!props && base instanceof Value) return base;
this.base = base;
this.properties = props || [];
if (tag) this[tag] = true;
return this;
}
Value.prototype.children = ['base', 'properties'];
Value.prototype.add = function(props) {
this.properties = this.properties.concat(props);
return this;
};
Value.prototype.hasProperties = function() {
return !!this.properties.length;
};
Value.prototype.isArray = function() {
return !this.properties.length && this.base instanceof Arr;
};
Value.prototype.isComplex = function() {
return this.hasProperties() || this.base.isComplex();
};
Value.prototype.isAssignable = function() {
return this.hasProperties() || this.base.isAssignable();
};
Value.prototype.isSimpleNumber = function() {
return this.base instanceof Literal && SIMPLENUM.test(this.base.value);
};
Value.prototype.isString = function() {
return this.base instanceof Literal && IS_STRING.test(this.base.value);
};
Value.prototype.isAtomic = function() {
var node, _i, _len, _ref2;
_ref2 = this.properties.concat(this.base);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
node = _ref2[_i];
if (node.soak || node instanceof Call) return false;
}
return true;
};
Value.prototype.isStatement = function(o) {
return !this.properties.length && this.base.isStatement(o);
};
Value.prototype.assigns = function(name) {
return !this.properties.length && this.base.assigns(name);
};
Value.prototype.jumps = function(o) {
return !this.properties.length && this.base.jumps(o);
};
Value.prototype.isObject = function(onlyGenerated) {
if (this.properties.length) return false;
return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated);
};
Value.prototype.isSplice = function() {
return last(this.properties) instanceof Slice;
};
Value.prototype.unwrap = function() {
if (this.properties.length) {
return this;
} else {
return this.base;
}
};
Value.prototype.cacheReference = function(o) {
var base, bref, name, nref;
name = last(this.properties);
if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) {
return [this, this];
}
base = new Value(this.base, this.properties.slice(0, -1));
if (base.isComplex()) {
bref = new Literal(o.scope.freeVariable('base'));
base = new Value(new Parens(new Assign(bref, base)));
}
if (!name) return [base, bref];
if (name.isComplex()) {
nref = new Literal(o.scope.freeVariable('name'));
name = new Index(new Assign(nref, name.index));
nref = new Index(nref);
}
return [base.add(name), new Value(bref || base.base, [nref || name])];
};
Value.prototype.compileNode = function(o) {
var code, prop, props, _i, _len;
this.base.front = this.front;
props = this.properties;
code = this.base.compile(o, props.length ? LEVEL_ACCESS : null);
if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) {
code = "" + code + ".";
}
for (_i = 0, _len = props.length; _i < _len; _i++) {
prop = props[_i];
code += prop.compile(o);
}
return code;
};
Value.prototype.unfoldSoak = function(o) {
var result,
_this = this;
if (this.unfoldedSoak != null) return this.unfoldedSoak;
result = (function() {
var fst, i, ifn, prop, ref, snd, _i, _len, _ref2;
if (ifn = _this.base.unfoldSoak(o)) {
Array.prototype.push.apply(ifn.body.properties, _this.properties);
return ifn;
}
_ref2 = _this.properties;
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
prop = _ref2[i];
if (!prop.soak) continue;
prop.soak = false;
fst = new Value(_this.base, _this.properties.slice(0, i));
snd = new Value(_this.base, _this.properties.slice(i));
if (fst.isComplex()) {
ref = new Literal(o.scope.freeVariable('ref'));
fst = new Parens(new Assign(ref, fst));
snd.base = ref;
}
return new If(new Existence(fst), snd, {
soak: true
});
}
return null;
})();
return this.unfoldedSoak = result || false;
};
return Value;
})(Base);
exports.Comment = Comment = (function(_super) {
__extends(Comment, _super);
Comment.name = 'Comment';
function Comment(comment) {
this.comment = comment;
}
Comment.prototype.isStatement = YES;
Comment.prototype.makeReturn = THIS;
Comment.prototype.compileNode = function(o, level) {
var code;
code = '/*' + multident(this.comment, this.tab) + ("\n" + this.tab + "*/\n");
if ((level || o.level) === LEVEL_TOP) code = o.indent + code;
return code;
};
return Comment;
})(Base);
exports.Call = Call = (function(_super) {
__extends(Call, _super);
Call.name = 'Call';
function Call(variable, args, soak) {
this.args = args != null ? args : [];
this.soak = soak;
this.isNew = false;
this.isSuper = variable === 'super';
this.variable = this.isSuper ? null : variable;
}
Call.prototype.children = ['variable', 'args'];
Call.prototype.newInstance = function() {
var base, _ref2;
base = ((_ref2 = this.variable) != null ? _ref2.base : void 0) || this.variable;
if (base instanceof Call && !base.isNew) {
base.newInstance();
} else {
this.isNew = true;
}
return this;
};
Call.prototype.superReference = function(o) {
var accesses, method, name;
method = o.scope.method;
if (!method) throw SyntaxError('cannot call super outside of a function.');
name = method.name;
if (name == null) {
throw SyntaxError('cannot call super on an anonymous function.');
}
if (method.klass) {
accesses = [new Access(new Literal('__super__'))];
if (method["static"]) {
accesses.push(new Access(new Literal('constructor')));
}
accesses.push(new Access(new Literal(name)));
return (new Value(new Literal(method.klass), accesses)).compile(o);
} else {
return "" + name + ".__super__.constructor";
}
};
Call.prototype.unfoldSoak = function(o) {
var call, ifn, left, list, rite, _i, _len, _ref2, _ref3;
if (this.soak) {
if (this.variable) {
if (ifn = unfoldSoak(o, this, 'variable')) return ifn;
_ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1];
} else {
left = new Literal(this.superReference(o));
rite = new Value(left);
}
rite = new Call(rite, this.args);
rite.isNew = this.isNew;
left = new Literal("typeof " + (left.compile(o)) + " === \"function\"");
return new If(left, new Value(rite), {
soak: true
});
}
call = this;
list = [];
while (true) {
if (call.variable instanceof Call) {
list.push(call);
call = call.variable;
continue;
}
if (!(call.variable instanceof Value)) break;
list.push(call);
if (!((call = call.variable.base) instanceof Call)) break;
}
_ref3 = list.reverse();
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
call = _ref3[_i];
if (ifn) {
if (call.variable instanceof Call) {
call.variable = ifn;
} else {
call.variable.base = ifn;
}
}
ifn = unfoldSoak(o, call, 'variable');
}
return ifn;
};
Call.prototype.filterImplicitObjects = function(list) {
var node, nodes, obj, prop, properties, _i, _j, _len, _len1, _ref2;
nodes = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
node = list[_i];
if (!((typeof node.isObject === "function" ? node.isObject() : void 0) && node.base.generated)) {
nodes.push(node);
continue;
}
obj = null;
_ref2 = node.base.properties;
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
prop = _ref2[_j];
if (prop instanceof Assign || prop instanceof Comment) {
if (!obj) nodes.push(obj = new Obj(properties = [], true));
properties.push(prop);
} else {
nodes.push(prop);
obj = null;
}
}
}
return nodes;
};
Call.prototype.compileNode = function(o) {
var arg, args, code, _ref2;
if ((_ref2 = this.variable) != null) _ref2.front = this.front;
if (code = Splat.compileSplattedArray(o, this.args, true)) {
return this.compileSplat(o, code);
}
args = this.filterImplicitObjects(this.args);
args = ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = args.length; _i < _len; _i++) {
arg = args[_i];
_results.push(arg.compile(o, LEVEL_LIST));
}
return _results;
})()).join(', ');
if (this.isSuper) {
return this.superReference(o) + (".call(this" + (args && ', ' + args) + ")");
} else {
return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")");
}
};
Call.prototype.compileSuper = function(args, o) {
return "" + (this.superReference(o)) + ".call(this" + (args.length ? ', ' : '') + args + ")";
};
Call.prototype.compileSplat = function(o, splatArgs) {
var base, fun, idt, name, ref;
if (this.isSuper) {
return "" + (this.superReference(o)) + ".apply(this, " + splatArgs + ")";
}
if (this.isNew) {
idt = this.tab + TAB;
return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args), t = typeof result;\n" + idt + "return t == \"object\" || t == \"function\" ? result || child : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function(){})";
}
base = new Value(this.variable);
if ((name = base.properties.pop()) && base.isComplex()) {
ref = o.scope.freeVariable('ref');
fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o));
} else {
fun = base.compile(o, LEVEL_ACCESS);
if (SIMPLENUM.test(fun)) fun = "(" + fun + ")";
if (name) {
ref = fun;
fun += name.compile(o);
} else {
ref = 'null';
}
}
return "" + fun + ".apply(" + ref + ", " + splatArgs + ")";
};
return Call;
})(Base);
exports.Extends = Extends = (function(_super) {
__extends(Extends, _super);
Extends.name = 'Extends';
function Extends(child, parent) {
this.child = child;
this.parent = parent;
}
Extends.prototype.children = ['child', 'parent'];
Extends.prototype.compile = function(o) {
return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o);
};
return Extends;
})(Base);
exports.Access = Access = (function(_super) {
__extends(Access, _super);
Access.name = 'Access';
function Access(name, tag) {
this.name = name;
this.name.asKey = true;
this.soak = tag === 'soak';
}
Access.prototype.children = ['name'];
Access.prototype.compile = function(o) {
var name;
name = this.name.compile(o);
if (IDENTIFIER.test(name)) {
return "." + name;
} else {
return "[" + name + "]";
}
};
Access.prototype.isComplex = NO;
return Access;
})(Base);
exports.Index = Index = (function(_super) {
__extends(Index, _super);
Index.name = 'Index';
function Index(index) {
this.index = index;
}
Index.prototype.children = ['index'];
Index.prototype.compile = function(o) {
return "[" + (this.index.compile(o, LEVEL_PAREN)) + "]";
};
Index.prototype.isComplex = function() {
return this.index.isComplex();
};
return Index;
})(Base);
exports.Range = Range = (function(_super) {
__extends(Range, _super);
Range.name = 'Range';
Range.prototype.children = ['from', 'to'];
function Range(from, to, tag) {
this.from = from;
this.to = to;
this.exclusive = tag === 'exclusive';
this.equals = this.exclusive ? '' : '=';
}
Range.prototype.compileVariables = function(o) {
var step, _ref2, _ref3, _ref4, _ref5;
o = merge(o, {
top: true
});
_ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1];
_ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1];
if (step = del(o, 'step')) {
_ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1];
}
_ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1];
if (this.stepVar) return this.stepNum = this.stepVar.match(SIMPLENUM);
};
Range.prototype.compileNode = function(o) {
var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, stepPart, to, varPart, _ref2, _ref3;
if (!this.fromVar) this.compileVariables(o);
if (!o.index) return this.compileArray(o);
known = this.fromNum && this.toNum;
idx = del(o, 'index');
idxName = del(o, 'name');
namedIndex = idxName && idxName !== idx;
varPart = "" + idx + " = " + this.fromC;
if (this.toC !== this.toVar) varPart += ", " + this.toC;
if (this.step !== this.stepVar) varPart += ", " + this.step;
_ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1];
condPart = this.stepNum ? +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar);
stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? "" + idx + "++" : "" + idx + "--" : namedIndex ? "" + cond + " ? ++" + idx + " : --" + idx : "" + cond + " ? " + idx + "++ : " + idx + "--";
if (namedIndex) varPart = "" + idxName + " = " + varPart;
if (namedIndex) stepPart = "" + idxName + " = " + stepPart;
return "" + varPart + "; " + condPart + "; " + stepPart;
};
Range.prototype.compileArray = function(o) {
var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results;
if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) {
range = (function() {
_results = [];
for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this);
if (this.exclusive) range.pop();
return "[" + (range.join(', ')) + "]";
}
idt = this.tab + TAB;
i = o.scope.freeVariable('i');
result = o.scope.freeVariable('results');
pre = "\n" + idt + result + " = [];";
if (this.fromNum && this.toNum) {
o.index = i;
body = this.compileNode(o);
} else {
vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : '');
cond = "" + this.fromVar + " <= " + this.toVar;
body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--";
}
post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent;
hasArgs = function(node) {
return node != null ? node.contains(function(n) {
return n instanceof Literal && n.value === 'arguments' && !n.asKey;
}) : void 0;
};
if (hasArgs(this.from) || hasArgs(this.to)) args = ', arguments';
return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")";
};
return Range;
})(Base);
exports.Slice = Slice = (function(_super) {
__extends(Slice, _super);
Slice.name = 'Slice';
Slice.prototype.children = ['range'];
function Slice(range) {
this.range = range;
Slice.__super__.constructor.call(this);
}
Slice.prototype.compileNode = function(o) {
var compiled, from, fromStr, to, toStr, _ref2;
_ref2 = this.range, to = _ref2.to, from = _ref2.from;
fromStr = from && from.compile(o, LEVEL_PAREN) || '0';
compiled = to && to.compile(o, LEVEL_PAREN);
if (to && !(!this.range.exclusive && +compiled === -1)) {
toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? "" + (+compiled + 1) : (compiled = to.compile(o, LEVEL_ACCESS), "" + compiled + " + 1 || 9e9"));
}
return ".slice(" + fromStr + (toStr || '') + ")";
};
return Slice;
})(Base);
exports.Obj = Obj = (function(_super) {
__extends(Obj, _super);
Obj.name = 'Obj';
function Obj(props, generated) {
this.generated = generated != null ? generated : false;
this.objects = this.properties = props || [];
}
Obj.prototype.children = ['properties'];
Obj.prototype.compileNode = function(o) {
var i, idt, indent, join, lastNoncom, node, obj, prop, propName, propNames, props, _i, _j, _len, _len1, _ref2;
props = this.properties;
propNames = [];
_ref2 = this.properties;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
prop = _ref2[_i];
if (prop.isComplex()) prop = prop.variable;
if (prop != null) {
propName = prop.unwrapAll().value.toString();
if (__indexOf.call(propNames, propName) >= 0) {
throw SyntaxError("multiple object literal properties named \"" + propName + "\"");
}
propNames.push(propName);
}
}
if (!props.length) return (this.front ? '({})' : '{}');
if (this.generated) {
for (_j = 0, _len1 = props.length; _j < _len1; _j++) {
node = props[_j];
if (node instanceof Value) {
throw new Error('cannot have an implicit value in an implicit object');
}
}
}
idt = o.indent += TAB;
lastNoncom = this.lastNonComment(this.properties);
props = (function() {
var _k, _len2, _results;
_results = [];
for (i = _k = 0, _len2 = props.length; _k < _len2; i = ++_k) {
prop = props[i];
join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n';
indent = prop instanceof Comment ? '' : idt;
if (prop instanceof Value && prop["this"]) {
prop = new Assign(prop.properties[0].name, prop, 'object');
}
if (!(prop instanceof Comment)) {
if (!(prop instanceof Assign)) prop = new Assign(prop, prop, 'object');
(prop.variable.base || prop.variable).asKey = true;
}
_results.push(indent + prop.compile(o, LEVEL_TOP) + join);
}
return _results;
})();
props = props.join('');
obj = "{" + (props && '\n' + props + '\n' + this.tab) + "}";
if (this.front) {
return "(" + obj + ")";
} else {
return obj;
}
};
Obj.prototype.assigns = function(name) {
var prop, _i, _len, _ref2;
_ref2 = this.properties;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
prop = _ref2[_i];
if (prop.assigns(name)) return true;
}
return false;
};
return Obj;
})(Base);
exports.Arr = Arr = (function(_super) {
__extends(Arr, _super);
Arr.name = 'Arr';
function Arr(objs) {
this.objects = objs || [];
}
Arr.prototype.children = ['objects'];
Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects;
Arr.prototype.compileNode = function(o) {
var code, obj, objs;
if (!this.objects.length) return '[]';
o.indent += TAB;
objs = this.filterImplicitObjects(this.objects);
if (code = Splat.compileSplattedArray(o, objs)) return code;
code = ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = objs.length; _i < _len; _i++) {
obj = objs[_i];
_results.push(obj.compile(o, LEVEL_LIST));
}
return _results;
})()).join(', ');
if (code.indexOf('\n') >= 0) {
return "[\n" + o.indent + code + "\n" + this.tab + "]";
} else {
return "[" + code + "]";
}
};
Arr.prototype.assigns = function(name) {
var obj, _i, _len, _ref2;
_ref2 = this.objects;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
obj = _ref2[_i];
if (obj.assigns(name)) return true;
}
return false;
};
return Arr;
})(Base);
exports.Class = Class = (function(_super) {
__extends(Class, _super);
Class.name = 'Class';
function Class(variable, parent, body) {
this.variable = variable;
this.parent = parent;
this.body = body != null ? body : new Block;
this.boundFuncs = [];
this.body.classBody = true;
}
Class.prototype.children = ['variable', 'parent', 'body'];
Class.prototype.determineName = function() {
var decl, tail;
if (!this.variable) return null;
decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value;
if (__indexOf.call(STRICT_PROSCRIBED, decl) >= 0) {
throw SyntaxError("variable name may not be " + decl);
}
return decl && (decl = IDENTIFIER.test(decl) && decl);
};
Class.prototype.setContext = function(name) {
return this.body.traverseChildren(false, function(node) {
if (node.classBody) return false;
if (node instanceof Literal && node.value === 'this') {
return node.value = name;
} else if (node instanceof Code) {
node.klass = name;
if (node.bound) return node.context = name;
}
});
};
Class.prototype.addBoundFunctions = function(o) {
var bvar, lhs, _i, _len, _ref2, _results;
if (this.boundFuncs.length) {
_ref2 = this.boundFuncs;
_results = [];
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
bvar = _ref2[_i];
lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o);
_results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)")));
}
return _results;
}
};
Class.prototype.addProperties = function(node, name, o) {
var assign, base, exprs, func, props;
props = node.base.properties.slice(0);
exprs = (function() {
var _results;
_results = [];
while (assign = props.shift()) {
if (assign instanceof Assign) {
base = assign.variable.base;
delete assign.context;
func = assign.value;
if (base.value === 'constructor') {
if (this.ctor) {
throw new Error('cannot define more than one constructor in a class');
}
if (func.bound) {
throw new Error('cannot define a constructor as a bound function');
}
if (func instanceof Code) {
assign = this.ctor = func;
} else {
this.externalCtor = o.scope.freeVariable('class');
assign = new Assign(new Literal(this.externalCtor), func);
}
} else {
if (assign.variable["this"]) {
func["static"] = true;
if (func.bound) func.context = name;
} else {
assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), new Access(base)]);
if (func instanceof Code && func.bound) {
this.boundFuncs.push(base);
func.bound = false;
}
}
}
}
_results.push(assign);
}
return _results;
}).call(this);
return compact(exprs);
};
Class.prototype.walkBody = function(name, o) {
var _this = this;
return this.traverseChildren(false, function(child) {
var exps, i, node, _i, _len, _ref2;
if (child instanceof Class) return false;
if (child instanceof Block) {
_ref2 = exps = child.expressions;
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
node = _ref2[i];
if (node instanceof Value && node.isObject(true)) {
exps[i] = _this.addProperties(node, name, o);
}
}
return child.expressions = exps = flatten(exps);
}
});
};
Class.prototype.hoistDirectivePrologue = function() {
var expressions, index, node;
index = 0;
expressions = this.body.expressions;
while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) {
++index;
}
return this.directives = expressions.splice(0, index);
};
Class.prototype.ensureConstructor = function(name) {
if (!this.ctor) {
this.ctor = new Code;
if (this.parent) {
this.ctor.body.push(new Literal("" + name + ".__super__.constructor.apply(this, arguments)"));
}
if (this.externalCtor) {
this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)"));
}
this.ctor.body.makeReturn();
this.body.expressions.unshift(this.ctor);
}
this.ctor.ctor = this.ctor.name = name;
this.ctor.klass = null;
return this.ctor.noReturn = true;
};
Class.prototype.compileNode = function(o) {
var call, decl, klass, lname, name, params, _ref2;
decl = this.determineName();
name = decl || '_Class';
if (name.reserved) name = "_" + name;
lname = new Literal(name);
this.hoistDirectivePrologue();
this.setContext(name);
this.walkBody(name, o);
this.ensureConstructor(name);
this.body.spaced = true;
if (!(this.ctor instanceof Code)) this.body.expressions.unshift(this.ctor);
if (decl) {
this.body.expressions.unshift(new Assign(new Value(new Literal(name), [new Access(new Literal('name'))]), new Literal("'" + name + "'")));
}
this.body.expressions.push(lname);
(_ref2 = this.body.expressions).unshift.apply(_ref2, this.directives);
this.addBoundFunctions(o);
call = Closure.wrap(this.body);
if (this.parent) {
this.superClass = new Literal(o.scope.freeVariable('super', false));
this.body.expressions.unshift(new Extends(lname, this.superClass));
call.args.push(this.parent);
params = call.variable.params || call.variable.base.params;
params.push(new Param(this.superClass));
}
klass = new Parens(call, true);
if (this.variable) klass = new Assign(this.variable, klass);
return klass.compile(o);
};
return Class;
})(Base);
exports.Assign = Assign = (function(_super) {
__extends(Assign, _super);
Assign.name = 'Assign';
function Assign(variable, value, context, options) {
var forbidden, name, _ref2;
this.variable = variable;
this.value = value;
this.context = context;
this.param = options && options.param;
this.subpattern = options && options.subpattern;
forbidden = (_ref2 = (name = this.variable.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0);
if (forbidden && this.context !== 'object') {
throw SyntaxError("variable name may not be \"" + name + "\"");
}
}
Assign.prototype.children = ['variable', 'value'];
Assign.prototype.isStatement = function(o) {
return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0;
};
Assign.prototype.assigns = function(name) {
return this[this.context === 'object' ? 'value' : 'variable'].assigns(name);
};
Assign.prototype.unfoldSoak = function(o) {
return unfoldSoak(o, this, 'variable');
};
Assign.prototype.compileNode = function(o) {
var isValue, match, name, val, varBase, _ref2, _ref3, _ref4, _ref5;
if (isValue = this.variable instanceof Value) {
if (this.variable.isArray() || this.variable.isObject()) {
return this.compilePatternMatch(o);
}
if (this.variable.isSplice()) return this.compileSplice(o);
if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') {
return this.compileConditional(o);
}
}
name = this.variable.compile(o, LEVEL_LIST);
if (!this.context) {
if (!(varBase = this.variable.unwrapAll()).isAssignable()) {
throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned.");
}
if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) {
if (this.param) {
o.scope.add(name, 'var');
} else {
o.scope.find(name);
}
}
}
if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) {
if (match[1]) this.value.klass = match[1];
this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5];
}
val = this.value.compile(o, LEVEL_LIST);
if (this.context === 'object') return "" + name + ": " + val;
val = name + (" " + (this.context || '=') + " ") + val;
if (o.level <= LEVEL_LIST) {
return val;
} else {
return "(" + val + ")";
}
};
Assign.prototype.compilePatternMatch = function(o) {
var acc, assigns, code, i, idx, isObject, ivar, name, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8;
top = o.level === LEVEL_TOP;
value = this.value;
objects = this.variable.base.objects;
if (!(olen = objects.length)) {
code = value.compile(o);
if (o.level >= LEVEL_OP) {
return "(" + code + ")";
} else {
return code;
}
}
isObject = this.variable.isObject();
if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) {
if (obj instanceof Assign) {
_ref2 = obj, (_ref3 = _ref2.variable, idx = _ref3.base), obj = _ref2.value;
} else {
if (obj.base instanceof Parens) {
_ref4 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref4[0], idx = _ref4[1];
} else {
idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0);
}
}
acc = IDENTIFIER.test(idx.unwrap().value || 0);
value = new Value(value);
value.properties.push(new (acc ? Access : Index)(idx));
if (_ref5 = obj.unwrap().value, __indexOf.call(RESERVED, _ref5) >= 0) {
throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (value.compile(o)));
}
return new Assign(obj, value, null, {
param: this.param
}).compile(o, LEVEL_TOP);
}
vvar = value.compile(o, LEVEL_LIST);
assigns = [];
splat = false;
if (!IDENTIFIER.test(vvar) || this.variable.assigns(vvar)) {
assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar);
vvar = ref;
}
for (i = _i = 0, _len = objects.length; _i < _len; i = ++_i) {
obj = objects[i];
idx = i;
if (isObject) {
if (obj instanceof Assign) {
_ref6 = obj, (_ref7 = _ref6.variable, idx = _ref7.base), obj = _ref6.value;
} else {
if (obj.base instanceof Parens) {
_ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref8[0], idx = _ref8[1];
} else {
idx = obj["this"] ? obj.properties[0].name : obj;
}
}
}
if (!splat && obj instanceof Splat) {
name = obj.name.unwrap().value;
obj = obj.unwrap();
val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i;
if (rest = olen - i - 1) {
ivar = o.scope.freeVariable('i');
val += ", " + ivar + " = " + vvar + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])";
} else {
val += ") : []";
}
val = new Literal(val);
splat = "" + ivar + "++";
} else {
name = obj.unwrap().value;
if (obj instanceof Splat) {
obj = obj.name.compile(o);
throw new SyntaxError("multiple splats are disallowed in an assignment: " + obj + "...");
}
if (typeof idx === 'number') {
idx = new Literal(splat || idx);
acc = false;
} else {
acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0);
}
val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]);
}
if ((name != null) && __indexOf.call(RESERVED, name) >= 0) {
throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (val.compile(o)));
}
assigns.push(new Assign(obj, val, null, {
param: this.param,
subpattern: true
}).compile(o, LEVEL_LIST));
}
if (!(top || this.subpattern)) assigns.push(vvar);
code = assigns.join(', ');
if (o.level < LEVEL_LIST) {
return code;
} else {
return "(" + code + ")";
}
};
Assign.prototype.compileConditional = function(o) {
var left, right, _ref2;
_ref2 = this.variable.cacheReference(o), left = _ref2[0], right = _ref2[1];
if (left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) {
throw new Error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been defined.");
}
if (__indexOf.call(this.context, "?") >= 0) o.isExistentialEquals = true;
return new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compile(o);
};
Assign.prototype.compileSplice = function(o) {
var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4;
_ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive;
name = this.variable.compile(o);
_ref3 = (from != null ? from.cache(o, LEVEL_OP) : void 0) || ['0', '0'], fromDecl = _ref3[0], fromRef = _ref3[1];
if (to) {
if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) {
to = +to.compile(o) - +fromRef;
if (!exclusive) to += 1;
} else {
to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef;
if (!exclusive) to += ' + 1';
}
} else {
to = "9e9";
}
_ref4 = this.value.cache(o, LEVEL_LIST), valDef = _ref4[0], valRef = _ref4[1];
code = "[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat(" + valDef + ")), " + valRef;
if (o.level > LEVEL_TOP) {
return "(" + code + ")";
} else {
return code;
}
};
return Assign;
})(Base);
exports.Code = Code = (function(_super) {
__extends(Code, _super);
Code.name = 'Code';
function Code(params, body, tag) {
this.params = params || [];
this.body = body || new Block;
this.bound = tag === 'boundfunc';
if (this.bound) this.context = '_this';
}
Code.prototype.children = ['params', 'body'];
Code.prototype.isStatement = function() {
return !!this.ctor;
};
Code.prototype.jumps = NO;
Code.prototype.compileNode = function(o) {
var code, exprs, i, idt, lit, name, p, param, params, ref, splats, uniqs, val, wasEmpty, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8;
o.scope = new Scope(o.scope, this.body, this);
o.scope.shared = del(o, 'sharedScope');
o.indent += TAB;
delete o.bare;
delete o.isExistentialEquals;
params = [];
exprs = [];
_ref2 = this.paramNames();
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
name = _ref2[_i];
if (!o.scope.check(name)) o.scope.parameter(name);
}
_ref3 = this.params;
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
param = _ref3[_j];
if (!param.splat) continue;
_ref4 = this.params;
for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) {
p = _ref4[_k];
if (p.name.value) o.scope.add(p.name.value, 'var', true);
}
splats = new Assign(new Value(new Arr((function() {
var _l, _len3, _ref5, _results;
_ref5 = this.params;
_results = [];
for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) {
p = _ref5[_l];
_results.push(p.asReference(o));
}
return _results;
}).call(this))), new Value(new Literal('arguments')));
break;
}
_ref5 = this.params;
for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) {
param = _ref5[_l];
if (param.isComplex()) {
val = ref = param.asReference(o);
if (param.value) val = new Op('?', ref, param.value);
exprs.push(new Assign(new Value(param.name), val, '=', {
param: true
}));
} else {
ref = param;
if (param.value) {
lit = new Literal(ref.name.value + ' == null');
val = new Assign(new Value(param.name), param.value, '=');
exprs.push(new If(lit, val));
}
}
if (!splats) params.push(ref);
}
wasEmpty = this.body.isEmpty();
if (splats) exprs.unshift(splats);
if (exprs.length) {
(_ref6 = this.body.expressions).unshift.apply(_ref6, exprs);
}
for (i = _m = 0, _len4 = params.length; _m < _len4; i = ++_m) {
p = params[i];
o.scope.parameter(params[i] = p.compile(o));
}
uniqs = [];
_ref7 = this.paramNames();
for (_n = 0, _len5 = _ref7.length; _n < _len5; _n++) {
name = _ref7[_n];
if (__indexOf.call(uniqs, name) >= 0) {
throw SyntaxError("multiple parameters named '" + name + "'");
}
uniqs.push(name);
}
if (!(wasEmpty || this.noReturn)) this.body.makeReturn();
if (this.bound) {
if ((_ref8 = o.scope.parent.method) != null ? _ref8.bound : void 0) {
this.bound = this.context = o.scope.parent.method.context;
} else if (!this["static"]) {
o.scope.parent.assign('_this', 'this');
}
}
idt = o.indent;
code = 'function';
if (this.ctor) code += ' ' + this.name;
code += '(' + params.join(', ') + ') {';
if (!this.body.isEmpty()) {
code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab;
}
code += '}';
if (this.ctor) return this.tab + code;
if (this.front || (o.level >= LEVEL_ACCESS)) {
return "(" + code + ")";
} else {
return code;
}
};
Code.prototype.paramNames = function() {
var names, param, _i, _len, _ref2;
names = [];
_ref2 = this.params;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
param = _ref2[_i];
names.push.apply(names, param.names());
}
return names;
};
Code.prototype.traverseChildren = function(crossScope, func) {
if (crossScope) {
return Code.__super__.traverseChildren.call(this, crossScope, func);
}
};
return Code;
})(Base);
exports.Param = Param = (function(_super) {
__extends(Param, _super);
Param.name = 'Param';
function Param(name, value, splat) {
var _ref2;
this.name = name;
this.value = value;
this.splat = splat;
if (_ref2 = (name = this.name.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) {
throw SyntaxError("parameter name \"" + name + "\" is not allowed");
}
}
Param.prototype.children = ['name', 'value'];
Param.prototype.compile = function(o) {
return this.name.compile(o, LEVEL_LIST);
};
Param.prototype.asReference = function(o) {
var node;
if (this.reference) return this.reference;
node = this.name;
if (node["this"]) {
node = node.properties[0].name;
if (node.value.reserved) {
node = new Literal(o.scope.freeVariable(node.value));
}
} else if (node.isComplex()) {
node = new Literal(o.scope.freeVariable('arg'));
}
node = new Value(node);
if (this.splat) node = new Splat(node);
return this.reference = node;
};
Param.prototype.isComplex = function() {
return this.name.isComplex();
};
Param.prototype.names = function(name) {
var atParam, names, obj, _i, _len, _ref2;
if (name == null) name = this.name;
atParam = function(obj) {
var value;
value = obj.properties[0].name.value;
if (value.reserved) {
return [];
} else {
return [value];
}
};
if (name instanceof Literal) return [name.value];
if (name instanceof Value) return atParam(name);
names = [];
_ref2 = name.objects;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
obj = _ref2[_i];
if (obj instanceof Assign) {
names.push(obj.variable.base.value);
} else if (obj.isArray() || obj.isObject()) {
names.push.apply(names, this.names(obj.base));
} else if (obj["this"]) {
names.push.apply(names, atParam(obj));
} else {
names.push(obj.base.value);
}
}
return names;
};
return Param;
})(Base);
exports.Splat = Splat = (function(_super) {
__extends(Splat, _super);
Splat.name = 'Splat';
Splat.prototype.children = ['name'];
Splat.prototype.isAssignable = YES;
function Splat(name) {
this.name = name.compile ? name : new Literal(name);
}
Splat.prototype.assigns = function(name) {
return this.name.assigns(name);
};
Splat.prototype.compile = function(o) {
if (this.index != null) {
return this.compileParam(o);
} else {
return this.name.compile(o);
}
};
Splat.prototype.unwrap = function() {
return this.name;
};
Splat.compileSplattedArray = function(o, list, apply) {
var args, base, code, i, index, node, _i, _len;
index = -1;
while ((node = list[++index]) && !(node instanceof Splat)) {
continue;
}
if (index >= list.length) return '';
if (list.length === 1) {
code = list[0].compile(o, LEVEL_LIST);
if (apply) return code;
return "" + (utility('slice')) + ".call(" + code + ")";
}
args = list.slice(index);
for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) {
node = args[i];
code = node.compile(o, LEVEL_LIST);
args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]";
}
if (index === 0) {
return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")");
}
base = (function() {
var _j, _len1, _ref2, _results;
_ref2 = list.slice(0, index);
_results = [];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
node = _ref2[_j];
_results.push(node.compile(o, LEVEL_LIST));
}
return _results;
})();
return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")";
};
return Splat;
})(Base);
exports.While = While = (function(_super) {
__extends(While, _super);
While.name = 'While';
function While(condition, options) {
this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition;
this.guard = options != null ? options.guard : void 0;
}
While.prototype.children = ['condition', 'guard', 'body'];
While.prototype.isStatement = YES;
While.prototype.makeReturn = function(res) {
if (res) {
return While.__super__.makeReturn.apply(this, arguments);
} else {
this.returns = !this.jumps({
loop: true
});
return this;
}
};
While.prototype.addBody = function(body) {
this.body = body;
return this;
};
While.prototype.jumps = function() {
var expressions, node, _i, _len;
expressions = this.body.expressions;
if (!expressions.length) return false;
for (_i = 0, _len = expressions.length; _i < _len; _i++) {
node = expressions[_i];
if (node.jumps({
loop: true
})) return node;
}
return false;
};
While.prototype.compileNode = function(o) {
var body, code, rvar, set;
o.indent += TAB;
set = '';
body = this.body;
if (body.isEmpty()) {
body = '';
} else {
if (this.returns) {
body.makeReturn(rvar = o.scope.freeVariable('results'));
set = "" + this.tab + rvar + " = [];\n";
}
if (this.guard) {
if (body.expressions.length > 1) {
body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
} else {
if (this.guard) body = Block.wrap([new If(this.guard, body)]);
}
}
body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab;
}
code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}");
if (this.returns) code += "\n" + this.tab + "return " + rvar + ";";
return code;
};
return While;
})(Base);
exports.Op = Op = (function(_super) {
var CONVERSIONS, INVERSIONS;
__extends(Op, _super);
Op.name = 'Op';
function Op(op, first, second, flip) {
if (op === 'in') return new In(first, second);
if (op === 'do') return this.generateDo(first);
if (op === 'new') {
if (first instanceof Call && !first["do"] && !first.isNew) {
return first.newInstance();
}
if (first instanceof Code && first.bound || first["do"]) {
first = new Parens(first);
}
}
this.operator = CONVERSIONS[op] || op;
this.first = first;
this.second = second;
this.flip = !!flip;
return this;
}
CONVERSIONS = {
'==': '===',
'!=': '!==',
'of': 'in'
};
INVERSIONS = {
'!==': '===',
'===': '!=='
};
Op.prototype.children = ['first', 'second'];
Op.prototype.isSimpleNumber = NO;
Op.prototype.isUnary = function() {
return !this.second;
};
Op.prototype.isComplex = function() {
var _ref2;
return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex();
};
Op.prototype.isChainable = function() {
var _ref2;
return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!==';
};
Op.prototype.invert = function() {
var allInvertable, curr, fst, op, _ref2;
if (this.isChainable() && this.first.isChainable()) {
allInvertable = true;
curr = this;
while (curr && curr.operator) {
allInvertable && (allInvertable = curr.operator in INVERSIONS);
curr = curr.first;
}
if (!allInvertable) return new Parens(this).invert();
curr = this;
while (curr && curr.operator) {
curr.invert = !curr.invert;
curr.operator = INVERSIONS[curr.operator];
curr = curr.first;
}
return this;
} else if (op = INVERSIONS[this.operator]) {
this.operator = op;
if (this.first.unwrap() instanceof Op) this.first.invert();
return this;
} else if (this.second) {
return new Parens(this).invert();
} else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((_ref2 = fst.operator) === '!' || _ref2 === 'in' || _ref2 === 'instanceof')) {
return fst;
} else {
return new Op('!', this);
}
};
Op.prototype.unfoldSoak = function(o) {
var _ref2;
return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first');
};
Op.prototype.generateDo = function(exp) {
var call, func, param, passedParams, ref, _i, _len, _ref2;
passedParams = [];
func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp;
_ref2 = func.params || [];
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
param = _ref2[_i];
if (param.value) {
passedParams.push(param.value);
delete param.value;
} else {
passedParams.push(param);
}
}
call = new Call(exp, passedParams);
call["do"] = true;
return call;
};
Op.prototype.compileNode = function(o) {
var code, isChain, _ref2, _ref3;
isChain = this.isChainable() && this.first.isChainable();
if (!isChain) this.first.front = this.front;
if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) {
throw SyntaxError('delete operand may not be argument or var');
}
if (((_ref2 = this.operator) === '--' || _ref2 === '++') && (_ref3 = this.first.unwrapAll().value, __indexOf.call(STRICT_PROSCRIBED, _ref3) >= 0)) {
throw SyntaxError('prefix increment/decrement may not have eval or arguments operand');
}
if (this.isUnary()) return this.compileUnary(o);
if (isChain) return this.compileChain(o);
if (this.operator === '?') return this.compileExistence(o);
code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP);
if (o.level <= LEVEL_OP) {
return code;
} else {
return "(" + code + ")";
}
};
Op.prototype.compileChain = function(o) {
var code, fst, shared, _ref2;
_ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1];
fst = this.first.compile(o, LEVEL_OP);
code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP));
return "(" + code + ")";
};
Op.prototype.compileExistence = function(o) {
var fst, ref;
if (this.first.isComplex() && o.level > LEVEL_TOP) {
ref = new Literal(o.scope.freeVariable('ref'));
fst = new Parens(new Assign(ref, this.first));
} else {
fst = this.first;
ref = fst;
}
return new If(new Existence(fst), ref, {
type: 'if'
}).addElse(this.second).compile(o);
};
Op.prototype.compileUnary = function(o) {
var op, parts, plusMinus;
if (o.level >= LEVEL_ACCESS) return (new Parens(this)).compile(o);
parts = [op = this.operator];
plusMinus = op === '+' || op === '-';
if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) {
parts.push(' ');
}
if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) {
this.first = new Parens(this.first);
}
parts.push(this.first.compile(o, LEVEL_OP));
if (this.flip) parts.reverse();
return parts.join('');
};
Op.prototype.toString = function(idt) {
return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator);
};
return Op;
})(Base);
exports.In = In = (function(_super) {
__extends(In, _super);
In.name = 'In';
function In(object, array) {
this.object = object;
this.array = array;
}
In.prototype.children = ['object', 'array'];
In.prototype.invert = NEGATE;
In.prototype.compileNode = function(o) {
var hasSplat, obj, _i, _len, _ref2;
if (this.array instanceof Value && this.array.isArray()) {
_ref2 = this.array.base.objects;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
obj = _ref2[_i];
if (!(obj instanceof Splat)) continue;
hasSplat = true;
break;
}
if (!hasSplat) return this.compileOrTest(o);
}
return this.compileLoopTest(o);
};
In.prototype.compileOrTest = function(o) {
var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3;
if (this.array.base.objects.length === 0) return "" + (!!this.negated);
_ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1];
_ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1];
tests = (function() {
var _i, _len, _ref4, _results;
_ref4 = this.array.base.objects;
_results = [];
for (i = _i = 0, _len = _ref4.length; _i < _len; i = ++_i) {
item = _ref4[i];
_results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_ACCESS));
}
return _results;
}).call(this);
tests = tests.join(cnj);
if (o.level < LEVEL_OP) {
return tests;
} else {
return "(" + tests + ")";
}
};
In.prototype.compileLoopTest = function(o) {
var code, ref, sub, _ref2;
_ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1];
code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0');
if (sub === ref) return code;
code = sub + ', ' + code;
if (o.level < LEVEL_LIST) {
return code;
} else {
return "(" + code + ")";
}
};
In.prototype.toString = function(idt) {
return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : ''));
};
return In;
})(Base);
exports.Try = Try = (function(_super) {
__extends(Try, _super);
Try.name = 'Try';
function Try(attempt, error, recovery, ensure) {
this.attempt = attempt;
this.error = error;
this.recovery = recovery;
this.ensure = ensure;
}
Try.prototype.children = ['attempt', 'recovery', 'ensure'];
Try.prototype.isStatement = YES;
Try.prototype.jumps = function(o) {
var _ref2;
return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0);
};
Try.prototype.makeReturn = function(res) {
if (this.attempt) this.attempt = this.attempt.makeReturn(res);
if (this.recovery) this.recovery = this.recovery.makeReturn(res);
return this;
};
Try.prototype.compileNode = function(o) {
var catchPart, ensurePart, errorPart, tryPart;
o.indent += TAB;
errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' ';
tryPart = this.attempt.compile(o, LEVEL_TOP);
catchPart = (function() {
var _ref2;
if (this.recovery) {
if (_ref2 = this.error.value, __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) {
throw SyntaxError("catch variable may not be \"" + this.error.value + "\"");
}
if (!o.scope.check(this.error.value)) {
o.scope.add(this.error.value, 'param');
}
return " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}";
} else if (!(this.ensure || this.recovery)) {
return ' catch (_error) {}';
}
}).call(this);
ensurePart = this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : '';
return "" + this.tab + "try {\n" + tryPart + "\n" + this.tab + "}" + (catchPart || '') + ensurePart;
};
return Try;
})(Base);
exports.Throw = Throw = (function(_super) {
__extends(Throw, _super);
Throw.name = 'Throw';
function Throw(expression) {
this.expression = expression;
}
Throw.prototype.children = ['expression'];
Throw.prototype.isStatement = YES;
Throw.prototype.jumps = NO;
Throw.prototype.makeReturn = THIS;
Throw.prototype.compileNode = function(o) {
return this.tab + ("throw " + (this.expression.compile(o)) + ";");
};
return Throw;
})(Base);
exports.Existence = Existence = (function(_super) {
__extends(Existence, _super);
Existence.name = 'Existence';
function Existence(expression) {
this.expression = expression;
}
Existence.prototype.children = ['expression'];
Existence.prototype.invert = NEGATE;
Existence.prototype.compileNode = function(o) {
var cmp, cnj, code, _ref2;
this.expression.front = this.front;
code = this.expression.compile(o, LEVEL_OP);
if (IDENTIFIER.test(code) && !o.scope.check(code)) {
_ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1];
code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null";
} else {
code = "" + code + " " + (this.negated ? '==' : '!=') + " null";
}
if (o.level <= LEVEL_COND) {
return code;
} else {
return "(" + code + ")";
}
};
return Existence;
})(Base);
exports.Parens = Parens = (function(_super) {
__extends(Parens, _super);
Parens.name = 'Parens';
function Parens(body) {
this.body = body;
}
Parens.prototype.children = ['body'];
Parens.prototype.unwrap = function() {
return this.body;
};
Parens.prototype.isComplex = function() {
return this.body.isComplex();
};
Parens.prototype.compileNode = function(o) {
var bare, code, expr;
expr = this.body.unwrap();
if (expr instanceof Value && expr.isAtomic()) {
expr.front = this.front;
return expr.compile(o);
}
code = expr.compile(o, LEVEL_PAREN);
bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns));
if (bare) {
return code;
} else {
return "(" + code + ")";
}
};
return Parens;
})(Base);
exports.For = For = (function(_super) {
__extends(For, _super);
For.name = 'For';
function For(body, source) {
var _ref2;
this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index;
this.body = Block.wrap([body]);
this.own = !!source.own;
this.object = !!source.object;
if (this.object) {
_ref2 = [this.index, this.name], this.name = _ref2[0], this.index = _ref2[1];
}
if (this.index instanceof Value) {
throw SyntaxError('index cannot be a pattern matching expression');
}
this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length;
this.pattern = this.name instanceof Value;
if (this.range && this.index) {
throw SyntaxError('indexes do not apply to range loops');
}
if (this.range && this.pattern) {
throw SyntaxError('cannot pattern match over range loops');
}
this.returns = false;
}
For.prototype.children = ['body', 'source', 'guard', 'step'];
For.prototype.compileNode = function(o) {
var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, kvar, kvarAssign, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2;
body = Block.wrap([this.body]);
lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0;
if (lastJumps && lastJumps instanceof Return) this.returns = false;
source = this.range ? this.source.base : this.source;
scope = o.scope;
name = this.name && this.name.compile(o, LEVEL_LIST);
index = this.index && this.index.compile(o, LEVEL_LIST);
if (name && !this.pattern) {
scope.find(name, {
immediate: true
});
}
if (index) {
scope.find(index, {
immediate: true
});
}
if (this.returns) rvar = scope.freeVariable('results');
ivar = (this.object && index) || scope.freeVariable('i');
kvar = (this.range && name) || index || ivar;
kvarAssign = kvar !== ivar ? "" + kvar + " = " : "";
if (this.step && !this.range) stepvar = scope.freeVariable("step");
if (this.pattern) name = ivar;
varPart = '';
guardPart = '';
defPart = '';
idt1 = this.tab + TAB;
if (this.range) {
forPart = source.compile(merge(o, {
index: ivar,
name: name,
step: this.step
}));
} else {
svar = this.source.compile(o, LEVEL_LIST);
if ((name || this.own) && !IDENTIFIER.test(svar)) {
defPart = "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n";
svar = ref;
}
if (name && !this.pattern) {
namePart = "" + name + " = " + svar + "[" + kvar + "]";
}
if (!this.object) {
lvar = scope.freeVariable('len');
forVarPart = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length";
if (this.step) {
forVarPart += ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP));
}
stepPart = "" + kvarAssign + (this.step ? "" + ivar + " += " + stepvar : (kvar !== ivar ? "++" + ivar : "" + ivar + "++"));
forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart;
}
}
if (this.returns) {
resultPart = "" + this.tab + rvar + " = [];\n";
returnResult = "\n" + this.tab + "return " + rvar + ";";
body.makeReturn(rvar);
}
if (this.guard) {
if (body.expressions.length > 1) {
body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
} else {
if (this.guard) body = Block.wrap([new If(this.guard, body)]);
}
}
if (this.pattern) {
body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + kvar + "]")));
}
defPart += this.pluckDirectCall(o, body);
if (namePart) varPart = "\n" + idt1 + namePart + ";";
if (this.object) {
forPart = "" + kvar + " in " + svar;
if (this.own) {
guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + kvar + ")) continue;";
}
}
body = body.compile(merge(o, {
indent: idt1
}), LEVEL_TOP);
if (body) body = '\n' + body + '\n';
return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || '');
};
For.prototype.pluckDirectCall = function(o, body) {
var base, defs, expr, fn, idx, ref, val, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
defs = '';
_ref2 = body.expressions;
for (idx = _i = 0, _len = _ref2.length; _i < _len; idx = ++_i) {
expr = _ref2[idx];
expr = expr.unwrapAll();
if (!(expr instanceof Call)) continue;
val = expr.variable.unwrapAll();
if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) {
continue;
}
fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val;
ref = new Literal(o.scope.freeVariable('fn'));
base = new Value(ref);
if (val.base) _ref7 = [base, val], val.base = _ref7[0], base = _ref7[1];
body.expressions[idx] = new Call(base, expr.args);
defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n';
}
return defs;
};
return For;
})(While);
exports.Switch = Switch = (function(_super) {
__extends(Switch, _super);
Switch.name = 'Switch';
function Switch(subject, cases, otherwise) {
this.subject = subject;
this.cases = cases;
this.otherwise = otherwise;
}
Switch.prototype.children = ['subject', 'cases', 'otherwise'];
Switch.prototype.isStatement = YES;
Switch.prototype.jumps = function(o) {
var block, conds, _i, _len, _ref2, _ref3, _ref4;
if (o == null) {
o = {
block: true
};
}
_ref2 = this.cases;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
_ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1];
if (block.jumps(o)) return block;
}
return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0;
};
Switch.prototype.makeReturn = function(res) {
var pair, _i, _len, _ref2, _ref3;
_ref2 = this.cases;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
pair = _ref2[_i];
pair[1].makeReturn(res);
}
if (res) {
this.otherwise || (this.otherwise = new Block([new Literal('void 0')]));
}
if ((_ref3 = this.otherwise) != null) _ref3.makeReturn(res);
return this;
};
Switch.prototype.compileNode = function(o) {
var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _j, _len, _len1, _ref2, _ref3, _ref4, _ref5;
idt1 = o.indent + TAB;
idt2 = o.indent = idt1 + TAB;
code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n");
_ref3 = this.cases;
for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) {
_ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1];
_ref5 = flatten([conditions]);
for (_j = 0, _len1 = _ref5.length; _j < _len1; _j++) {
cond = _ref5[_j];
if (!this.subject) cond = cond.invert();
code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n");
}
if (body = block.compile(o, LEVEL_TOP)) code += body + '\n';
if (i === this.cases.length - 1 && !this.otherwise) break;
expr = this.lastNonComment(block.expressions);
if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) {
continue;
}
code += idt2 + 'break;\n';
}
if (this.otherwise && this.otherwise.expressions.length) {
code += idt1 + ("default:\n" + (this.otherwise.compile(o, LEVEL_TOP)) + "\n");
}
return code + this.tab + '}';
};
return Switch;
})(Base);
exports.If = If = (function(_super) {
__extends(If, _super);
If.name = 'If';
function If(condition, body, options) {
this.body = body;
if (options == null) options = {};
this.condition = options.type === 'unless' ? condition.invert() : condition;
this.elseBody = null;
this.isChain = false;
this.soak = options.soak;
}
If.prototype.children = ['condition', 'body', 'elseBody'];
If.prototype.bodyNode = function() {
var _ref2;
return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0;
};
If.prototype.elseBodyNode = function() {
var _ref2;
return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0;
};
If.prototype.addElse = function(elseBody) {
if (this.isChain) {
this.elseBodyNode().addElse(elseBody);
} else {
this.isChain = elseBody instanceof If;
this.elseBody = this.ensureBlock(elseBody);
}
return this;
};
If.prototype.isStatement = function(o) {
var _ref2;
return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0);
};
If.prototype.jumps = function(o) {
var _ref2;
return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0);
};
If.prototype.compileNode = function(o) {
if (this.isStatement(o)) {
return this.compileStatement(o);
} else {
return this.compileExpression(o);
}
};
If.prototype.makeReturn = function(res) {
if (res) {
this.elseBody || (this.elseBody = new Block([new Literal('void 0')]));
}
this.body && (this.body = new Block([this.body.makeReturn(res)]));
this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)]));
return this;
};
If.prototype.ensureBlock = function(node) {
if (node instanceof Block) {
return node;
} else {
return new Block([node]);
}
};
If.prototype.compileStatement = function(o) {
var body, bodyc, child, cond, exeq, ifPart, _ref2;
child = del(o, 'chainChild');
exeq = del(o, 'isExistentialEquals');
if (exeq) {
return new If(this.condition.invert(), this.elseBodyNode(), {
type: 'if'
}).compile(o);
}
cond = this.condition.compile(o, LEVEL_PAREN);
o.indent += TAB;
body = this.ensureBlock(this.body);
bodyc = body.compile(o);
if (1 === ((_ref2 = body.expressions) != null ? _ref2.length : void 0) && !this.elseBody && !child && bodyc && cond && -1 === (bodyc.indexOf('\n')) && 80 > cond.length + bodyc.length) {
return "" + this.tab + "if (" + cond + ") " + (bodyc.replace(/^\s+/, ''));
}
if (bodyc) bodyc = "\n" + bodyc + "\n" + this.tab;
ifPart = "if (" + cond + ") {" + bodyc + "}";
if (!child) ifPart = this.tab + ifPart;
if (!this.elseBody) return ifPart;
return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}");
};
If.prototype.compileExpression = function(o) {
var alt, body, code, cond;
cond = this.condition.compile(o, LEVEL_COND);
body = this.bodyNode().compile(o, LEVEL_LIST);
alt = this.elseBodyNode() ? this.elseBodyNode().compile(o, LEVEL_LIST) : 'void 0';
code = "" + cond + " ? " + body + " : " + alt;
if (o.level >= LEVEL_COND) {
return "(" + code + ")";
} else {
return code;
}
};
If.prototype.unfoldSoak = function() {
return this.soak && this;
};
return If;
})(Base);
Closure = {
wrap: function(expressions, statement, noReturn) {
var args, call, func, mentionsArgs, meth;
if (expressions.jumps()) return expressions;
func = new Code([], Block.wrap([expressions]));
args = [];
if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) {
meth = new Literal(mentionsArgs ? 'apply' : 'call');
args = [new Literal('this')];
if (mentionsArgs) args.push(new Literal('arguments'));
func = new Value(func, [new Access(meth)]);
}
func.noReturn = noReturn;
call = new Call(func, args);
if (statement) {
return Block.wrap([call]);
} else {
return call;
}
},
literalArgs: function(node) {
return node instanceof Literal && node.value === 'arguments' && !node.asKey;
},
literalThis: function(node) {
return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound);
}
};
unfoldSoak = function(o, parent, name) {
var ifn;
if (!(ifn = parent[name].unfoldSoak(o))) return;
parent[name] = ifn.body;
ifn.body = new Value(parent);
return ifn;
};
UTILITIES = {
"extends": function() {
return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp')) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor; child.__super__ = parent.prototype; return child; }";
},
bind: function() {
return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }';
},
indexOf: function() {
return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }";
},
hasProp: function() {
return '{}.hasOwnProperty';
},
slice: function() {
return '[].slice';
}
};
LEVEL_TOP = 1;
LEVEL_PAREN = 2;
LEVEL_LIST = 3;
LEVEL_COND = 4;
LEVEL_OP = 5;
LEVEL_ACCESS = 6;
TAB = ' ';
IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*";
IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$");
SIMPLENUM = /^[+-]?\d+$/;
METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$");
IS_STRING = /^['"]/;
utility = function(name) {
var ref;
ref = "__" + name;
Scope.root.assign(ref, UTILITIES[name]());
return ref;
};
multident = function(code, tab) {
code = code.replace(/\n/g, '$&' + tab);
return code.replace(/\s+$/, '');
};
});
define('ace/mode/coffee/scope', ['require', 'exports', 'module' , 'ace/mode/coffee/helpers'], function(require, exports, module) {
// Generated by CoffeeScript 1.2.1-pre
var Scope, extend, last, _ref;
_ref = require('./helpers'), extend = _ref.extend, last = _ref.last;
exports.Scope = Scope = (function() {
Scope.name = 'Scope';
Scope.root = null;
function Scope(parent, expressions, method) {
this.parent = parent;
this.expressions = expressions;
this.method = method;
this.variables = [
{
name: 'arguments',
type: 'arguments'
}
];
this.positions = {};
if (!this.parent) Scope.root = this;
}
Scope.prototype.add = function(name, type, immediate) {
if (this.shared && !immediate) return this.parent.add(name, type, immediate);
if (Object.prototype.hasOwnProperty.call(this.positions, name)) {
return this.variables[this.positions[name]].type = type;
} else {
return this.positions[name] = this.variables.push({
name: name,
type: type
}) - 1;
}
};
Scope.prototype.find = function(name, options) {
if (this.check(name, options)) return true;
this.add(name, 'var');
return false;
};
Scope.prototype.parameter = function(name) {
if (this.shared && this.parent.check(name, true)) return;
return this.add(name, 'param');
};
Scope.prototype.check = function(name, immediate) {
var found, _ref1;
found = !!this.type(name);
if (found || immediate) return found;
return !!((_ref1 = this.parent) != null ? _ref1.check(name) : void 0);
};
Scope.prototype.temporary = function(name, index) {
if (name.length > 1) {
return '_' + name + (index > 1 ? index - 1 : '');
} else {
return '_' + (index + parseInt(name, 36)).toString(36).replace(/\d/g, 'a');
}
};
Scope.prototype.type = function(name) {
var v, _i, _len, _ref1;
_ref1 = this.variables;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
if (v.name === name) return v.type;
}
return null;
};
Scope.prototype.freeVariable = function(name, reserve) {
var index, temp;
if (reserve == null) reserve = true;
index = 0;
while (this.check((temp = this.temporary(name, index)))) {
index++;
}
if (reserve) this.add(temp, 'var', true);
return temp;
};
Scope.prototype.assign = function(name, value) {
this.add(name, {
value: value,
assigned: true
}, true);
return this.hasAssignments = true;
};
Scope.prototype.hasDeclarations = function() {
return !!this.declaredVariables().length;
};
Scope.prototype.declaredVariables = function() {
var realVars, tempVars, v, _i, _len, _ref1;
realVars = [];
tempVars = [];
_ref1 = this.variables;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
if (v.type === 'var') {
(v.name.charAt(0) === '_' ? tempVars : realVars).push(v.name);
}
}
return realVars.sort().concat(tempVars.sort());
};
Scope.prototype.assignedVariables = function() {
var v, _i, _len, _ref1, _results;
_ref1 = this.variables;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
v = _ref1[_i];
if (v.type.assigned) _results.push("" + v.name + " = " + v.type.value);
}
return _results;
};
return Scope;
})();
});
|
JavaScript
|
/* vim:ts=4:sts=4:sw=4:
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Mihai Sucan <mihai DOT sucan AT gmail DOT com>
* Chris Spencer <chris.ag.spencer AT googlemail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/markdown', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/javascript', 'ace/mode/xml', 'ace/mode/html', 'ace/tokenizer', 'ace/mode/markdown_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var JavaScriptMode = require("./javascript").Mode;
var XmlMode = require("./xml").Mode;
var HtmlMode = require("./html").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var MarkdownHighlightRules = require("./markdown_highlight_rules").MarkdownHighlightRules;
var Mode = function() {
var highlighter = new MarkdownHighlightRules();
this.$tokenizer = new Tokenizer(highlighter.getRules());
this.$embeds = highlighter.getEmbeds();
this.createModeDelegates({
"js-": JavaScriptMode,
"xml-": XmlMode,
"html-": HtmlMode
});
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
if (state == "listblock") {
var match = /^((?:.+)?)([-+*][ ]+)/.exec(line);
if (match) {
return new Array(match[1].length + 1).join(" ") + match[2];
} else {
return "";
}
} else {
return this.$getIndent(line);
}
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
var re = /^(\s*)\/\//;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "//");
}
};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "regex_allowed") {
var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || state == "regex_allowed") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("jslint", function(results) {
var errors = [];
for (var i=0; i<results.data.length; i++) {
var error = results.data[i];
if (error)
errors.push({
row: error.line-1,
column: error.character-1,
text: error.reason,
type: "warning",
lint: error
});
}
session.setAnnotations(errors);
});
worker.on("narcissus", function(e) {
session.setAnnotations([e.data]);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var unicode = require("../unicode");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = function() {
// see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects
var globals = lang.arrayToMap(
// Constructors
("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" +
// E4X
"Namespace|QName|XML|XMLList|" +
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
// Errors
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" +
"SyntaxError|TypeError|URIError|" +
// Non-constructor functions
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" +
"isNaN|parseFloat|parseInt|" +
// Other
"JSON|Math|" +
// Pseudo
"this|arguments|prototype|window|document"
).split("|")
);
var keywords = lang.arrayToMap(
("break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" +
"const|yield|import|get|set").split("|")
);
// keywords which can be followed by regular expressions
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield";
var deprecated = lang.arrayToMap(
("__parent__|__count__|escape|unescape|with|__proto__").split("|")
);
var definitions = lang.arrayToMap(("const|let|var|function").split("|"));
var buildinConstants = lang.arrayToMap(
("null|Infinity|NaN|undefined").split("|")
);
var futureReserved = lang.arrayToMap(
("class|enum|extends|super|export|implements|private|" +
"public|interface|package|protected|static").split("|")
);
// TODO: Unicode escape sequences
var identifierRe = "[" + unicode.packages.L + "\\$_]["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]*\\b";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-6][0-7]?|" + // oct
"37[0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "comment",
regex : /\/\/.*$/
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
merge : true,
regex : /\/\*/,
next : "comment"
}, {
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hex
regex : /0[xX][0-9a-fA-F]+\b/
}, {
token : "constant.numeric", // float
regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
}, { // match stuff like: Sound.prototype.play = function() { }
token : [
"storage.type",
"punctuation.operator",
"support.function",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: Sound.prototype.play = myfunc
token : [
"storage.type",
"punctuation.operator",
"support.function",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)",
next: "function_arguments"
}, { // match stuff like: Sound.play = function() { }
token : [
"storage.type",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: play = function() { }
token : [
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match regular function like: function myFunc(arg) { }
token : [
"storage.type",
"text",
"entity.name.function",
"text",
"paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: foobar: function() { }
token : [
"entity.name.function",
"text",
"punctuation.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // Attempt to match : function() { } (this is for issues with 'foo': function() { })
token : [
"text",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : "constant.language.boolean",
regex : /(?:true|false)\b/
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "regex_allowed"
}, {
token : ["punctuation.operator", "support.function"],
regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : ["punctuation.operator", "support.function.dom"],
regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : ["punctuation.operator", "support.constant"],
regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/
}, {
token : function(value) {
if (globals.hasOwnProperty(value))
return "variable.language";
else if (deprecated.hasOwnProperty(value))
return "invalid.deprecated";
else if (definitions.hasOwnProperty(value))
return "storage.type";
else if (keywords.hasOwnProperty(value))
return "keyword";
else if (buildinConstants.hasOwnProperty(value))
return "constant.language";
else if (futureReserved.hasOwnProperty(value))
return "invalid.illegal";
else if (value == "debugger")
return "invalid.deprecated";
else
return "identifier";
},
regex : identifierRe
}, {
token : "keyword.operator",
regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,
next : "regex_allowed"
}, {
token : "punctuation.operator",
regex : /\?|\:|\,|\;|\./,
next : "regex_allowed"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "regex_allowed"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token : "keyword.operator",
regex : /\/=?/,
next : "regex_allowed"
}, {
token: "comment",
regex: /^#!.*$/
}, {
token : "text",
regex : /\s+/
}
],
// regular expressions are only allowed after certain tokens. This
// makes sure we don't mix up regexps with the divison operator
"regex_allowed": [
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment_regex_allowed"
}, {
token : "comment",
regex : "\\/\\/.*$"
}, {
token: "string.regexp",
regex: "\\/",
next: "regex",
merge: true
}, {
token : "text",
regex : "\\s+"
}, {
// immediately return to the start mode without matching
// anything
token: "empty",
regex: "",
next: "start"
}
],
"regex": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
// flag
token: "string.regexp",
regex: "/\\w*",
next: "start",
merge: true
}, {
token: "string.regexp",
regex: "[^\\\\/\\[]+",
merge: true
}, {
token: "string.regexp.charachterclass",
regex: "\\[",
next: "regex_character_class",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"regex_character_class": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "string.regexp.charachterclass",
regex: "]",
next: "regex",
merge: true
}, {
token: "string.regexp.charachterclass",
regex: "[^\\\\\\]]+",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe,
}, {
token: "punctuation.operator",
regex: "[, ]+",
merge: true
}, {
token: "punctuation.operator",
regex: "$",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"comment_regex_allowed" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
merge : true,
next : "regex_allowed"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
merge : true,
next : "start"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : '[^"\\\\]+',
merge : true
}, {
token : "string",
regex : "\\\\$",
next : "qqstring",
merge : true
}, {
token : "string",
regex : '"|$',
next : "start",
merge : true
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "[^'\\\\]+",
merge : true
}, {
token : "string",
regex : "\\\\$",
next : "qstring",
merge : true
}, {
token : "string",
regex : "'|$",
next : "start",
merge : true
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
});
define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc",
merge : true,
regex : "\\s+"
}, {
token : "comment.doc",
merge : true,
regex : "TODO"
}, {
token : "comment.doc",
merge : true,
regex : "[^@\\*]+"
}, {
token : "comment.doc",
merge : true,
regex : "."
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
merge : true,
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
merge : true,
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = function () {
this.add("braces", "insertion", function (state, action, editor, session, text) {
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '{' + selected + '}',
selection: false
};
} else {
return {
text: '{}',
selection: [1, 1]
};
}
} else if (text == '}') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1});
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString());
var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '(' + selected + ')',
selection: false
};
} else {
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
// We're escaped.
if (leftChar == '\\') {
return null;
}
// Find what token we're inside.
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
// Try and be smart about when we auto insert.
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
// Ignore input and move right one if we're typing over the closing quote.
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
define('ace/mode/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/xml_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/xml'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var XmlFoldMode = require("./folding/xml").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new XmlHighlightRules().getRules());
this.$behaviour = new XmlBehaviour();
this.foldingRules = new XmlFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/xml_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var xmlUtil = require("./xml_util");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var XmlHighlightRules = function() {
// regexp must not have capturing parentheses
// regexps are ordered -> the first match is used
this.$rules = {
start : [{
token : "text",
regex : "<\\!\\[CDATA\\[",
next : "cdata"
}, {
token : "xml_pe",
regex : "<\\?.*?\\?>"
}, {
token : "comment",
merge : true,
regex : "<\\!--",
next : "comment"
}, {
token : "xml_pe",
regex : "<\\!.*?>"
}, {
token : "meta.tag", // opening tag
regex : "<\\/?",
next : "tag"
}, {
token : "text",
regex : "\\s+"
}, {
token : "constant.character.entity",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}, {
token : "text",
regex : "[^<]+"
}],
cdata : [{
token : "text",
regex : "\\]\\]>",
next : "start"
}, {
token : "text",
regex : "\\s+"
}, {
token : "text",
regex : "(?:[^\\]]|\\](?!\\]>))+"
}],
comment : [{
token : "comment",
regex : ".*?-->",
next : "start"
}, {
token : "comment",
merge : true,
regex : ".+"
}]
};
xmlUtil.tag(this.$rules, "tag", "start");
};
oop.inherits(XmlHighlightRules, TextHighlightRules);
exports.XmlHighlightRules = XmlHighlightRules;
});
define('ace/mode/xml_util', ['require', 'exports', 'module' , 'ace/lib/lang'], function(require, exports, module) {
var lang = require("../lib/lang");
var formTags = lang.arrayToMap(
("button|form|input|label|select|textarea").split("|")
);
var tableTags = lang.arrayToMap(
("table|tbody|td|tfoot|th|tr").split("|")
);
function string(state) {
return [{
token : "string",
regex : '".*?"'
}, {
token : "string", // multi line string start
merge : true,
regex : '["].*',
next : state + "_qqstring"
}, {
token : "string",
regex : "'.*?'"
}, {
token : "string", // multi line string start
merge : true,
regex : "['].*",
next : state + "_qstring"
}];
}
function multiLineString(quote, state) {
return [{
token : "string",
merge : true,
regex : ".*?" + quote,
next : state
}, {
token : "string",
merge : true,
regex : '.+'
}];
}
exports.tag = function(states, name, nextState) {
states[name] = [{
token : "text",
regex : "\\s+"
}, {
//token : "meta.tag",
token : function(value) {
if ( value==='a' ) {
return "meta.tag.anchor";
}
else if ( value==='img' ) {
return "meta.tag.image";
}
else if ( value==='script' ) {
return "meta.tag.script";
}
else if ( value==='style' ) {
return "meta.tag.style";
}
else if (formTags.hasOwnProperty(value.toLowerCase())) {
return "meta.tag.form";
}
else if (tableTags.hasOwnProperty(value.toLowerCase())) {
return "meta.tag.table";
}
else {
return "meta.tag";
}
},
merge : true,
regex : "[-_a-zA-Z0-9:]+",
next : name + "_embed_attribute_list"
}, {
token: "empty",
regex: "",
next : name + "_embed_attribute_list"
}];
states[name + "_qstring"] = multiLineString("'", name + "_embed_attribute_list");
states[name + "_qqstring"] = multiLineString("\"", name + "_embed_attribute_list");
states[name + "_embed_attribute_list"] = [{
token : "meta.tag",
merge : true,
regex : "\/?>",
next : nextState
}, {
token : "keyword.operator",
regex : "="
}, {
token : "entity.other.attribute-name",
regex : "[-_a-zA-Z0-9:]+"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "text",
regex : "\\s+"
}].concat(string(name));
};
});
define('ace/mode/behaviour/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
var XmlBehaviour = function () {
this.inherit(CstyleBehaviour, ["string_dquotes"]); // Get string behaviour
this.add("brackets", "insertion", function (state, action, editor, session, text) {
if (text == '<') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return false;
} else {
return {
text: '<>',
selection: [1, 1]
}
}
} else if (text == '>') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '>') { // need some kind of matching check here
return {
text: '',
selection: [1, 1]
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChars = line.substring(cursor.column, cursor.column + 2);
if (rightChars == '</') {
var indent = this.$getIndent(session.doc.getLine(cursor.row)) + session.getTabString();
var next_indent = this.$getIndent(session.doc.getLine(cursor.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
}
}
}
});
}
oop.inherits(XmlBehaviour, Behaviour);
exports.XmlBehaviour = XmlBehaviour;
});
define('ace/mode/folding/xml', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/range', 'ace/mode/folding/fold_mode', 'ace/token_iterator'], function(require, exports, module) {
var oop = require("../../lib/oop");
var lang = require("../../lib/lang");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var TokenIterator = require("../../token_iterator").TokenIterator;
var FoldMode = exports.FoldMode = function(voidElements) {
BaseFoldMode.call(this);
this.voidElements = voidElements || {};
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidget = function(session, foldStyle, row) {
var tag = this._getFirstTagInLine(session, row);
if (tag.closing)
return foldStyle == "markbeginend" ? "end" : "";
if (!tag.tagName || this.voidElements[tag.tagName.toLowerCase()])
return "";
if (tag.selfClosing)
return "";
if (tag.value.indexOf("/" + tag.tagName) !== -1)
return "";
return "start";
};
this._getFirstTagInLine = function(session, row) {
var tokens = session.getTokens(row);
var value = "";
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i];
if (token.type.indexOf("meta.tag") === 0)
value += token.value;
else
value += lang.stringRepeat(" ", token.value.length);
}
return this._parseTag(value);
};
this.tagRe = /^(\s*)(<?(\/?)([-_a-zA-Z0-9:!]*)\s*(\/?)>?)/;
this._parseTag = function(tag) {
var match = this.tagRe.exec(tag);
var column = this.tagRe.lastIndex || 0;
this.tagRe.lastIndex = 0;
return {
value: tag,
match: match ? match[2] : "",
closing: match ? !!match[3] : false,
selfClosing: match ? !!match[5] || match[2] == "/>" : false,
tagName: match ? match[4] : "",
column: match[1] ? column + match[1].length : column
};
};
this._readTagForward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var start;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!start) {
var start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
}
value += token.value;
if (value.indexOf(">") !== -1) {
var tag = this._parseTag(value);
tag.start = start;
tag.end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
iterator.stepForward();
return tag;
}
}
} while(token = iterator.stepForward());
return null;
};
this._readTagBackward = function(iterator) {
var token = iterator.getCurrentToken();
if (!token)
return null;
var value = "";
var end;
do {
if (token.type.indexOf("meta.tag") === 0) {
if (!end) {
end = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn() + token.value.length
};
}
value = token.value + value;
if (value.indexOf("<") !== -1) {
var tag = this._parseTag(value);
tag.end = end;
tag.start = {
row: iterator.getCurrentTokenRow(),
column: iterator.getCurrentTokenColumn()
};
iterator.stepBackward();
return tag;
}
}
} while(token = iterator.stepBackward());
return null;
};
this._pop = function(stack, tag) {
while (stack.length) {
var top = stack[stack.length-1];
if (!tag || top.tagName == tag.tagName) {
return stack.pop();
}
else if (this.voidElements[tag.tagName]) {
return;
}
else if (this.voidElements[top.tagName]) {
stack.pop();
continue;
} else {
return null;
}
}
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var firstTag = this._getFirstTagInLine(session, row);
if (!firstTag.match)
return null;
var isBackward = firstTag.closing || firstTag.selfClosing;
var stack = [];
var tag;
if (!isBackward) {
var iterator = new TokenIterator(session, row, firstTag.column);
var start = {
row: row,
column: firstTag.column + firstTag.tagName.length + 2
};
while (tag = this._readTagForward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (tag.closing) {
this._pop(stack, tag);
if (stack.length == 0)
return Range.fromPoints(start, tag.start);
}
else {
stack.push(tag)
}
}
}
else {
var iterator = new TokenIterator(session, row, firstTag.column + firstTag.match.length);
var end = {
row: row,
column: firstTag.column
};
while (tag = this._readTagBackward(iterator)) {
if (tag.selfClosing) {
if (!stack.length) {
tag.start.column += tag.tagName.length + 2;
tag.end.column -= 2;
return Range.fromPoints(tag.start, tag.end);
} else
continue;
}
if (!tag.closing) {
this._pop(stack, tag);
if (stack.length == 0) {
tag.start.column += tag.tagName.length + 2;
return Range.fromPoints(tag.start, end);
}
}
else {
stack.push(tag)
}
}
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/mode/javascript', 'ace/mode/css', 'ace/tokenizer', 'ace/mode/html_highlight_rules', 'ace/mode/behaviour/xml', 'ace/mode/folding/html'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var JavaScriptMode = require("./javascript").Mode;
var CssMode = require("./css").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var XmlBehaviour = require("./behaviour/xml").XmlBehaviour;
var HtmlFoldMode = require("./folding/html").FoldMode;
var Mode = function() {
var highlighter = new HtmlHighlightRules();
this.$tokenizer = new Tokenizer(highlighter.getRules());
this.$behaviour = new XmlBehaviour();
this.$embeds = highlighter.getEmbeds();
this.createModeDelegates({
"js-": JavaScriptMode,
"css-": CssMode
});
this.foldingRules = new HtmlFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
return 0;
};
this.getNextLineIndent = function(state, line, tab) {
return this.$getIndent(line);
};
this.checkOutdent = function(state, line, input) {
return false;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new CssHighlightRules().getRules(), "i");
this.$outdent = new MatchingBraceOutdent();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.foldingRules = "cStyle";
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
// ignore braces in comments
var tokens = this.$tokenizer.getLineTokens(line, state).tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
var match = line.match(/^.*\{\s*$/);
if (match) {
indent += tab;
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "worker-css.js", "ace/mode/css_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("csslint", function(e) {
var errors = [];
e.data.forEach(function(message) {
errors.push({
row: message.line - 1,
column: message.col - 1,
text: message.message,
type: message.type,
lint: message
});
});
session.setAnnotations(errors);
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var CssHighlightRules = function() {
var properties = lang.arrayToMap(
("animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index").split("|")
);
var functions = lang.arrayToMap(
("rgb|rgba|url|attr|counter|counters").split("|")
);
var constants = lang.arrayToMap(
("absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|font-size|font|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|top|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero").split("|")
);
var colors = lang.arrayToMap(
("aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|" +
"purple|red|silver|teal|white|yellow").split("|")
);
var fonts = lang.arrayToMap(
("arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|" +
"symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|" +
"serif|monospace").split("|")
);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
var numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
var pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b";
var pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b";
var base_ruleset = [
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "ruleset_comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : ["constant.numeric", "keyword"],
regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"
}, {
token : ["constant.numeric"],
regex : "([0-9]+)"
}, {
token : "constant.numeric", // hex6 color
regex : "#[a-f0-9]{6}"
}, {
token : "constant.numeric", // hex3 color
regex : "#[a-f0-9]{3}"
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"],
regex : pseudoElements
}, {
token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"],
regex : pseudoClasses
}, {
token : function(value) {
if (properties.hasOwnProperty(value.toLowerCase())) {
return "support.type";
}
else if (functions.hasOwnProperty(value.toLowerCase())) {
return "support.function";
}
else if (constants.hasOwnProperty(value.toLowerCase())) {
return "support.constant";
}
else if (colors.hasOwnProperty(value.toLowerCase())) {
return "support.constant.color";
}
else if (fonts.hasOwnProperty(value.toLowerCase())) {
return "support.constant.fonts";
}
else {
return "text";
}
},
regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"
}
];
var ruleset = lang.copyArray(base_ruleset);
ruleset.unshift({
token : "paren.rparen",
regex : "\\}",
next: "start"
});
var media_ruleset = lang.copyArray( base_ruleset );
media_ruleset.unshift({
token : "paren.rparen",
regex : "\\}",
next: "media"
});
var base_comment = [{
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}];
var comment = lang.copyArray(base_comment);
comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
});
var media_comment = lang.copyArray(base_comment);
media_comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "media"
});
var ruleset_comment = lang.copyArray(base_comment);
ruleset_comment.unshift({
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "ruleset"
});
this.$rules = {
"start" : [{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment"
}, {
token: "paren.lparen",
regex: "\\{",
next: "ruleset"
}, {
token: "string",
regex: "@.*?{",
next: "media"
},{
token: "keyword",
regex: "#[a-z0-9-_]+"
},{
token: "variable",
regex: "\\.[a-z0-9-_]+"
},{
token: "string",
regex: ":[a-z0-9-_]+"
},{
token: "constant",
regex: "[a-z0-9-_]+"
}],
"media" : [ {
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "media_comment"
}, {
token: "paren.lparen",
regex: "\\{",
next: "media_ruleset"
},{
token: "string",
regex: "\\}",
next: "start"
},{
token: "keyword",
regex: "#[a-z0-9-_]+"
},{
token: "variable",
regex: "\\.[a-z0-9-_]+"
},{
token: "string",
regex: ":[a-z0-9-_]+"
},{
token: "constant",
regex: "[a-z0-9-_]+"
}],
"comment" : comment,
"ruleset" : ruleset,
"ruleset_comment" : ruleset_comment,
"media_ruleset" : media_ruleset,
"media_comment" : media_comment
};
};
oop.inherits(CssHighlightRules, TextHighlightRules);
exports.CssHighlightRules = CssHighlightRules;
});
define('ace/mode/html_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/css_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_util', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var xmlUtil = require("./xml_util");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var HtmlHighlightRules = function() {
// regexp must not have capturing parentheses
// regexps are ordered -> the first match is used
this.$rules = {
start : [{
token : "text",
merge : true,
regex : "<\\!\\[CDATA\\[",
next : "cdata"
}, {
token : "xml_pe",
regex : "<\\?.*?\\?>"
}, {
token : "comment",
merge : true,
regex : "<\\!--",
next : "comment"
}, {
token : "xml_pe",
regex : "<\\!.*?>"
}, {
token : "meta.tag",
regex : "<(?=\s*script\\b)",
next : "script"
}, {
token : "meta.tag",
regex : "<(?=\s*style\\b)",
next : "style"
}, {
token : "meta.tag", // opening tag
regex : "<\\/?",
next : "tag"
}, {
token : "text",
regex : "\\s+"
}, {
token : "constant.character.entity",
regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)"
}, {
token : "text",
regex : "[^<]+"
} ],
cdata : [ {
token : "text",
regex : "\\]\\]>",
next : "start"
}, {
token : "text",
merge : true,
regex : "\\s+"
}, {
token : "text",
merge : true,
regex : ".+"
} ],
comment : [ {
token : "comment",
regex : ".*?-->",
next : "start"
}, {
token : "comment",
merge : true,
regex : ".+"
} ]
};
xmlUtil.tag(this.$rules, "tag", "start");
xmlUtil.tag(this.$rules, "style", "css-start");
xmlUtil.tag(this.$rules, "script", "js-start");
this.embedRules(JavaScriptHighlightRules, "js-", [{
token: "comment",
regex: "\\/\\/.*(?=<\\/script>)",
next: "tag"
}, {
token: "meta.tag",
regex: "<\\/(?=script)",
next: "tag"
}]);
this.embedRules(CssHighlightRules, "css-", [{
token: "meta.tag",
regex: "<\\/(?=style)",
next: "tag"
}]);
};
oop.inherits(HtmlHighlightRules, TextHighlightRules);
exports.HtmlHighlightRules = HtmlHighlightRules;
});
define('ace/mode/folding/html', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/mixed', 'ace/mode/folding/xml', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../../lib/oop");
var MixedFoldMode = require("./mixed").FoldMode;
var XmlFoldMode = require("./xml").FoldMode;
var CStyleFoldMode = require("./cstyle").FoldMode;
var FoldMode = exports.FoldMode = function() {
MixedFoldMode.call(this, new XmlFoldMode({
// void elements
"area": 1,
"base": 1,
"br": 1,
"col": 1,
"command": 1,
"embed": 1,
"hr": 1,
"img": 1,
"input": 1,
"keygen": 1,
"link": 1,
"meta": 1,
"param": 1,
"source": 1,
"track": 1,
"wbr": 1,
// optional tags
"li": 1,
"dt": 1,
"dd": 1,
"p": 1,
"rt": 1,
"rp": 1,
"optgroup": 1,
"option": 1,
"colgroup": 1,
"td": 1,
"th": 1
}), {
"js-": new CStyleFoldMode(),
"css-": new CStyleFoldMode()
});
};
oop.inherits(FoldMode, MixedFoldMode);
});
define('ace/mode/folding/mixed', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(defaultMode, subModes) {
this.defaultMode = defaultMode;
this.subModes = subModes;
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.$getMode = function(state) {
for (var key in this.subModes) {
if (state.indexOf(key) === 0)
return this.subModes[key];
}
return null;
};
this.$tryMode = function(state, session, foldStyle, row) {
var mode = this.$getMode(state);
return (mode ? mode.getFoldWidget(session, foldStyle, row) : "");
};
this.getFoldWidget = function(session, foldStyle, row) {
return (
this.$tryMode(session.getState(row-1), session, foldStyle, row) ||
this.$tryMode(session.getState(row), session, foldStyle, row) ||
this.defaultMode.getFoldWidget(session, foldStyle, row)
);
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
var mode = this.$getMode(session.getState(row-1));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.$getMode(session.getState(row));
if (!mode || !mode.getFoldWidget(session, foldStyle, row))
mode = this.defaultMode;
return mode.getFoldWidgetRange(session, foldStyle, row);
};
}).call(FoldMode.prototype);
});
define('ace/mode/markdown_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules', 'ace/mode/javascript_highlight_rules', 'ace/mode/xml_highlight_rules', 'ace/mode/html_highlight_rules', 'ace/mode/css_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules;
var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules;
var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
function github_embed(tag, prefix) {
return { // Github style block
token : "support.function",
regex : "^```" + tag + "\\s*$",
next : prefix + "start"
};
}
var MarkdownHighlightRules = function() {
// regexp must not have capturing parentheses
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [ {
token : "empty_line",
regex : '^$'
}, { // code span `
token : ["support.function", "support.function", "support.function"],
regex : "(`+)([^\\r]*?[^`])(\\1)"
}, { // code block
token : "support.function",
regex : "^[ ]{4}.+"
}, { // h1
token: "markup.heading.1",
regex: "^=+(?=\\s*$)"
}, { // h2
token: "markup.heading.1",
regex: "^\\-+(?=\\s*$)"
}, { // header
token : function(value) {
return "markup.heading." + value.length;
},
regex : "^#{1,6}"
}, github_embed("javascript", "js-"),
github_embed("xml", "xml-"),
github_embed("html", "html-"),
github_embed("css", "css-"),
{ // Github style block
token : "support.function",
regex : "^```[a-zA-Z]+\\s*$",
next : "githubblock"
}, { // block quote
token : "string",
regex : "^>[ ].+$",
next : "blockquote"
}, { // reference
token : ["text", "constant", "text", "url", "string", "text"],
regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$"
}, { // link by reference
token : ["text", "string", "text", "constant", "text"],
regex : "(\\[)((?:[[^\\]]*\\]|[^\\[\\]])*)(\\][ ]?(?:\\n[ ]*)?\\[)(.*?)(\\])"
}, { // link by url
token : ["text", "string", "text", "markup.underline", "string", "text"],
regex : "(\\[)"+
"(\\[[^\\]]*\\]|[^\\[\\]]*)"+
"(\\]\\([ \\t]*)"+
"(<?(?:(?:[^\\(]*?\\([^\\)]*?\\)\\S*?)|(?:.*?))>?)"+
"((?:[ \t]*\"(?:.*?)\"[ \\t]*)?)"+
"(\\))"
}, { // HR *
token : "constant",
regex : "^[ ]{0,2}(?:[ ]?\\*[ ]?){3,}\\s*$"
}, { // HR -
token : "constant",
regex : "^[ ]{0,2}(?:[ ]?\\-[ ]?){3,}\\s*$"
}, { // HR _
token : "constant",
regex : "^[ ]{0,2}(?:[ ]?\\_[ ]?){3,}\\s*$"
}, { // list
token : "markup.list",
regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+",
next : "listblock"
}, { // strong ** __
token : ["string", "string", "string"],
regex : "([*]{2}|[_]{2}(?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
}, { // emphasis * _
token : ["string", "string", "string"],
regex : "([*]|[_](?=\\S))([^\\r]*?\\S[*_]*)(\\1)"
}, { //
token : ["text", "url", "text"],
regex : "(<)("+
"(?:https?|ftp|dict):[^'\">\\s]+"+
"|"+
"(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+
")(>)"
}, {
token : "text",
regex : "[^\\*_%$`\\[#<>]+"
} ],
"listblock" : [ { // Lists only escape on completely blank lines.
token : "empty_line",
regex : "^$",
next : "start"
}, {
token : "markup.list",
regex : ".+"
} ],
"blockquote" : [ { // BLockquotes only escape on blank lines.
token : "empty_line",
regex : "^\\s*$",
next : "start"
}, {
token : "string",
regex : ".+"
} ],
"githubblock" : [ {
token : "support.function",
regex : "^```",
next : "start"
}, {
token : "support.function",
regex : ".+"
} ]
};
this.embedRules(JavaScriptHighlightRules, "js-", [{
token : "support.function",
regex : "^```",
next : "start"
}]);
this.embedRules(HtmlHighlightRules, "html-", [{
token : "support.function",
regex : "^```",
next : "start"
}]);
this.embedRules(CssHighlightRules, "css-", [{
token : "support.function",
regex : "^```",
next : "start"
}]);
this.embedRules(XmlHighlightRules, "xml-", [{
token : "support.function",
regex : "^```",
next : "start"
}]);
};
oop.inherits(MarkdownHighlightRules, TextHighlightRules);
exports.MarkdownHighlightRules = MarkdownHighlightRules;
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Gastón Kleiman <gaston.kleiman AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/scad', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/scad_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var scadHighlightRules = require("./scad_highlight_rules").scadHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new scadHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
var re = /^(\s*)\/\//;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "//");
}
};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/scad_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var scadHighlightRules = function() {
var keywords = lang.arrayToMap(
("module|if|else|for").split("|")
);
var buildinConstants = lang.arrayToMap(
("NULL").split("|")
);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "comment",
regex : "\\/\\/.*$"
},
DocCommentHighlightRules.getStartRule("start"),
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // multi line string start
regex : '["].*\\\\$',
next : "qqstring"
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "string", // multi line string start
regex : "['].*\\\\$",
next : "qstring"
}, {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+\\b"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "constant", // <CONSTANT>
regex : "<[a-zA-Z0-9.]+>"
}, {
token : "keyword", // pre-compiler directivs
regex : "(?:use|include)"
}, {
token : function(value) {
if (value == "this")
return "variable.language";
else if (keywords.hasOwnProperty(value))
return "keyword";
else if (buildinConstants.hasOwnProperty(value))
return "constant.language";
else
return "identifier";
},
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|==|=|!=|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|new|delete|typeof|void)"
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"qqstring" : [
{
token : "string",
regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
}
],
"qstring" : [
{
token : "string",
regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(scadHighlightRules, TextHighlightRules);
exports.scadHighlightRules = scadHighlightRules;
});
define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc",
merge : true,
regex : "\\s+"
}, {
token : "comment.doc",
merge : true,
regex : "TODO"
}, {
token : "comment.doc",
merge : true,
regex : "[^@\\*]+"
}, {
token : "comment.doc",
merge : true,
regex : "."
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
merge : true,
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
merge : true,
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = function () {
this.add("braces", "insertion", function (state, action, editor, session, text) {
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '{' + selected + '}',
selection: false
};
} else {
return {
text: '{}',
selection: [1, 1]
};
}
} else if (text == '}') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1});
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString());
var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '(' + selected + ')',
selection: false
};
} else {
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
// We're escaped.
if (leftChar == '\\') {
return null;
}
// Find what token we're inside.
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
// Try and be smart about when we auto insert.
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
// Ignore input and move right one if we're typing over the closing quote.
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/tomorrow_night', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-tomorrow-night";
exports.cssText = "\
.ace-tomorrow-night .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-tomorrow-night .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-tomorrow-night .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-tomorrow-night .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-tomorrow-night .ace_scroller {\
background-color: #1D1F21;\
}\
\
.ace-tomorrow-night .ace_text-layer {\
cursor: text;\
color: #C5C8C6;\
}\
\
.ace-tomorrow-night .ace_cursor {\
border-left: 2px solid #AEAFAD;\
}\
\
.ace-tomorrow-night .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #AEAFAD;\
}\
\
.ace-tomorrow-night .ace_marker-layer .ace_selection {\
background: #373B41;\
}\
\
.ace-tomorrow-night.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #1D1F21;\
border-radius: 2px;\
}\
\
.ace-tomorrow-night .ace_marker-layer .ace_step {\
background: rgb(102, 82, 0);\
}\
\
.ace-tomorrow-night .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid #4B4E55;\
}\
\
.ace-tomorrow-night .ace_marker-layer .ace_active_line {\
background: #282A2E;\
}\
\
.ace-tomorrow-night .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-tomorrow-night .ace_marker-layer .ace_selected_word {\
border: 1px solid #373B41;\
}\
\
.ace-tomorrow-night .ace_invisible {\
color: #4B4E55;\
}\
\
.ace-tomorrow-night .ace_keyword, .ace-tomorrow-night .ace_meta {\
color:#B294BB;\
}\
\
.ace-tomorrow-night .ace_keyword.ace_operator {\
color:#8ABEB7;\
}\
\
.ace-tomorrow-night .ace_constant.ace_language {\
color:#DE935F;\
}\
\
.ace-tomorrow-night .ace_constant.ace_numeric {\
color:#DE935F;\
}\
\
.ace-tomorrow-night .ace_constant.ace_other {\
color:#CED1CF;\
}\
\
.ace-tomorrow-night .ace_invalid {\
color:#CED2CF;\
background-color:#DF5F5F;\
}\
\
.ace-tomorrow-night .ace_invalid.ace_deprecated {\
color:#CED2CF;\
background-color:#B798BF;\
}\
\
.ace-tomorrow-night .ace_support.ace_constant {\
color:#DE935F;\
}\
\
.ace-tomorrow-night .ace_fold {\
background-color: #81A2BE;\
border-color: #C5C8C6;\
}\
\
.ace-tomorrow-night .ace_support.ace_function {\
color:#81A2BE;\
}\
\
.ace-tomorrow-night .ace_storage {\
color:#B294BB;\
}\
\
.ace-tomorrow-night .ace_storage.ace_type, .ace-tomorrow-night .ace_support.ace_type{\
color:#B294BB;\
}\
\
.ace-tomorrow-night .ace_variable {\
color:#81A2BE;\
}\
\
.ace-tomorrow-night .ace_variable.ace_parameter {\
color:#DE935F;\
}\
\
.ace-tomorrow-night .ace_string {\
color:#B5BD68;\
}\
\
.ace-tomorrow-night .ace_string.ace_regexp {\
color:#CC6666;\
}\
\
.ace-tomorrow-night .ace_comment {\
color:#969896;\
}\
\
.ace-tomorrow-night .ace_variable {\
color:#CC6666;\
}\
\
.ace-tomorrow-night .ace_meta.ace_tag {\
color:#CC6666;\
}\
\
.ace-tomorrow-night .ace_entity.ace_other.ace_attribute-name {\
color:#CC6666;\
}\
\
.ace-tomorrow-night .ace_entity.ace_name.ace_function {\
color:#81A2BE;\
}\
\
.ace-tomorrow-night .ace_markup.ace_underline {\
text-decoration:underline;\
}\
\
.ace-tomorrow-night .ace_markup.ace_heading {\
color:#B5BD68;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Rich Healey <richo AT psych0tik DOT net>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/sh', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/sh_highlight_rules', 'ace/range'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var ShHighlightRules = require("./sh_highlight_rules").ShHighlightRules;
var Range = require("../range").Range;
var Mode = function() {
this.$tokenizer = new Tokenizer(new ShHighlightRules().getRules());
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
var re = /^(\s*)#/;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "#");
}
};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[\:]\s*$/);
if (match) {
indent += tab;
}
}
return indent;
};
var outdents = {
"pass": 1,
"return": 1,
"raise": 1,
"break": 1,
"continue": 1
};
this.checkOutdent = function(state, line, input) {
if (input !== "\r\n" && input !== "\r" && input !== "\n")
return false;
var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens;
if (!tokens)
return false;
// ignore trailing comments
do {
var last = tokens.pop();
} while (last && (last.type == "comment" || (last.type == "text" && last.value.match(/^\s+$/))));
if (!last)
return false;
return (last.type == "keyword" && outdents[last.value]);
};
this.autoOutdent = function(state, doc, row) {
// outdenting in sh is slightly different because it always applies
// to the next line and only of a new line is inserted
row += 1;
var indent = this.$getIndent(doc.getLine(row));
var tab = doc.getTabString();
if (indent.slice(-tab.length) == tab)
doc.remove(new Range(row, indent.length-tab.length, row, indent.length));
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/sh_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var ShHighlightRules = function() {
var reservedKeywords = lang.arrayToMap(
('!|{|}|case|do|done|elif|else|'+
'esac|fi|for|if|in|then|until|while|'+
'&|;|export|local|read|typeset|unset|'+
'elif|select|set'
).split('|')
);
var languageConstructs = lang.arrayToMap(
('[|]|alias|bg|bind|break|builtin|'+
'cd|command|compgen|complete|continue|'+
'dirs|disown|echo|enable|eval|exec|'+
'exit|fc|fg|getopts|hash|help|history|'+
'jobs|kill|let|logout|popd|printf|pushd|'+
'pwd|return|set|shift|shopt|source|'+
'suspend|test|times|trap|type|ulimit|'+
'umask|unalias|wait'
).split('|')
);
var integer = "(?:(?:[1-9]\\d*)|(?:0))";
// var integer = "(?:" + decimalInteger + ")";
var fraction = "(?:\\.\\d+)";
var intPart = "(?:\\d+)";
var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + ")";
var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";
var fileDescriptor = "(?:&" + intPart + ")";
var variableName = "[a-zA-Z][a-zA-Z0-9_]*";
var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))";
var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))";
var func = "(?:" + variableName + "\\s*\\(\\))";
this.$rules = {
"start" : [ {
token : "comment",
regex : "#.*$"
}, {
token : "string", // " string
regex : '"(?:[^\\\\]|\\\\.)*?"'
}, {
token : "variable.language",
regex : builtinVariable
}, {
token : "variable",
regex : variable
}, {
token : "support.function",
regex : func,
}, {
token : "support.function",
regex : fileDescriptor
}, {
token : "string", // ' string
regex : "'(?:[^\\\\]|\\\\.)*?'"
}, {
token : "constant.numeric", // float
regex : floatNumber
}, {
token : "constant.numeric", // integer
regex : integer + "\\b"
}, {
token : function(value) {
if (reservedKeywords.hasOwnProperty(value))
return "keyword";
else if (languageConstructs.hasOwnProperty(value))
return "constant.language";
else if (value == "debugger")
return "invalid.deprecated";
else
return "identifier";
},
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!="
}, {
token : "paren.lparen",
regex : "[\\[\\(\\{]"
}, {
token : "paren.rparen",
regex : "[\\]\\)\\}]"
}, {
token : "text",
regex : "\\s+"
} ]
};
};
oop.inherits(ShHighlightRules, TextHighlightRules);
exports.ShHighlightRules = ShHighlightRules;
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* The Original Code is Ajax.org Code Editor (ACE).
*
* Contributor(s):
* Jonathan Camile <jonathan.camile AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/pgsql', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/pgsql_highlight_rules', 'ace/range'], function(require, exports, module) {
var oop = require("ace/lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var PgsqlHighlightRules = require("ace/mode/pgsql_highlight_rules").PgsqlHighlightRules;
var Range = require("ace/range").Range;
// var EditSession = require("ace/edit_session").EditSession;
var Mode = function() {
this.$tokenizer = new Tokenizer(new PgsqlHighlightRules().getRules());
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
// var outentedRows = [];
var re = /^(\s*)--/;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "--");
}
};
this.getNextLineIndent = function(state, line, tab) {
if (state == "start" || state == "keyword.statementEnd") {
return "";
} else {
return this.$getIndent(line); // Keep whatever indent the previous line has
}
}
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/pgsql_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules', 'ace/mode/perl_highlight_rules', 'ace/mode/python_highlight_rules'], function(require, exports, module) {
var oop = require("ace/lib/oop");
var lang = require("ace/lib/lang");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
// Supporting perl and python for now -- both in pg core and ace
var PerlHighlightRules = require("./perl_highlight_rules").PerlHighlightRules;
var PythonHighlightRules = require("./python_highlight_rules").PythonHighlightRules;
var PgsqlHighlightRules = function() {
// Keywords, functions, operators last updated for pg 9.1.
var keywords = lang.arrayToMap(
("abort|absolute|abstime|access|aclitem|action|add|admin|after|aggregate|all|also|alter|always|" +
"analyse|analyze|and|any|anyarray|anyelement|anyenum|anynonarray|array|as|asc|assertion|" +
"assignment|asymmetric|at|attribute|authorization|backward|before|begin|between|bigint|" +
"binary|bit|bool|boolean|both|box|bpchar|by|bytea|cache|called|cascade|cascaded|case|cast|" +
"catalog|chain|char|character|characteristics|check|checkpoint|cid|cidr|circle|class|close|" +
"cluster|coalesce|collate|collation|column|comment|comments|commit|committed|concurrently|" +
"configuration|connection|constraint|constraints|content|continue|conversion|copy|cost|" +
"create|cross|cstring|csv|current|current_catalog|current_date|current_role|" +
"current_schema|current_time|current_timestamp|current_user|cursor|cycle|data|database|" +
"date|day|deallocate|dec|decimal|declare|default|defaults|deferrable|deferred|definer|delete|" +
"delimiter|delimiters|desc|dictionary|disable|discard|distinct|do|document|domain|double|" +
"drop|each|else|enable|encoding|encrypted|end|enum|escape|except|exclude|excluding|exclusive|" +
"execute|exists|explain|extension|external|extract|false|family|fdw_handler|fetch|first|" +
"float|float4|float8|following|for|force|foreign|forward|freeze|from|full|function|functions|" +
"global|grant|granted|greatest|group|gtsvector|handler|having|header|hold|hour|identity|if|" +
"ilike|immediate|immutable|implicit|in|including|increment|index|indexes|inet|inherit|" +
"inherits|initially|inline|inner|inout|input|insensitive|insert|instead|int|int2|int2vector|" +
"int4|int8|integer|internal|intersect|interval|into|invoker|is|isnull|isolation|join|key|label|" +
"language|language_handler|large|last|lc_collate|lc_ctype|leading|least|left|level|like|" +
"limit|line|listen|load|local|localtime|localtimestamp|location|lock|lseg|macaddr|mapping|" +
"match|maxvalue|minute|minvalue|mode|money|month|move|name|names|national|natural|nchar|next|no|" +
"none|not|nothing|notify|notnull|nowait|null|nullif|nulls|numeric|object|of|off|offset|oid|oids|" +
"oidvector|on|only|opaque|operator|option|options|or|order|out|outer|over|overlaps|overlay|" +
"owned|owner|parser|partial|partition|passing|password|path|pg_attribute|pg_auth_members|" +
"pg_authid|pg_class|pg_database|pg_node_tree|pg_proc|pg_type|placing|plans|point|polygon|" +
"position|preceding|precision|prepare|prepared|preserve|primary|prior|privileges|" +
"procedural|procedure|quote|range|read|real|reassign|recheck|record|recursive|ref|refcursor|" +
"references|regclass|regconfig|regdictionary|regoper|regoperator|regproc|regprocedure|" +
"regtype|reindex|relative|release|reltime|rename|repeatable|replace|replica|reset|restart|" +
"restrict|returning|returns|revoke|right|role|rollback|row|rows|rule|savepoint|schema|scroll|" +
"search|second|security|select|sequence|sequences|serializable|server|session|session_user|" +
"set|setof|share|show|similar|simple|smallint|smgr|some|stable|standalone|start|statement|" +
"statistics|stdin|stdout|storage|strict|strip|substring|symmetric|sysid|system|table|tables|" +
"tablespace|temp|template|temporary|text|then|tid|time|timestamp|timestamptz|timetz|" +
"tinterval|to|trailing|transaction|treat|trigger|trim|true|truncate|trusted|tsquery|tsvector|" +
"txid_snapshot|type|unbounded|uncommitted|unencrypted|union|unique|unknown|unlisten|" +
"unlogged|until|update|user|using|uuid|vacuum|valid|validate|validator|value|values|varbit|" +
"varchar|variadic|varying|verbose|version|view|void|volatile|when|where|whitespace|window|" +
"with|without|work|wrapper|write|xid|xml|xmlattributes|xmlconcat|xmlelement|xmlexists|" +
"xmlforest|xmlparse|xmlpi|xmlroot|xmlserialize|year|yes|zone").split("|")
);
var builtinFunctions = lang.arrayToMap(
("RI_FKey_cascade_del|RI_FKey_cascade_upd|RI_FKey_check_ins|RI_FKey_check_upd|" +
"RI_FKey_noaction_del|RI_FKey_noaction_upd|RI_FKey_restrict_del|RI_FKey_restrict_upd|" +
"RI_FKey_setdefault_del|RI_FKey_setdefault_upd|RI_FKey_setnull_del|" +
"RI_FKey_setnull_upd|abbrev|abs|abstime|abstimeeq|abstimege|abstimegt|abstimein|abstimele|" +
"abstimelt|abstimene|abstimeout|abstimerecv|abstimesend|aclcontains|aclexplode|aclinsert|" +
"aclitemeq|aclitemin|aclitemout|aclremove|acos|age|any_in|any_out|anyarray_in|anyarray_out|" +
"anyarray_recv|anyarray_send|anyelement_in|anyelement_out|anyenum_in|anyenum_out|" +
"anynonarray_in|anynonarray_out|anytextcat|area|areajoinsel|areasel|array_agg|" +
"array_agg_finalfn|array_agg_transfn|array_append|array_cat|array_dims|array_eq|" +
"array_fill|array_ge|array_gt|array_in|array_larger|array_le|array_length|array_lower|" +
"array_lt|array_ndims|array_ne|array_out|array_prepend|array_recv|array_send|" +
"array_smaller|array_to_string|array_upper|arraycontained|arraycontains|arrayoverlap|" +
"ascii|ascii_to_mic|ascii_to_utf8|asin|atan|atan2|avg|big5_to_euc_tw|big5_to_mic|" +
"big5_to_utf8|bit_and|bit_in|bit_length|bit_or|bit_out|bit_recv|bit_send|bitand|bitcat|" +
"bitcmp|biteq|bitge|bitgt|bitle|bitlt|bitne|bitnot|bitor|bitshiftleft|bitshiftright|" +
"bittypmodin|bittypmodout|bitxor|bool|bool_and|bool_or|booland_statefunc|booleq|boolge|" +
"boolgt|boolin|boolle|boollt|boolne|boolor_statefunc|boolout|boolrecv|boolsend|box|" +
"box_above|box_above_eq|box_add|box_below|box_below_eq|box_center|box_contain|" +
"box_contain_pt|box_contained|box_distance|box_div|box_eq|box_ge|box_gt|box_in|" +
"box_intersect|box_le|box_left|box_lt|box_mul|box_out|box_overabove|box_overbelow|" +
"box_overlap|box_overleft|box_overright|box_recv|box_right|box_same|box_send|box_sub|" +
"bpchar_larger|bpchar_pattern_ge|bpchar_pattern_gt|bpchar_pattern_le|" +
"bpchar_pattern_lt|bpchar_smaller|bpcharcmp|bpchareq|bpcharge|bpchargt|bpchariclike|" +
"bpcharicnlike|bpcharicregexeq|bpcharicregexne|bpcharin|bpcharle|bpcharlike|bpcharlt|" +
"bpcharne|bpcharnlike|bpcharout|bpcharrecv|bpcharregexeq|bpcharregexne|bpcharsend|" +
"bpchartypmodin|bpchartypmodout|broadcast|btabstimecmp|btarraycmp|btbeginscan|btboolcmp|" +
"btbpchar_pattern_cmp|btbuild|btbuildempty|btbulkdelete|btcharcmp|btcostestimate|" +
"btendscan|btfloat48cmp|btfloat4cmp|btfloat84cmp|btfloat8cmp|btgetbitmap|btgettuple|" +
"btinsert|btint24cmp|btint28cmp|btint2cmp|btint42cmp|btint48cmp|btint4cmp|btint82cmp|" +
"btint84cmp|btint8cmp|btmarkpos|btnamecmp|btoidcmp|btoidvectorcmp|btoptions|btrecordcmp|" +
"btreltimecmp|btrescan|btrestrpos|btrim|bttext_pattern_cmp|bttextcmp|bttidcmp|" +
"bttintervalcmp|btvacuumcleanup|byteacat|byteacmp|byteaeq|byteage|byteagt|byteain|byteale|" +
"bytealike|bytealt|byteane|byteanlike|byteaout|bytearecv|byteasend|cash_cmp|cash_div_cash|" +
"cash_div_flt4|cash_div_flt8|cash_div_int2|cash_div_int4|cash_eq|cash_ge|cash_gt|cash_in|" +
"cash_le|cash_lt|cash_mi|cash_mul_flt4|cash_mul_flt8|cash_mul_int2|cash_mul_int4|cash_ne|" +
"cash_out|cash_pl|cash_recv|cash_send|cash_words|cashlarger|cashsmaller|cbrt|ceil|ceiling|" +
"center|char|char_length|character_length|chareq|charge|chargt|charin|charle|charlt|charne|" +
"charout|charrecv|charsend|chr|cideq|cidin|cidout|cidr|cidr_in|cidr_out|cidr_recv|cidr_send|" +
"cidrecv|cidsend|circle|circle_above|circle_add_pt|circle_below|circle_center|" +
"circle_contain|circle_contain_pt|circle_contained|circle_distance|circle_div_pt|" +
"circle_eq|circle_ge|circle_gt|circle_in|circle_le|circle_left|circle_lt|circle_mul_pt|" +
"circle_ne|circle_out|circle_overabove|circle_overbelow|circle_overlap|circle_overleft|" +
"circle_overright|circle_recv|circle_right|circle_same|circle_send|circle_sub_pt|" +
"clock_timestamp|close_lb|close_ls|close_lseg|close_pb|close_pl|close_ps|close_sb|" +
"close_sl|col_description|concat|concat_ws|contjoinsel|contsel|convert|convert_from|" +
"convert_to|corr|cos|cot|count|covar_pop|covar_samp|cstring_in|cstring_out|cstring_recv|" +
"cstring_send|cume_dist|current_database|current_query|current_schema|current_schemas|" +
"current_setting|current_user|currtid|currtid2|currval|cursor_to_xml|" +
"cursor_to_xmlschema|database_to_xml|database_to_xml_and_xmlschema|" +
"database_to_xmlschema|date|date_cmp|date_cmp_timestamp|date_cmp_timestamptz|date_eq|" +
"date_eq_timestamp|date_eq_timestamptz|date_ge|date_ge_timestamp|date_ge_timestamptz|" +
"date_gt|date_gt_timestamp|date_gt_timestamptz|date_in|date_larger|date_le|" +
"date_le_timestamp|date_le_timestamptz|date_lt|date_lt_timestamp|date_lt_timestamptz|" +
"date_mi|date_mi_interval|date_mii|date_ne|date_ne_timestamp|date_ne_timestamptz|" +
"date_out|date_part|date_pl_interval|date_pli|date_recv|date_send|date_smaller|" +
"date_trunc|datetime_pl|datetimetz_pl|dcbrt|decode|degrees|dense_rank|dexp|diagonal|" +
"diameter|dispell_init|dispell_lexize|dist_cpoly|dist_lb|dist_pb|dist_pc|dist_pl|" +
"dist_ppath|dist_ps|dist_sb|dist_sl|div|dlog1|dlog10|domain_in|domain_recv|dpow|dround|" +
"dsimple_init|dsimple_lexize|dsnowball_init|dsnowball_lexize|dsqrt|dsynonym_init|" +
"dsynonym_lexize|dtrunc|encode|enum_cmp|enum_eq|enum_first|enum_ge|enum_gt|enum_in|" +
"enum_larger|enum_last|enum_le|enum_lt|enum_ne|enum_out|enum_range|enum_recv|enum_send|" +
"enum_smaller|eqjoinsel|eqsel|euc_cn_to_mic|euc_cn_to_utf8|" +
"euc_jis_2004_to_shift_jis_2004|euc_jis_2004_to_utf8|euc_jp_to_mic|euc_jp_to_sjis|" +
"euc_jp_to_utf8|euc_kr_to_mic|euc_kr_to_utf8|euc_tw_to_big5|euc_tw_to_mic|" +
"euc_tw_to_utf8|every|exp|factorial|family|fdw_handler_in|fdw_handler_out|first_value|" +
"float4|float48div|float48eq|float48ge|float48gt|float48le|float48lt|float48mi|float48mul|" +
"float48ne|float48pl|float4_accum|float4abs|float4div|float4eq|float4ge|float4gt|float4in|" +
"float4larger|float4le|float4lt|float4mi|float4mul|float4ne|float4out|float4pl|float4recv|" +
"float4send|float4smaller|float4um|float4up|float8|float84div|float84eq|float84ge|" +
"float84gt|float84le|float84lt|float84mi|float84mul|float84ne|float84pl|float8_accum|" +
"float8_avg|float8_corr|float8_covar_pop|float8_covar_samp|float8_regr_accum|" +
"float8_regr_avgx|float8_regr_avgy|float8_regr_intercept|float8_regr_r2|" +
"float8_regr_slope|float8_regr_sxx|float8_regr_sxy|float8_regr_syy|float8_stddev_pop|" +
"float8_stddev_samp|float8_var_pop|float8_var_samp|float8abs|float8div|float8eq|" +
"float8ge|float8gt|float8in|float8larger|float8le|float8lt|float8mi|float8mul|float8ne|" +
"float8out|float8pl|float8recv|float8send|float8smaller|float8um|float8up|floor|" +
"flt4_mul_cash|flt8_mul_cash|fmgr_c_validator|fmgr_internal_validator|" +
"fmgr_sql_validator|format|format_type|gb18030_to_utf8|gbk_to_utf8|generate_series|" +
"generate_subscripts|get_bit|get_byte|get_current_ts_config|getdatabaseencoding|" +
"getpgusername|gin_cmp_prefix|gin_cmp_tslexeme|gin_extract_tsquery|" +
"gin_extract_tsvector|gin_tsquery_consistent|ginarrayconsistent|ginarrayextract|" +
"ginbeginscan|ginbuild|ginbuildempty|ginbulkdelete|gincostestimate|ginendscan|" +
"gingetbitmap|gininsert|ginmarkpos|ginoptions|ginqueryarrayextract|ginrescan|" +
"ginrestrpos|ginvacuumcleanup|gist_box_compress|gist_box_consistent|" +
"gist_box_decompress|gist_box_penalty|gist_box_picksplit|gist_box_same|gist_box_union|" +
"gist_circle_compress|gist_circle_consistent|gist_point_compress|" +
"gist_point_consistent|gist_point_distance|gist_poly_compress|gist_poly_consistent|" +
"gistbeginscan|gistbuild|gistbuildempty|gistbulkdelete|gistcostestimate|gistendscan|" +
"gistgetbitmap|gistgettuple|gistinsert|gistmarkpos|gistoptions|gistrescan|gistrestrpos|" +
"gistvacuumcleanup|gtsquery_compress|gtsquery_consistent|gtsquery_decompress|" +
"gtsquery_penalty|gtsquery_picksplit|gtsquery_same|gtsquery_union|gtsvector_compress|" +
"gtsvector_consistent|gtsvector_decompress|gtsvector_penalty|gtsvector_picksplit|" +
"gtsvector_same|gtsvector_union|gtsvectorin|gtsvectorout|has_any_column_privilege|" +
"has_column_privilege|has_database_privilege|has_foreign_data_wrapper_privilege|" +
"has_function_privilege|has_language_privilege|has_schema_privilege|" +
"has_sequence_privilege|has_server_privilege|has_table_privilege|" +
"has_tablespace_privilege|hash_aclitem|hash_array|hash_numeric|hashbeginscan|" +
"hashbpchar|hashbuild|hashbuildempty|hashbulkdelete|hashchar|hashcostestimate|" +
"hashendscan|hashenum|hashfloat4|hashfloat8|hashgetbitmap|hashgettuple|hashinet|" +
"hashinsert|hashint2|hashint2vector|hashint4|hashint8|hashmacaddr|hashmarkpos|hashname|" +
"hashoid|hashoidvector|hashoptions|hashrescan|hashrestrpos|hashtext|hashvacuumcleanup|" +
"hashvarlena|height|host|hostmask|iclikejoinsel|iclikesel|icnlikejoinsel|icnlikesel|" +
"icregexeqjoinsel|icregexeqsel|icregexnejoinsel|icregexnesel|inet_client_addr|" +
"inet_client_port|inet_in|inet_out|inet_recv|inet_send|inet_server_addr|" +
"inet_server_port|inetand|inetmi|inetmi_int8|inetnot|inetor|inetpl|initcap|int2|int24div|" +
"int24eq|int24ge|int24gt|int24le|int24lt|int24mi|int24mul|int24ne|int24pl|int28div|int28eq|" +
"int28ge|int28gt|int28le|int28lt|int28mi|int28mul|int28ne|int28pl|int2_accum|" +
"int2_avg_accum|int2_mul_cash|int2_sum|int2abs|int2and|int2div|int2eq|int2ge|int2gt|int2in|" +
"int2larger|int2le|int2lt|int2mi|int2mod|int2mul|int2ne|int2not|int2or|int2out|int2pl|" +
"int2recv|int2send|int2shl|int2shr|int2smaller|int2um|int2up|int2vectoreq|int2vectorin|" +
"int2vectorout|int2vectorrecv|int2vectorsend|int2xor|int4|int42div|int42eq|int42ge|" +
"int42gt|int42le|int42lt|int42mi|int42mul|int42ne|int42pl|int48div|int48eq|int48ge|int48gt|" +
"int48le|int48lt|int48mi|int48mul|int48ne|int48pl|int4_accum|int4_avg_accum|int4_mul_cash|" +
"int4_sum|int4abs|int4and|int4div|int4eq|int4ge|int4gt|int4in|int4inc|int4larger|int4le|" +
"int4lt|int4mi|int4mod|int4mul|int4ne|int4not|int4or|int4out|int4pl|int4recv|int4send|" +
"int4shl|int4shr|int4smaller|int4um|int4up|int4xor|int8|int82div|int82eq|int82ge|int82gt|" +
"int82le|int82lt|int82mi|int82mul|int82ne|int82pl|int84div|int84eq|int84ge|int84gt|int84le|" +
"int84lt|int84mi|int84mul|int84ne|int84pl|int8_accum|int8_avg|int8_avg_accum|int8_sum|" +
"int8abs|int8and|int8div|int8eq|int8ge|int8gt|int8in|int8inc|int8inc_any|" +
"int8inc_float8_float8|int8larger|int8le|int8lt|int8mi|int8mod|int8mul|int8ne|int8not|" +
"int8or|int8out|int8pl|int8pl_inet|int8recv|int8send|int8shl|int8shr|int8smaller|int8um|" +
"int8up|int8xor|integer_pl_date|inter_lb|inter_sb|inter_sl|internal_in|internal_out|" +
"interval_accum|interval_avg|interval_cmp|interval_div|interval_eq|interval_ge|" +
"interval_gt|interval_hash|interval_in|interval_larger|interval_le|interval_lt|" +
"interval_mi|interval_mul|interval_ne|interval_out|interval_pl|interval_pl_date|" +
"interval_pl_time|interval_pl_timestamp|interval_pl_timestamptz|interval_pl_timetz|" +
"interval_recv|interval_send|interval_smaller|interval_um|intervaltypmodin|" +
"intervaltypmodout|intinterval|isclosed|isfinite|ishorizontal|iso8859_1_to_utf8|" +
"iso8859_to_utf8|iso_to_koi8r|iso_to_mic|iso_to_win1251|iso_to_win866|isopen|isparallel|" +
"isperp|isvertical|johab_to_utf8|justify_days|justify_hours|justify_interval|" +
"koi8r_to_iso|koi8r_to_mic|koi8r_to_utf8|koi8r_to_win1251|koi8r_to_win866|" +
"koi8u_to_utf8|lag|language_handler_in|language_handler_out|last_value|lastval|" +
"latin1_to_mic|latin2_to_mic|latin2_to_win1250|latin3_to_mic|latin4_to_mic|lead|left|" +
"length|like|like_escape|likejoinsel|likesel|line|line_distance|line_eq|line_horizontal|" +
"line_in|line_interpt|line_intersect|line_out|line_parallel|line_perp|line_recv|" +
"line_send|line_vertical|ln|lo_close|lo_creat|lo_create|lo_export|lo_import|lo_lseek|" +
"lo_open|lo_tell|lo_truncate|lo_unlink|log|loread|lower|lowrite|lpad|lseg|lseg_center|" +
"lseg_distance|lseg_eq|lseg_ge|lseg_gt|lseg_horizontal|lseg_in|lseg_interpt|" +
"lseg_intersect|lseg_le|lseg_length|lseg_lt|lseg_ne|lseg_out|lseg_parallel|lseg_perp|" +
"lseg_recv|lseg_send|lseg_vertical|ltrim|macaddr_cmp|macaddr_eq|macaddr_ge|macaddr_gt|" +
"macaddr_in|macaddr_le|macaddr_lt|macaddr_ne|macaddr_out|macaddr_recv|macaddr_send|" +
"makeaclitem|masklen|max|md5|mic_to_ascii|mic_to_big5|mic_to_euc_cn|mic_to_euc_jp|" +
"mic_to_euc_kr|mic_to_euc_tw|mic_to_iso|mic_to_koi8r|mic_to_latin1|mic_to_latin2|" +
"mic_to_latin3|mic_to_latin4|mic_to_sjis|mic_to_win1250|mic_to_win1251|mic_to_win866|" +
"min|mktinterval|mod|money|mul_d_interval|name|nameeq|namege|namegt|nameiclike|nameicnlike|" +
"nameicregexeq|nameicregexne|namein|namele|namelike|namelt|namene|namenlike|nameout|" +
"namerecv|nameregexeq|nameregexne|namesend|neqjoinsel|neqsel|netmask|network|network_cmp|" +
"network_eq|network_ge|network_gt|network_le|network_lt|network_ne|network_sub|" +
"network_subeq|network_sup|network_supeq|nextval|nlikejoinsel|nlikesel|notlike|now|" +
"npoints|nth_value|ntile|numeric_abs|numeric_accum|numeric_add|numeric_avg|" +
"numeric_avg_accum|numeric_cmp|numeric_div|numeric_div_trunc|numeric_eq|numeric_exp|" +
"numeric_fac|numeric_ge|numeric_gt|numeric_in|numeric_inc|numeric_larger|numeric_le|" +
"numeric_ln|numeric_log|numeric_lt|numeric_mod|numeric_mul|numeric_ne|numeric_out|" +
"numeric_power|numeric_recv|numeric_send|numeric_smaller|numeric_sqrt|" +
"numeric_stddev_pop|numeric_stddev_samp|numeric_sub|numeric_uminus|numeric_uplus|" +
"numeric_var_pop|numeric_var_samp|numerictypmodin|numerictypmodout|numnode|" +
"obj_description|octet_length|oid|oideq|oidge|oidgt|oidin|oidlarger|oidle|oidlt|oidne|oidout|" +
"oidrecv|oidsend|oidsmaller|oidvectoreq|oidvectorge|oidvectorgt|oidvectorin|oidvectorle|" +
"oidvectorlt|oidvectorne|oidvectorout|oidvectorrecv|oidvectorsend|oidvectortypes|on_pb|" +
"on_pl|on_ppath|on_ps|on_sb|on_sl|opaque_in|opaque_out|overlaps|overlay|path|path_add|" +
"path_add_pt|path_center|path_contain_pt|path_distance|path_div_pt|path_in|path_inter|" +
"path_length|path_mul_pt|path_n_eq|path_n_ge|path_n_gt|path_n_le|path_n_lt|path_npoints|" +
"path_out|path_recv|path_send|path_sub_pt|pclose|percent_rank|pg_advisory_lock|" +
"pg_advisory_lock_shared|pg_advisory_unlock|pg_advisory_unlock_all|" +
"pg_advisory_unlock_shared|pg_advisory_xact_lock|pg_advisory_xact_lock_shared|" +
"pg_available_extension_versions|pg_available_extensions|pg_backend_pid|" +
"pg_cancel_backend|pg_char_to_encoding|pg_client_encoding|pg_collation_is_visible|" +
"pg_column_size|pg_conf_load_time|pg_conversion_is_visible|pg_create_restore_point|" +
"pg_current_xlog_insert_location|pg_current_xlog_location|pg_cursor|pg_database_size|" +
"pg_describe_object|pg_encoding_max_length|pg_encoding_to_char|" +
"pg_extension_config_dump|pg_extension_update_paths|pg_function_is_visible|" +
"pg_get_constraintdef|pg_get_expr|pg_get_function_arguments|" +
"pg_get_function_identity_arguments|pg_get_function_result|pg_get_functiondef|" +
"pg_get_indexdef|pg_get_keywords|pg_get_ruledef|pg_get_serial_sequence|" +
"pg_get_triggerdef|pg_get_userbyid|pg_get_viewdef|pg_has_role|pg_indexes_size|" +
"pg_is_in_recovery|pg_is_other_temp_schema|pg_is_xlog_replay_paused|" +
"pg_last_xact_replay_timestamp|pg_last_xlog_receive_location|" +
"pg_last_xlog_replay_location|pg_listening_channels|pg_lock_status|pg_ls_dir|" +
"pg_my_temp_schema|pg_node_tree_in|pg_node_tree_out|pg_node_tree_recv|" +
"pg_node_tree_send|pg_notify|pg_opclass_is_visible|pg_operator_is_visible|" +
"pg_options_to_table|pg_postmaster_start_time|pg_prepared_statement|pg_prepared_xact|" +
"pg_read_binary_file|pg_read_file|pg_relation_filenode|pg_relation_filepath|" +
"pg_relation_size|pg_reload_conf|pg_rotate_logfile|pg_sequence_parameters|" +
"pg_show_all_settings|pg_size_pretty|pg_sleep|pg_start_backup|pg_stat_clear_snapshot|" +
"pg_stat_file|pg_stat_get_activity|pg_stat_get_analyze_count|" +
"pg_stat_get_autoanalyze_count|pg_stat_get_autovacuum_count|" +
"pg_stat_get_backend_activity|pg_stat_get_backend_activity_start|" +
"pg_stat_get_backend_client_addr|pg_stat_get_backend_client_port|" +
"pg_stat_get_backend_dbid|pg_stat_get_backend_idset|pg_stat_get_backend_pid|" +
"pg_stat_get_backend_start|pg_stat_get_backend_userid|pg_stat_get_backend_waiting|" +
"pg_stat_get_backend_xact_start|pg_stat_get_bgwriter_buf_written_checkpoints|" +
"pg_stat_get_bgwriter_buf_written_clean|pg_stat_get_bgwriter_maxwritten_clean|" +
"pg_stat_get_bgwriter_requested_checkpoints|pg_stat_get_bgwriter_stat_reset_time|" +
"pg_stat_get_bgwriter_timed_checkpoints|pg_stat_get_blocks_fetched|" +
"pg_stat_get_blocks_hit|pg_stat_get_buf_alloc|pg_stat_get_buf_fsync_backend|" +
"pg_stat_get_buf_written_backend|pg_stat_get_db_blocks_fetched|" +
"pg_stat_get_db_blocks_hit|pg_stat_get_db_conflict_all|" +
"pg_stat_get_db_conflict_bufferpin|pg_stat_get_db_conflict_lock|" +
"pg_stat_get_db_conflict_snapshot|pg_stat_get_db_conflict_startup_deadlock|" +
"pg_stat_get_db_conflict_tablespace|pg_stat_get_db_numbackends|" +
"pg_stat_get_db_stat_reset_time|pg_stat_get_db_tuples_deleted|" +
"pg_stat_get_db_tuples_fetched|pg_stat_get_db_tuples_inserted|" +
"pg_stat_get_db_tuples_returned|pg_stat_get_db_tuples_updated|" +
"pg_stat_get_db_xact_commit|pg_stat_get_db_xact_rollback|pg_stat_get_dead_tuples|" +
"pg_stat_get_function_calls|pg_stat_get_function_self_time|" +
"pg_stat_get_function_time|pg_stat_get_last_analyze_time|" +
"pg_stat_get_last_autoanalyze_time|pg_stat_get_last_autovacuum_time|" +
"pg_stat_get_last_vacuum_time|pg_stat_get_live_tuples|pg_stat_get_numscans|" +
"pg_stat_get_tuples_deleted|pg_stat_get_tuples_fetched|" +
"pg_stat_get_tuples_hot_updated|pg_stat_get_tuples_inserted|" +
"pg_stat_get_tuples_returned|pg_stat_get_tuples_updated|pg_stat_get_vacuum_count|" +
"pg_stat_get_wal_senders|pg_stat_get_xact_blocks_fetched|" +
"pg_stat_get_xact_blocks_hit|pg_stat_get_xact_function_calls|" +
"pg_stat_get_xact_function_self_time|pg_stat_get_xact_function_time|" +
"pg_stat_get_xact_numscans|pg_stat_get_xact_tuples_deleted|" +
"pg_stat_get_xact_tuples_fetched|pg_stat_get_xact_tuples_hot_updated|" +
"pg_stat_get_xact_tuples_inserted|pg_stat_get_xact_tuples_returned|" +
"pg_stat_get_xact_tuples_updated|pg_stat_reset|pg_stat_reset_shared|" +
"pg_stat_reset_single_function_counters|pg_stat_reset_single_table_counters|" +
"pg_stop_backup|pg_switch_xlog|pg_table_is_visible|pg_table_size|" +
"pg_tablespace_databases|pg_tablespace_size|pg_terminate_backend|pg_timezone_abbrevs|" +
"pg_timezone_names|pg_total_relation_size|pg_try_advisory_lock|" +
"pg_try_advisory_lock_shared|pg_try_advisory_xact_lock|" +
"pg_try_advisory_xact_lock_shared|pg_ts_config_is_visible|pg_ts_dict_is_visible|" +
"pg_ts_parser_is_visible|pg_ts_template_is_visible|pg_type_is_visible|pg_typeof|" +
"pg_xlog_replay_pause|pg_xlog_replay_resume|pg_xlogfile_name|pg_xlogfile_name_offset|" +
"pi|plainto_tsquery|plpgsql_call_handler|plpgsql_inline_handler|plpgsql_validator|" +
"point|point_above|point_add|point_below|point_distance|point_div|point_eq|point_horiz|" +
"point_in|point_left|point_mul|point_ne|point_out|point_recv|point_right|point_send|" +
"point_sub|point_vert|poly_above|poly_below|poly_center|poly_contain|poly_contain_pt|" +
"poly_contained|poly_distance|poly_in|poly_left|poly_npoints|poly_out|poly_overabove|" +
"poly_overbelow|poly_overlap|poly_overleft|poly_overright|poly_recv|poly_right|" +
"poly_same|poly_send|polygon|popen|position|positionjoinsel|positionsel|" +
"postgresql_fdw_validator|pow|power|prsd_end|prsd_headline|prsd_lextype|prsd_nexttoken|" +
"prsd_start|pt_contained_circle|pt_contained_poly|query_to_xml|" +
"query_to_xml_and_xmlschema|query_to_xmlschema|querytree|quote_ident|quote_literal|" +
"quote_nullable|radians|radius|random|rank|record_eq|record_ge|record_gt|record_in|" +
"record_le|record_lt|record_ne|record_out|record_recv|record_send|regclass|regclassin|" +
"regclassout|regclassrecv|regclasssend|regconfigin|regconfigout|regconfigrecv|" +
"regconfigsend|regdictionaryin|regdictionaryout|regdictionaryrecv|regdictionarysend|" +
"regexeqjoinsel|regexeqsel|regexnejoinsel|regexnesel|regexp_matches|regexp_replace|" +
"regexp_split_to_array|regexp_split_to_table|regoperatorin|regoperatorout|" +
"regoperatorrecv|regoperatorsend|regoperin|regoperout|regoperrecv|regopersend|" +
"regprocedurein|regprocedureout|regprocedurerecv|regproceduresend|regprocin|regprocout|" +
"regprocrecv|regprocsend|regr_avgx|regr_avgy|regr_count|regr_intercept|regr_r2|" +
"regr_slope|regr_sxx|regr_sxy|regr_syy|regtypein|regtypeout|regtyperecv|regtypesend|" +
"reltime|reltimeeq|reltimege|reltimegt|reltimein|reltimele|reltimelt|reltimene|reltimeout|" +
"reltimerecv|reltimesend|repeat|replace|reverse|right|round|row_number|rpad|rtrim|" +
"scalargtjoinsel|scalargtsel|scalarltjoinsel|scalarltsel|schema_to_xml|" +
"schema_to_xml_and_xmlschema|schema_to_xmlschema|session_user|set_bit|set_byte|" +
"set_config|set_masklen|setseed|setval|setweight|shell_in|shell_out|" +
"shift_jis_2004_to_euc_jis_2004|shift_jis_2004_to_utf8|shobj_description|sign|" +
"similar_escape|sin|sjis_to_euc_jp|sjis_to_mic|sjis_to_utf8|slope|smgreq|smgrin|smgrne|" +
"smgrout|split_part|sqrt|statement_timestamp|stddev|stddev_pop|stddev_samp|string_agg|" +
"string_agg_finalfn|string_agg_transfn|string_to_array|strip|strpos|substr|substring|sum|" +
"suppress_redundant_updates_trigger|table_to_xml|table_to_xml_and_xmlschema|" +
"table_to_xmlschema|tan|text|text_ge|text_gt|text_larger|text_le|text_lt|text_pattern_ge|" +
"text_pattern_gt|text_pattern_le|text_pattern_lt|text_smaller|textanycat|textcat|texteq|" +
"texticlike|texticnlike|texticregexeq|texticregexne|textin|textlen|textlike|textne|" +
"textnlike|textout|textrecv|textregexeq|textregexne|textsend|thesaurus_init|" +
"thesaurus_lexize|tideq|tidge|tidgt|tidin|tidlarger|tidle|tidlt|tidne|tidout|tidrecv|tidsend|" +
"tidsmaller|time_cmp|time_eq|time_ge|time_gt|time_hash|time_in|time_larger|time_le|time_lt|" +
"time_mi_interval|time_mi_time|time_ne|time_out|time_pl_interval|time_recv|time_send|" +
"time_smaller|timedate_pl|timemi|timenow|timeofday|timepl|timestamp_cmp|" +
"timestamp_cmp_date|timestamp_cmp_timestamptz|timestamp_eq|timestamp_eq_date|" +
"timestamp_eq_timestamptz|timestamp_ge|timestamp_ge_date|timestamp_ge_timestamptz|" +
"timestamp_gt|timestamp_gt_date|timestamp_gt_timestamptz|timestamp_hash|timestamp_in|" +
"timestamp_larger|timestamp_le|timestamp_le_date|timestamp_le_timestamptz|" +
"timestamp_lt|timestamp_lt_date|timestamp_lt_timestamptz|timestamp_mi|" +
"timestamp_mi_interval|timestamp_ne|timestamp_ne_date|timestamp_ne_timestamptz|" +
"timestamp_out|timestamp_pl_interval|timestamp_recv|timestamp_send|timestamp_smaller|" +
"timestamptypmodin|timestamptypmodout|timestamptz_cmp|timestamptz_cmp_date|" +
"timestamptz_cmp_timestamp|timestamptz_eq|timestamptz_eq_date|" +
"timestamptz_eq_timestamp|timestamptz_ge|timestamptz_ge_date|" +
"timestamptz_ge_timestamp|timestamptz_gt|timestamptz_gt_date|" +
"timestamptz_gt_timestamp|timestamptz_in|timestamptz_larger|timestamptz_le|" +
"timestamptz_le_date|timestamptz_le_timestamp|timestamptz_lt|timestamptz_lt_date|" +
"timestamptz_lt_timestamp|timestamptz_mi|timestamptz_mi_interval|timestamptz_ne|" +
"timestamptz_ne_date|timestamptz_ne_timestamp|timestamptz_out|" +
"timestamptz_pl_interval|timestamptz_recv|timestamptz_send|timestamptz_smaller|" +
"timestamptztypmodin|timestamptztypmodout|timetypmodin|timetypmodout|timetz_cmp|" +
"timetz_eq|timetz_ge|timetz_gt|timetz_hash|timetz_in|timetz_larger|timetz_le|timetz_lt|" +
"timetz_mi_interval|timetz_ne|timetz_out|timetz_pl_interval|timetz_recv|timetz_send|" +
"timetz_smaller|timetzdate_pl|timetztypmodin|timetztypmodout|timezone|tinterval|" +
"tintervalct|tintervalend|tintervaleq|tintervalge|tintervalgt|tintervalin|tintervalle|" +
"tintervalleneq|tintervallenge|tintervallengt|tintervallenle|tintervallenlt|" +
"tintervallenne|tintervallt|tintervalne|tintervalout|tintervalov|tintervalrecv|" +
"tintervalrel|tintervalsame|tintervalsend|tintervalstart|to_ascii|to_char|to_date|to_hex|" +
"to_number|to_timestamp|to_tsquery|to_tsvector|transaction_timestamp|translate|" +
"trigger_in|trigger_out|trunc|ts_debug|ts_headline|ts_lexize|ts_match_qv|ts_match_tq|" +
"ts_match_tt|ts_match_vq|ts_parse|ts_rank|ts_rank_cd|ts_rewrite|ts_stat|ts_token_type|" +
"ts_typanalyze|tsmatchjoinsel|tsmatchsel|tsq_mcontained|tsq_mcontains|tsquery_and|" +
"tsquery_cmp|tsquery_eq|tsquery_ge|tsquery_gt|tsquery_le|tsquery_lt|tsquery_ne|" +
"tsquery_not|tsquery_or|tsqueryin|tsqueryout|tsqueryrecv|tsquerysend|tsvector_cmp|" +
"tsvector_concat|tsvector_eq|tsvector_ge|tsvector_gt|tsvector_le|tsvector_lt|" +
"tsvector_ne|tsvector_update_trigger|tsvector_update_trigger_column|tsvectorin|" +
"tsvectorout|tsvectorrecv|tsvectorsend|txid_current|txid_current_snapshot|" +
"txid_snapshot_in|txid_snapshot_out|txid_snapshot_recv|txid_snapshot_send|" +
"txid_snapshot_xip|txid_snapshot_xmax|txid_snapshot_xmin|txid_visible_in_snapshot|" +
"uhc_to_utf8|unique_key_recheck|unknownin|unknownout|unknownrecv|unknownsend|unnest|" +
"upper|utf8_to_ascii|utf8_to_big5|utf8_to_euc_cn|utf8_to_euc_jis_2004|utf8_to_euc_jp|" +
"utf8_to_euc_kr|utf8_to_euc_tw|utf8_to_gb18030|utf8_to_gbk|utf8_to_iso8859|" +
"utf8_to_iso8859_1|utf8_to_johab|utf8_to_koi8r|utf8_to_koi8u|utf8_to_shift_jis_2004|" +
"utf8_to_sjis|utf8_to_uhc|utf8_to_win|uuid_cmp|uuid_eq|uuid_ge|uuid_gt|uuid_hash|uuid_in|" +
"uuid_le|uuid_lt|uuid_ne|uuid_out|uuid_recv|uuid_send|var_pop|var_samp|varbit_in|" +
"varbit_out|varbit_recv|varbit_send|varbitcmp|varbiteq|varbitge|varbitgt|varbitle|" +
"varbitlt|varbitne|varbittypmodin|varbittypmodout|varcharin|varcharout|varcharrecv|" +
"varcharsend|varchartypmodin|varchartypmodout|variance|version|void_in|void_out|" +
"void_recv|void_send|width|width_bucket|win1250_to_latin2|win1250_to_mic|win1251_to_iso|" +
"win1251_to_koi8r|win1251_to_mic|win1251_to_win866|win866_to_iso|win866_to_koi8r|" +
"win866_to_mic|win866_to_win1251|win_to_utf8|xideq|xideqint4|xidin|xidout|xidrecv|xidsend|" +
"xml|xml_in|xml_is_well_formed|xml_is_well_formed_content|xml_is_well_formed_document|" +
"xml_out|xml_recv|xml_send|xmlagg|xmlcomment|xmlconcat2|xmlexists|xmlvalidate|xpath|" +
"xpath_exists").split("|")
);
var sqlRules = [
{
token : "string", // single line string -- assume dollar strings if multi-line for now
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "variable.language", // pg identifier
regex : '".*?"'
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : function(value) {
value = value.toLowerCase();
if (keywords.hasOwnProperty(value)) {
return "keyword";
} else if (builtinFunctions.hasOwnProperty(value)) {
return "support.function";
} else {
return "identifier";
}
},
regex : "[a-zA-Z_][a-zA-Z0-9_$]*\\b" // TODO - Unicode in identifiers
}, {
token : "keyword.operator",
regex : "!|!!|!~|!~\\*|!~~|!~~\\*|#|##|#<|#<=|#<>|#=|#>|#>=|%|\\&|\\&\\&|\\&<|\\&<\\||\\&>|\\*|\\+|" +
"\\-|/|<|<#>|<\\->|<<|<<=|<<\\||<=|<>|<\\?>|<@|<\\^|=|>|>=|>>|>>=|>\\^|\\?#|\\?\\-|\\?\\-\\||" +
"\\?\\||\\?\\|\\||@|@\\-@|@>|@@|@@@|\\^|\\||\\|\\&>|\\|/|\\|>>|\\|\\||\\|\\|/|~|~\\*|~<=~|~<~|" +
"~=|~>=~|~>~|~~|~~\\*"
}, {
token : "paren.lparen",
regex : "[\\(]"
}, {
token : "paren.rparen",
regex : "[\\)]"
}, {
token : "text",
regex : "\\s+"
}
];
this.$rules = {
"start" : [
{
token : "comment",
regex : "--.*$"
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi-line comment
merge : true,
regex : "\\/\\*",
next : "comment"
},{
token : "keyword.statementBegin",
regex : "^[a-zA-Z]+", // Could enumerate starting keywords but this allows things to work when new statements are added.
next : "statement"
},{
token : "support.buildin", // psql directive
regex : "^\\\\[\\S]+.*$"
}
],
"statement" : [
{
token : "comment",
regex : "--.*$"
}, {
token : "comment", // multi-line comment
merge : true,
regex : "\\/\\*",
next : "commentStatement"
}, {
token : "statementEnd",
regex : ";",
next : "start"
}, {
token : "string", // perl, python, tcl are in the pg default dist (no tcl highlighter)
regex : "\\$perl\\$",
next : "perl-start"
}, {
token : "string",
regex : "\\$python\\$",
next : "python-start"
},{
token : "string",
regex : "\\$[\\w_0-9]*\\$$", // dollar quote at the end of a line
next : "dollarSql"
}, {
token : "string",
regex : "\\$[\\w_0-9]*\\$",
next : "dollarStatementString"
}
].concat(sqlRules),
"dollarSql" : [
{
token : "comment",
regex : "--.*$"
}, {
token : "comment", // multi-line comment
merge : true,
regex : "\\/\\*",
next : "commentDollarSql"
}, {
token : "string", // end quoting with dollar at the start of a line
regex : "^\\$[\\w_0-9]*\\$",
next : "statement"
}, {
token : "string",
regex : "\\$[\\w_0-9]*\\$",
next : "dollarSqlString"
}
].concat(sqlRules),
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"commentStatement" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "statement"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"commentDollarSql" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "dollarSql"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"dollarStatementString" : [
{
token : "string", // closing dollarstring
regex : ".*?\\$[\\w_0-9]*\\$",
next : "statement"
}, {
token : "string", // dollarstring spanning whole line
merge : true,
regex : ".+"
}
],
"dollarSqlString" : [
{
token : "string", // closing dollarstring
regex : ".*?\\$[\\w_0-9]*\\$",
next : "dollarSql"
}, {
token : "string", // dollarstring spanning whole line
merge : true,
regex : ".+"
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]);
this.embedRules(PerlHighlightRules, "perl-", [{token : "string", regex : "\\$perl\\$", next : "statement"}]);
this.embedRules(PythonHighlightRules, "python-", [{token : "string", regex : "\\$python\\$", next : "statement"}]);
};
oop.inherits(PgsqlHighlightRules, TextHighlightRules);
exports.PgsqlHighlightRules = PgsqlHighlightRules;
});
define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc",
merge : true,
regex : "\\s+"
}, {
token : "comment.doc",
merge : true,
regex : "TODO"
}, {
token : "comment.doc",
merge : true,
regex : "[^@\\*]+"
}, {
token : "comment.doc",
merge : true,
regex : "."
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
merge : true,
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
merge : true,
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
define('ace/mode/perl_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var PerlHighlightRules = function() {
var keywords = lang.arrayToMap(
("base|constant|continue|else|elsif|for|foreach|format|goto|if|last|local|my|next|" +
"no|package|parent|redo|require|scalar|sub|unless|until|while|use|vars").split("|")
);
var buildinConstants = lang.arrayToMap(
("ARGV|ENV|INC|SIG").split("|")
);
var builtinFunctions = lang.arrayToMap(
("getprotobynumber|getprotobyname|getservbyname|gethostbyaddr|" +
"gethostbyname|getservbyport|getnetbyaddr|getnetbyname|getsockname|" +
"getpeername|setpriority|getprotoent|setprotoent|getpriority|" +
"endprotoent|getservent|setservent|endservent|sethostent|socketpair|" +
"getsockopt|gethostent|endhostent|setsockopt|setnetent|quotemeta|" +
"localtime|prototype|getnetent|endnetent|rewinddir|wantarray|getpwuid|" +
"closedir|getlogin|readlink|endgrent|getgrgid|getgrnam|shmwrite|" +
"shutdown|readline|endpwent|setgrent|readpipe|formline|truncate|" +
"dbmclose|syswrite|setpwent|getpwnam|getgrent|getpwent|ucfirst|sysread|" +
"setpgrp|shmread|sysseek|sysopen|telldir|defined|opendir|connect|" +
"lcfirst|getppid|binmode|syscall|sprintf|getpgrp|readdir|seekdir|" +
"waitpid|reverse|unshift|symlink|dbmopen|semget|msgrcv|rename|listen|" +
"chroot|msgsnd|shmctl|accept|unpack|exists|fileno|shmget|system|" +
"unlink|printf|gmtime|msgctl|semctl|values|rindex|substr|splice|" +
"length|msgget|select|socket|return|caller|delete|alarm|ioctl|index|" +
"undef|lstat|times|srand|chown|fcntl|close|write|umask|rmdir|study|" +
"sleep|chomp|untie|print|utime|mkdir|atan2|split|crypt|flock|chmod|" +
"BEGIN|bless|chdir|semop|shift|reset|link|stat|chop|grep|fork|dump|" +
"join|open|tell|pipe|exit|glob|warn|each|bind|sort|pack|eval|push|" +
"keys|getc|kill|seek|sqrt|send|wait|rand|tied|read|time|exec|recv|" +
"eof|chr|int|ord|exp|pos|pop|sin|log|abs|oct|hex|tie|cos|vec|END|ref|" +
"map|die|uc|lc|do").split("|")
);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "comment",
regex : "#.*$"
}, {
token : "string.regexp",
regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // multi line string start
merge : true,
regex : '["].*\\\\$',
next : "qqstring"
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "string", // multi line string start
merge : true,
regex : "['].*\\\\$",
next : "qstring"
}, {
token : "constant.numeric", // hex
regex : "0x[0-9a-fA-F]+\\b"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : function(value) {
if (keywords.hasOwnProperty(value))
return "keyword";
else if (buildinConstants.hasOwnProperty(value))
return "constant.language";
else if (builtinFunctions.hasOwnProperty(value))
return "support.function";
else
return "identifier";
},
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "\\.\\.\\.|\\|\\|=|>>=|<<=|<=>|&&=|=>|!~|\\^=|&=|\\|=|\\.=|x=|%=|\\/=|\\*=|\\-=|\\+=|=~|\\*\\*|\\-\\-|\\.\\.|\\|\\||&&|\\+\\+|\\->|!=|==|>=|<=|>>|<<|,|=|\\?\\:|\\^|\\||x|%|\\/|\\*|<|&|\\\\|~|!|>|\\.|\\-|\\+|\\-C|\\-b|\\-S|\\-u|\\-t|\\-p|\\-l|\\-d|\\-f|\\-g|\\-s|\\-z|\\-k|\\-e|\\-O|\\-T|\\-B|\\-M|\\-A|\\-X|\\-W|\\-c|\\-R|\\-o|\\-x|\\-w|\\-r|\\b(?:and|cmp|eq|ge|gt|le|lt|ne|not|or|xor)"
}, {
token : "lparen",
regex : "[[({]"
}, {
token : "rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"qqstring" : [
{
token : "string",
regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
}
],
"qstring" : [
{
token : "string",
regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
}
]
};
};
oop.inherits(PerlHighlightRules, TextHighlightRules);
exports.PerlHighlightRules = PerlHighlightRules;
});
define('ace/mode/python_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var PythonHighlightRules = function() {
var keywords = lang.arrayToMap(
("and|as|assert|break|class|continue|def|del|elif|else|except|exec|" +
"finally|for|from|global|if|import|in|is|lambda|not|or|pass|print|" +
"raise|return|try|while|with|yield").split("|")
);
var builtinConstants = lang.arrayToMap(
("True|False|None|NotImplemented|Ellipsis|__debug__").split("|")
);
var builtinFunctions = lang.arrayToMap(
("abs|divmod|input|open|staticmethod|all|enumerate|int|ord|str|any|" +
"eval|isinstance|pow|sum|basestring|execfile|issubclass|print|super|" +
"binfile|iter|property|tuple|bool|filter|len|range|type|bytearray|" +
"float|list|raw_input|unichr|callable|format|locals|reduce|unicode|" +
"chr|frozenset|long|reload|vars|classmethod|getattr|map|repr|xrange|" +
"cmp|globals|max|reversed|zip|compile|hasattr|memoryview|round|" +
"__import__|complex|hash|min|set|apply|delattr|help|next|setattr|" +
"buffer|dict|hex|object|slice|coerce|dir|id|oct|sorted|intern").split("|")
);
var futureReserved = lang.arrayToMap(
("").split("|")
);
var strPre = "(?:r|u|ur|R|U|UR|Ur|uR)?";
var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
var octInteger = "(?:0[oO]?[0-7]+)";
var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
var binInteger = "(?:0[bB][01]+)";
var integer = "(?:" + decimalInteger + "|" + octInteger + "|" + hexInteger + "|" + binInteger + ")";
var exponent = "(?:[eE][+-]?\\d+)";
var fraction = "(?:\\.\\d+)";
var intPart = "(?:\\d+)";
var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
var exponentFloat = "(?:(?:" + pointFloat + "|" + intPart + ")" + exponent + ")";
var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";
this.$rules = {
"start" : [ {
token : "comment",
regex : "#.*$"
}, {
token : "string", // """ string
regex : strPre + '"{3}(?:[^\\\\]|\\\\.)*?"{3}'
}, {
token : "string", // multi line """ string start
merge : true,
regex : strPre + '"{3}.*$',
next : "qqstring"
}, {
token : "string", // " string
regex : strPre + '"(?:[^\\\\]|\\\\.)*?"'
}, {
token : "string", // ''' string
regex : strPre + "'{3}(?:[^\\\\]|\\\\.)*?'{3}"
}, {
token : "string", // multi line ''' string start
merge : true,
regex : strPre + "'{3}.*$",
next : "qstring"
}, {
token : "string", // ' string
regex : strPre + "'(?:[^\\\\]|\\\\.)*?'"
}, {
token : "constant.numeric", // imaginary
regex : "(?:" + floatNumber + "|\\d+)[jJ]\\b"
}, {
token : "constant.numeric", // float
regex : floatNumber
}, {
token : "constant.numeric", // long integer
regex : integer + "[lL]\\b"
}, {
token : "constant.numeric", // integer
regex : integer + "\\b"
}, {
token : function(value) {
if (keywords.hasOwnProperty(value))
return "keyword";
else if (builtinConstants.hasOwnProperty(value))
return "constant.language";
else if (futureReserved.hasOwnProperty(value))
return "invalid.illegal";
else if (builtinFunctions.hasOwnProperty(value))
return "support.function";
else if (value == "debugger")
return "invalid.deprecated";
else
return "identifier";
},
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|%|<<|>>|&|\\||\\^|~|<|>|<=|=>|==|!=|<>|="
}, {
token : "paren.lparen",
regex : "[\\[\\(\\{]"
}, {
token : "paren.rparen",
regex : "[\\]\\)\\}]"
}, {
token : "text",
regex : "\\s+"
} ],
"qqstring" : [ {
token : "string", // multi line """ string end
regex : '(?:[^\\\\]|\\\\.)*?"{3}',
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ],
"qstring" : [ {
token : "string", // multi line ''' string end
regex : "(?:[^\\\\]|\\\\.)*?'{3}",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ]
};
};
oop.inherits(PythonHighlightRules, TextHighlightRules);
exports.PythonHighlightRules = PythonHighlightRules;
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* André Fiedler <fiedler dot andre a t gmail dot com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/php', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/php_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var PhpHighlightRules = require("./php_highlight_rules").PhpHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new PhpHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
var re = /^(\s*)#/;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "#");
}
};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start") {
var match = line.match(/^.*[\{\(\[\:]\s*$/);
if (match) {
indent += tab;
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/php_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var PhpHighlightRules = function() {
var docComment = DocCommentHighlightRules;
// http://php.net/quickref.php
var builtinFunctions = lang.arrayToMap(
('abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|aggregate_methods_by_list|aggregate_methods_by_regexp|' +
'aggregate_properties|aggregate_properties_by_list|aggregate_properties_by_regexp|aggregation_info|amqpconnection|amqpexchange|amqpqueue|' +
'apache_child_terminate|apache_get_modules|apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|' +
'apache_reset_timeout|apache_response_headers|apache_setenv|apc_add|apc_bin_dump|apc_bin_dumpfile|apc_bin_load|apc_bin_loadfile|' +
'apc_cache_info|apc_cas|apc_clear_cache|apc_compile_file|apc_dec|apc_define_constants|apc_delete|apc_delete_file|apc_exists|apc_fetch|' +
'apc_inc|apc_load_constants|apc_sma_info|apc_store|apciterator|apd_breakpoint|apd_callstack|apd_clunk|apd_continue|apd_croak|' +
'apd_dump_function_table|apd_dump_persistent_resources|apd_dump_regular_resources|apd_echo|apd_get_active_symbols|apd_set_pprof_trace|' +
'apd_set_session|apd_set_session_trace|apd_set_session_trace_socket|appenditerator|array|array_change_key_case|array_chunk|array_combine|' +
'array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_fill_keys|array_filter|' +
'array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|' +
'array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|' +
'array_reduce|array_replace|array_replace_recursive|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|' +
'array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|' +
'array_values|array_walk|array_walk_recursive|arrayaccess|arrayiterator|arrayobject|arsort|asin|asinh|asort|assert|assert_options|atan|' +
'atan2|atanh|audioproperties|badfunctioncallexception|badmethodcallexception|base64_decode|base64_encode|base_convert|basename|' +
'bbcode_add_element|bbcode_add_smiley|bbcode_create|bbcode_destroy|bbcode_parse|bbcode_set_arg_parser|bbcode_set_flags|bcadd|bccomp|bcdiv|' +
'bcmod|bcmul|bcompiler_load|bcompiler_load_exe|bcompiler_parse_class|bcompiler_read|bcompiler_write_class|bcompiler_write_constant|' +
'bcompiler_write_exe_footer|bcompiler_write_file|bcompiler_write_footer|bcompiler_write_function|bcompiler_write_functions_from_file|' +
'bcompiler_write_header|bcompiler_write_included_filename|bcpow|bcpowmod|bcscale|bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|' +
'bindtextdomain|bson_decode|bson_encode|bumpValue|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|' +
'cachingiterator|cairo|cairo_create|cairo_font_face_get_type|cairo_font_face_status|cairo_font_options_create|cairo_font_options_equal|' +
'cairo_font_options_get_antialias|cairo_font_options_get_hint_metrics|cairo_font_options_get_hint_style|' +
'cairo_font_options_get_subpixel_order|cairo_font_options_hash|cairo_font_options_merge|cairo_font_options_set_antialias|' +
'cairo_font_options_set_hint_metrics|cairo_font_options_set_hint_style|cairo_font_options_set_subpixel_order|cairo_font_options_status|' +
'cairo_format_stride_for_width|cairo_image_surface_create|cairo_image_surface_create_for_data|cairo_image_surface_create_from_png|' +
'cairo_image_surface_get_data|cairo_image_surface_get_format|cairo_image_surface_get_height|cairo_image_surface_get_stride|' +
'cairo_image_surface_get_width|cairo_matrix_create_scale|cairo_matrix_create_translate|cairo_matrix_invert|cairo_matrix_multiply|' +
'cairo_matrix_rotate|cairo_matrix_transform_distance|cairo_matrix_transform_point|cairo_matrix_translate|cairo_pattern_add_color_stop_rgb|' +
'cairo_pattern_add_color_stop_rgba|cairo_pattern_create_for_surface|cairo_pattern_create_linear|cairo_pattern_create_radial|' +
'cairo_pattern_create_rgb|cairo_pattern_create_rgba|cairo_pattern_get_color_stop_count|cairo_pattern_get_color_stop_rgba|' +
'cairo_pattern_get_extend|cairo_pattern_get_filter|cairo_pattern_get_linear_points|cairo_pattern_get_matrix|' +
'cairo_pattern_get_radial_circles|cairo_pattern_get_rgba|cairo_pattern_get_surface|cairo_pattern_get_type|cairo_pattern_set_extend|' +
'cairo_pattern_set_filter|cairo_pattern_set_matrix|cairo_pattern_status|cairo_pdf_surface_create|cairo_pdf_surface_set_size|' +
'cairo_ps_get_levels|cairo_ps_level_to_string|cairo_ps_surface_create|cairo_ps_surface_dsc_begin_page_setup|' +
'cairo_ps_surface_dsc_begin_setup|cairo_ps_surface_dsc_comment|cairo_ps_surface_get_eps|cairo_ps_surface_restrict_to_level|' +
'cairo_ps_surface_set_eps|cairo_ps_surface_set_size|cairo_scaled_font_create|cairo_scaled_font_extents|cairo_scaled_font_get_ctm|' +
'cairo_scaled_font_get_font_face|cairo_scaled_font_get_font_matrix|cairo_scaled_font_get_font_options|cairo_scaled_font_get_scale_matrix|' +
'cairo_scaled_font_get_type|cairo_scaled_font_glyph_extents|cairo_scaled_font_status|cairo_scaled_font_text_extents|' +
'cairo_surface_copy_page|cairo_surface_create_similar|cairo_surface_finish|cairo_surface_flush|cairo_surface_get_content|' +
'cairo_surface_get_device_offset|cairo_surface_get_font_options|cairo_surface_get_type|cairo_surface_mark_dirty|' +
'cairo_surface_mark_dirty_rectangle|cairo_surface_set_device_offset|cairo_surface_set_fallback_resolution|cairo_surface_show_page|' +
'cairo_surface_status|cairo_surface_write_to_png|cairo_svg_surface_create|cairo_svg_surface_restrict_to_version|' +
'cairo_svg_version_to_string|cairoantialias|cairocontent|cairocontext|cairoexception|cairoextend|cairofillrule|cairofilter|cairofontface|' +
'cairofontoptions|cairofontslant|cairofonttype|cairofontweight|cairoformat|cairogradientpattern|cairohintmetrics|cairohintstyle|' +
'cairoimagesurface|cairolineargradient|cairolinecap|cairolinejoin|cairomatrix|cairooperator|cairopath|cairopattern|cairopatterntype|' +
'cairopdfsurface|cairopslevel|cairopssurface|cairoradialgradient|cairoscaledfont|cairosolidpattern|cairostatus|cairosubpixelorder|' +
'cairosurface|cairosurfacepattern|cairosurfacetype|cairosvgsurface|cairosvgversion|cairotoyfontface|cal_days_in_month|cal_from_jd|cal_info|' +
'cal_to_jd|calcul_hmac|calculhmac|call_user_func|call_user_func_array|call_user_method|call_user_method_array|callbackfilteriterator|ceil|' +
'chdb|chdb_create|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_alias|class_exists|class_implements|' +
'class_parents|classkit_import|classkit_method_add|classkit_method_copy|classkit_method_redefine|classkit_method_remove|' +
'classkit_method_rename|clearstatcache|clone|closedir|closelog|collator|com|com_addref|com_create_guid|com_event_sink|com_get|' +
'com_get_active_object|com_invoke|com_isenum|com_load|com_load_typelib|com_message_pump|com_print_typeinfo|com_propget|com_propput|' +
'com_propset|com_release|com_set|compact|connection_aborted|connection_status|connection_timeout|constant|construct|construct|construct|' +
'convert_cyr_string|convert_uudecode|convert_uuencode|copy|cos|cosh|count|count_chars|countable|counter_bump|counter_bump_value|' +
'counter_create|counter_get|counter_get_meta|counter_get_named|counter_get_value|counter_reset|counter_reset_value|crack_check|' +
'crack_closedict|crack_getlastmessage|crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|' +
'ctype_graph|ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|cubrid_affected_rows|cubrid_bind|' +
'cubrid_client_encoding|cubrid_close|cubrid_close_prepare|cubrid_close_request|cubrid_col_get|cubrid_col_size|cubrid_column_names|' +
'cubrid_column_types|cubrid_commit|cubrid_connect|cubrid_connect_with_url|cubrid_current_oid|cubrid_data_seek|cubrid_db_name|' +
'cubrid_disconnect|cubrid_drop|cubrid_errno|cubrid_error|cubrid_error_code|cubrid_error_code_facility|cubrid_error_msg|cubrid_execute|' +
'cubrid_fetch|cubrid_fetch_array|cubrid_fetch_assoc|cubrid_fetch_field|cubrid_fetch_lengths|cubrid_fetch_object|cubrid_fetch_row|' +
'cubrid_field_flags|cubrid_field_len|cubrid_field_name|cubrid_field_seek|cubrid_field_table|cubrid_field_type|cubrid_free_result|' +
'cubrid_get|cubrid_get_autocommit|cubrid_get_charset|cubrid_get_class_name|cubrid_get_client_info|cubrid_get_db_parameter|' +
'cubrid_get_server_info|cubrid_insert_id|cubrid_is_instance|cubrid_list_dbs|cubrid_load_from_glo|cubrid_lob_close|cubrid_lob_export|' +
'cubrid_lob_get|cubrid_lob_send|cubrid_lob_size|cubrid_lock_read|cubrid_lock_write|cubrid_move_cursor|cubrid_new_glo|cubrid_next_result|' +
'cubrid_num_cols|cubrid_num_fields|cubrid_num_rows|cubrid_ping|cubrid_prepare|cubrid_put|cubrid_query|cubrid_real_escape_string|' +
'cubrid_result|cubrid_rollback|cubrid_save_to_glo|cubrid_schema|cubrid_send_glo|cubrid_seq_drop|cubrid_seq_insert|cubrid_seq_put|' +
'cubrid_set_add|cubrid_set_autocommit|cubrid_set_db_parameter|cubrid_set_drop|cubrid_unbuffered_query|cubrid_version|curl_close|' +
'curl_copy_handle|curl_errno|curl_error|curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|' +
'curl_multi_getcontent|curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_setopt_array|' +
'curl_version|current|cyrus_authenticate|cyrus_bind|cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|date_add|date_create|' +
'date_create_from_format|date_date_set|date_default_timezone_get|date_default_timezone_set|date_diff|date_format|date_get_last_errors|' +
'date_interval_create_from_date_string|date_interval_format|date_isodate_set|date_modify|date_offset_get|date_parse|date_parse_from_format|' +
'date_sub|date_sun_info|date_sunrise|date_sunset|date_time_set|date_timestamp_get|date_timestamp_set|date_timezone_get|date_timezone_set|' +
'dateinterval|dateperiod|datetime|datetimezone|db2_autocommit|db2_bind_param|db2_client_info|db2_close|db2_column_privileges|db2_columns|' +
'db2_commit|db2_conn_error|db2_conn_errormsg|db2_connect|db2_cursor_type|db2_escape_string|db2_exec|db2_execute|db2_fetch_array|' +
'db2_fetch_assoc|db2_fetch_both|db2_fetch_object|db2_fetch_row|db2_field_display_size|db2_field_name|db2_field_num|db2_field_precision|' +
'db2_field_scale|db2_field_type|db2_field_width|db2_foreign_keys|db2_free_result|db2_free_stmt|db2_get_option|db2_last_insert_id|' +
'db2_lob_read|db2_next_result|db2_num_fields|db2_num_rows|db2_pclose|db2_pconnect|db2_prepare|db2_primary_keys|db2_procedure_columns|' +
'db2_procedures|db2_result|db2_rollback|db2_server_info|db2_set_option|db2_special_columns|db2_statistics|db2_stmt_error|db2_stmt_errormsg|' +
'db2_table_privileges|db2_tables|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|dba_handlers|dba_insert|dba_key_split|dba_list|' +
'dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|dbase_add_record|dbase_close|dbase_create|dbase_delete_record|' +
'dbase_get_header_info|dbase_get_record|dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|' +
'dbase_replace_record|dbplus_add|dbplus_aql|dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|' +
'dbplus_flush|dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|dbplus_lockrel|' +
'dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|dbplus_resolve|dbplus_restorepos|' +
'dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|' +
'dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|' +
'dbplus_update|dbplus_xlockrel|dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|' +
'dbx_sort|dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debug_zval_dump|decbin|dechex|decoct|define|' +
'define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|dio_seek|dio_stat|dio_tcsetattr|' +
'dio_truncate|dio_write|dir|directoryiterator|dirname|disk_free_space|disk_total_space|diskfreespace|dl|dngettext|dns_check_record|' +
'dns_get_mx|dns_get_record|dom_import_simplexml|domainexception|domattr|domattribute_name|domattribute_set_value|domattribute_specified|' +
'domattribute_value|domcharacterdata|domcomment|domdocument|domdocument_add_root|domdocument_create_attribute|' +
'domdocument_create_cdata_section|domdocument_create_comment|domdocument_create_element|domdocument_create_element_ns|' +
'domdocument_create_entity_reference|domdocument_create_processing_instruction|domdocument_create_text_node|domdocument_doctype|' +
'domdocument_document_element|domdocument_dump_file|domdocument_dump_mem|domdocument_get_element_by_id|domdocument_get_elements_by_tagname|' +
'domdocument_html_dump_mem|domdocument_xinclude|domdocumentfragment|domdocumenttype|domdocumenttype_entities|' +
'domdocumenttype_internal_subset|domdocumenttype_name|domdocumenttype_notations|domdocumenttype_public_id|domdocumenttype_system_id|' +
'domelement|domelement_get_attribute|domelement_get_attribute_node|domelement_get_elements_by_tagname|domelement_has_attribute|' +
'domelement_remove_attribute|domelement_set_attribute|domelement_set_attribute_node|domelement_tagname|domentity|domentityreference|' +
'domexception|domimplementation|domnamednodemap|domnode|domnode_add_namespace|domnode_append_child|domnode_append_sibling|' +
'domnode_attributes|domnode_child_nodes|domnode_clone_node|domnode_dump_node|domnode_first_child|domnode_get_content|' +
'domnode_has_attributes|domnode_has_child_nodes|domnode_insert_before|domnode_is_blank_node|domnode_last_child|domnode_next_sibling|' +
'domnode_node_name|domnode_node_type|domnode_node_value|domnode_owner_document|domnode_parent_node|domnode_prefix|domnode_previous_sibling|' +
'domnode_remove_child|domnode_replace_child|domnode_replace_node|domnode_set_content|domnode_set_name|domnode_set_namespace|' +
'domnode_unlink_node|domnodelist|domnotation|domprocessinginstruction|domprocessinginstruction_data|domprocessinginstruction_target|' +
'domtext|domxml_new_doc|domxml_open_file|domxml_open_mem|domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|' +
'domxml_xslt_stylesheet_file|domxml_xslt_version|domxpath|domxsltstylesheet_process|domxsltstylesheet_result_dump_file|' +
'domxsltstylesheet_result_dump_mem|dotnet|dotnet_load|doubleval|each|easter_date|easter_days|echo|empty|emptyiterator|' +
'enchant_broker_describe|enchant_broker_dict_exists|enchant_broker_free|enchant_broker_free_dict|enchant_broker_get_error|' +
'enchant_broker_init|enchant_broker_list_dicts|enchant_broker_request_dict|enchant_broker_request_pwl_dict|enchant_broker_set_ordering|' +
'enchant_dict_add_to_personal|enchant_dict_add_to_session|enchant_dict_check|enchant_dict_describe|enchant_dict_get_error|' +
'enchant_dict_is_in_session|enchant_dict_quick_check|enchant_dict_store_replacement|enchant_dict_suggest|end|ereg|ereg_replace|eregi|' +
'eregi_replace|error_get_last|error_log|error_reporting|errorexception|escapeshellarg|escapeshellcmd|eval|event_add|event_base_free|' +
'event_base_loop|event_base_loopbreak|event_base_loopexit|event_base_new|event_base_priority_init|event_base_set|event_buffer_base_set|' +
'event_buffer_disable|event_buffer_enable|event_buffer_fd_set|event_buffer_free|event_buffer_new|event_buffer_priority_set|' +
'event_buffer_read|event_buffer_set_callback|event_buffer_timeout_set|event_buffer_watermark_set|event_buffer_write|event_del|event_free|' +
'event_new|event_set|exception|exec|exif_imagetype|exif_read_data|exif_tagname|exif_thumbnail|exit|exp|expect_expectl|expect_popen|explode|' +
'expm1|export|export|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|fam_monitor_collection|fam_monitor_directory|' +
'fam_monitor_file|fam_next_event|fam_open|fam_pending|fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|' +
'fbsql_blob_size|fbsql_change_user|fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|' +
'fbsql_create_db|fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|' +
'fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|fbsql_fetch_row|' +
'fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|fbsql_field_type|fbsql_free_result|' +
'fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|fbsql_list_fields|fbsql_list_tables|fbsql_next_result|' +
'fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|' +
'fbsql_rows_fetched|fbsql_select_db|fbsql_set_characterset|fbsql_set_lob_mode|fbsql_set_password|fbsql_set_transaction|fbsql_start_db|' +
'fbsql_stop_db|fbsql_table_name|fbsql_tablename|fbsql_username|fbsql_warnings|fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|' +
'fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|' +
'fdf_get_status|fdf_get_value|fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|' +
'fdf_save_string|fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_on_import_javascript|fdf_set_opt|' +
'fdf_set_status|fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file|' +
'file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filepro|' +
'filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|filepro_retrieve|filepro_rowcount|filesize|filesystemiterator|' +
'filetype|filter_has_var|filter_id|filter_input|filter_input_array|filter_list|filter_var|filter_var_array|filteriterator|finfo_buffer|' +
'finfo_close|finfo_file|finfo_open|finfo_set_flags|floatval|flock|floor|flush|fmod|fnmatch|fopen|forward_static_call|' +
'forward_static_call_array|fpassthru|fprintf|fputcsv|fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|' +
'ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|' +
'ftp_mdtm|ftp_mkdir|ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|' +
'ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|func_get_args|' +
'func_num_args|function_exists|fwrite|gc_collect_cycles|gc_disable|gc_enable|gc_enabled|gd_info|gearmanclient|gearmanjob|gearmantask|' +
'gearmanworker|geoip_continent_code_by_name|geoip_country_code3_by_name|geoip_country_code_by_name|geoip_country_name_by_name|' +
'geoip_database_info|geoip_db_avail|geoip_db_filename|geoip_db_get_all_info|geoip_id_by_name|geoip_isp_by_name|geoip_org_by_name|' +
'geoip_record_by_name|geoip_region_by_name|geoip_region_name_by_code|geoip_time_zone_by_country_and_region|getMeta|getNamed|getValue|' +
'get_browser|get_called_class|get_cfg_var|get_class|get_class_methods|get_class_vars|get_current_user|get_declared_classes|' +
'get_declared_interfaces|get_defined_constants|get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|' +
'get_html_translation_table|get_include_path|get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|' +
'get_meta_tags|get_object_vars|get_parent_class|get_required_files|get_resource_type|getallheaders|getconstant|getconstants|getconstructor|' +
'getcwd|getdate|getdefaultproperties|getdoccomment|getendline|getenv|getextension|getextensionname|getfilename|gethostbyaddr|gethostbyname|' +
'gethostbynamel|gethostname|getimagesize|getinterfacenames|getinterfaces|getlastmod|getmethod|getmethods|getmodifiers|getmxrr|getmygid|' +
'getmyinode|getmypid|getmyuid|getname|getnamespacename|getopt|getparentclass|getproperties|getproperty|getprotobyname|getprotobynumber|' +
'getrandmax|getrusage|getservbyname|getservbyport|getshortname|getstartline|getstaticproperties|getstaticpropertyvalue|gettext|' +
'gettimeofday|gettype|glob|globiterator|gmagick|gmagickdraw|gmagickpixel|gmdate|gmmktime|gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|' +
'gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|' +
'gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_nextprime|gmp_or|gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|' +
'gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_testbit|gmp_xor|gmstrftime|' +
'gnupg_adddecryptkey|gnupg_addencryptkey|gnupg_addsignkey|gnupg_cleardecryptkeys|gnupg_clearencryptkeys|gnupg_clearsignkeys|gnupg_decrypt|' +
'gnupg_decryptverify|gnupg_encrypt|gnupg_encryptsign|gnupg_export|gnupg_geterror|gnupg_getprotocol|gnupg_import|gnupg_init|gnupg_keyinfo|' +
'gnupg_setarmor|gnupg_seterrormode|gnupg_setsignmode|gnupg_sign|gnupg_verify|gopher_parsedir|grapheme_extract|grapheme_stripos|' +
'grapheme_stristr|grapheme_strlen|grapheme_strpos|grapheme_strripos|grapheme_strrpos|grapheme_strstr|grapheme_substr|gregoriantojd|' +
'gupnp_context_get_host_ip|gupnp_context_get_port|gupnp_context_get_subscription_timeout|gupnp_context_host_path|gupnp_context_new|' +
'gupnp_context_set_subscription_timeout|gupnp_context_timeout_add|gupnp_context_unhost_path|gupnp_control_point_browse_start|' +
'gupnp_control_point_browse_stop|gupnp_control_point_callback_set|gupnp_control_point_new|gupnp_device_action_callback_set|' +
'gupnp_device_info_get|gupnp_device_info_get_service|gupnp_root_device_get_available|gupnp_root_device_get_relative_location|' +
'gupnp_root_device_new|gupnp_root_device_set_available|gupnp_root_device_start|gupnp_root_device_stop|gupnp_service_action_get|' +
'gupnp_service_action_return|gupnp_service_action_return_error|gupnp_service_action_set|gupnp_service_freeze_notify|gupnp_service_info_get|' +
'gupnp_service_info_get_introspection|gupnp_service_introspection_get_state_variable|gupnp_service_notify|gupnp_service_proxy_action_get|' +
'gupnp_service_proxy_action_set|gupnp_service_proxy_add_notify|gupnp_service_proxy_callback_set|gupnp_service_proxy_get_subscribed|' +
'gupnp_service_proxy_remove_notify|gupnp_service_proxy_set_subscribed|gupnp_service_thaw_notify|gzclose|gzcompress|gzdecode|gzdeflate|' +
'gzencode|gzeof|gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|' +
'halt_compiler|haruannotation|haruannotation_setborderstyle|haruannotation_sethighlightmode|haruannotation_seticon|' +
'haruannotation_setopened|harudestination|harudestination_setfit|harudestination_setfitb|harudestination_setfitbh|harudestination_setfitbv|' +
'harudestination_setfith|harudestination_setfitr|harudestination_setfitv|harudestination_setxyz|harudoc|harudoc_addpage|' +
'harudoc_addpagelabel|harudoc_construct|harudoc_createoutline|harudoc_getcurrentencoder|harudoc_getcurrentpage|harudoc_getencoder|' +
'harudoc_getfont|harudoc_getinfoattr|harudoc_getpagelayout|harudoc_getpagemode|harudoc_getstreamsize|harudoc_insertpage|harudoc_loadjpeg|' +
'harudoc_loadpng|harudoc_loadraw|harudoc_loadttc|harudoc_loadttf|harudoc_loadtype1|harudoc_output|harudoc_readfromstream|' +
'harudoc_reseterror|harudoc_resetstream|harudoc_save|harudoc_savetostream|harudoc_setcompressionmode|harudoc_setcurrentencoder|' +
'harudoc_setencryptionmode|harudoc_setinfoattr|harudoc_setinfodateattr|harudoc_setopenaction|harudoc_setpagelayout|harudoc_setpagemode|' +
'harudoc_setpagesconfiguration|harudoc_setpassword|harudoc_setpermission|harudoc_usecnsencodings|harudoc_usecnsfonts|' +
'harudoc_usecntencodings|harudoc_usecntfonts|harudoc_usejpencodings|harudoc_usejpfonts|harudoc_usekrencodings|harudoc_usekrfonts|' +
'haruencoder|haruencoder_getbytetype|haruencoder_gettype|haruencoder_getunicode|haruencoder_getwritingmode|haruexception|harufont|' +
'harufont_getascent|harufont_getcapheight|harufont_getdescent|harufont_getencodingname|harufont_getfontname|harufont_gettextwidth|' +
'harufont_getunicodewidth|harufont_getxheight|harufont_measuretext|haruimage|haruimage_getbitspercomponent|haruimage_getcolorspace|' +
'haruimage_getheight|haruimage_getsize|haruimage_getwidth|haruimage_setcolormask|haruimage_setmaskimage|haruoutline|' +
'haruoutline_setdestination|haruoutline_setopened|harupage|harupage_arc|harupage_begintext|harupage_circle|harupage_closepath|' +
'harupage_concat|harupage_createdestination|harupage_createlinkannotation|harupage_createtextannotation|harupage_createurlannotation|' +
'harupage_curveto|harupage_curveto2|harupage_curveto3|harupage_drawimage|harupage_ellipse|harupage_endpath|harupage_endtext|' +
'harupage_eofill|harupage_eofillstroke|harupage_fill|harupage_fillstroke|harupage_getcharspace|harupage_getcmykfill|harupage_getcmykstroke|' +
'harupage_getcurrentfont|harupage_getcurrentfontsize|harupage_getcurrentpos|harupage_getcurrenttextpos|harupage_getdash|' +
'harupage_getfillingcolorspace|harupage_getflatness|harupage_getgmode|harupage_getgrayfill|harupage_getgraystroke|harupage_getheight|' +
'harupage_gethorizontalscaling|harupage_getlinecap|harupage_getlinejoin|harupage_getlinewidth|harupage_getmiterlimit|harupage_getrgbfill|' +
'harupage_getrgbstroke|harupage_getstrokingcolorspace|harupage_gettextleading|harupage_gettextmatrix|harupage_gettextrenderingmode|' +
'harupage_gettextrise|harupage_gettextwidth|harupage_gettransmatrix|harupage_getwidth|harupage_getwordspace|harupage_lineto|' +
'harupage_measuretext|harupage_movetextpos|harupage_moveto|harupage_movetonextline|harupage_rectangle|harupage_setcharspace|' +
'harupage_setcmykfill|harupage_setcmykstroke|harupage_setdash|harupage_setflatness|harupage_setfontandsize|harupage_setgrayfill|' +
'harupage_setgraystroke|harupage_setheight|harupage_sethorizontalscaling|harupage_setlinecap|harupage_setlinejoin|harupage_setlinewidth|' +
'harupage_setmiterlimit|harupage_setrgbfill|harupage_setrgbstroke|harupage_setrotate|harupage_setsize|harupage_setslideshow|' +
'harupage_settextleading|harupage_settextmatrix|harupage_settextrenderingmode|harupage_settextrise|harupage_setwidth|harupage_setwordspace|' +
'harupage_showtext|harupage_showtextnextline|harupage_stroke|harupage_textout|harupage_textrect|hasconstant|hash|hash_algos|hash_copy|' +
'hash_file|hash_final|hash_hmac|hash_hmac_file|hash_init|hash_update|hash_update_file|hash_update_stream|hasmethod|hasproperty|header|' +
'header_register_callback|header_remove|headers_list|headers_sent|hebrev|hebrevc|hex2bin|hexdec|highlight_file|highlight_string|' +
'html_entity_decode|htmlentities|htmlspecialchars|htmlspecialchars_decode|http_build_cookie|http_build_query|http_build_str|http_build_url|' +
'http_cache_etag|http_cache_last_modified|http_chunked_decode|http_date|http_deflate|http_get|http_get_request_body|' +
'http_get_request_body_stream|http_get_request_headers|http_head|http_inflate|http_match_etag|http_match_modified|' +
'http_match_request_header|http_negotiate_charset|http_negotiate_content_type|http_negotiate_language|http_parse_cookie|http_parse_headers|' +
'http_parse_message|http_parse_params|http_persistent_handles_clean|http_persistent_handles_count|http_persistent_handles_ident|' +
'http_post_data|http_post_fields|http_put_data|http_put_file|http_put_stream|http_redirect|http_request|http_request_body_encode|' +
'http_request_method_exists|http_request_method_name|http_request_method_register|http_request_method_unregister|http_response_code|' +
'http_send_content_disposition|http_send_content_type|http_send_data|http_send_file|http_send_last_modified|http_send_status|' +
'http_send_stream|http_support|http_throttle|httpdeflatestream|httpdeflatestream_construct|httpdeflatestream_factory|' +
'httpdeflatestream_finish|httpdeflatestream_flush|httpdeflatestream_update|httpinflatestream|httpinflatestream_construct|' +
'httpinflatestream_factory|httpinflatestream_finish|httpinflatestream_flush|httpinflatestream_update|httpmessage|httpmessage_addheaders|' +
'httpmessage_construct|httpmessage_detach|httpmessage_factory|httpmessage_fromenv|httpmessage_fromstring|httpmessage_getbody|' +
'httpmessage_getheader|httpmessage_getheaders|httpmessage_gethttpversion|httpmessage_getparentmessage|httpmessage_getrequestmethod|' +
'httpmessage_getrequesturl|httpmessage_getresponsecode|httpmessage_getresponsestatus|httpmessage_gettype|httpmessage_guesscontenttype|' +
'httpmessage_prepend|httpmessage_reverse|httpmessage_send|httpmessage_setbody|httpmessage_setheaders|httpmessage_sethttpversion|' +
'httpmessage_setrequestmethod|httpmessage_setrequesturl|httpmessage_setresponsecode|httpmessage_setresponsestatus|httpmessage_settype|' +
'httpmessage_tomessagetypeobject|httpmessage_tostring|httpquerystring|httpquerystring_construct|httpquerystring_get|httpquerystring_mod|' +
'httpquerystring_set|httpquerystring_singleton|httpquerystring_toarray|httpquerystring_tostring|httpquerystring_xlate|httprequest|' +
'httprequest_addcookies|httprequest_addheaders|httprequest_addpostfields|httprequest_addpostfile|httprequest_addputdata|' +
'httprequest_addquerydata|httprequest_addrawpostdata|httprequest_addssloptions|httprequest_clearhistory|httprequest_construct|' +
'httprequest_enablecookies|httprequest_getcontenttype|httprequest_getcookies|httprequest_getheaders|httprequest_gethistory|' +
'httprequest_getmethod|httprequest_getoptions|httprequest_getpostfields|httprequest_getpostfiles|httprequest_getputdata|' +
'httprequest_getputfile|httprequest_getquerydata|httprequest_getrawpostdata|httprequest_getrawrequestmessage|' +
'httprequest_getrawresponsemessage|httprequest_getrequestmessage|httprequest_getresponsebody|httprequest_getresponsecode|' +
'httprequest_getresponsecookies|httprequest_getresponsedata|httprequest_getresponseheader|httprequest_getresponseinfo|' +
'httprequest_getresponsemessage|httprequest_getresponsestatus|httprequest_getssloptions|httprequest_geturl|httprequest_resetcookies|' +
'httprequest_send|httprequest_setcontenttype|httprequest_setcookies|httprequest_setheaders|httprequest_setmethod|httprequest_setoptions|' +
'httprequest_setpostfields|httprequest_setpostfiles|httprequest_setputdata|httprequest_setputfile|httprequest_setquerydata|' +
'httprequest_setrawpostdata|httprequest_setssloptions|httprequest_seturl|httprequestpool|httprequestpool_attach|httprequestpool_construct|' +
'httprequestpool_destruct|httprequestpool_detach|httprequestpool_getattachedrequests|httprequestpool_getfinishedrequests|' +
'httprequestpool_reset|httprequestpool_send|httprequestpool_socketperform|httprequestpool_socketselect|httpresponse|httpresponse_capture|' +
'httpresponse_getbuffersize|httpresponse_getcache|httpresponse_getcachecontrol|httpresponse_getcontentdisposition|' +
'httpresponse_getcontenttype|httpresponse_getdata|httpresponse_getetag|httpresponse_getfile|httpresponse_getgzip|httpresponse_getheader|' +
'httpresponse_getlastmodified|httpresponse_getrequestbody|httpresponse_getrequestbodystream|httpresponse_getrequestheaders|' +
'httpresponse_getstream|httpresponse_getthrottledelay|httpresponse_guesscontenttype|httpresponse_redirect|httpresponse_send|' +
'httpresponse_setbuffersize|httpresponse_setcache|httpresponse_setcachecontrol|httpresponse_setcontentdisposition|' +
'httpresponse_setcontenttype|httpresponse_setdata|httpresponse_setetag|httpresponse_setfile|httpresponse_setgzip|httpresponse_setheader|' +
'httpresponse_setlastmodified|httpresponse_setstream|httpresponse_setthrottledelay|httpresponse_status|hw_array2objrec|hw_changeobject|' +
'hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|' +
'hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|hw_edittext|hw_error|' +
'hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|hw_getchildcollobj|hw_getchilddoccoll|' +
'hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|' +
'hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|' +
'hw_incollections|hw_info|hw_inscoll|hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|' +
'hw_new_document|hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|' +
'hwapi_attribute|hwapi_attribute_key|hwapi_attribute_langdepvalue|hwapi_attribute_value|hwapi_attribute_values|hwapi_checkin|' +
'hwapi_checkout|hwapi_children|hwapi_content|hwapi_content_mimetype|hwapi_content_read|hwapi_copy|hwapi_dbstat|hwapi_dcstat|' +
'hwapi_dstanchors|hwapi_dstofsrcanchor|hwapi_error_count|hwapi_error_reason|hwapi_find|hwapi_ftstat|hwapi_hgcsp|hwapi_hwstat|' +
'hwapi_identify|hwapi_info|hwapi_insert|hwapi_insertanchor|hwapi_insertcollection|hwapi_insertdocument|hwapi_link|hwapi_lock|hwapi_move|' +
'hwapi_new_content|hwapi_object|hwapi_object_assign|hwapi_object_attreditable|hwapi_object_count|hwapi_object_insert|hwapi_object_new|' +
'hwapi_object_remove|hwapi_object_title|hwapi_object_value|hwapi_objectbyanchor|hwapi_parents|hwapi_reason_description|hwapi_reason_type|' +
'hwapi_remove|hwapi_replace|hwapi_setcommittedversion|hwapi_srcanchors|hwapi_srcsofdst|hwapi_unlock|hwapi_user|hwapi_userlist|hypot|' +
'ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|ibase_blob_create|ibase_blob_echo|' +
'ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|' +
'ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|' +
'ibase_field_info|ibase_free_event_handler|ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|' +
'ibase_name_result|ibase_num_fields|ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|' +
'ibase_rollback|ibase_rollback_ret|ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|' +
'ibase_trans|ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|' +
'iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|id3_get_frame_long_name|id3_get_frame_short_name|id3_get_genre_id|id3_get_genre_list|' +
'id3_get_genre_name|id3_get_tag|id3_get_version|id3_remove_tag|id3_set_tag|id3v2attachedpictureframe|id3v2frame|id3v2tag|idate|' +
'idn_to_ascii|idn_to_unicode|idn_to_utf8|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|ifx_close|ifx_connect|ifx_copy_blob|' +
'ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|' +
'ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|' +
'ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|' +
'ifxus_open_slob|ifxus_read_slob|ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|iis_add_server|iis_get_dir_security|' +
'iis_get_script_map|iis_get_server_by_comment|iis_get_server_by_path|iis_get_server_rights|iis_get_service_state|iis_remove_server|' +
'iis_set_app_settings|iis_set_dir_security|iis_set_script_map|iis_set_server_rights|iis_start_server|iis_start_service|iis_stop_server|' +
'iis_stop_service|image2wbmp|image_type_to_extension|image_type_to_mime_type|imagealphablending|imageantialias|imagearc|imagechar|' +
'imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|imagecolorclosestalpha|imagecolorclosesthwb|' +
'imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|imagecolorresolve|imagecolorresolvealpha|imagecolorset|' +
'imagecolorsforindex|imagecolorstotal|imagecolortransparent|imageconvolution|imagecopy|imagecopymerge|imagecopymergegray|' +
'imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|imagecreatefromgd2part|imagecreatefromgif|' +
'imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|imagecreatefromxbm|imagecreatefromxpm|' +
'imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|imagefilledellipse|imagefilledpolygon|' +
'imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|imageftbbox|imagefttext|imagegammacorrect|imagegd|' +
'imagegd2|imagegif|imagegrabscreen|imagegrabwindow|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|imageline|imageloadfont|' +
'imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepsencodefont|imagepsextendfont|imagepsfreefont|imagepsloadfont|imagepsslantfont|' +
'imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|' +
'imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imagick|' +
'imagick_adaptiveblurimage|imagick_adaptiveresizeimage|imagick_adaptivesharpenimage|imagick_adaptivethresholdimage|imagick_addimage|' +
'imagick_addnoiseimage|imagick_affinetransformimage|imagick_animateimages|imagick_annotateimage|imagick_appendimages|imagick_averageimages|' +
'imagick_blackthresholdimage|imagick_blurimage|imagick_borderimage|imagick_charcoalimage|imagick_chopimage|imagick_clear|imagick_clipimage|' +
'imagick_clippathimage|imagick_clone|imagick_clutimage|imagick_coalesceimages|imagick_colorfloodfillimage|imagick_colorizeimage|' +
'imagick_combineimages|imagick_commentimage|imagick_compareimagechannels|imagick_compareimagelayers|imagick_compareimages|' +
'imagick_compositeimage|imagick_construct|imagick_contrastimage|imagick_contraststretchimage|imagick_convolveimage|imagick_cropimage|' +
'imagick_cropthumbnailimage|imagick_current|imagick_cyclecolormapimage|imagick_decipherimage|imagick_deconstructimages|' +
'imagick_deleteimageartifact|imagick_despeckleimage|imagick_destroy|imagick_displayimage|imagick_displayimages|imagick_distortimage|' +
'imagick_drawimage|imagick_edgeimage|imagick_embossimage|imagick_encipherimage|imagick_enhanceimage|imagick_equalizeimage|' +
'imagick_evaluateimage|imagick_extentimage|imagick_flattenimages|imagick_flipimage|imagick_floodfillpaintimage|imagick_flopimage|' +
'imagick_frameimage|imagick_fximage|imagick_gammaimage|imagick_gaussianblurimage|imagick_getcolorspace|imagick_getcompression|' +
'imagick_getcompressionquality|imagick_getcopyright|imagick_getfilename|imagick_getfont|imagick_getformat|imagick_getgravity|' +
'imagick_gethomeurl|imagick_getimage|imagick_getimagealphachannel|imagick_getimageartifact|imagick_getimagebackgroundcolor|' +
'imagick_getimageblob|imagick_getimageblueprimary|imagick_getimagebordercolor|imagick_getimagechanneldepth|' +
'imagick_getimagechanneldistortion|imagick_getimagechanneldistortions|imagick_getimagechannelextrema|imagick_getimagechannelmean|' +
'imagick_getimagechannelrange|imagick_getimagechannelstatistics|imagick_getimageclipmask|imagick_getimagecolormapcolor|' +
'imagick_getimagecolors|imagick_getimagecolorspace|imagick_getimagecompose|imagick_getimagecompression|imagick_getimagecompressionquality|' +
'imagick_getimagedelay|imagick_getimagedepth|imagick_getimagedispose|imagick_getimagedistortion|imagick_getimageextrema|' +
'imagick_getimagefilename|imagick_getimageformat|imagick_getimagegamma|imagick_getimagegeometry|imagick_getimagegravity|' +
'imagick_getimagegreenprimary|imagick_getimageheight|imagick_getimagehistogram|imagick_getimageindex|imagick_getimageinterlacescheme|' +
'imagick_getimageinterpolatemethod|imagick_getimageiterations|imagick_getimagelength|imagick_getimagemagicklicense|imagick_getimagematte|' +
'imagick_getimagemattecolor|imagick_getimageorientation|imagick_getimagepage|imagick_getimagepixelcolor|imagick_getimageprofile|' +
'imagick_getimageprofiles|imagick_getimageproperties|imagick_getimageproperty|imagick_getimageredprimary|imagick_getimageregion|' +
'imagick_getimagerenderingintent|imagick_getimageresolution|imagick_getimagesblob|imagick_getimagescene|imagick_getimagesignature|' +
'imagick_getimagesize|imagick_getimagetickspersecond|imagick_getimagetotalinkdensity|imagick_getimagetype|imagick_getimageunits|' +
'imagick_getimagevirtualpixelmethod|imagick_getimagewhitepoint|imagick_getimagewidth|imagick_getinterlacescheme|imagick_getiteratorindex|' +
'imagick_getnumberimages|imagick_getoption|imagick_getpackagename|imagick_getpage|imagick_getpixeliterator|imagick_getpixelregioniterator|' +
'imagick_getpointsize|imagick_getquantumdepth|imagick_getquantumrange|imagick_getreleasedate|imagick_getresource|imagick_getresourcelimit|' +
'imagick_getsamplingfactors|imagick_getsize|imagick_getsizeoffset|imagick_getversion|imagick_hasnextimage|imagick_haspreviousimage|' +
'imagick_identifyimage|imagick_implodeimage|imagick_labelimage|imagick_levelimage|imagick_linearstretchimage|imagick_liquidrescaleimage|' +
'imagick_magnifyimage|imagick_mapimage|imagick_mattefloodfillimage|imagick_medianfilterimage|imagick_mergeimagelayers|imagick_minifyimage|' +
'imagick_modulateimage|imagick_montageimage|imagick_morphimages|imagick_mosaicimages|imagick_motionblurimage|imagick_negateimage|' +
'imagick_newimage|imagick_newpseudoimage|imagick_nextimage|imagick_normalizeimage|imagick_oilpaintimage|imagick_opaquepaintimage|' +
'imagick_optimizeimagelayers|imagick_orderedposterizeimage|imagick_paintfloodfillimage|imagick_paintopaqueimage|' +
'imagick_painttransparentimage|imagick_pingimage|imagick_pingimageblob|imagick_pingimagefile|imagick_polaroidimage|imagick_posterizeimage|' +
'imagick_previewimages|imagick_previousimage|imagick_profileimage|imagick_quantizeimage|imagick_quantizeimages|imagick_queryfontmetrics|' +
'imagick_queryfonts|imagick_queryformats|imagick_radialblurimage|imagick_raiseimage|imagick_randomthresholdimage|imagick_readimage|' +
'imagick_readimageblob|imagick_readimagefile|imagick_recolorimage|imagick_reducenoiseimage|imagick_removeimage|imagick_removeimageprofile|' +
'imagick_render|imagick_resampleimage|imagick_resetimagepage|imagick_resizeimage|imagick_rollimage|imagick_rotateimage|' +
'imagick_roundcorners|imagick_sampleimage|imagick_scaleimage|imagick_separateimagechannel|imagick_sepiatoneimage|' +
'imagick_setbackgroundcolor|imagick_setcolorspace|imagick_setcompression|imagick_setcompressionquality|imagick_setfilename|' +
'imagick_setfirstiterator|imagick_setfont|imagick_setformat|imagick_setgravity|imagick_setimage|imagick_setimagealphachannel|' +
'imagick_setimageartifact|imagick_setimagebackgroundcolor|imagick_setimagebias|imagick_setimageblueprimary|imagick_setimagebordercolor|' +
'imagick_setimagechanneldepth|imagick_setimageclipmask|imagick_setimagecolormapcolor|imagick_setimagecolorspace|imagick_setimagecompose|' +
'imagick_setimagecompression|imagick_setimagecompressionquality|imagick_setimagedelay|imagick_setimagedepth|imagick_setimagedispose|' +
'imagick_setimageextent|imagick_setimagefilename|imagick_setimageformat|imagick_setimagegamma|imagick_setimagegravity|' +
'imagick_setimagegreenprimary|imagick_setimageindex|imagick_setimageinterlacescheme|imagick_setimageinterpolatemethod|' +
'imagick_setimageiterations|imagick_setimagematte|imagick_setimagemattecolor|imagick_setimageopacity|imagick_setimageorientation|' +
'imagick_setimagepage|imagick_setimageprofile|imagick_setimageproperty|imagick_setimageredprimary|imagick_setimagerenderingintent|' +
'imagick_setimageresolution|imagick_setimagescene|imagick_setimagetickspersecond|imagick_setimagetype|imagick_setimageunits|' +
'imagick_setimagevirtualpixelmethod|imagick_setimagewhitepoint|imagick_setinterlacescheme|imagick_setiteratorindex|imagick_setlastiterator|' +
'imagick_setoption|imagick_setpage|imagick_setpointsize|imagick_setresolution|imagick_setresourcelimit|imagick_setsamplingfactors|' +
'imagick_setsize|imagick_setsizeoffset|imagick_settype|imagick_shadeimage|imagick_shadowimage|imagick_sharpenimage|imagick_shaveimage|' +
'imagick_shearimage|imagick_sigmoidalcontrastimage|imagick_sketchimage|imagick_solarizeimage|imagick_spliceimage|imagick_spreadimage|' +
'imagick_steganoimage|imagick_stereoimage|imagick_stripimage|imagick_swirlimage|imagick_textureimage|imagick_thresholdimage|' +
'imagick_thumbnailimage|imagick_tintimage|imagick_transformimage|imagick_transparentpaintimage|imagick_transposeimage|' +
'imagick_transverseimage|imagick_trimimage|imagick_uniqueimagecolors|imagick_unsharpmaskimage|imagick_valid|imagick_vignetteimage|' +
'imagick_waveimage|imagick_whitethresholdimage|imagick_writeimage|imagick_writeimagefile|imagick_writeimages|imagick_writeimagesfile|' +
'imagickdraw|imagickdraw_affine|imagickdraw_annotation|imagickdraw_arc|imagickdraw_bezier|imagickdraw_circle|imagickdraw_clear|' +
'imagickdraw_clone|imagickdraw_color|imagickdraw_comment|imagickdraw_composite|imagickdraw_construct|imagickdraw_destroy|' +
'imagickdraw_ellipse|imagickdraw_getclippath|imagickdraw_getcliprule|imagickdraw_getclipunits|imagickdraw_getfillcolor|' +
'imagickdraw_getfillopacity|imagickdraw_getfillrule|imagickdraw_getfont|imagickdraw_getfontfamily|imagickdraw_getfontsize|' +
'imagickdraw_getfontstyle|imagickdraw_getfontweight|imagickdraw_getgravity|imagickdraw_getstrokeantialias|imagickdraw_getstrokecolor|' +
'imagickdraw_getstrokedasharray|imagickdraw_getstrokedashoffset|imagickdraw_getstrokelinecap|imagickdraw_getstrokelinejoin|' +
'imagickdraw_getstrokemiterlimit|imagickdraw_getstrokeopacity|imagickdraw_getstrokewidth|imagickdraw_gettextalignment|' +
'imagickdraw_gettextantialias|imagickdraw_gettextdecoration|imagickdraw_gettextencoding|imagickdraw_gettextundercolor|' +
'imagickdraw_getvectorgraphics|imagickdraw_line|imagickdraw_matte|imagickdraw_pathclose|imagickdraw_pathcurvetoabsolute|' +
'imagickdraw_pathcurvetoquadraticbezierabsolute|imagickdraw_pathcurvetoquadraticbezierrelative|' +
'imagickdraw_pathcurvetoquadraticbeziersmoothabsolute|imagickdraw_pathcurvetoquadraticbeziersmoothrelative|imagickdraw_pathcurvetorelative|' +
'imagickdraw_pathcurvetosmoothabsolute|imagickdraw_pathcurvetosmoothrelative|imagickdraw_pathellipticarcabsolute|' +
'imagickdraw_pathellipticarcrelative|imagickdraw_pathfinish|imagickdraw_pathlinetoabsolute|imagickdraw_pathlinetohorizontalabsolute|' +
'imagickdraw_pathlinetohorizontalrelative|imagickdraw_pathlinetorelative|imagickdraw_pathlinetoverticalabsolute|' +
'imagickdraw_pathlinetoverticalrelative|imagickdraw_pathmovetoabsolute|imagickdraw_pathmovetorelative|imagickdraw_pathstart|' +
'imagickdraw_point|imagickdraw_polygon|imagickdraw_polyline|imagickdraw_pop|imagickdraw_popclippath|imagickdraw_popdefs|' +
'imagickdraw_poppattern|imagickdraw_push|imagickdraw_pushclippath|imagickdraw_pushdefs|imagickdraw_pushpattern|imagickdraw_rectangle|' +
'imagickdraw_render|imagickdraw_rotate|imagickdraw_roundrectangle|imagickdraw_scale|imagickdraw_setclippath|imagickdraw_setcliprule|' +
'imagickdraw_setclipunits|imagickdraw_setfillalpha|imagickdraw_setfillcolor|imagickdraw_setfillopacity|imagickdraw_setfillpatternurl|' +
'imagickdraw_setfillrule|imagickdraw_setfont|imagickdraw_setfontfamily|imagickdraw_setfontsize|imagickdraw_setfontstretch|' +
'imagickdraw_setfontstyle|imagickdraw_setfontweight|imagickdraw_setgravity|imagickdraw_setstrokealpha|imagickdraw_setstrokeantialias|' +
'imagickdraw_setstrokecolor|imagickdraw_setstrokedasharray|imagickdraw_setstrokedashoffset|imagickdraw_setstrokelinecap|' +
'imagickdraw_setstrokelinejoin|imagickdraw_setstrokemiterlimit|imagickdraw_setstrokeopacity|imagickdraw_setstrokepatternurl|' +
'imagickdraw_setstrokewidth|imagickdraw_settextalignment|imagickdraw_settextantialias|imagickdraw_settextdecoration|' +
'imagickdraw_settextencoding|imagickdraw_settextundercolor|imagickdraw_setvectorgraphics|imagickdraw_setviewbox|imagickdraw_skewx|' +
'imagickdraw_skewy|imagickdraw_translate|imagickpixel|imagickpixel_clear|imagickpixel_construct|imagickpixel_destroy|imagickpixel_getcolor|' +
'imagickpixel_getcolorasstring|imagickpixel_getcolorcount|imagickpixel_getcolorvalue|imagickpixel_gethsl|imagickpixel_issimilar|' +
'imagickpixel_setcolor|imagickpixel_setcolorvalue|imagickpixel_sethsl|imagickpixeliterator|imagickpixeliterator_clear|' +
'imagickpixeliterator_construct|imagickpixeliterator_destroy|imagickpixeliterator_getcurrentiteratorrow|' +
'imagickpixeliterator_getiteratorrow|imagickpixeliterator_getnextiteratorrow|imagickpixeliterator_getpreviousiteratorrow|' +
'imagickpixeliterator_newpixeliterator|imagickpixeliterator_newpixelregioniterator|imagickpixeliterator_resetiterator|' +
'imagickpixeliterator_setiteratorfirstrow|imagickpixeliterator_setiteratorlastrow|imagickpixeliterator_setiteratorrow|' +
'imagickpixeliterator_synciterator|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|imap_bodystruct|imap_check|' +
'imap_clearflag_full|imap_close|imap_create|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|imap_expunge|imap_fetch_overview|' +
'imap_fetchbody|imap_fetchheader|imap_fetchmime|imap_fetchstructure|imap_fetchtext|imap_gc|imap_get_quota|imap_get_quotaroot|imap_getacl|' +
'imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|imap_listmailbox|imap_listscan|' +
'imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|imap_mailboxmsginfo|imap_mime_header_decode|' +
'imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|imap_rename|imap_renamemailbox|imap_reopen|' +
'imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_savebody|imap_scan|imap_scanmailbox|imap_search|' +
'imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|imap_uid|imap_undelete|' +
'imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implementsinterface|implode|import_request_variables|in_array|include|' +
'include_once|inclued_get_data|inet_ntop|inet_pton|infiniteiterator|ingres_autocommit|ingres_autocommit_state|ingres_charset|ingres_close|' +
'ingres_commit|ingres_connect|ingres_cursor|ingres_errno|ingres_error|ingres_errsqlstate|ingres_escape_string|ingres_execute|' +
'ingres_fetch_array|ingres_fetch_assoc|ingres_fetch_object|ingres_fetch_proc_return|ingres_fetch_row|ingres_field_length|ingres_field_name|' +
'ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|ingres_free_result|ingres_next_error|ingres_num_fields|' +
'ingres_num_rows|ingres_pconnect|ingres_prepare|ingres_query|ingres_result_seek|ingres_rollback|ingres_set_environment|' +
'ingres_unbuffered_query|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|innamespace|inotify_add_watch|inotify_init|inotify_queue_len|' +
'inotify_read|inotify_rm_watch|interface_exists|intl_error_name|intl_get_error_code|intl_get_error_message|intl_is_failure|' +
'intldateformatter|intval|invalidargumentexception|invoke|invokeargs|ip2long|iptcembed|iptcparse|is_a|is_array|is_bool|is_callable|is_dir|' +
'is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|' +
'is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isabstract|' +
'iscloneable|isdisabled|isfinal|isinstance|isinstantiable|isinterface|isinternal|isiterateable|isset|issubclassof|isuserdefined|iterator|' +
'iterator_apply|iterator_count|iterator_to_array|iteratoraggregate|iteratoriterator|java_last_exception_clear|java_last_exception_get|' +
'jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|json_decode|json_encode|' +
'json_last_error|jsonserializable|judy|judy_type|judy_version|juliantojd|kadm5_chpass_principal|kadm5_create_principal|' +
'kadm5_delete_principal|kadm5_destroy|kadm5_flush|kadm5_get_policies|kadm5_get_principal|kadm5_get_principals|kadm5_init_with_password|' +
'kadm5_modify_principal|key|krsort|ksort|lcfirst|lcg_value|lchgrp|lchown|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|' +
'ldap_connect|ldap_count_entries|ldap_delete|ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|' +
'ldap_first_entry|ldap_first_reference|ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|' +
'ldap_get_values_len|ldap_list|ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|' +
'ldap_next_reference|ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_sasl_bind|ldap_search|ldap_set_option|' +
'ldap_set_rebind_proc|ldap_sort|ldap_start_tls|ldap_t61_to_8859|ldap_unbind|lengthexception|levenshtein|libxml_clear_errors|' +
'libxml_disable_entity_loader|libxml_get_errors|libxml_get_last_error|libxml_set_streams_context|libxml_use_internal_errors|libxmlerror|' +
'limititerator|link|linkinfo|list|locale|localeconv|localtime|log|log10|log1p|logicexception|long2ip|lstat|ltrim|lzf_compress|' +
'lzf_decompress|lzf_optimized_for|m_checkstatus|m_completeauthorizations|m_connect|m_connectionerror|m_deletetrans|m_destroyconn|' +
'm_destroyengine|m_getcell|m_getcellbynum|m_getcommadelimited|m_getheader|m_initconn|m_initengine|m_iscommadelimited|m_maxconntimeout|' +
'm_monitor|m_numcolumns|m_numrows|m_parsecommadelimited|m_responsekeys|m_responseparam|m_returnstatus|m_setblocking|m_setdropfile|m_setip|' +
'm_setssl|m_setssl_cafile|m_setssl_files|m_settimeout|m_sslcert_gen_hash|m_transactionssent|m_transinqueue|m_transkeyval|m_transnew|' +
'm_transsend|m_uwait|m_validateidentifier|m_verifyconnection|m_verifysslcert|magic_quotes_runtime|mail|' +
'mailparse_determine_best_xfer_encoding|mailparse_msg_create|mailparse_msg_extract_part|mailparse_msg_extract_part_file|' +
'mailparse_msg_extract_whole_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|mailparse_msg_get_structure|' +
'mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|mailparse_stream_encode|mailparse_uudecode_all|main|max|' +
'maxdb_affected_rows|maxdb_autocommit|maxdb_bind_param|maxdb_bind_result|maxdb_change_user|maxdb_character_set_name|maxdb_client_encoding|' +
'maxdb_close|maxdb_close_long_data|maxdb_commit|maxdb_connect|maxdb_connect_errno|maxdb_connect_error|maxdb_data_seek|maxdb_debug|' +
'maxdb_disable_reads_from_master|maxdb_disable_rpl_parse|maxdb_dump_debug_info|maxdb_embedded_connect|maxdb_enable_reads_from_master|' +
'maxdb_enable_rpl_parse|maxdb_errno|maxdb_error|maxdb_escape_string|maxdb_execute|maxdb_fetch|maxdb_fetch_array|maxdb_fetch_assoc|' +
'maxdb_fetch_field|maxdb_fetch_field_direct|maxdb_fetch_fields|maxdb_fetch_lengths|maxdb_fetch_object|maxdb_fetch_row|maxdb_field_count|' +
'maxdb_field_seek|maxdb_field_tell|maxdb_free_result|maxdb_get_client_info|maxdb_get_client_version|maxdb_get_host_info|maxdb_get_metadata|' +
'maxdb_get_proto_info|maxdb_get_server_info|maxdb_get_server_version|maxdb_info|maxdb_init|maxdb_insert_id|maxdb_kill|maxdb_master_query|' +
'maxdb_more_results|maxdb_multi_query|maxdb_next_result|maxdb_num_fields|maxdb_num_rows|maxdb_options|maxdb_param_count|maxdb_ping|' +
'maxdb_prepare|maxdb_query|maxdb_real_connect|maxdb_real_escape_string|maxdb_real_query|maxdb_report|maxdb_rollback|' +
'maxdb_rpl_parse_enabled|maxdb_rpl_probe|maxdb_rpl_query_type|maxdb_select_db|maxdb_send_long_data|maxdb_send_query|maxdb_server_end|' +
'maxdb_server_init|maxdb_set_opt|maxdb_sqlstate|maxdb_ssl_set|maxdb_stat|maxdb_stmt_affected_rows|maxdb_stmt_bind_param|' +
'maxdb_stmt_bind_result|maxdb_stmt_close|maxdb_stmt_close_long_data|maxdb_stmt_data_seek|maxdb_stmt_errno|maxdb_stmt_error|' +
'maxdb_stmt_execute|maxdb_stmt_fetch|maxdb_stmt_free_result|maxdb_stmt_init|maxdb_stmt_num_rows|maxdb_stmt_param_count|maxdb_stmt_prepare|' +
'maxdb_stmt_reset|maxdb_stmt_result_metadata|maxdb_stmt_send_long_data|maxdb_stmt_sqlstate|maxdb_stmt_store_result|maxdb_store_result|' +
'maxdb_thread_id|maxdb_thread_safe|maxdb_use_result|maxdb_warning_count|mb_check_encoding|mb_convert_case|mb_convert_encoding|' +
'mb_convert_kana|mb_convert_variables|mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|' +
'mb_encode_numericentity|mb_encoding_aliases|mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|' +
'mb_ereg_search_getregs|mb_ereg_search_init|mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|' +
'mb_get_info|mb_http_input|mb_http_output|mb_internal_encoding|mb_language|mb_list_encodings|mb_output_handler|mb_parse_str|' +
'mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_stripos|mb_stristr|' +
'mb_strlen|mb_strpos|mb_strrchr|mb_strrichr|mb_strripos|mb_strrpos|mb_strstr|mb_strtolower|mb_strtoupper|mb_strwidth|' +
'mb_substitute_character|mb_substr|mb_substr_count|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|' +
'mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|' +
'mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|' +
'mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|mcrypt_get_block_size|' +
'mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|mcrypt_module_close|' +
'mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|mcrypt_module_is_block_algorithm|' +
'mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|mcrypt_module_self_test|mcrypt_ofb|md5|md5_file|' +
'mdecrypt_generic|memcache|memcache_debug|memcached|memory_get_peak_usage|memory_get_usage|messageformatter|metaphone|method_exists|mhash|' +
'mhash_count|mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_keypress|' +
'ming_setcubicthreshold|ming_setscale|ming_setswfcompression|ming_useconstants|ming_useswfversion|mkdir|mktime|money_format|mongo|' +
'mongobindata|mongocode|mongocollection|mongoconnectionexception|mongocursor|mongocursorexception|mongocursortimeoutexception|mongodate|' +
'mongodb|mongodbref|mongoexception|mongogridfs|mongogridfscursor|mongogridfsexception|mongogridfsfile|mongoid|mongoint32|mongoint64|' +
'mongomaxkey|mongominkey|mongoregex|mongotimestamp|move_uploaded_file|mpegfile|mqseries_back|mqseries_begin|mqseries_close|mqseries_cmit|' +
'mqseries_conn|mqseries_connx|mqseries_disc|mqseries_get|mqseries_inq|mqseries_open|mqseries_put|mqseries_put1|mqseries_set|' +
'mqseries_strerror|msession_connect|msession_count|msession_create|msession_destroy|msession_disconnect|msession_find|msession_get|' +
'msession_get_array|msession_get_data|msession_inc|msession_list|msession_listvar|msession_lock|msession_plugin|msession_randstr|' +
'msession_set|msession_set_array|msession_set_data|msession_timeout|msession_uniq|msession_unlock|msg_get_queue|msg_queue_exists|' +
'msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql_affected_rows|msql_close|msql_connect|msql_create_db|' +
'msql_createdb|msql_data_seek|msql_db_query|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|msql_fetch_field|msql_fetch_object|' +
'msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|msql_field_type|msql_fieldflags|' +
'msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|msql_list_fields|msql_list_tables|' +
'msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|msql_result|msql_select_db|msql_tablename|' +
'mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|mssql_fetch_assoc|mssql_fetch_batch|' +
'mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|mssql_field_seek|mssql_field_type|' +
'mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|mssql_min_error_severity|' +
'mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|mssql_result|mssql_rows_affected|' +
'mssql_select_db|mt_getrandmax|mt_rand|mt_srand|multipleiterator|mysql_affected_rows|mysql_client_encoding|mysql_close|mysql_connect|' +
'mysql_create_db|mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|' +
'mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|' +
'mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|' +
'mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|' +
'mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|' +
'mysql_select_db|mysql_set_charset|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli|mysqli_bind_param|' +
'mysqli_bind_result|mysqli_client_encoding|mysqli_connect|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_driver|' +
'mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_escape_string|mysqli_execute|mysqli_fetch|mysqli_get_metadata|' +
'mysqli_master_query|mysqli_param_count|mysqli_report|mysqli_result|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' +
'mysqli_send_long_data|mysqli_send_query|mysqli_set_opt|mysqli_slave_query|mysqli_stmt|mysqli_warning|mysqlnd_ms_get_stats|' +
'mysqlnd_ms_query_is_select|mysqlnd_ms_set_user_pick_server|mysqlnd_qc_change_handler|mysqlnd_qc_clear_cache|mysqlnd_qc_get_cache_info|' +
'mysqlnd_qc_get_core_stats|mysqlnd_qc_get_handler|mysqlnd_qc_get_query_trace_log|mysqlnd_qc_set_user_handlers|natcasesort|natsort|' +
'ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|' +
'ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|' +
'ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|' +
'ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|' +
'ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|ncurses_filter|' +
'ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|ncurses_has_colors|' +
'ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|ncurses_init_color|' +
'ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|ncurses_keyok|' +
'ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|ncurses_move|' +
'ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|' +
'ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|' +
'ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|' +
'ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|ncurses_putp|' +
'ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|ncurses_resetty|' +
'ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|ncurses_slk_attr|' +
'ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|ncurses_slk_noutrefresh|' +
'ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|ncurses_start_color|' +
'ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|ncurses_ungetmouse|' +
'ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|ncurses_vline|ncurses_waddch|' +
'ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|ncurses_wcolor_set|ncurses_werase|' +
'ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|ncurses_wrefresh|ncurses_wstandend|' +
'ncurses_wstandout|ncurses_wvline|newinstance|newinstanceargs|newt_bell|newt_button|newt_button_bar|newt_centered_window|newt_checkbox|' +
'newt_checkbox_get_value|newt_checkbox_set_flags|newt_checkbox_set_value|newt_checkbox_tree|newt_checkbox_tree_add_item|' +
'newt_checkbox_tree_find_item|newt_checkbox_tree_get_current|newt_checkbox_tree_get_entry_value|newt_checkbox_tree_get_multi_selection|' +
'newt_checkbox_tree_get_selection|newt_checkbox_tree_multi|newt_checkbox_tree_set_current|newt_checkbox_tree_set_entry|' +
'newt_checkbox_tree_set_entry_value|newt_checkbox_tree_set_width|newt_clear_key_buffer|newt_cls|newt_compact_button|' +
'newt_component_add_callback|newt_component_takes_focus|newt_create_grid|newt_cursor_off|newt_cursor_on|newt_delay|newt_draw_form|' +
'newt_draw_root_text|newt_entry|newt_entry_get_value|newt_entry_set|newt_entry_set_filter|newt_entry_set_flags|newt_finished|newt_form|' +
'newt_form_add_component|newt_form_add_components|newt_form_add_hot_key|newt_form_destroy|newt_form_get_current|newt_form_run|' +
'newt_form_set_background|newt_form_set_height|newt_form_set_size|newt_form_set_timer|newt_form_set_width|newt_form_watch_fd|' +
'newt_get_screen_size|newt_grid_add_components_to_form|newt_grid_basic_window|newt_grid_free|newt_grid_get_size|newt_grid_h_close_stacked|' +
'newt_grid_h_stacked|newt_grid_place|newt_grid_set_field|newt_grid_simple_window|newt_grid_v_close_stacked|newt_grid_v_stacked|' +
'newt_grid_wrapped_window|newt_grid_wrapped_window_at|newt_init|newt_label|newt_label_set_text|newt_listbox|newt_listbox_append_entry|' +
'newt_listbox_clear|newt_listbox_clear_selection|newt_listbox_delete_entry|newt_listbox_get_current|newt_listbox_get_selection|' +
'newt_listbox_insert_entry|newt_listbox_item_count|newt_listbox_select_item|newt_listbox_set_current|newt_listbox_set_current_by_key|' +
'newt_listbox_set_data|newt_listbox_set_entry|newt_listbox_set_width|newt_listitem|newt_listitem_get_data|newt_listitem_set|' +
'newt_open_window|newt_pop_help_line|newt_pop_window|newt_push_help_line|newt_radio_get_current|newt_radiobutton|newt_redraw_help_line|' +
'newt_reflow_text|newt_refresh|newt_resize_screen|newt_resume|newt_run_form|newt_scale|newt_scale_set|newt_scrollbar_set|' +
'newt_set_help_callback|newt_set_suspend_callback|newt_suspend|newt_textbox|newt_textbox_get_num_lines|newt_textbox_reflowed|' +
'newt_textbox_set_height|newt_textbox_set_text|newt_vertical_scrollbar|newt_wait_for_key|newt_win_choice|newt_win_entries|newt_win_menu|' +
'newt_win_message|newt_win_messagev|newt_win_ternary|next|ngettext|nl2br|nl_langinfo|norewinditerator|normalizer|notes_body|notes_copy_db|' +
'notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|' +
'notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|nthmac|number_format|' +
'numberformatter|oauth|oauth_get_sbs|oauth_urlencode|oauthexception|oauthprovider|ob_clean|ob_deflatehandler|ob_end_clean|ob_end_flush|' +
'ob_etaghandler|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|ob_gzhandler|ob_iconv_handler|' +
'ob_implicit_flush|ob_inflatehandler|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_array_by_name|oci_bind_by_name|oci_cancel|' +
'oci_client_version|oci_close|oci_collection_append|oci_collection_assign|oci_collection_element_assign|oci_collection_element_get|' +
'oci_collection_free|oci_collection_max|oci_collection_size|oci_collection_trim|oci_commit|oci_connect|oci_define_by_name|oci_error|' +
'oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|' +
'oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_append|' +
'oci_lob_close|oci_lob_copy|oci_lob_eof|oci_lob_erase|oci_lob_export|oci_lob_flush|oci_lob_free|oci_lob_getbuffering|oci_lob_import|' +
'oci_lob_is_equal|oci_lob_load|oci_lob_read|oci_lob_rewind|oci_lob_save|oci_lob_savefile|oci_lob_seek|oci_lob_setbuffering|oci_lob_size|' +
'oci_lob_tell|oci_lob_truncate|oci_lob_write|oci_lob_writetemporary|oci_lob_writetofile|oci_new_collection|oci_new_connect|oci_new_cursor|' +
'oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|oci_server_version|' +
'oci_set_action|oci_set_client_identifier|oci_set_client_info|oci_set_edition|oci_set_module_name|oci_set_prefetch|oci_statement_type|' +
'ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|' +
'ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|' +
'ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|' +
'ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|' +
'ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|' +
'octdec|odbc_autocommit|odbc_binmode|odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|' +
'odbc_data_source|odbc_do|odbc_error|odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|' +
'odbc_fetch_row|odbc_field_len|odbc_field_name|odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|' +
'odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|' +
'odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|' +
'odbc_statistics|odbc_tableprivileges|odbc_tables|openal_buffer_create|openal_buffer_data|openal_buffer_destroy|openal_buffer_get|' +
'openal_buffer_loadwav|openal_context_create|openal_context_current|openal_context_destroy|openal_context_process|openal_context_suspend|' +
'openal_device_close|openal_device_open|openal_listener_get|openal_listener_set|openal_source_create|openal_source_destroy|' +
'openal_source_get|openal_source_pause|openal_source_play|openal_source_rewind|openal_source_set|openal_source_stop|openal_stream|opendir|' +
'openlog|openssl_cipher_iv_length|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_get_public_key|openssl_csr_get_subject|' +
'openssl_csr_new|openssl_csr_sign|openssl_decrypt|openssl_dh_compute_key|openssl_digest|openssl_encrypt|openssl_error_string|' +
'openssl_free_key|openssl_get_cipher_methods|openssl_get_md_methods|openssl_get_privatekey|openssl_get_publickey|openssl_open|' +
'openssl_pkcs12_export|openssl_pkcs12_export_to_file|openssl_pkcs12_read|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|' +
'openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_free|openssl_pkey_get_details|openssl_pkey_get_private|' +
'openssl_pkey_get_public|openssl_pkey_new|openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|' +
'openssl_random_pseudo_bytes|openssl_seal|openssl_sign|openssl_verify|openssl_x509_check_private_key|openssl_x509_checkpurpose|' +
'openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|openssl_x509_parse|openssl_x509_read|ord|outeriterator|' +
'outofboundsexception|outofrangeexception|output_add_rewrite_var|output_reset_rewrite_vars|overflowexception|overload|override_function|' +
'ovrimos_close|ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|' +
'ovrimos_field_len|ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|' +
'ovrimos_num_rows|ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parentiterator|parse_ini_file|parse_ini_string|' +
'parse_str|parse_url|parsekit_compile_file|parsekit_compile_string|parsekit_func_arginfo|passthru|pathinfo|pclose|pcntl_alarm|pcntl_exec|' +
'pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_signal_dispatch|pcntl_sigprocmask|pcntl_sigtimedwait|pcntl_sigwaitinfo|' +
'pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|' +
'pdf_activate_item|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|pdf_add_locallink|pdf_add_nameddest|pdf_add_note|pdf_add_outline|' +
'pdf_add_pdflink|pdf_add_table_cell|pdf_add_textflow|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|pdf_begin_document|' +
'pdf_begin_font|pdf_begin_glyph|pdf_begin_item|pdf_begin_layer|pdf_begin_page|pdf_begin_page_ext|pdf_begin_pattern|pdf_begin_template|' +
'pdf_begin_template_ext|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|pdf_closepath|' +
'pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_create_3dview|pdf_create_action|pdf_create_annotation|' +
'pdf_create_bookmark|pdf_create_field|pdf_create_fieldgroup|pdf_create_gstate|pdf_create_pvf|pdf_create_textflow|pdf_curveto|' +
'pdf_define_layer|pdf_delete|pdf_delete_pvf|pdf_delete_table|pdf_delete_textflow|pdf_encoding_set_char|pdf_end_document|pdf_end_font|' +
'pdf_end_glyph|pdf_end_item|pdf_end_layer|pdf_end_page|pdf_end_page_ext|pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|' +
'pdf_fill_imageblock|pdf_fill_pdfblock|pdf_fill_stroke|pdf_fill_textblock|pdf_findfont|pdf_fit_image|pdf_fit_pdi_page|pdf_fit_table|' +
'pdf_fit_textflow|pdf_fit_textline|pdf_get_apiname|pdf_get_buffer|pdf_get_errmsg|pdf_get_errnum|pdf_get_font|pdf_get_fontname|' +
'pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|' +
'pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_info_font|pdf_info_matchbox|pdf_info_table|pdf_info_textflow|pdf_info_textline|' +
'pdf_initgraphics|pdf_lineto|pdf_load_3ddata|pdf_load_font|pdf_load_iccprofile|pdf_load_image|pdf_makespotcolor|pdf_moveto|pdf_new|' +
'pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|' +
'pdf_open_pdi_document|pdf_open_pdi_page|pdf_open_tiff|pdf_pcos_get_number|pdf_pcos_get_stream|pdf_pcos_get_string|pdf_place_image|' +
'pdf_place_pdi_page|pdf_process_pdi|pdf_rect|pdf_restore|pdf_resume_page|pdf_rotate|pdf_save|pdf_scale|pdf_set_border_color|' +
'pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_gstate|pdf_set_horiz_scaling|pdf_set_info|' +
'pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|pdf_set_info_title|pdf_set_layer_dependency|' +
'pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|pdf_set_value|' +
'pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setdashpattern|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|' +
'pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|' +
'pdf_setrgbcolor_stroke|pdf_shading|pdf_shading_pattern|pdf_shfill|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|' +
'pdf_suspend_page|pdf_translate|pdf_utf16_to_utf8|pdf_utf32_to_utf16|pdf_utf8_to_utf16|pdo|pdo_cubrid_schema|pdo_pgsqllobcreate|' +
'pdo_pgsqllobopen|pdo_pgsqllobunlink|pdo_sqlitecreateaggregate|pdo_sqlitecreatefunction|pdoexception|pdostatement|pfsockopen|' +
'pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|pg_connection_busy|pg_connection_reset|pg_connection_status|' +
'pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|pg_escape_bytea|pg_escape_string|pg_execute|pg_fetch_all|' +
'pg_fetch_all_columns|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|pg_field_is_null|pg_field_name|' +
'pg_field_num|pg_field_prtlen|pg_field_size|pg_field_table|pg_field_type|pg_field_type_oid|pg_free_result|pg_get_notify|pg_get_pid|' +
'pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|pg_lo_open|' +
'pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|pg_options|' +
'pg_parameter_status|pg_pconnect|pg_ping|pg_port|pg_prepare|pg_put_line|pg_query|pg_query_params|pg_result_error|pg_result_error_field|' +
'pg_result_seek|pg_result_status|pg_select|pg_send_execute|pg_send_prepare|pg_send_query|pg_send_query_params|pg_set_client_encoding|' +
'pg_set_error_verbosity|pg_trace|pg_transaction_status|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|pg_version|php_check_syntax|' +
'php_ini_loaded_file|php_ini_scanned_files|php_logo_guid|php_sapi_name|php_strip_whitespace|php_uname|phpcredits|phpinfo|phpversion|pi|' +
'png2wbmp|popen|pos|posix_access|posix_ctermid|posix_errno|posix_get_last_error|posix_getcwd|posix_getegid|posix_geteuid|posix_getgid|' +
'posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|posix_getppid|posix_getpwnam|' +
'posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_initgroups|posix_isatty|posix_kill|posix_mkfifo|posix_mknod|posix_setegid|' +
'posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|posix_uname|pow|preg_filter|' +
'preg_grep|preg_last_error|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|' +
'printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|' +
'printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|' +
'printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|' +
'printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|' +
'printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|property_exists|' +
'ps_add_bookmark|ps_add_launchlink|ps_add_locallink|ps_add_note|ps_add_pdflink|ps_add_weblink|ps_arc|ps_arcn|ps_begin_page|' +
'ps_begin_pattern|ps_begin_template|ps_circle|ps_clip|ps_close|ps_close_image|ps_closepath|ps_closepath_stroke|ps_continue_text|ps_curveto|' +
'ps_delete|ps_end_page|ps_end_pattern|ps_end_template|ps_fill|ps_fill_stroke|ps_findfont|ps_get_buffer|ps_get_parameter|ps_get_value|' +
'ps_hyphenate|ps_include_file|ps_lineto|ps_makespotcolor|ps_moveto|ps_new|ps_open_file|ps_open_image|ps_open_image_file|' +
'ps_open_memory_image|ps_place_image|ps_rect|ps_restore|ps_rotate|ps_save|ps_scale|ps_set_border_color|ps_set_border_dash|' +
'ps_set_border_style|ps_set_info|ps_set_parameter|ps_set_text_pos|ps_set_value|ps_setcolor|ps_setdash|ps_setflat|ps_setfont|ps_setgray|' +
'ps_setlinecap|ps_setlinejoin|ps_setlinewidth|ps_setmiterlimit|ps_setoverprintmode|ps_setpolydash|ps_shading|ps_shading_pattern|ps_shfill|' +
'ps_show|ps_show2|ps_show_boxed|ps_show_xy|ps_show_xy2|ps_string_geometry|ps_stringwidth|ps_stroke|ps_symbol|ps_symbol_name|' +
'ps_symbol_width|ps_translate|pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|' +
'pspell_config_data_dir|pspell_config_dict_dir|pspell_config_ignore|pspell_config_mode|pspell_config_personal|pspell_config_repl|' +
'pspell_config_runtogether|pspell_config_save_repl|pspell_new|pspell_new_config|pspell_new_personal|pspell_save_wordlist|' +
'pspell_store_replacement|pspell_suggest|putenv|px_close|px_create_fp|px_date2string|px_delete|px_delete_record|px_get_field|px_get_info|' +
'px_get_parameter|px_get_record|px_get_schema|px_get_value|px_insert_record|px_new|px_numfields|px_numrecords|px_open_fp|px_put_record|' +
'px_retrieve_record|px_set_blob_file|px_set_parameter|px_set_tablename|px_set_targetencoding|px_set_value|px_timestamp2string|' +
'px_update_record|qdom_error|qdom_tree|quoted_printable_decode|quoted_printable_encode|quotemeta|rad2deg|radius_acct_open|' +
'radius_add_server|radius_auth_open|radius_close|radius_config|radius_create_request|radius_cvt_addr|radius_cvt_int|radius_cvt_string|' +
'radius_demangle|radius_demangle_mppe_key|radius_get_attr|radius_get_vendor_attr|radius_put_addr|radius_put_attr|radius_put_int|' +
'radius_put_string|radius_put_vendor_addr|radius_put_vendor_attr|radius_put_vendor_int|radius_put_vendor_string|' +
'radius_request_authenticator|radius_send_request|radius_server_secret|radius_strerror|rand|range|rangeexception|rar_wrapper_cache_stats|' +
'rararchive|rarentry|rarexception|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|readline_add_history|' +
'readline_callback_handler_install|readline_callback_handler_remove|readline_callback_read_char|readline_clear_history|' +
'readline_completion_function|readline_info|readline_list_history|readline_on_new_line|readline_read_history|readline_redisplay|' +
'readline_write_history|readlink|realpath|realpath_cache_get|realpath_cache_size|recode|recode_file|recode_string|recursivearrayiterator|' +
'recursivecachingiterator|recursivecallbackfilteriterator|recursivedirectoryiterator|recursivefilteriterator|recursiveiterator|' +
'recursiveiteratoriterator|recursiveregexiterator|recursivetreeiterator|reflection|reflectionclass|reflectionexception|reflectionextension|' +
'reflectionfunction|reflectionfunctionabstract|reflectionmethod|reflectionobject|reflectionparameter|reflectionproperty|reflector|' +
'regexiterator|register_shutdown_function|register_tick_function|rename|rename_function|require|require_once|reset|resetValue|' +
'resourcebundle|restore_error_handler|restore_exception_handler|restore_include_path|return|rewind|rewinddir|rmdir|round|rpm_close|' +
'rpm_get_tag|rpm_is_valid|rpm_open|rpm_version|rrd_create|rrd_error|rrd_fetch|rrd_first|rrd_graph|rrd_info|rrd_last|rrd_lastupdate|' +
'rrd_restore|rrd_tune|rrd_update|rrd_xport|rrdcreator|rrdgraph|rrdupdater|rsort|rtrim|runkit_class_adopt|runkit_class_emancipate|' +
'runkit_constant_add|runkit_constant_redefine|runkit_constant_remove|runkit_function_add|runkit_function_copy|runkit_function_redefine|' +
'runkit_function_remove|runkit_function_rename|runkit_import|runkit_lint|runkit_lint_file|runkit_method_add|runkit_method_copy|' +
'runkit_method_redefine|runkit_method_remove|runkit_method_rename|runkit_return_value_used|runkit_sandbox_output_handler|' +
'runkit_superglobals|runtimeexception|samconnection_commit|samconnection_connect|samconnection_constructor|samconnection_disconnect|' +
'samconnection_errno|samconnection_error|samconnection_isconnected|samconnection_peek|samconnection_peekall|samconnection_receive|' +
'samconnection_remove|samconnection_rollback|samconnection_send|samconnection_setDebug|samconnection_subscribe|samconnection_unsubscribe|' +
'sammessage_body|sammessage_constructor|sammessage_header|sca_createdataobject|sca_getservice|sca_localproxy_createdataobject|' +
'sca_soapproxy_createdataobject|scandir|sdo_das_changesummary_beginlogging|sdo_das_changesummary_endlogging|' +
'sdo_das_changesummary_getchangeddataobjects|sdo_das_changesummary_getchangetype|sdo_das_changesummary_getoldcontainer|' +
'sdo_das_changesummary_getoldvalues|sdo_das_changesummary_islogging|sdo_das_datafactory_addpropertytotype|sdo_das_datafactory_addtype|' +
'sdo_das_datafactory_getdatafactory|sdo_das_dataobject_getchangesummary|sdo_das_relational_applychanges|sdo_das_relational_construct|' +
'sdo_das_relational_createrootdataobject|sdo_das_relational_executepreparedquery|sdo_das_relational_executequery|' +
'sdo_das_setting_getlistindex|sdo_das_setting_getpropertyindex|sdo_das_setting_getpropertyname|sdo_das_setting_getvalue|' +
'sdo_das_setting_isset|sdo_das_xml_addtypes|sdo_das_xml_create|sdo_das_xml_createdataobject|sdo_das_xml_createdocument|' +
'sdo_das_xml_document_getrootdataobject|sdo_das_xml_document_getrootelementname|sdo_das_xml_document_getrootelementuri|' +
'sdo_das_xml_document_setencoding|sdo_das_xml_document_setxmldeclaration|sdo_das_xml_document_setxmlversion|sdo_das_xml_loadfile|' +
'sdo_das_xml_loadstring|sdo_das_xml_savefile|sdo_das_xml_savestring|sdo_datafactory_create|sdo_dataobject_clear|' +
'sdo_dataobject_createdataobject|sdo_dataobject_getcontainer|sdo_dataobject_getsequence|sdo_dataobject_gettypename|' +
'sdo_dataobject_gettypenamespaceuri|sdo_exception_getcause|sdo_list_insert|sdo_model_property_getcontainingtype|' +
'sdo_model_property_getdefault|sdo_model_property_getname|sdo_model_property_gettype|sdo_model_property_iscontainment|' +
'sdo_model_property_ismany|sdo_model_reflectiondataobject_construct|sdo_model_reflectiondataobject_export|' +
'sdo_model_reflectiondataobject_getcontainmentproperty|sdo_model_reflectiondataobject_getinstanceproperties|' +
'sdo_model_reflectiondataobject_gettype|sdo_model_type_getbasetype|sdo_model_type_getname|sdo_model_type_getnamespaceuri|' +
'sdo_model_type_getproperties|sdo_model_type_getproperty|sdo_model_type_isabstracttype|sdo_model_type_isdatatype|sdo_model_type_isinstance|' +
'sdo_model_type_isopentype|sdo_model_type_issequencedtype|sdo_sequence_getproperty|sdo_sequence_insert|sdo_sequence_move|seekableiterator|' +
'sem_acquire|sem_get|sem_release|sem_remove|serializable|serialize|session_cache_expire|session_cache_limiter|session_commit|' +
'session_decode|session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|' +
'session_pgsql_add_error|session_pgsql_get_error|session_pgsql_get_field|session_pgsql_reset|session_pgsql_set_field|session_pgsql_status|' +
'session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|' +
'session_unregister|session_unset|session_write_close|setCounterClass|set_error_handler|set_exception_handler|set_file_buffer|' +
'set_include_path|set_magic_quotes_runtime|set_socket_blocking|set_time_limit|setcookie|setlocale|setproctitle|setrawcookie|' +
'setstaticpropertyvalue|setthreadtitle|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_has_var|shm_put_var|' +
'shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|signeurlpaiement|' +
'similar_text|simplexml_import_dom|simplexml_load_file|simplexml_load_string|simplexmlelement|simplexmliterator|sin|sinh|sizeof|sleep|snmp|' +
'snmp2_get|snmp2_getnext|snmp2_real_walk|snmp2_set|snmp2_walk|snmp3_get|snmp3_getnext|snmp3_real_walk|snmp3_set|snmp3_walk|' +
'snmp_get_quick_print|snmp_get_valueretrieval|snmp_read_mib|snmp_set_enum_print|snmp_set_oid_numeric_print|snmp_set_oid_output_format|' +
'snmp_set_quick_print|snmp_set_valueretrieval|snmpget|snmpgetnext|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|soapclient|soapfault|' +
'soapheader|soapparam|soapserver|soapvar|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|socket_create|' +
'socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|socket_last_error|' +
'socket_listen|socket_read|socket_recv|socket_recvfrom|socket_select|socket_send|socket_sendto|socket_set_block|socket_set_blocking|' +
'socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|socket_strerror|socket_write|solr_get_version|solrclient|' +
'solrclientexception|solrdocument|solrdocumentfield|solrexception|solrgenericresponse|solrillegalargumentexception|' +
'solrillegaloperationexception|solrinputdocument|solrmodifiableparams|solrobject|solrparams|solrpingresponse|solrquery|solrqueryresponse|' +
'solrresponse|solrupdateresponse|solrutils|sort|soundex|sphinxclient|spl_autoload|spl_autoload_call|spl_autoload_extensions|' +
'spl_autoload_functions|spl_autoload_register|spl_autoload_unregister|spl_classes|spl_object_hash|splbool|spldoublylinkedlist|splenum|' +
'splfileinfo|splfileobject|splfixedarray|splfloat|splheap|splint|split|spliti|splmaxheap|splminheap|splobjectstorage|splobserver|' +
'splpriorityqueue|splqueue|splstack|splstring|splsubject|spltempfileobject|spoofchecker|sprintf|sql_regcase|sqlite3|sqlite3result|' +
'sqlite3stmt|sqlite_array_query|sqlite_busy_timeout|sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|' +
'sqlite_create_function|sqlite_current|sqlite_error_string|sqlite_escape_string|sqlite_exec|sqlite_factory|sqlite_fetch_all|' +
'sqlite_fetch_array|sqlite_fetch_column_types|sqlite_fetch_object|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|' +
'sqlite_has_more|sqlite_has_prev|sqlite_key|sqlite_last_error|sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|' +
'sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|sqlite_prev|sqlite_query|sqlite_rewind|sqlite_seek|sqlite_single_query|' +
'sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqlite_valid|sqrt|srand|sscanf|ssdeep_fuzzy_compare|' +
'ssdeep_fuzzy_hash|ssdeep_fuzzy_hash_filename|ssh2_auth_hostbased_file|ssh2_auth_none|ssh2_auth_password|ssh2_auth_pubkey_file|' +
'ssh2_connect|ssh2_exec|ssh2_fetch_stream|ssh2_fingerprint|ssh2_methods_negotiated|ssh2_publickey_add|ssh2_publickey_init|' +
'ssh2_publickey_list|ssh2_publickey_remove|ssh2_scp_recv|ssh2_scp_send|ssh2_sftp|ssh2_sftp_lstat|ssh2_sftp_mkdir|ssh2_sftp_readlink|' +
'ssh2_sftp_realpath|ssh2_sftp_rename|ssh2_sftp_rmdir|ssh2_sftp_stat|ssh2_sftp_symlink|ssh2_sftp_unlink|ssh2_shell|ssh2_tunnel|stat|' +
'stats_absolute_deviation|stats_cdf_beta|stats_cdf_binomial|stats_cdf_cauchy|stats_cdf_chisquare|stats_cdf_exponential|stats_cdf_f|' +
'stats_cdf_gamma|stats_cdf_laplace|stats_cdf_logistic|stats_cdf_negative_binomial|stats_cdf_noncentral_chisquare|stats_cdf_noncentral_f|' +
'stats_cdf_poisson|stats_cdf_t|stats_cdf_uniform|stats_cdf_weibull|stats_covariance|stats_den_uniform|stats_dens_beta|stats_dens_cauchy|' +
'stats_dens_chisquare|stats_dens_exponential|stats_dens_f|stats_dens_gamma|stats_dens_laplace|stats_dens_logistic|' +
'stats_dens_negative_binomial|stats_dens_normal|stats_dens_pmf_binomial|stats_dens_pmf_hypergeometric|stats_dens_pmf_poisson|stats_dens_t|' +
'stats_dens_weibull|stats_harmonic_mean|stats_kurtosis|stats_rand_gen_beta|stats_rand_gen_chisquare|stats_rand_gen_exponential|' +
'stats_rand_gen_f|stats_rand_gen_funiform|stats_rand_gen_gamma|stats_rand_gen_ibinomial|stats_rand_gen_ibinomial_negative|' +
'stats_rand_gen_int|stats_rand_gen_ipoisson|stats_rand_gen_iuniform|stats_rand_gen_noncenral_chisquare|stats_rand_gen_noncentral_f|' +
'stats_rand_gen_noncentral_t|stats_rand_gen_normal|stats_rand_gen_t|stats_rand_get_seeds|stats_rand_phrase_to_seeds|stats_rand_ranf|' +
'stats_rand_setall|stats_skew|stats_standard_deviation|stats_stat_binomial_coef|stats_stat_correlation|stats_stat_gennch|' +
'stats_stat_independent_t|stats_stat_innerproduct|stats_stat_noncentral_t|stats_stat_paired_t|stats_stat_percentile|stats_stat_powersum|' +
'stats_variance|stomp|stomp_connect_error|stomp_version|stompexception|stompframe|str_getcsv|str_ireplace|str_pad|str_repeat|str_replace|' +
'str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|stream_bucket_append|stream_bucket_make_writeable|' +
'stream_bucket_new|stream_bucket_prepend|stream_context_create|stream_context_get_default|stream_context_get_options|' +
'stream_context_get_params|stream_context_set_default|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|' +
'stream_encoding|stream_filter_append|stream_filter_prepend|stream_filter_register|stream_filter_remove|stream_get_contents|' +
'stream_get_filters|stream_get_line|stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_is_local|' +
'stream_notification_callback|stream_register_wrapper|stream_resolve_include_path|stream_select|stream_set_blocking|stream_set_read_buffer|' +
'stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_enable_crypto|stream_socket_get_name|' +
'stream_socket_pair|stream_socket_recvfrom|stream_socket_sendto|stream_socket_server|stream_socket_shutdown|stream_supports_lock|' +
'stream_wrapper_register|stream_wrapper_restore|stream_wrapper_unregister|streamwrapper|strftime|strip_tags|stripcslashes|stripos|' +
'stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|' +
'strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|svm|svmmodel|svn_add|' +
'svn_auth_get_parameter|svn_auth_set_parameter|svn_blame|svn_cat|svn_checkout|svn_cleanup|svn_client_version|svn_commit|svn_delete|' +
'svn_diff|svn_export|svn_fs_abort_txn|svn_fs_apply_text|svn_fs_begin_txn2|svn_fs_change_node_prop|svn_fs_check_path|' +
'svn_fs_contents_changed|svn_fs_copy|svn_fs_delete|svn_fs_dir_entries|svn_fs_file_contents|svn_fs_file_length|svn_fs_is_dir|svn_fs_is_file|' +
'svn_fs_make_dir|svn_fs_make_file|svn_fs_node_created_rev|svn_fs_node_prop|svn_fs_props_changed|svn_fs_revision_prop|svn_fs_revision_root|' +
'svn_fs_txn_root|svn_fs_youngest_rev|svn_import|svn_log|svn_ls|svn_mkdir|svn_repos_create|svn_repos_fs|svn_repos_fs_begin_txn_for_commit|' +
'svn_repos_fs_commit_txn|svn_repos_hotcopy|svn_repos_open|svn_repos_recover|svn_revert|svn_status|svn_update|swf_actiongeturl|' +
'swf_actiongotoframe|swf_actiongotolabel|swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|' +
'swf_actiontogglequality|swf_actionwaitforframe|swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|' +
'swf_defineline|swf_definepoly|swf_definerect|swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|' +
'swf_fontslant|swf_fonttracking|swf_getbitmapinfo|swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|' +
'swf_nextid|swf_oncondition|swf_openfile|swf_ortho|swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|' +
'swf_pushmatrix|swf_removeobject|swf_rotate|swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|' +
'swf_shapefillbitmapclip|swf_shapefillbitmaptile|swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|' +
'swf_showframe|swf_startbutton|swf_startdoaction|swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|' +
'swfbitmap|swfbutton|swfdisplayitem|swffill|swffont|swffontchar|swfgradient|swfmorph|swfmovie|swfprebuiltclip|swfshape|swfsound|' +
'swfsoundinstance|swfsprite|swftext|swftextfield|swfvideostream|swish_construct|swish_getmetalist|swish_getpropertylist|swish_prepare|' +
'swish_query|swishresult_getmetalist|swishresult_stem|swishresults_getparsedwords|swishresults_getremovedstopwords|swishresults_nextresult|' +
'swishresults_seekresult|swishsearch_execute|swishsearch_resetlimit|swishsearch_setlimit|swishsearch_setphrasedelimiter|' +
'swishsearch_setsort|swishsearch_setstructure|sybase_affected_rows|sybase_close|sybase_connect|sybase_data_seek|' +
'sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|sybase_fetch_row|' +
'sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|' +
'sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|' +
'sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|sys_get_temp_dir|sys_getloadavg|syslog|system|tag|tan|tanh|' +
'tcpwrap_check|tempnam|textdomain|tidy|tidy_access_count|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_error_buffer|' +
'tidy_get_output|tidy_load_config|tidy_reset_config|tidy_save_config|tidy_set_encoding|tidy_setopt|tidy_warning_count|tidynode|time|' +
'time_nanosleep|time_sleep_until|timezone_abbreviations_list|timezone_identifiers_list|timezone_location_get|timezone_name_from_abbr|' +
'timezone_name_get|timezone_offset_get|timezone_open|timezone_transitions_get|timezone_version_get|tmpfile|token_get_all|token_name|' +
'tokyotyrant|tokyotyrantquery|tokyotyranttable|tostring|tostring|touch|transliterator|traversable|trigger_error|trim|uasort|ucfirst|' +
'ucwords|udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|' +
'udm_check_stored|udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|' +
'udm_free_res|udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|' +
'uksort|umask|underflowexception|unexpectedvalueexception|uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|' +
'urldecode|urlencode|use_soap_error_handler|user_error|usleep|usort|utf8_decode|utf8_encode|v8js|v8jsexception|var_dump|var_export|variant|' +
'variant_abs|variant_add|variant_and|variant_cast|variant_cat|variant_cmp|variant_date_from_timestamp|variant_date_to_timestamp|' +
'variant_div|variant_eqv|variant_fix|variant_get_type|variant_idiv|variant_imp|variant_int|variant_mod|variant_mul|variant_neg|variant_not|' +
'variant_or|variant_pow|variant_round|variant_set|variant_set_type|variant_sub|variant_xor|version_compare|vfprintf|virtual|' +
'vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|' +
'vpopmail_alias_del|vpopmail_alias_del_domain|vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|' +
'vpopmail_del_domain_ex|vpopmail_del_user|vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|' +
'w32api_init_dtype|w32api_invoke_function|w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|' +
'wddx_packet_start|wddx_serialize_value|wddx_serialize_vars|win32_continue_service|win32_create_service|win32_delete_service|' +
'win32_get_last_control_message|win32_pause_service|win32_ps_list_procs|win32_ps_stat_mem|win32_ps_stat_proc|win32_query_service_status|' +
'win32_set_service_status|win32_start_service|win32_start_service_ctrl_dispatcher|win32_stop_service|wincache_fcache_fileinfo|' +
'wincache_fcache_meminfo|wincache_lock|wincache_ocache_fileinfo|wincache_ocache_meminfo|wincache_refresh_if_changed|' +
'wincache_rplist_fileinfo|wincache_rplist_meminfo|wincache_scache_info|wincache_scache_meminfo|wincache_ucache_add|wincache_ucache_cas|' +
'wincache_ucache_clear|wincache_ucache_dec|wincache_ucache_delete|wincache_ucache_exists|wincache_ucache_get|wincache_ucache_inc|' +
'wincache_ucache_info|wincache_ucache_meminfo|wincache_ucache_set|wincache_unlock|wordwrap|xattr_get|xattr_list|xattr_remove|xattr_set|' +
'xattr_supported|xdiff_file_bdiff|xdiff_file_bdiff_size|xdiff_file_bpatch|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|' +
'xdiff_file_patch|xdiff_file_patch_binary|xdiff_file_rabdiff|xdiff_string_bdiff|xdiff_string_bdiff_size|xdiff_string_bpatch|' +
'xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xdiff_string_rabdiff|' +
'xhprof_disable|xhprof_enable|xhprof_sample_disable|xhprof_sample_enable|xml_error_string|xml_get_current_byte_index|' +
'xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|xml_parser_create|' +
'xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|xml_set_default_handler|' +
'xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|xml_set_notation_decl_handler|' +
'xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|xml_set_unparsed_entity_decl_handler|xmlreader|' +
'xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|xmlrpc_is_fault|xmlrpc_parse_method_descriptions|' +
'xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|xmlrpc_server_destroy|' +
'xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xmlwriter_end_attribute|xmlwriter_end_cdata|' +
'xmlwriter_end_comment|xmlwriter_end_document|xmlwriter_end_dtd|xmlwriter_end_dtd_attlist|xmlwriter_end_dtd_element|' +
'xmlwriter_end_dtd_entity|xmlwriter_end_element|xmlwriter_end_pi|xmlwriter_flush|xmlwriter_full_end_element|xmlwriter_open_memory|' +
'xmlwriter_open_uri|xmlwriter_output_memory|xmlwriter_set_indent|xmlwriter_set_indent_string|xmlwriter_start_attribute|' +
'xmlwriter_start_attribute_ns|xmlwriter_start_cdata|xmlwriter_start_comment|xmlwriter_start_document|xmlwriter_start_dtd|' +
'xmlwriter_start_dtd_attlist|xmlwriter_start_dtd_element|xmlwriter_start_dtd_entity|xmlwriter_start_element|xmlwriter_start_element_ns|' +
'xmlwriter_start_pi|xmlwriter_text|xmlwriter_write_attribute|xmlwriter_write_attribute_ns|xmlwriter_write_cdata|xmlwriter_write_comment|' +
'xmlwriter_write_dtd|xmlwriter_write_dtd_attlist|xmlwriter_write_dtd_element|xmlwriter_write_dtd_entity|xmlwriter_write_element|' +
'xmlwriter_write_element_ns|xmlwriter_write_pi|xmlwriter_write_raw|xpath_eval|xpath_eval_expression|xpath_new_context|xpath_register_ns|' +
'xpath_register_ns_auto|xptr_eval|xptr_new_context|xslt_backend_info|xslt_backend_name|xslt_backend_version|xslt_create|xslt_errno|' +
'xslt_error|xslt_free|xslt_getopt|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|xslt_set_object|' +
'xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|xslt_setopt|xsltprocessor|yaml_emit|' +
'yaml_emit_file|yaml_parse|yaml_parse_file|yaml_parse_url|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|yaz_close|yaz_connect|yaz_database|' +
'yaz_element|yaz_errno|yaz_error|yaz_es|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|yaz_range|yaz_record|yaz_scan|' +
'yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|yp_err_string|yp_errno|yp_first|' +
'yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_thread_id|zend_version|zip_close|zip_entry_close|' +
'zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|zip_open|zip_read|' +
'ziparchive|ziparchive_addemptydir|ziparchive_addfile|ziparchive_addfromstring|ziparchive_close|ziparchive_deleteindex|' +
'ziparchive_deletename|ziparchive_extractto|ziparchive_getarchivecomment|ziparchive_getcommentindex|ziparchive_getcommentname|' +
'ziparchive_getfromindex|ziparchive_getfromname|ziparchive_getnameindex|ziparchive_getstatusstring|ziparchive_getstream|' +
'ziparchive_locatename|ziparchive_open|ziparchive_renameindex|ziparchive_renamename|ziparchive_setCommentName|ziparchive_setarchivecomment|' +
'ziparchive_setcommentindex|ziparchive_statindex|ziparchive_statname|ziparchive_unchangeall|ziparchive_unchangearchive|' +
'ziparchive_unchangeindex|ziparchive_unchangename|zlib_get_coding_type').split('|')
);
// http://php.net/manual/en/reserved.keywords.php
var keywords = lang.arrayToMap(
('abstract|and|array|as|break|case|catch|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|' +
'endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|interface|instanceof|namespace|new|or|private|protected|' +
'public|static|switch|throw|try|use|var|while|xor').split('|')
);
// http://php.net/manual/en/reserved.keywords.php
var languageConstructs = lang.arrayToMap(
('die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset').split('|')
);
var builtinConstants = lang.arrayToMap(
('true|false|null|__CLASS__|__DIR__|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__NAMESPACE__').split('|')
);
var builtinVariables = lang.arrayToMap(
('$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|' +
'$http_response_header|$argc|$argv').split('|')
);
// Discovery done by downloading 'Many HTML files' from: http://php.net/download-docs.php
// Then search for files containing 'deprecated' (case-insensitive) and look at each file that turns up.
var builtinFunctionsDeprecated = lang.arrayToMap(
('key_exists|cairo_matrix_create_scale|cairo_matrix_create_translate|call_user_method|call_user_method_array|com_addref|com_get|' +
'com_invoke|com_isenum|com_load|com_release|com_set|connection_timeout|cubrid_load_from_glo|cubrid_new_glo|cubrid_save_to_glo|' +
'cubrid_send_glo|define_syslog_variables|dl|ereg|ereg_replace|eregi|eregi_replace|hw_documentattributes|hw_documentbodytag|' +
'hw_documentsize|hw_outputdocument|imagedashedline|maxdb_bind_param|maxdb_bind_result|maxdb_client_encoding|maxdb_close_long_data|' +
'maxdb_execute|maxdb_fetch|maxdb_get_metadata|maxdb_param_count|maxdb_send_long_data|mcrypt_ecb|mcrypt_generic_end|mime_content_type|' +
'mysql_createdb|mysql_dbname|mysql_db_query|mysql_drop_db|mysql_dropdb|mysql_escape_string|mysql_fieldflags|mysql_fieldflags|' +
'mysql_fieldname|mysql_fieldtable|mysql_fieldtype|mysql_freeresult|mysql_listdbs|mysql_list_fields|mysql_listfields|mysql_list_tables|' +
'mysql_listtables|mysql_numfields|mysql_numrows|mysql_selectdb|mysql_tablename|mysqli_bind_param|mysqli_bind_result|' +
'mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_execute|' +
'mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' +
'mysqli_send_long_data|mysqli_send_query|mysqli_slave_query|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|' +
'ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|' +
'ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|' +
'ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|' +
'ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|' +
'ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|PDF_add_annotation|PDF_add_bookmark|' +
'PDF_add_launchlink|PDF_add_locallink|PDF_add_note|PDF_add_outline|PDF_add_pdflink|PDF_add_weblink|PDF_attach_file|PDF_begin_page|' +
'PDF_begin_template|PDF_close_pdi|PDF_close|PDF_findfont|PDF_get_font|PDF_get_fontname|PDF_get_fontsize|PDF_get_image_height|' +
'PDF_get_image_width|PDF_get_majorversion|PDF_get_minorversion|PDF_get_pdi_parameter|PDF_get_pdi_value|PDF_open_ccitt|PDF_open_file|' +
'PDF_open_gif|PDF_open_image_file|PDF_open_image|PDF_open_jpeg|PDF_open_pdi|PDF_open_tiff|PDF_place_image|PDF_place_pdi_page|' +
'PDF_set_border_color|PDF_set_border_dash|PDF_set_border_style|PDF_set_char_spacing|PDF_set_duration|PDF_set_horiz_scaling|' +
'PDF_set_info_author|PDF_set_info_creator|PDF_set_info_keywords|PDF_set_info_subject|PDF_set_info_title|PDF_set_leading|' +
'PDF_set_text_matrix|PDF_set_text_rendering|PDF_set_text_rise|PDF_set_word_spacing|PDF_setgray_fill|PDF_setgray_stroke|PDF_setgray|' +
'PDF_setpolydash|PDF_setrgbcolor_fill|PDF_setrgbcolor_stroke|PDF_setrgbcolor|PDF_show_boxed|php_check_syntax|px_set_tablename|' +
'px_set_targetencoding|runkit_sandbox_output_handler|session_is_registered|session_register|session_unregister' +
'set_magic_quotes_runtime|magic_quotes_runtime|set_socket_blocking|socket_set_blocking|set_socket_timeout|socket_set_timeout|split|spliti|' +
'sql_regcase').split('|')
);
var keywordsDeprecated = lang.arrayToMap(
('cfunction|old_function').split('|')
);
var futureReserved = lang.arrayToMap([]);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "support.php_tag", // php open tag
regex : "<\\?(?:php|\\=)"
},
{
token : "support.php_tag", // php close tag
regex : "\\?>"
},
{
token : "comment",
regex : "<\\!--",
next : "htmlcomment"
},
{
token : "meta.tag",
regex : "<style",
next : "css"
},
{
token : "meta.tag", // opening tag
regex : "<\\/?[-_a-zA-Z0-9:]+",
next : "htmltag"
},
{
token : 'meta.tag',
regex : '<\!DOCTYPE.*?>'
},
{
token : "comment",
regex : "\\/\\/.*$"
},
{
token : "comment",
regex : "#.*$"
},
docComment.getStartRule("doc-start"),
{
token : "comment", // multi line comment
regex : "\\/\\*",
next : "comment"
}, {
token : "string.regexp",
regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)"
}, {
token : "string", // " string start
regex : '"',
next : "qqstring"
}, {
token : "string", // ' string start
regex : "'",
next : "qstring"
}, {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+\\b"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "constant.language", // constants
regex : "\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|" +
"ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|" +
"HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|" +
"L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|" +
"VERSION))|__COMPILER_HALT_OFFSET__)\\b"
}, {
token : "constant.language", // constants
regex : "\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|" +
"SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|" +
"O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|" +
"R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|" +
"YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|" +
"ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|" +
"T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|" +
"HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|" +
"I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|" +
"O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|" +
"L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|" +
"M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|" +
"OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" +
"P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" +
"RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|" +
"T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b"
}, {
token : function(value) {
if (keywords.hasOwnProperty(value))
return "keyword";
else if (builtinConstants.hasOwnProperty(value))
return "constant.language";
else if (builtinVariables.hasOwnProperty(value))
return "variable.language";
else if (futureReserved.hasOwnProperty(value))
return "invalid.illegal";
else if (builtinFunctions.hasOwnProperty(value))
return "support.function";
else if (value == "debugger")
return "invalid.deprecated";
else
if(value.match(/^(\$[a-zA-Z][a-zA-Z0-9_]*|self|parent)$/))
return "variable";
return "identifier";
},
// TODO: Unicode escape sequences
// TODO: Unicode identifiers
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
}, {
token : "lparen",
regex : "[[({]"
}, {
token : "rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
regex : ".+"
}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : '\\\\(?:[nrtvef\\\\"$]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})'
}, {
token : "constant.language.escape",
regex : /\$[\w\d]+(?:\[[\w\d]+\])?/
}, {
token : "constant.language.escape",
regex : /\$\{[^"\}]+\}?/ // this is wrong but ok for now
}, {
token : "string",
regex : '"',
next : "start"
}, {
token : "string",
regex : '.+?'
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : "\\\\['\\\\]"
}, {
token : "string",
regex : "'",
next : "start"
}, {
token : "string",
regex : ".+?"
}
],
"htmlcomment" : [
{
token : "comment",
regex : ".*?-->",
next : "start"
}, {
token : "comment",
regex : ".+"
}
],
"htmltag" : [
{
token : "meta.tag",
regex : ">",
next : "start"
}, {
token : "text",
regex : "[-_a-zA-Z0-9:]+"
}, {
token : "text",
regex : "\\s+"
}, {
token : "string",
regex : '".*?"'
}, {
token : "string",
regex : "'.*?'"
}
],
"css" : [
{
token : "meta.tag",
regex : "<\/style>",
next : "htmltag"
}, {
token : "meta.tag",
regex : ">"
}, {
token : 'text',
regex : "(?:media|type|href)"
}, {
token : 'string',
regex : '=".*?"'
}, {
token : "paren.lparen",
regex : "\{",
next : "cssdeclaration"
}, {
token : "keyword",
regex : "#[A-Za-z0-9\-\_\.]+"
}, {
token : "variable",
regex : "\\.[A-Za-z0-9\-\_\.]+"
}, {
token : "constant",
regex : "[A-Za-z0-9]+"
}
],
"cssdeclaration" : [
{
token : "support.type",
regex : "[\-a-zA-Z]+",
next : "cssvalue"
},
{
token : "paren.rparen",
regex : '\}',
next : "css"
}
],
"cssvalue" : [
{
token : "text",
regex : "\:"
},
{
token : "constant",
regex : "#[0-9a-zA-Z]+"
},
{
token : "text",
regex : "[\-\_0-9a-zA-Z\"' ,%]+"
},
{
token : "text",
regex : ";",
next : "cssdeclaration"
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(PhpHighlightRules, TextHighlightRules);
exports.PhpHighlightRules = PhpHighlightRules;
});
define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc",
merge : true,
regex : "\\s+"
}, {
token : "comment.doc",
merge : true,
regex : "TODO"
}, {
token : "comment.doc",
merge : true,
regex : "[^@\\*]+"
}, {
token : "comment.doc",
merge : true,
regex : "."
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
merge : true,
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
merge : true,
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = function () {
this.add("braces", "insertion", function (state, action, editor, session, text) {
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '{' + selected + '}',
selection: false
};
} else {
return {
text: '{}',
selection: [1, 1]
};
}
} else if (text == '}') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1});
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString());
var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '(' + selected + ')',
selection: false
};
} else {
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
// We're escaped.
if (leftChar == '\\') {
return null;
}
// Find what token we're inside.
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
// Try and be smart about when we auto insert.
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
// Ignore input and move right one if we're typing over the closing quote.
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/theme/pastel_on_dark', ['require', 'exports', 'module', 'ace/lib/dom'], function(require, exports, module) {
exports.isDark = true;
exports.cssClass = "ace-pastel-on-dark";
exports.cssText = "\
.ace-pastel-on-dark .ace_editor {\
border: 2px solid rgb(159, 159, 159);\
}\
\
.ace-pastel-on-dark .ace_editor.ace_focus {\
border: 2px solid #327fbd;\
}\
\
.ace-pastel-on-dark .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
\
.ace-pastel-on-dark .ace_print_margin {\
width: 1px;\
background: #e8e8e8;\
}\
\
.ace-pastel-on-dark .ace_scroller {\
background-color: #2C2828;\
}\
\
.ace-pastel-on-dark .ace_text-layer {\
cursor: text;\
color: #8F938F;\
}\
\
.ace-pastel-on-dark .ace_cursor {\
border-left: 2px solid #A7A7A7;\
}\
\
.ace-pastel-on-dark .ace_cursor.ace_overwrite {\
border-left: 0px;\
border-bottom: 1px solid #A7A7A7;\
}\
\
.ace-pastel-on-dark .ace_marker-layer .ace_selection {\
background: rgba(221, 240, 255, 0.20);\
}\
\
.ace-pastel-on-dark.multiselect .ace_selection.start {\
box-shadow: 0 0 3px 0px #2C2828;\
border-radius: 2px;\
}\
\
.ace-pastel-on-dark .ace_marker-layer .ace_step {\
background: rgb(102, 82, 0);\
}\
\
.ace-pastel-on-dark .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgba(255, 255, 255, 0.25);\
}\
\
.ace-pastel-on-dark .ace_marker-layer .ace_active_line {\
background: rgba(255, 255, 255, 0.031);\
}\
\
.ace-pastel-on-dark .ace_gutter_active_line {\
background-color : #dcdcdc;\
}\
\
.ace-pastel-on-dark .ace_marker-layer .ace_selected_word {\
border: 1px solid rgba(221, 240, 255, 0.20);\
}\
\
.ace-pastel-on-dark .ace_invisible {\
color: rgba(255, 255, 255, 0.25);\
}\
\
.ace-pastel-on-dark .ace_keyword, .ace-pastel-on-dark .ace_meta {\
color:#757aD8;\
}\
\
.ace-pastel-on-dark .ace_keyword.ace_operator {\
color:#797878;\
}\
\
.ace-pastel-on-dark .ace_constant, .ace-pastel-on-dark .ace_constant.ace_other {\
color:#4FB7C5;\
}\
\
.ace-pastel-on-dark .ace_constant.ace_character, {\
color:#4FB7C5;\
}\
\
.ace-pastel-on-dark .ace_constant.ace_character.ace_escape, {\
color:#4FB7C5;\
}\
\
.ace-pastel-on-dark .ace_constant.ace_language {\
color:#DE8E30;\
}\
\
.ace-pastel-on-dark .ace_constant.ace_numeric {\
color:#CCCCCC;\
}\
\
.ace-pastel-on-dark .ace_invalid {\
color:#F8F8F8;\
background-color:rgba(86, 45, 86, 0.75);\
}\
\
.ace-pastel-on-dark .ace_invalid.ace_illegal {\
color:#F8F8F8;\
background-color:rgba(86, 45, 86, 0.75);\
}\
\
.ace-pastel-on-dark .ace_invalid.ace_deprecated {\
text-decoration:underline;\
font-style:italic;\
color:#D2A8A1;\
}\
\
.ace-pastel-on-dark .ace_fold {\
background-color: #757aD8;\
border-color: #8F938F;\
}\
\
.ace-pastel-on-dark .ace_support.ace_function {\
color:#AEB2F8;\
}\
\
.ace-pastel-on-dark .ace_string {\
color:#66A968;\
}\
\
.ace-pastel-on-dark .ace_string.ace_regexp {\
color:#E9C062;\
}\
\
.ace-pastel-on-dark .ace_comment {\
color:#A6C6FF;\
}\
\
.ace-pastel-on-dark .ace_variable {\
color:#BEBF55;\
}\
\
.ace-pastel-on-dark .ace_variable.ace_language {\
color:#C1C144;\
}\
\
.ace-pastel-on-dark .ace_xml_pe {\
color:#494949;\
}\
\
.ace-pastel-on-dark .ace_markup.ace_underline {\
text-decoration:underline;\
}";
var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});
|
JavaScript
|
define('ace/mode/java', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/javascript', 'ace/tokenizer', 'ace/mode/java_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var JavaScriptMode = require("./javascript").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var JavaHighlightRules = require("./java_highlight_rules").JavaHighlightRules;
var Mode = function() {
JavaScriptMode.call(this);
this.$tokenizer = new Tokenizer(new JavaHighlightRules().getRules());
};
oop.inherits(Mode, JavaScriptMode);
(function() {
this.createWorker = function(session) {
return null;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/javascript', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/javascript_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/range', 'ace/worker/worker_client', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var Range = require("../range").Range;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var Mode = function() {
this.$tokenizer = new Tokenizer(new JavaScriptHighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.toggleCommentLines = function(state, doc, startRow, endRow) {
var outdent = true;
var re = /^(\s*)\/\//;
for (var i=startRow; i<= endRow; i++) {
if (!re.test(doc.getLine(i))) {
outdent = false;
break;
}
}
if (outdent) {
var deleteRange = new Range(0, 0, 0, 0);
for (var i=startRow; i<= endRow; i++)
{
var line = doc.getLine(i);
var m = line.match(re);
deleteRange.start.row = i;
deleteRange.end.row = i;
deleteRange.end.column = m[0].length;
doc.replace(deleteRange, m[1]);
}
}
else {
doc.indentRows(startRow, endRow, "//");
}
};
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var endState = tokenizedLine.state;
if (tokens.length && tokens[tokens.length-1].type == "comment") {
return indent;
}
if (state == "start" || state == "regex_allowed") {
var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/);
if (match) {
indent += tab;
}
} else if (state == "doc-start") {
if (endState == "start" || state == "regex_allowed") {
return "";
}
var match = line.match(/^\s*(\/?)\*/);
if (match) {
if (match[1]) {
indent += " ";
}
indent += "* ";
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "worker-javascript.js", "ace/mode/javascript_worker", "JavaScriptWorker");
worker.attachToDocument(session.getDocument());
worker.on("jslint", function(results) {
var errors = [];
for (var i=0; i<results.data.length; i++) {
var error = results.data[i];
if (error)
errors.push({
row: error.line-1,
column: error.character-1,
text: error.reason,
type: "warning",
lint: error
});
}
session.setAnnotations(errors);
});
worker.on("narcissus", function(e) {
session.setAnnotations([e.data]);
});
worker.on("terminate", function() {
session.clearAnnotations();
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/javascript_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/unicode', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var unicode = require("../unicode");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JavaScriptHighlightRules = function() {
// see: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects
var globals = lang.arrayToMap(
// Constructors
("Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" +
// E4X
"Namespace|QName|XML|XMLList|" +
"ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" +
"Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" +
// Errors
"Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" +
"SyntaxError|TypeError|URIError|" +
// Non-constructor functions
"decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" +
"isNaN|parseFloat|parseInt|" +
// Other
"JSON|Math|" +
// Pseudo
"this|arguments|prototype|window|document"
).split("|")
);
var keywords = lang.arrayToMap(
("break|case|catch|continue|default|delete|do|else|finally|for|function|" +
"if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|" +
"const|yield|import|get|set").split("|")
);
// keywords which can be followed by regular expressions
var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield";
var deprecated = lang.arrayToMap(
("__parent__|__count__|escape|unescape|with|__proto__").split("|")
);
var definitions = lang.arrayToMap(("const|let|var|function").split("|"));
var buildinConstants = lang.arrayToMap(
("null|Infinity|NaN|undefined").split("|")
);
var futureReserved = lang.arrayToMap(
("class|enum|extends|super|export|implements|private|" +
"public|interface|package|protected|static").split("|")
);
// TODO: Unicode escape sequences
var identifierRe = "[" + unicode.packages.L + "\\$_]["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]*\\b";
var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex
"u[0-9a-fA-F]{4}|" + // unicode
"[0-2][0-7]{0,2}|" + // oct
"3[0-6][0-7]?|" + // oct
"37[0-7]?|" + // oct
"[4-7][0-7]?|" + //oct
".)";
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "comment",
regex : /\/\/.*$/
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
merge : true,
regex : /\/\*/,
next : "comment"
}, {
token : "string",
regex : "'(?=.)",
next : "qstring"
}, {
token : "string",
regex : '"(?=.)',
next : "qqstring"
}, {
token : "constant.numeric", // hex
regex : /0[xX][0-9a-fA-F]+\b/
}, {
token : "constant.numeric", // float
regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/
}, { // match stuff like: Sound.prototype.play = function() { }
token : [
"storage.type",
"punctuation.operator",
"support.function",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: Sound.prototype.play = myfunc
token : [
"storage.type",
"punctuation.operator",
"support.function",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text"
],
regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)",
next: "function_arguments"
}, { // match stuff like: Sound.play = function() { }
token : [
"storage.type",
"punctuation.operator",
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: play = function() { }
token : [
"entity.name.function",
"text",
"keyword.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // match regular function like: function myFunc(arg) { }
token : [
"storage.type",
"text",
"entity.name.function",
"text",
"paren.lparen"
],
regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()",
next: "function_arguments"
}, { // match stuff like: foobar: function() { }
token : [
"entity.name.function",
"text",
"punctuation.operator",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, { // Attempt to match : function() { } (this is for issues with 'foo': function() { })
token : [
"text",
"text",
"storage.type",
"text",
"paren.lparen"
],
regex : "(:)(\\s*)(function)(\\s*)(\\()",
next: "function_arguments"
}, {
token : "constant.language.boolean",
regex : /(?:true|false)\b/
}, {
token : "keyword",
regex : "(?:" + kwBeforeRe + ")\\b",
next : "regex_allowed"
}, {
token : ["punctuation.operator", "support.function"],
regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:opzzzz|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/
}, {
token : ["punctuation.operator", "support.function.dom"],
regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/
}, {
token : ["punctuation.operator", "support.constant"],
regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/
}, {
token : ["storage.type", "punctuation.operator", "support.function.firebug"],
regex : /(console)(\.)(warn|info|log|error|time|timeEnd|assert)\b/
}, {
token : function(value) {
if (globals.hasOwnProperty(value))
return "variable.language";
else if (deprecated.hasOwnProperty(value))
return "invalid.deprecated";
else if (definitions.hasOwnProperty(value))
return "storage.type";
else if (keywords.hasOwnProperty(value))
return "keyword";
else if (buildinConstants.hasOwnProperty(value))
return "constant.language";
else if (futureReserved.hasOwnProperty(value))
return "invalid.illegal";
else if (value == "debugger")
return "invalid.deprecated";
else
return "identifier";
},
regex : identifierRe
}, {
token : "keyword.operator",
regex : /!|\$|%|&|\*|\-\-|\-|\+\+|\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|\*=|%=|\+=|\-=|&=|\^=|\b(?:in|instanceof|new|delete|typeof|void)/,
next : "regex_allowed"
}, {
token : "punctuation.operator",
regex : /\?|\:|\,|\;|\./,
next : "regex_allowed"
}, {
token : "paren.lparen",
regex : /[\[({]/,
next : "regex_allowed"
}, {
token : "paren.rparen",
regex : /[\])}]/
}, {
token : "keyword.operator",
regex : /\/=?/,
next : "regex_allowed"
}, {
token: "comment",
regex: /^#!.*$/
}, {
token : "text",
regex : /\s+/
}
],
// regular expressions are only allowed after certain tokens. This
// makes sure we don't mix up regexps with the divison operator
"regex_allowed": [
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment_regex_allowed"
}, {
token : "comment",
regex : "\\/\\/.*$"
}, {
token: "string.regexp",
regex: "\\/",
next: "regex",
merge: true
}, {
token : "text",
regex : "\\s+"
}, {
// immediately return to the start mode without matching
// anything
token: "empty",
regex: "",
next: "start"
}
],
"regex": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
// flag
token: "string.regexp",
regex: "/\\w*",
next: "start",
merge: true
}, {
token: "string.regexp",
regex: "[^\\\\/\\[]+",
merge: true
}, {
token: "string.regexp.charachterclass",
regex: "\\[",
next: "regex_character_class",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"regex_character_class": [
{
token: "regexp.keyword.operator",
regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)"
}, {
token: "string.regexp.charachterclass",
regex: "]",
next: "regex",
merge: true
}, {
token: "string.regexp.charachterclass",
regex: "[^\\\\\\]]+",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"function_arguments": [
{
token: "variable.parameter",
regex: identifierRe,
}, {
token: "punctuation.operator",
regex: "[, ]+",
merge: true
}, {
token: "punctuation.operator",
regex: "$",
merge: true
}, {
token: "empty",
regex: "",
next: "start"
}
],
"comment_regex_allowed" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
merge : true,
next : "regex_allowed"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
merge : true,
next : "start"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
],
"qqstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : '[^"\\\\]+',
merge : true
}, {
token : "string",
regex : "\\\\$",
next : "qqstring",
merge : true
}, {
token : "string",
regex : '"|$',
next : "start",
merge : true
}
],
"qstring" : [
{
token : "constant.language.escape",
regex : escapedRe
}, {
token : "string",
regex : "[^'\\\\]+",
merge : true
}, {
token : "string",
regex : "\\\\$",
next : "qstring",
merge : true
}, {
token : "string",
regex : "'|$",
next : "start",
merge : true
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(JavaScriptHighlightRules, TextHighlightRules);
exports.JavaScriptHighlightRules = JavaScriptHighlightRules;
});
define('ace/mode/doc_comment_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var DocCommentHighlightRules = function() {
this.$rules = {
"start" : [ {
token : "comment.doc.tag",
regex : "@[\\w\\d_]+" // TODO: fix email addresses
}, {
token : "comment.doc",
merge : true,
regex : "\\s+"
}, {
token : "comment.doc",
merge : true,
regex : "TODO"
}, {
token : "comment.doc",
merge : true,
regex : "[^@\\*]+"
}, {
token : "comment.doc",
merge : true,
regex : "."
}]
};
};
oop.inherits(DocCommentHighlightRules, TextHighlightRules);
DocCommentHighlightRules.getStartRule = function(start) {
return {
token : "comment.doc", // doc comment
merge : true,
regex : "\\/\\*(?=\\*)",
next : start
};
};
DocCommentHighlightRules.getEndRule = function (start) {
return {
token : "comment.doc", // closing comment
merge : true,
regex : "\\*\\/",
next : start
};
};
exports.DocCommentHighlightRules = DocCommentHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = function () {
this.add("braces", "insertion", function (state, action, editor, session, text) {
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '{' + selected + '}',
selection: false
};
} else {
return {
text: '{}',
selection: [1, 1]
};
}
} else if (text == '}') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1});
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString());
var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '(' + selected + ')',
selection: false
};
} else {
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
// We're escaped.
if (leftChar == '\\') {
return null;
}
// Find what token we're inside.
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
// Try and be smart about when we auto insert.
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
// Ignore input and move right one if we're typing over the closing quote.
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
define('ace/mode/java_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/doc_comment_highlight_rules', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules;
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JavaHighlightRules = function() {
// taken from http://download.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
var keywords = lang.arrayToMap(
("abstract|continue|for|new|switch|" +
"assert|default|goto|package|synchronized|" +
"boolean|do|if|private|this|" +
"break|double|implements|protected|throw|" +
"byte|else|import|public|throws|" +
"case|enum|instanceof|return|transient|" +
"catch|extends|int|short|try|" +
"char|final|interface|static|void|" +
"class|finally|long|strictfp|volatile|" +
"const|float|native|super|while").split("|")
);
var buildinConstants = lang.arrayToMap(
("null|Infinity|NaN|undefined").split("|")
);
var langClasses = lang.arrayToMap(
("AbstractMethodError|AssertionError|ClassCircularityError|"+
"ClassFormatError|Deprecated|EnumConstantNotPresentException|"+
"ExceptionInInitializerError|IllegalAccessError|"+
"IllegalThreadStateException|InstantiationError|InternalError|"+
"NegativeArraySizeException|NoSuchFieldError|Override|Process|"+
"ProcessBuilder|SecurityManager|StringIndexOutOfBoundsException|"+
"SuppressWarnings|TypeNotPresentException|UnknownError|"+
"UnsatisfiedLinkError|UnsupportedClassVersionError|VerifyError|"+
"InstantiationException|IndexOutOfBoundsException|"+
"ArrayIndexOutOfBoundsException|CloneNotSupportedException|"+
"NoSuchFieldException|IllegalArgumentException|NumberFormatException|"+
"SecurityException|Void|InheritableThreadLocal|IllegalStateException|"+
"InterruptedException|NoSuchMethodException|IllegalAccessException|"+
"UnsupportedOperationException|Enum|StrictMath|Package|Compiler|"+
"Readable|Runtime|StringBuilder|Math|IncompatibleClassChangeError|"+
"NoSuchMethodError|ThreadLocal|RuntimePermission|ArithmeticException|"+
"NullPointerException|Long|Integer|Short|Byte|Double|Number|Float|"+
"Character|Boolean|StackTraceElement|Appendable|StringBuffer|"+
"Iterable|ThreadGroup|Runnable|Thread|IllegalMonitorStateException|"+
"StackOverflowError|OutOfMemoryError|VirtualMachineError|"+
"ArrayStoreException|ClassCastException|LinkageError|"+
"NoClassDefFoundError|ClassNotFoundException|RuntimeException|"+
"Exception|ThreadDeath|Error|Throwable|System|ClassLoader|"+
"Cloneable|Class|CharSequence|Comparable|String|Object").split("|")
);
var importClasses = lang.arrayToMap(
("").split("|")
);
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "comment",
regex : "\\/\\/.*$"
},
DocCommentHighlightRules.getStartRule("doc-start"),
{
token : "comment", // multi line comment
merge : true,
regex : "\\/\\*",
next : "comment"
}, {
token : "string.regexp",
regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)"
}, {
token : "string", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
}, {
token : "string", // single line
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+\\b"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "constant.language.boolean",
regex : "(?:true|false)\\b"
}, {
token : function(value) {
if (value == "this")
return "variable.language";
else if (keywords.hasOwnProperty(value))
return "keyword";
else if (langClasses.hasOwnProperty(value))
return "support.function";
else if (importClasses.hasOwnProperty(value))
return "support.function";
else if (buildinConstants.hasOwnProperty(value))
return "constant.language";
else
return "identifier";
},
// TODO: Unicode escape sequences
// TODO: Unicode identifiers
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)"
}, {
token : "lparen",
regex : "[[({]"
}, {
token : "rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"comment" : [
{
token : "comment", // closing comment
regex : ".*?\\*\\/",
next : "start"
}, {
token : "comment", // comment spanning whole line
merge : true,
regex : ".+"
}
]
};
this.embedRules(DocCommentHighlightRules, "doc-",
[ DocCommentHighlightRules.getEndRule("start") ]);
};
oop.inherits(JavaHighlightRules, TextHighlightRules);
exports.JavaHighlightRules = JavaHighlightRules;
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Satoshi Murakami <murky.satyr AT gmail DOT com>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/coffee', ['require', 'exports', 'module' , 'ace/tokenizer', 'ace/mode/coffee_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/folding/pythonic', 'ace/range', 'ace/mode/text', 'ace/worker/worker_client', 'ace/lib/oop'], function(require, exports, module) {
var Tokenizer = require("../tokenizer").Tokenizer;
var Rules = require("./coffee_highlight_rules").CoffeeHighlightRules;
var Outdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var PythonFoldMode = require("./folding/pythonic").FoldMode;
var Range = require("../range").Range;
var TextMode = require("./text").Mode;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var oop = require("../lib/oop");
function Mode() {
this.$tokenizer = new Tokenizer(new Rules().getRules());
this.$outdent = new Outdent();
this.foldingRules = new PythonFoldMode("=|=>|->|\\s*class [^#]*");
}
oop.inherits(Mode, TextMode);
(function() {
var indenter = /(?:[({[=:]|[-=]>|\b(?:else|switch|try|catch(?:\s*[$A-Za-z_\x7f-\uffff][$\w\x7f-\uffff]*)?|finally))\s*$/;
var commentLine = /^(\s*)#/;
var hereComment = /^\s*###(?!#)/;
var indentation = /^\s*/;
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokens = this.$tokenizer.getLineTokens(line, state).tokens;
if (!(tokens.length && tokens[tokens.length - 1].type === 'comment') &&
state === 'start' && indenter.test(line))
indent += tab;
return indent;
};
this.toggleCommentLines = function(state, doc, startRow, endRow){
console.log("toggle");
var range = new Range(0, 0, 0, 0);
for (var i = startRow; i <= endRow; ++i) {
var line = doc.getLine(i);
if (hereComment.test(line))
continue;
if (commentLine.test(line))
line = line.replace(commentLine, '$1');
else
line = line.replace(indentation, '$&#');
range.end.row = range.start.row = i;
range.end.column = line.length + 1;
doc.replace(range, line);
}
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "worker-coffee.js", "ace/mode/coffee_worker", "Worker");
worker.attachToDocument(session.getDocument());
worker.on("error", function(e) {
session.setAnnotations([e.data]);
});
worker.on("ok", function(e) {
session.clearAnnotations();
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/coffee_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/lang', 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var lang = require("../lib/lang");
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
oop.inherits(CoffeeHighlightRules, TextHighlightRules);
function CoffeeHighlightRules() {
var identifier = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*";
var stringfill = {
token : "string",
merge : true,
regex : ".+"
};
var keywords = lang.arrayToMap((
"this|throw|then|try|typeof|super|switch|return|break|by)|continue|" +
"catch|class|in|instanceof|is|isnt|if|else|extends|for|forown|" +
"finally|function|while|when|new|no|not|delete|debugger|do|loop|of|off|" +
"or|on|unless|until|and|yes").split("|")
);
var langConstant = lang.arrayToMap((
"true|false|null|undefined").split("|")
);
var illegal = lang.arrayToMap((
"case|const|default|function|var|void|with|enum|export|implements|" +
"interface|let|package|private|protected|public|static|yield|" +
"__hasProp|extends|slice|bind|indexOf").split("|")
);
var supportClass = lang.arrayToMap((
"Array|Boolean|Date|Function|Number|Object|RegExp|ReferenceError|" +
"RangeError|String|SyntaxError|Error|EvalError|TypeError|URIError").split("|")
);
var supportFunction = lang.arrayToMap((
"Math|JSON|isNaN|isFinite|parseInt|parseFloat|encodeURI|" +
"encodeURIComponent|decodeURI|decodeURIComponent|RangeError|String|" +
"SyntaxError|Error|EvalError|TypeError|URIError").split("|")
);
this.$rules = {
start : [
{
token : "identifier",
regex : "(?:(?:\\.|::)\\s*)" + identifier
}, {
token : "variable",
regex : "@(?:" + identifier + ")?"
}, {
token: function(value) {
if (keywords.hasOwnProperty(value))
return "keyword";
else if (langConstant.hasOwnProperty(value))
return "constant.language";
else if (illegal.hasOwnProperty(value))
return "invalid.illegal";
else if (supportClass.hasOwnProperty(value))
return "language.support.class";
else if (supportFunction.hasOwnProperty(value))
return "language.support.function";
else
return "identifier";
},
regex : identifier
}, {
token : "constant.numeric",
regex : "(?:0x[\\da-fA-F]+|(?:\\d+(?:\\.\\d+)?|\\.\\d+)(?:[eE][+-]?\\d+)?)"
}, {
token : "string",
merge : true,
regex : "'''",
next : "qdoc"
}, {
token : "string",
merge : true,
regex : '"""',
next : "qqdoc"
}, {
token : "string",
merge : true,
regex : "'",
next : "qstring"
}, {
token : "string",
merge : true,
regex : '"',
next : "qqstring"
}, {
token : "string",
merge : true,
regex : "`",
next : "js"
}, {
token : "string.regex",
merge : true,
regex : "///",
next : "heregex"
}, {
token : "string.regex",
regex : "/(?!\\s)[^[/\\n\\\\]*(?: (?:\\\\.|\\[[^\\]\\n\\\\]*(?:\\\\.[^\\]\\n\\\\]*)*\\])[^[/\\n\\\\]*)*/[imgy]{0,4}(?!\\w)"
}, {
token : "comment",
merge : true,
regex : "###(?!#)",
next : "comment"
}, {
token : "comment",
regex : "#.*"
}, {
token : "punctuation.operator",
regex : "\\?|\\:|\\,|\\."
}, {
token : "keyword.operator",
regex : "(?:[\\-=]>|[-+*/%<>&|^!?=]=|>>>=?|\\-\\-|\\+\\+|::|&&=|\\|\\|=|<<=|>>=|\\?\\.|\\.{2,3}|\\!)"
}, {
token : "paren.lparen",
regex : "[({[]"
}, {
token : "paren.rparen",
regex : "[\\]})]"
}, {
token : "text",
regex : "\\s+"
}],
qdoc : [{
token : "string",
regex : ".*?'''",
next : "start"
}, stringfill],
qqdoc : [{
token : "string",
regex : '.*?"""',
next : "start"
}, stringfill],
qstring : [{
token : "string",
regex : "[^\\\\']*(?:\\\\.[^\\\\']*)*'",
merge : true,
next : "start"
}, stringfill],
qqstring : [{
token : "string",
regex : '[^\\\\"]*(?:\\\\.[^\\\\"]*)*"',
merge : true,
next : "start"
}, stringfill],
js : [{
token : "string",
merge : true,
regex : "[^\\\\`]*(?:\\\\.[^\\\\`]*)*`",
next : "start"
}, stringfill],
heregex : [{
token : "string.regex",
regex : '.*?///[imgy]{0,4}',
next : "start"
}, {
token : "comment.regex",
regex : "\\s+(?:#.*)?"
}, {
token : "string.regex",
merge : true,
regex : "\\S+"
}],
comment : [{
token : "comment",
regex : '.*?###',
next : "start"
}, {
token : "comment",
merge : true,
regex : ".+"
}]
};
}
exports.CoffeeHighlightRules = CoffeeHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/folding/pythonic', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function(markers) {
this.foldingStartMarker = new RegExp("(?:([\\[{])|(" + markers + "))(?:\\s*)(?:#.*)?$");
};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
if (match[1])
return this.openingBracketBlock(session, match[1], row, match.index);
if (match[2])
return this.indentationBlock(session, row, match.index + match[2].length);
return this.indentationBlock(session, row);
}
}
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Colin Gourlay <colin DOT j DOT gourlay AT gmail DOT com>
* Lee Gao
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/lua', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/lua_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules;
var Mode = function() {
this.$tokenizer = new Tokenizer(new LuaHighlightRules().getRules());
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
var tokens = tokenizedLine.tokens;
var chunks = ["function", "then", "do", "repeat"];
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
if (match) {
indent += tab;
} else {
for (var i in tokens){
var token = tokens[i];
if (token.type != "keyword") continue;
var chunk_i = chunks.indexOf(token.value);
if (chunk_i != -1){
indent += tab;
break;
}
}
}
}
return indent;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/lua_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var lang = require("../lib/lang");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var LuaHighlightRules = function() {
var keywords = lang.arrayToMap(
("break|do|else|elseif|end|for|function|if|in|local|repeat|"+
"return|then|until|while|or|and|not").split("|")
);
var builtinConstants = lang.arrayToMap(
("true|false|nil|_G|_VERSION").split("|")
);
var builtinFunctions = lang.arrayToMap(
("string|xpcall|package|tostring|print|os|unpack|require|"+
"getfenv|setmetatable|next|assert|tonumber|io|rawequal|"+
"collectgarbage|getmetatable|module|rawset|math|debug|"+
"pcall|table|newproxy|type|coroutine|_G|select|gcinfo|"+
"pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|"+
"load|error|loadfile|"+
"sub|upper|len|gfind|rep|find|match|char|dump|gmatch|"+
"reverse|byte|format|gsub|lower|preload|loadlib|loaded|"+
"loaders|cpath|config|path|seeall|exit|setlocale|date|"+
"getenv|difftime|remove|time|clock|tmpname|rename|execute|"+
"lines|write|close|flush|open|output|type|read|stderr|"+
"stdin|input|stdout|popen|tmpfile|log|max|acos|huge|"+
"ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|"+
"frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|"+
"atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|"+
"gethook|setmetatable|setlocal|traceback|setfenv|getinfo|"+
"setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|"+
"foreachi|maxn|foreach|concat|sort|remove|resume|yield|"+
"status|wrap|create|running").split("|")
);
var stdLibaries = lang.arrayToMap(
("string|package|os|io|math|debug|table|coroutine").split("|")
);
var metatableMethods = lang.arrayToMap(
("__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|"+
"__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber").split("|")
);
var futureReserved = lang.arrayToMap(
("").split("|")
);
var deprecatedIn5152 = lang.arrayToMap(
("setn|foreach|foreachi|gcinfo|log10|maxn").split("|")
);
var strPre = "";
var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
var integer = "(?:" + decimalInteger + "|" + hexInteger + ")";
var fraction = "(?:\\.\\d+)";
var intPart = "(?:\\d+)";
var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
var floatNumber = "(?:" + pointFloat + ")";
var comment_stack = [];
this.$rules = {
"start" :
// bracketed comments
[{
token : "comment", // --[[ comment
regex : strPre + '\\-\\-\\[\\[.*\\]\\]'
}, {
token : "comment", // --[=[ comment
regex : strPre + '\\-\\-\\[\\=\\[.*\\]\\=\\]'
}, {
token : "comment", // --[==[ comment
regex : strPre + '\\-\\-\\[\\={2}\\[.*\\]\\={2}\\]'
}, {
token : "comment", // --[===[ comment
regex : strPre + '\\-\\-\\[\\={3}\\[.*\\]\\={3}\\]'
}, {
token : "comment", // --[====[ comment
regex : strPre + '\\-\\-\\[\\={4}\\[.*\\]\\={4}\\]'
}, {
token : "comment", // --[====+[ comment
regex : strPre + '\\-\\-\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]'
},
// multiline bracketed comments
{
token : "comment", // --[[ comment
regex : strPre + '\\-\\-\\[\\[.*$',
merge : true,
next : "qcomment"
}, {
token : "comment", // --[=[ comment
regex : strPre + '\\-\\-\\[\\=\\[.*$',
merge : true,
next : "qcomment1"
}, {
token : "comment", // --[==[ comment
regex : strPre + '\\-\\-\\[\\={2}\\[.*$',
merge : true,
next : "qcomment2"
}, {
token : "comment", // --[===[ comment
regex : strPre + '\\-\\-\\[\\={3}\\[.*$',
merge : true,
next : "qcomment3"
}, {
token : "comment", // --[====[ comment
regex : strPre + '\\-\\-\\[\\={4}\\[.*$',
merge : true,
next : "qcomment4"
}, {
token : function(value){ // --[====+[ comment
// WARNING: EXTREMELY SLOW, but this is the only way to circumvent the
// limits imposed by the current automaton.
// I've never personally seen any practical code where 5 or more '='s are
// used for string or commenting, so this will rarely be invoked.
var pattern = /\-\-\[(\=+)\[/, match;
// you can never be too paranoid ;)
if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined)
comment_stack.push(match.length);
return "comment";
},
regex : strPre + '\\-\\-\\[\\={5}\\=*\\[.*$',
merge : true,
next : "qcomment5"
},
// single line comments
{
token : "comment",
regex : "\\-\\-.*$"
},
// bracketed strings
{
token : "string", // [[ string
regex : strPre + '\\[\\[.*\\]\\]'
}, {
token : "string", // [=[ string
regex : strPre + '\\[\\=\\[.*\\]\\=\\]'
}, {
token : "string", // [==[ string
regex : strPre + '\\[\\={2}\\[.*\\]\\={2}\\]'
}, {
token : "string", // [===[ string
regex : strPre + '\\[\\={3}\\[.*\\]\\={3}\\]'
}, {
token : "string", // [====[ string
regex : strPre + '\\[\\={4}\\[.*\\]\\={4}\\]'
}, {
token : "string", // [====+[ string
regex : strPre + '\\[\\={5}\\=*\\[.*\\]\\={5}\\=*\\]'
},
// multiline bracketed strings
{
token : "string", // [[ string
regex : strPre + '\\[\\[.*$',
merge : true,
next : "qstring"
}, {
token : "string", // [=[ string
regex : strPre + '\\[\\=\\[.*$',
merge : true,
next : "qstring1"
}, {
token : "string", // [==[ string
regex : strPre + '\\[\\={2}\\[.*$',
merge : true,
next : "qstring2"
}, {
token : "string", // [===[ string
regex : strPre + '\\[\\={3}\\[.*$',
merge : true,
next : "qstring3"
}, {
token : "string", // [====[ string
regex : strPre + '\\[\\={4}\\[.*$',
merge : true,
next : "qstring4"
}, {
token : function(value){ // --[====+[ string
// WARNING: EXTREMELY SLOW, see above.
var pattern = /\[(\=+)\[/, match;
if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined)
comment_stack.push(match.length);
return "string";
},
regex : strPre + '\\[\\={5}\\=*\\[.*$',
merge : true,
next : "qstring5"
},
{
token : "string", // " string
regex : strPre + '"(?:[^\\\\]|\\\\.)*?"'
}, {
token : "string", // ' string
regex : strPre + "'(?:[^\\\\]|\\\\.)*?'"
}, {
token : "constant.numeric", // float
regex : floatNumber
}, {
token : "constant.numeric", // integer
regex : integer + "\\b"
}, {
token : function(value) {
if (keywords.hasOwnProperty(value))
return "keyword";
else if (builtinConstants.hasOwnProperty(value))
return "constant.language";
else if (futureReserved.hasOwnProperty(value))
return "invalid.illegal";
else if (stdLibaries.hasOwnProperty(value))
return "constant.library";
else if (deprecatedIn5152.hasOwnProperty(value))
return "invalid.deprecated";
else if (builtinFunctions.hasOwnProperty(value))
return "support.function";
else if (metatableMethods.hasOwnProperty(value))
return "support.function";
else
return "identifier";
},
regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
}, {
token : "keyword.operator",
regex : "\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\."
}, {
token : "paren.lparen",
regex : "[\\[\\(\\{]"
}, {
token : "paren.rparen",
regex : "[\\]\\)\\}]"
}, {
token : "text",
regex : "\\s+"
} ],
"qcomment": [ {
token : "comment",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\]",
next : "start"
}, {
token : "comment",
merge : true,
regex : '.+'
} ],
"qcomment1": [ {
token : "comment",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\=\\]",
next : "start"
}, {
token : "comment",
merge : true,
regex : '.+'
} ],
"qcomment2": [ {
token : "comment",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]",
next : "start"
}, {
token : "comment",
merge : true,
regex : '.+'
} ],
"qcomment3": [ {
token : "comment",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]",
next : "start"
}, {
token : "comment",
merge : true,
regex : '.+'
} ],
"qcomment4": [ {
token : "comment",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]",
next : "start"
}, {
token : "comment",
merge : true,
regex : '.+'
} ],
"qcomment5": [ {
token : function(value){
// very hackish, mutates the qcomment5 field on the fly.
var pattern = /\](\=+)\]/, rule = this.rules.qcomment5[0], match;
rule.next = "start";
if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined){
var found = match.length, expected;
if ((expected = comment_stack.pop()) != found){
comment_stack.push(expected);
rule.next = "qcomment5";
}
}
return "comment";
},
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]",
next : "start"
}, {
token : "comment",
merge : true,
regex : '.+'
} ],
"qstring": [ {
token : "string",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\]",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ],
"qstring1": [ {
token : "string",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\=\\]",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ],
"qstring2": [ {
token : "string",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={2}\\]",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ],
"qstring3": [ {
token : "string",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={3}\\]",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ],
"qstring4": [ {
token : "string",
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={4}\\]",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ],
"qstring5": [ {
token : function(value){
// very hackish, mutates the qstring5 field on the fly.
var pattern = /\](\=+)\]/, rule = this.rules.qstring5[0], match;
rule.next = "start";
if ((match = pattern.exec(value)) != null && (match = match[1]) != undefined){
var found = match.length, expected;
if ((expected = comment_stack.pop()) != found){
comment_stack.push(expected);
rule.next = "qstring5";
}
}
return "string";
},
regex : "(?:[^\\\\]|\\\\.)*?\\]\\={5}\\=*\\]",
next : "start"
}, {
token : "string",
merge : true,
regex : '.+'
} ]
};
}
oop.inherits(LuaHighlightRules, TextHighlightRules);
exports.LuaHighlightRules = LuaHighlightRules;
});
|
JavaScript
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define('ace/mode/json', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/json_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/mode/behaviour/cstyle', 'ace/mode/folding/cstyle', 'ace/worker/worker_client'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextMode = require("./text").Mode;
var Tokenizer = require("../tokenizer").Tokenizer;
var HighlightRules = require("./json_highlight_rules").JsonHighlightRules;
var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour;
var CStyleFoldMode = require("./folding/cstyle").FoldMode;
var WorkerClient = require("../worker/worker_client").WorkerClient;
var Mode = function() {
this.$tokenizer = new Tokenizer(new HighlightRules().getRules());
this.$outdent = new MatchingBraceOutdent();
this.$behaviour = new CstyleBehaviour();
this.foldingRules = new CStyleFoldMode();
};
oop.inherits(Mode, TextMode);
(function() {
this.getNextLineIndent = function(state, line, tab) {
var indent = this.$getIndent(line);
if (state == "start") {
var match = line.match(/^.*[\{\(\[]\s*$/);
if (match) {
indent += tab;
}
}
return indent;
};
this.checkOutdent = function(state, line, input) {
return this.$outdent.checkOutdent(line, input);
};
this.autoOutdent = function(state, doc, row) {
this.$outdent.autoOutdent(doc, row);
};
this.createWorker = function(session) {
var worker = new WorkerClient(["ace"], "worker-json.js", "ace/mode/json_worker", "JsonWorker");
worker.attachToDocument(session.getDocument());
worker.on("error", function(e) {
session.setAnnotations([e.data]);
});
worker.on("ok", function() {
session.clearAnnotations();
});
return worker;
};
}).call(Mode.prototype);
exports.Mode = Mode;
});
define('ace/mode/json_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var JsonHighlightRules = function() {
// regexp must not have capturing parentheses. Use (?:) instead.
// regexps are ordered -> the first match is used
this.$rules = {
"start" : [
{
token : "variable", // single line
regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]\\s*(?=:)'
}, {
token : "string", // single line
regex : '"',
next : "string"
}, {
token : "constant.numeric", // hex
regex : "0[xX][0-9a-fA-F]+\\b"
}, {
token : "constant.numeric", // float
regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b"
}, {
token : "constant.language.boolean",
regex : "(?:true|false)\\b"
}, {
token : "invalid.illegal", // single quoted strings are not allowed
regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
}, {
token : "invalid.illegal", // comments are not allowed
regex : "\\/\\/.*$"
}, {
token : "paren.lparen",
regex : "[[({]"
}, {
token : "paren.rparen",
regex : "[\\])}]"
}, {
token : "text",
regex : "\\s+"
}
],
"string" : [
{
token : "constant.language.escape",
regex : /\\(?:x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4})/
}, {
token : "string",
regex : '[^"\\\\]+',
merge : true
}, {
token : "string",
regex : '"',
next : "start",
merge : true
}, {
token : "string",
regex : "",
next : "start",
merge : true
}
]
};
};
oop.inherits(JsonHighlightRules, TextHighlightRules);
exports.JsonHighlightRules = JsonHighlightRules;
});
define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../range").Range;
var MatchingBraceOutdent = function() {};
(function() {
this.checkOutdent = function(line, input) {
if (! /^\s+$/.test(line))
return false;
return /^\s*\}/.test(input);
};
this.autoOutdent = function(doc, row) {
var line = doc.getLine(row);
var match = line.match(/^(\s*\})/);
if (!match) return 0;
var column = match[1].length;
var openBracePos = doc.findMatchingBracket({row: row, column: column});
if (!openBracePos || openBracePos.row == row) return 0;
var indent = this.$getIndent(doc.getLine(openBracePos.row));
doc.replace(new Range(row, 0, row, column-1), indent);
};
this.$getIndent = function(line) {
var match = line.match(/^(\s+)/);
if (match) {
return match[1];
}
return "";
};
}).call(MatchingBraceOutdent.prototype);
exports.MatchingBraceOutdent = MatchingBraceOutdent;
});
define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Behaviour = require("../behaviour").Behaviour;
var CstyleBehaviour = function () {
this.add("braces", "insertion", function (state, action, editor, session, text) {
if (text == '{') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '{' + selected + '}',
selection: false
};
} else {
return {
text: '{}',
selection: [1, 1]
};
}
} else if (text == '}') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
} else if (text == "\n") {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == '}') {
var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column + 1});
if (!openBracePos)
return null;
var indent = this.getNextLineIndent(state, line.substring(0, line.length - 1), session.getTabString());
var next_indent = this.$getIndent(session.doc.getLine(openBracePos.row));
return {
text: '\n' + indent + '\n' + next_indent,
selection: [1, indent.length, 1, indent.length]
};
}
}
});
this.add("braces", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '{') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.end.column, range.end.column + 1);
if (rightChar == '}') {
range.end.column++;
return range;
}
}
});
this.add("parens", "insertion", function (state, action, editor, session, text) {
if (text == '(') {
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: '(' + selected + ')',
selection: false
};
} else {
return {
text: '()',
selection: [1, 1]
};
}
} else if (text == ')') {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == ')') {
var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
if (matching !== null) {
return {
text: '',
selection: [1, 1]
};
}
}
}
});
this.add("parens", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && selected == '(') {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == ')') {
range.end.column++;
return range;
}
}
});
this.add("string_dquotes", "insertion", function (state, action, editor, session, text) {
if (text == '"' || text == "'") {
var quote = text;
var selection = editor.getSelectionRange();
var selected = session.doc.getTextRange(selection);
if (selected !== "") {
return {
text: quote + selected + quote,
selection: false
};
} else {
var cursor = editor.getCursorPosition();
var line = session.doc.getLine(cursor.row);
var leftChar = line.substring(cursor.column-1, cursor.column);
// We're escaped.
if (leftChar == '\\') {
return null;
}
// Find what token we're inside.
var tokens = session.getTokens(selection.start.row);
var col = 0, token;
var quotepos = -1; // Track whether we're inside an open quote.
for (var x = 0; x < tokens.length; x++) {
token = tokens[x];
if (token.type == "string") {
quotepos = -1;
} else if (quotepos < 0) {
quotepos = token.value.indexOf(quote);
}
if ((token.value.length + col) > selection.start.column) {
break;
}
col += tokens[x].value.length;
}
// Try and be smart about when we auto insert.
if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
return {
text: quote + quote,
selection: [1,1]
};
} else if (token && token.type === "string") {
// Ignore input and move right one if we're typing over the closing quote.
var rightChar = line.substring(cursor.column, cursor.column + 1);
if (rightChar == quote) {
return {
text: '',
selection: [1, 1]
};
}
}
}
}
});
this.add("string_dquotes", "deletion", function (state, action, editor, session, range) {
var selected = session.doc.getTextRange(range);
if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
var line = session.doc.getLine(range.start.row);
var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
if (rightChar == '"') {
range.end.column++;
return range;
}
}
});
};
oop.inherits(CstyleBehaviour, Behaviour);
exports.CstyleBehaviour = CstyleBehaviour;
});
define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
var oop = require("../../lib/oop");
var Range = require("../../range").Range;
var BaseFoldMode = require("./fold_mode").FoldMode;
var FoldMode = exports.FoldMode = function() {};
oop.inherits(FoldMode, BaseFoldMode);
(function() {
this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
this.getFoldWidgetRange = function(session, foldStyle, row) {
var line = session.getLine(row);
var match = line.match(this.foldingStartMarker);
if (match) {
var i = match.index;
if (match[1])
return this.openingBracketBlock(session, match[1], row, i);
var range = session.getCommentFoldRange(row, i + match[0].length);
range.end.column -= 2;
return range;
}
if (foldStyle !== "markbeginend")
return;
var match = line.match(this.foldingStopMarker);
if (match) {
var i = match.index + match[0].length;
if (match[2]) {
var range = session.getCommentFoldRange(row, i);
range.end.column -= 2;
return range;
}
var end = {row: row, column: i};
var start = session.$findOpeningBracket(match[1], end);
if (!start)
return;
start.column++;
end.column--;
return Range.fromPoints(start, end);
}
};
}).call(FoldMode.prototype);
});
define('ace/mode/folding/fold_mode', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
var Range = require("../../range").Range;
var FoldMode = exports.FoldMode = function() {};
(function() {
this.foldingStartMarker = null;
this.foldingStopMarker = null;
// must return "" if there's no fold, to enable caching
this.getFoldWidget = function(session, foldStyle, row) {
var line = session.getLine(row);
if (this.foldingStartMarker.test(line))
return "start";
if (foldStyle == "markbeginend"
&& this.foldingStopMarker
&& this.foldingStopMarker.test(line))
return "end";
return "";
};
this.getFoldWidgetRange = function(session, foldStyle, row) {
return null;
};
this.indentationBlock = function(session, row, column) {
var re = /^\s*/;
var startRow = row;
var endRow = row;
var line = session.getLine(row);
var startColumn = column || line.length;
var startLevel = line.match(re)[0].length;
var maxRow = session.getLength()
while (++row < maxRow) {
line = session.getLine(row);
var level = line.match(re)[0].length;
if (level == line.length)
continue;
if (level <= startLevel)
break;
endRow = row;
}
if (endRow > startRow) {
var endColumn = session.getLine(endRow).length;
return new Range(startRow, startColumn, endRow, endColumn);
}
};
this.openingBracketBlock = function(session, bracket, row, column, typeRe, allowBlankLine) {
var start = {row: row, column: column + 1};
var end = session.$findClosingBracket(bracket, start, typeRe, allowBlankLine);
if (!end)
return;
var fw = session.foldWidgets[end.row];
if (fw == null)
fw = this.getFoldWidget(session, end.row);
if (fw == "start") {
end.row --;
end.column = session.getLine(end.row).length;
}
return Range.fromPoints(start, end);
};
}).call(FoldMode.prototype);
});
|
JavaScript
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.