index.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. $(document).unbind('ready');
  297. $('#content').html(
  298. Handlebars.compile(t)(c)
  299. );
  300. render.links('#content');
  301. render.buttons('#content');
  302. render.accordions('#content');
  303. render.menus('#content');
  304. render.form('#content');
  305. $(window).resize();
  306. },
  307. accordions: function(selector){
  308. $(selector).find('.accordion').each(function(){
  309. var icons = {};
  310. if($(this).children('.icons').length == 1){
  311. icons = JSON.parse($(this).children('.icons').text());
  312. }
  313. $(this).children('.icons').remove();
  314. $(this).accordion({
  315. collapsible: true,
  316. icons: icons,
  317. active: false
  318. });
  319. });
  320. },
  321. buttons: function(selector){
  322. $(selector).find('.button').button();
  323. $(selector).find('input[type=submit]').button();
  324. $(selector).find('input[type=button]').button();
  325. $(selector).find('button').button();
  326. },
  327. menus: function(selector){
  328. $(selector).find('.menu').css({
  329. 'list-style':'none'
  330. }).menu({
  331. icons:{
  332. submenu: "ui-icon-circle-triangle-e"
  333. }
  334. }).removeClass('ui-corner-all').addClass('ui-corner-bottom').parent().click(function(e){
  335. e.stopPropagation();
  336. });
  337. },
  338. form: function(selector){
  339. $(selector).find('#form').width('320px').children();
  340. render.inputs(selector);
  341. },
  342. inputs: function(selector){
  343. $(selector).find('input[type=text],input[type=password]').each(function(){
  344. var input = $(this),
  345. height = input.height()>=17?17:input.height();
  346. input.siblings('.input-clear').remove();
  347. input.off('focus').off('blur').after(
  348. $('<div>').css({
  349. position: 'absolute',
  350. right: $(window).width() - (input.outerWidth() + input.position().left)+2,
  351. top: input.position().top+2,
  352. 'background-image': 'url(img/headers/icons/clear.png)',
  353. 'background-position': 'center',
  354. 'background-size': height+'px '+height+'px',
  355. 'background-repeat': 'no-repeat',
  356. width: input.height(),
  357. height: input.height(),
  358. cursor: 'pointer'
  359. }).hide().addClass('input-clear').mousedown(function(){
  360. input.val('');
  361. })
  362. );
  363. input.focus(function(){
  364. input.next().show();
  365. }).blur(function(e){
  366. input.next().hide();
  367. });
  368. });
  369. $(selector).find('input[type=text],input[type=password],textarea').each(function(){
  370. var input = $(this);
  371. if(input.hasClass('fill-width')){
  372. input.css('width','calc(100% - '+(input.outerWidth()-input.width())+'px)');
  373. }
  374. });
  375. },
  376. dialog: function(selector,title){
  377. $(selector).dialog({
  378. close: function(){
  379. flag('error',false);
  380. var fn = $(this).data('callback');
  381. if(exists(fn)){
  382. fn();
  383. }
  384. loading(false);
  385. },
  386. resizable: false,
  387. draggable: false,
  388. title: title,
  389. buttons: [
  390. {
  391. text: 'Ok',
  392. class: 'recommend-force',
  393. click: function(){
  394. $(this).dialog('close');
  395. }
  396. }
  397. ]
  398. });
  399. },
  400. links: function(selector){
  401. $(selector).find('a').each(function(){
  402. var href = this.href;
  403. if(href.indexOf('#')!=-1&&(href.indexOf(location.origin)!=-1||href.indexOf('#')==0)){
  404. href = href.substr(href.indexOf('#')+1);
  405. $(this).click(function(e){
  406. try{
  407. if(($(this).hasClass('topbar-home') || $(this).hasClass('topbar-back'))&&$(window).width()<767){
  408. $('#topbar').children('div.topbar-right,div.topbar-left').toggle();
  409. $('#topbar').toggleClass('overflow-hide');
  410. $(window).resize();
  411. }else if($(this).hasClass('topbar-history')){
  412. back();
  413. }else{
  414. loadState(href);
  415. }
  416. }catch(error){
  417. console.error(error);
  418. }
  419. e.preventDefault();
  420. return false;
  421. });
  422. }
  423. });
  424. }
  425. },
  426. back = window.back = function(){
  427. if(exists(State.data.back)){
  428. if(!History.back()){
  429. loadState(State.data.back);
  430. }
  431. }else if(State.data.type != 'page' || State.data.id != 'index'){
  432. loadState('page-index');
  433. }else{
  434. location.reload();
  435. }
  436. },
  437. alert = function(text,title,callback){
  438. $('#dialog').text(text).data('callback',callback);
  439. render.dialog('#dialog',title,callback);
  440. },
  441. loading = function(state){
  442. state = exists(state)?state:false;
  443. console.log('loading state '+state);
  444. if(!flag('error') && !state){
  445. $('#loading').hide();
  446. }else if(state){
  447. $('#loading').show();
  448. }
  449. };
  450. if(exists($.cookie('key'))){
  451. setKey($.cookie('key'));
  452. }else{
  453. setKey(null);
  454. }
  455. $(document).ready(function(){
  456. $.ajaxSetup({
  457. async: false,
  458. cache: false,
  459. timeout: 30000 // 30 seconds
  460. });
  461. $(document).ajaxError(function(event, request, settings) {
  462. error({error:'Request timed out'});
  463. });
  464. if(!exists($.support.touch)){
  465. $.support.touch = 'ontouchstart' in window || 'onmsgesturechange' in window;
  466. }
  467. $('#content').niceScroll({
  468. cursorwidth: 10,
  469. nativeparentscrolling: false,
  470. preservenativescrolling: false
  471. });
  472. $('#content,#topbar').click(function(){
  473. $('.menu').hide();
  474. });
  475. document.addEventListener('touchmove',function(e){
  476. e.preventDefault();
  477. });
  478. $(window).resize(function(){
  479. if($(window).width()>767){
  480. $('#topbar div.topbar-right, #topbar div.topbar-left').css({
  481. 'display': ''
  482. });
  483. }
  484. $('#content').height($('body').height()-$('#topbar').height());
  485. $('#content').getNiceScroll().resize();
  486. render.inputs('#content');
  487. render.inputs('#topbar');
  488. });
  489. $.get(location.href,{
  490. get: 'settings',
  491. timestamp: +new Date,
  492. back: false
  493. },function(d){
  494. if(!exists(d.error)){
  495. settings = d.settings;
  496. if(d.version != $.localStorage('version')){
  497. $.localStorage('version',d.version);
  498. $.localStorage('templates',null);
  499. templates = [];
  500. }else{
  501. templates = $.localStorage('templates');
  502. if(templates === null){
  503. templates = [];
  504. }
  505. }
  506. replaceState(location.href);
  507. }else{
  508. error(d.error);
  509. }
  510. },'json');
  511. $(window).on('statechange',function(){
  512. if(!flag('handled')){
  513. console.log('unhandled state change event');
  514. stateChange();
  515. }
  516. });
  517. var getState = History.getState;
  518. History.getState = function(flag){
  519. if(exists(flag)){
  520. return State;
  521. }else{
  522. return getState.call(History);
  523. }
  524. };
  525. });
  526. shortcut.add('f12',function(){
  527. if(!flag('firebug-lite')){
  528. $('head').append(
  529. $('<script>').attr({
  530. 'type': 'text/javascript',
  531. 'src': 'https://getfirebug.com/firebug-lite.js#startOpened',
  532. 'id': 'FirebugLite'
  533. })
  534. );
  535. $('<image>').attr('src','https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png');
  536. flag('firebug-lite',true);
  537. }
  538. });
  539. shortcut.add('Ctrl+f12',function(){
  540. if(!flag('manifesto')){
  541. if(window.applicationCache){
  542. if(window.applicationCache.status==window.applicationCache.UNCACHED){
  543. $('head').append(
  544. $('<script>').attr({
  545. 'type': 'text/javascript',
  546. 'src': 'http://manifesto.ericdelabar.com/manifesto.js?x="+(Math.random())'
  547. })
  548. );
  549. (function wait(){
  550. if($('#cacheStatus').length == 0){
  551. setTimeout(wait,10);
  552. }else{
  553. $('#cacheStatus').niceScroll();
  554. }
  555. })();
  556. }else{
  557. alert("Manifest file is valid.");
  558. }
  559. }else{
  560. alert("This browser does not support HTML5 Offline Application Cache.");
  561. }
  562. flag('manifesto',true);
  563. }
  564. });
  565. shortcut.add('Shift+f12',function(){
  566. templates = [];
  567. $.localStorage('templates',null);
  568. console.log('Templates cleared.');
  569. });
  570. $.fn.serializeObject = function(){
  571. var o = {},
  572. a = this.serializeArray();
  573. $.each(a,function(){
  574. if(o[this.name] !== undefined){
  575. if(!o[this.name].push){
  576. o[this.name] = [o[this.name]];
  577. }
  578. o[this.name].push(this.value || '');
  579. }else{
  580. o[this.name] = this.value || '';
  581. }
  582. });
  583. return o;
  584. };
  585. String.prototype.capitalize = function(lower) {
  586. return (lower?this.toLowerCase():this).replace(/(?:^|\s)\S/g, function(a){
  587. return a.toUpperCase();
  588. });
  589. };
  590. })(jQuery,History,console);