index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. // TODO - Add initial page loading and handlers
  2. (function($,History,console){
  3. var State = History.getState(),
  4. Old = {},
  5. Key = null,
  6. flags = [],
  7. templates = [],
  8. flag = window.flag = function(name,value){
  9. if(exists(value)){
  10. flags[name] = value;
  11. }else{
  12. return exists(flags[name])?flags[name]:false;
  13. }
  14. },
  15. settings = {},
  16. exists = function(v){
  17. return typeof v != 'undefined';
  18. },
  19. get = window.get = function(s){
  20. return settings[s];
  21. },
  22. set = window.set = function(s,v){
  23. settings[s] = v;
  24. return v;
  25. },
  26. setKey = window.setKey = function(key){
  27. if(key !== null){
  28. console.log('Key change to '+key);
  29. Key = key;
  30. var d = new Date();
  31. d.setTime(d.getTime()+get('expire'));
  32. $.cookie('key',key,{
  33. expires: d
  34. });
  35. }else{
  36. console.log('Key deleted');
  37. Key = null;
  38. $.removeCookie('key');
  39. }
  40. },
  41. getKey = window.getKey = function(){
  42. return Key;
  43. },
  44. template = window.template = function(name,template){
  45. var d = +new Date,
  46. id = (function(name){
  47. for(var i in templates){
  48. if(templates[i].name == name){
  49. return i;
  50. }
  51. }
  52. return false;
  53. })(name);
  54. if(exists(template)){
  55. if(template === null){
  56. if(id!==false){
  57. templates.splice(id,1);
  58. }
  59. $.localStorage('templates',templates);
  60. console.log('Dropping template for: '+name);
  61. return '';
  62. }else{
  63. var o = {
  64. name: name,
  65. template: template,
  66. date: get('expire')+d
  67. }
  68. if(id===false){
  69. console.log('Storing new template for: '+name);
  70. templates.push(o);
  71. }else{
  72. console.log('Replacing old template for: '+name);
  73. templates[id] = o;
  74. }
  75. $.localStorage('templates',templates);
  76. }
  77. }else if(id!==false){
  78. console.log('Using cached template for: '+name);
  79. var template = templates[id].template;
  80. if(templates[id].date < d){
  81. delete templates[name];
  82. $.localStorage('templates',templates);
  83. }
  84. return template;
  85. }else{
  86. console.log('No cached template stored for: '+name);
  87. return '';
  88. }
  89. },
  90. apiCall = window.apiCall = function(data,callback){
  91. console.log('apiCall('+data.type+'-'+data.id+')');
  92. if(!flag('error')){
  93. loading(true);
  94. data.get = 'api';
  95. data.back = State.data.back;
  96. data.timestamp = +new Date;
  97. if(''!=template(data.type+'-'+data.id)){
  98. data.template = false;
  99. }
  100. $.get(location.href,data,function(d){
  101. if(exists(d['error'])){
  102. error(d);
  103. }else{
  104. d.state.title = d.state.title.capitalize();
  105. if(location.href.substr(location.href.lastIndexOf('/')+1) != d.state.url){
  106. console.log('Forced redirection to '+d.state.url);
  107. History.replaceState(d.state.data,d.state.title,d.state.url);
  108. getNewState();
  109. }
  110. document.title = d.state.title;
  111. }
  112. if(exists(callback)){
  113. console.log('Running apiCall callback');
  114. callback(d);
  115. }
  116. },'json');
  117. }
  118. },
  119. loadState = window.loadState = function(href,callback){
  120. console.log('loadState('+href+')');
  121. if(!flag('error')){
  122. loading(true);
  123. var data = {
  124. get:'state',
  125. timestamp: +new Date,
  126. back: location.href
  127. };
  128. ajax = $.ajax(href,{
  129. data: data,
  130. async: true,
  131. type: 'GET',
  132. success: function(d){
  133. if(exists(d['error'])){
  134. error(d);
  135. }else{
  136. d.state.title = d.state.title.capitalize();
  137. console.log('pushState: '+d.state.title+'['+href+']');
  138. History.pushState(d.state.data,d.state.title,href);
  139. getNewState();
  140. }
  141. if(exists(callback)){
  142. callback(d);
  143. }
  144. if(!exists(d['error'])){
  145. flag('handled',true);
  146. stateChange();
  147. flag('handled',false);
  148. }
  149. },
  150. error: function(x,t,e){
  151. error({
  152. error: '['+t+'] '+e
  153. });
  154. if(exists(callback)){
  155. callback({
  156. error: '['+t+'] '+e
  157. });
  158. }
  159. },
  160. dataType: 'json'
  161. });
  162. }
  163. },
  164. replaceState = window.replaceState = function(href,callback){
  165. console.log('apiState('+href+')');
  166. if(!flag('error')){
  167. loading(true);
  168. var data = {
  169. get:'state',
  170. timestamp: +new Date,
  171. back: State.data.back
  172. };
  173. $.ajax(href,{
  174. data: data,
  175. async: true,
  176. type: 'GET',
  177. success: function(d){
  178. if(exists(d['error'])){
  179. error(d);
  180. }else{
  181. d.state.title = d.state.title.capitalize();
  182. console.log('pushState: '+d.state.title+'['+href+']');
  183. History.replaceState(d.state.data,d.state.title,href);
  184. getNewState();
  185. }
  186. if(exists(callback)){
  187. callback(d);
  188. }
  189. console.log(d.state.title);
  190. if(!exists(d['error'])){
  191. flag('handled',true);
  192. stateChange();
  193. flag('handled',false);
  194. }
  195. },
  196. error: function(x,t,e){
  197. error({
  198. error: '['+t+'] '+e
  199. });
  200. if(exists(callback)){
  201. callback({
  202. error: '['+t+'] '+e
  203. });
  204. }
  205. },
  206. dataType: 'json'
  207. });
  208. }
  209. },
  210. error = function(e,callback){
  211. if(!flag('error')){
  212. flag('error',true);
  213. var msg = '['+State.url+']'+e.error;
  214. console.error(msg.trim()+"\n"+(exists(e.state)?JSON.stringify(e.state):''));
  215. alert(msg.trim(),'Error',callback);
  216. }
  217. },
  218. getNewState = function(){
  219. State = History.getState();
  220. console.log("State change: ["+State.title+"] "+JSON.stringify(State.data));
  221. if(!window.location.origin){
  222. window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
  223. }
  224. },
  225. stateChange = function(){
  226. getNewState();
  227. if(!equal(State.data,Old)){
  228. switch(State.data.type){
  229. case 'page':case 'user':case 'project':
  230. apiCall(State.data,function(d){
  231. if(!exists(d.error)){
  232. if(exists(d.context)){
  233. if(!exists(d.context.key)&&Key!==null){
  234. console.log('Context detected console.logout');
  235. setKey(null);
  236. }
  237. if(exists(d.template)){
  238. template(State.data.type+'-'+State.data.id,d.template);
  239. }else{
  240. d.template = template(State.data.type+'-'+State.data.id);
  241. }
  242. render.topbar(d.topbar.template,d.topbar.context);
  243. render.content(d.template,d.context);
  244. $(window).resize();
  245. loading(false);
  246. }else{
  247. console.error('No context given');
  248. back();
  249. }
  250. }else{
  251. error(d);
  252. back();
  253. }
  254. });
  255. break;
  256. case 'action':break;
  257. default:
  258. error({
  259. url: State.url,
  260. error: "Something went wrong!"
  261. });
  262. }
  263. Old = State.data;
  264. }else{
  265. console.log(State.data,Old);
  266. console.warn('Stopped double load of '+Old.type+'-'+Old.id);
  267. loading(false);
  268. }
  269. },
  270. equal = function(o1,o2){
  271. for(var i in o1){
  272. if(!exists(o2[i])||o2[i]!=o1[i]){
  273. return false;
  274. }
  275. }
  276. for(i in o2){
  277. if(!exists(o1[i])||o2[i]!=o1[i]){
  278. return false;
  279. }
  280. }
  281. return true;
  282. },
  283. render = window.render = {
  284. topbar: function(t,c){
  285. $('#topbar').html(Handlebars.compile(t)(c));
  286. render.links('#topbar');
  287. render.buttons('#topbar');
  288. render.menus('#topbar');
  289. if(State.url == location.origin+'/page-index'){
  290. $('#topbar').find('.topbar-history').hide();
  291. }
  292. $('#topbar').addClass('overflow-hide');
  293. $(window).resize();
  294. },
  295. content: function(t,c){
  296. $('#content').html(
  297. Handlebars.compile(t)(c)
  298. );
  299. render.links('#content');
  300. render.buttons('#content');
  301. render.accordions('#content');
  302. render.menus('#content');
  303. render.form('#content');
  304. $(window).resize();
  305. },
  306. accordions: function(selector){
  307. $(selector).find('.accordion').each(function(){
  308. var icons = {};
  309. if($(this).children('.icons').length == 1){
  310. icons = JSON.parse($(this).children('.icons').text());
  311. }
  312. $(this).children('.icons').remove();
  313. $(this).accordion({
  314. collapsible: true,
  315. icons: icons,
  316. active: false
  317. });
  318. });
  319. },
  320. buttons: function(selector){
  321. $(selector).find('.button').button();
  322. $(selector).find('input[type=submit]').button();
  323. $(selector).find('input[type=button]').button();
  324. $(selector).find('button').button();
  325. },
  326. menus: function(selector){
  327. $(selector).find('.menu').css({
  328. 'list-style':'none'
  329. }).menu({
  330. icons:{
  331. submenu: "ui-icon-circle-triangle-e"
  332. }
  333. }).removeClass('ui-corner-all').addClass('ui-corner-bottom').parent().click(function(e){
  334. e.stopPropagation();
  335. });
  336. },
  337. form: function(selector){
  338. $(selector).find('#form').width('320px').children();
  339. render.inputs(selector);
  340. },
  341. inputs: function(selector){
  342. $(selector).find('input[type=text],input[type=password]').each(function(){
  343. var input = $(this),
  344. height = input.height()>=17?17:input.height();
  345. input.siblings('.input-clear').remove();
  346. input.off('focus').off('blur').after(
  347. $('<div>').css({
  348. position: 'absolute',
  349. right: $(window).width() - (input.outerWidth() + input.position().left)+2,
  350. top: input.position().top+2,
  351. 'background-image': 'url(img/headers/icons/clear.png)',
  352. 'background-position': 'center',
  353. 'background-size': height+'px '+height+'px',
  354. 'background-repeat': 'no-repeat',
  355. width: input.height(),
  356. height: input.height(),
  357. cursor: 'pointer'
  358. }).hide().addClass('input-clear').mousedown(function(){
  359. input.val('');
  360. })
  361. );
  362. if(input.hasClass('fill-width')){
  363. input.css('width','calc(100% - '+(input.outerWidth()-input.width())+'px)');
  364. }
  365. input.focus(function(){
  366. input.next().show();
  367. }).blur(function(e){
  368. input.next().hide();
  369. });
  370. });
  371. },
  372. dialog: function(selector,title){
  373. $(selector).dialog({
  374. close: function(){
  375. flag('error',false);
  376. var fn = $(this).data('callback');
  377. if(exists(fn)){
  378. fn();
  379. }
  380. loading(false);
  381. },
  382. resizable: false,
  383. draggable: false,
  384. title: title,
  385. buttons: [
  386. {
  387. text: 'Ok',
  388. class: 'recommend-force',
  389. click: function(){
  390. $(this).dialog('close');
  391. }
  392. }
  393. ]
  394. });
  395. },
  396. links: function(selector){
  397. $(selector).find('a').each(function(){
  398. var href = this.href;
  399. if(href.indexOf('#')!=-1&&(href.indexOf(location.origin)!=-1||href.indexOf('#')==0)){
  400. href = href.substr(href.indexOf('#')+1);
  401. $(this).click(function(e){
  402. try{
  403. if(($(this).hasClass('topbar-home') || $(this).hasClass('topbar-back'))&&$(window).width()<767){
  404. $('#topbar').children('div.topbar-right,div.topbar-left').toggle();
  405. $('#topbar').toggleClass('overflow-hide');
  406. $(window).resize();
  407. }else if($(this).hasClass('topbar-history')){
  408. back();
  409. }else{
  410. loadState(href);
  411. }
  412. }catch(error){
  413. console.error(error);
  414. }
  415. e.preventDefault();
  416. return false;
  417. });
  418. }
  419. });
  420. }
  421. },
  422. back = window.back = function(){
  423. if(exists(State.data.back)){
  424. if(!History.back()){
  425. loadState(State.data.back);
  426. }
  427. }else if(State.data.type != 'page' || State.data.id != 'index'){
  428. loadState('page-index');
  429. }else{
  430. location.reload();
  431. }
  432. },
  433. alert = function(text,title,callback){
  434. $('#dialog').text(text).data('callback',callback);
  435. render.dialog('#dialog',title,callback);
  436. },
  437. loading = function(state){
  438. state = exists(state)?state:false;
  439. console.log('loading state '+state);
  440. if(!flag('error') && !state){
  441. $('#loading').hide();
  442. }else if(state){
  443. $('#loading').show();
  444. }
  445. };
  446. if(exists($.cookie('key'))){
  447. setKey($.cookie('key'));
  448. }else{
  449. setKey(null);
  450. }
  451. $(document).ready(function(){
  452. $.ajaxSetup({
  453. async: false,
  454. cache: false,
  455. timeout: 2000
  456. });
  457. $(document).ajaxError(function(event, request, settings) {
  458. error({error:'Request timed out'});
  459. });
  460. if(!exists($.support.touch)){
  461. $.support.touch = 'ontouchstart' in window || 'onmsgesturechange' in window;
  462. }
  463. $('#content').niceScroll({
  464. cursorwidth: 10,
  465. nativeparentscrolling: false,
  466. preservenativescrolling: false
  467. });
  468. $('#content,#topbar').click(function(){
  469. $('.menu').hide();
  470. });
  471. document.addEventListener('touchmove',function(e){
  472. e.preventDefault();
  473. });
  474. $(window).resize(function(){
  475. if($(window).width()>767){
  476. $('#topbar div.topbar-right, #topbar div.topbar-left').css({
  477. 'display': ''
  478. });
  479. }
  480. $('#content').height($('body').height()-$('#topbar').height());
  481. $('#content').getNiceScroll().resize();
  482. render.inputs('#content');
  483. render.inputs('#topbar');
  484. });
  485. $.get(location.href,{
  486. get: 'settings',
  487. timestamp: +new Date,
  488. back: false
  489. },function(d){
  490. if(!exists(d.error)){
  491. settings = d.settings;
  492. if(d.version != $.localStorage('version')){
  493. $.localStorage('version',d.version);
  494. $.localStorage('templates',null);
  495. templates = [];
  496. }else{
  497. templates = $.localStorage('templates');
  498. if(templates === null){
  499. templates = [];
  500. }
  501. }
  502. replaceState(location.href);
  503. }else{
  504. error(d.error);
  505. }
  506. },'json');
  507. $(window).on('statechange',function(){
  508. if(!flag('handled')){
  509. console.log('unhandled state change event');
  510. stateChange();
  511. }
  512. });
  513. var getState = History.getState;
  514. History.getState = function(flag){
  515. if(exists(flag)){
  516. return State;
  517. }else{
  518. return getState.call(History);
  519. }
  520. };
  521. });
  522. shortcut.add('f12',function(){
  523. if(!flag('firebug-lite')){
  524. $('head').append(
  525. $('<script>').attr({
  526. 'type': 'text/javascript',
  527. 'src': 'https://getfirebug.com/firebug-lite.js#startOpened',
  528. 'id': 'FirebugLite'
  529. })
  530. );
  531. $('<image>').attr('src','https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png');
  532. flag('firebug-lite',true);
  533. }
  534. });
  535. shortcut.add('Ctrl+f12',function(){
  536. if(!flag('manifesto')){
  537. if(window.applicationCache){
  538. if(window.applicationCache.status==window.applicationCache.UNCACHED){
  539. $('head').append(
  540. $('<script>').attr({
  541. 'type': 'text/javascript',
  542. 'src': 'http://manifesto.ericdelabar.com/manifesto.js?x="+(Math.random())'
  543. })
  544. );
  545. (function wait(){
  546. if($('#cacheStatus').length == 0){
  547. setTimeout(wait,10);
  548. }else{
  549. $('#cacheStatus').niceScroll();
  550. }
  551. })();
  552. }else{
  553. alert("Manifest file is valid.");
  554. }
  555. }else{
  556. alert("This browser does not support HTML5 Offline Application Cache.");
  557. }
  558. flag('manifesto',true);
  559. }
  560. });
  561. shortcut.add('Shift+f12',function(){
  562. templates = [];
  563. $.localStorage('templates',null);
  564. console.log('Templates cleared.');
  565. });
  566. $.fn.serializeObject = function(){
  567. var o = {},
  568. a = this.serializeArray();
  569. $.each(a,function(){
  570. if(o[this.name] !== undefined){
  571. if(!o[this.name].push){
  572. o[this.name] = [o[this.name]];
  573. }
  574. o[this.name].push(this.value || '');
  575. }else{
  576. o[this.name] = this.value || '';
  577. }
  578. });
  579. return o;
  580. };
  581. String.prototype.capitalize = function(lower) {
  582. return (lower?this.toLowerCase():this).replace(/(?:^|\s)\S/g, function(a){
  583. return a.toUpperCase();
  584. });
  585. };
  586. })(jQuery,History,console);