index.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. // TODO - Add initial page loading and handlers
  2. (function($,History){
  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. $('#loading').show();
  93. data.get = 'api';
  94. data.timestamp = +new Date;
  95. if(''!=template(data.type+'-'+data.id)){
  96. data.template = false;
  97. }
  98. $.get(location.href,data,function(d){
  99. if(exists(d['error'])){
  100. error(d);
  101. }else{
  102. if(location.href.substr(location.href.lastIndexOf('/')+1) != d.state.url){
  103. console.log('Forced redirection to '+d.state.url);
  104. History.replaceState(d.state.data,d.state.title,d.state.url);
  105. }
  106. }
  107. if(exists(callback)){
  108. callback(d);
  109. }
  110. },'json');
  111. },
  112. loadState = window.loadState = function(href,callback){
  113. console.log('loadState('+href+')');
  114. $('#loading').show();
  115. var data = {
  116. get:'state',
  117. timestamp: +new Date
  118. };
  119. ajax = $.ajax(href,{
  120. data: data,
  121. async: true,
  122. type: 'GET',
  123. success: function(d){
  124. if(exists(d['error'])){
  125. error(d);
  126. }else{
  127. console.log('pushState: '+d.state.title+'['+href+']');
  128. History.pushState(d.state.data,d.state.title,href);
  129. getNewState();
  130. }
  131. if(exists(callback)){
  132. callback(d);
  133. }
  134. },
  135. error: function(x,t,e){
  136. error({
  137. error: '['+t+'] '+e
  138. });
  139. if(exists(callback)){
  140. callback({
  141. error: '['+t+'] '+e
  142. });
  143. }
  144. },
  145. dataType: 'json'
  146. });
  147. },
  148. apiState = window.apiState = function(href,callback){
  149. console.log('apiState('+href+')');
  150. $('#loading').show();
  151. var data = {
  152. get:'state',
  153. timestamp: +new Date
  154. };
  155. $.ajax(href,{
  156. data: data,
  157. async: true,
  158. type: 'GET',
  159. success: function(d){
  160. if(exists(d['error'])){
  161. error(d);
  162. }else{
  163. console.log('pushState: '+d.state.title+'['+href+']');
  164. History.replaceState(d.state.data,d.state.title,href);
  165. getNewState();
  166. }
  167. if(exists(callback)){
  168. callback(d);
  169. }
  170. },
  171. error: function(x,t,e){
  172. error({
  173. error: '['+t+'] '+e
  174. });
  175. if(exists(callback)){
  176. callback({
  177. error: '['+t+'] '+e
  178. });
  179. }
  180. },
  181. dataType: 'json'
  182. });
  183. },
  184. error = function(e){
  185. var msg = '['+State.url+']'+e.error;
  186. console.error(msg.trim()+"\n"+(exists(e.state)?JSON.stringify(e.state):''));
  187. alert(msg.trim());
  188. $('#loading').hide();
  189. },
  190. getNewState = function(){
  191. State = History.getState();
  192. console.log("State change. "+JSON.stringify(State.data));
  193. if (!window.location.origin) {
  194. window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
  195. }
  196. },
  197. equal = function(o1,o2){
  198. for(var i in o1){
  199. if(!exists(o2[i])||o2[i]!=o1[i]){
  200. return false;
  201. }
  202. }
  203. for(i in o2){
  204. if(!exists(o1[i])||o2[i]!=o1[i]){
  205. return false;
  206. }
  207. }
  208. return true;
  209. },
  210. render = window.render = {
  211. topbar: function(t,c){
  212. $('#topbar').html(Handlebars.compile(t)(c));
  213. render.links('#topbar');
  214. render.buttons('#topbar');
  215. render.menus('#topbar');
  216. $(window).resize();
  217. },
  218. content: function(t,c){
  219. console.log(c);
  220. $('#content').html(
  221. Handlebars.compile(t)(c)
  222. );
  223. render.links('#content');
  224. render.buttons('#content');
  225. render.accordions('#content');
  226. render.menus('#content');
  227. render.form('#content');
  228. $(window).resize();
  229. },
  230. accordions: function(selector){
  231. $(selector).find('.accordion').each(function(){
  232. var icons = {};
  233. if($(this).children('.icons').length == 1){
  234. icons = JSON.parse($(this).children('.icons').text());
  235. }
  236. $(this).children('.icons').remove();
  237. $(this).accordion({
  238. collapsible: true,
  239. icons: icons,
  240. active: false
  241. });
  242. });
  243. },
  244. buttons: function(selector){
  245. $(selector).find('.button').button();
  246. $(selector).find('input[type=submit]').button();
  247. $(selector).find('input[type=button]').button();
  248. $(selector).find('button').button();
  249. },
  250. menus: function(selector){
  251. $(selector).find('.menu').css({
  252. 'list-style':'none'
  253. }).menu({
  254. icons:{
  255. submenu: "ui-icon-circle-triangle-e"
  256. }
  257. }).removeClass('ui-corner-all').addClass('ui-corner-bottom').parent().click(function(e){
  258. e.stopPropagation();
  259. });
  260. },
  261. form: function(selector){
  262. $(selector).find('#form').position({of:selector,my:'center',at:'center'});
  263. },
  264. links: function(selector){
  265. $(selector).find('a').each(function(){
  266. var href = this.href;
  267. if(href.indexOf('#')!=-1&&(href.indexOf(location.origin)!=-1||href.indexOf('#')==0)){
  268. href = href.substr(href.indexOf('#')+1);
  269. $(this).click(function(e){
  270. try{
  271. if(($(this).hasClass('topbar-home') || $(this).hasClass('topbar-back'))&&$(window).width()<767){
  272. $('#topbar').children('div.topbar-right,div.topbar-left').toggle();
  273. $(window).resize();
  274. }else if($(this).hasClass('topbar-history')){
  275. History.back();
  276. }else{
  277. loadState(href);
  278. }
  279. }catch(error){
  280. console.error(error);
  281. }
  282. e.preventDefault();
  283. return false;
  284. });
  285. }
  286. });
  287. }
  288. };
  289. if(exists($.cookie('key'))){
  290. setKey($.cookie('key'));
  291. }else{
  292. setKey(null);
  293. }
  294. $(document).ready(function(){
  295. $.fn.serializeObject = function(){
  296. var o = {},
  297. a = this.serializeArray();
  298. $.each(a,function(){
  299. if(o[this.name] !== undefined){
  300. if(!o[this.name].push){
  301. o[this.name] = [o[this.name]];
  302. }
  303. o[this.name].push(this.value || '');
  304. }else{
  305. o[this.name] = this.value || '';
  306. }
  307. });
  308. return o;
  309. };
  310. $.ajaxSetup({
  311. async: false,
  312. cache: false
  313. });
  314. templates = $.localStorage('templates');
  315. if(templates === null){
  316. templates = [];
  317. }
  318. if(!exists($.support.touch)){
  319. $.support.touch = 'ontouchstart' in window || 'onmsgesturechange' in window;
  320. }
  321. $(window).on('statechange',function(){
  322. getNewState();
  323. if(!equal(State.data,Old)){
  324. document.title = State.title;
  325. switch(State.data.type){
  326. case 'page':case 'user':case 'project':
  327. apiCall(State.data,function(d){
  328. if(exists(d.context)){
  329. if(!exists(d.context.key)&&Key!==null){
  330. console.log('Context detected logout');
  331. setKey(null);
  332. }
  333. if(exists(d.template)){
  334. template(State.data.type+'-'+State.data.id,d.template);
  335. }else{
  336. d.template = template(State.data.type+'-'+State.data.id);
  337. }
  338. render.topbar(d.topbar.template,d.topbar.context);
  339. render.content(d.template,d.context);
  340. $(window).resize();
  341. $('#loading').hide();
  342. }else{
  343. console.error('No context given');
  344. History.back();
  345. }
  346. });
  347. break;
  348. case 'action':break;
  349. default:
  350. error({
  351. url: State.url,
  352. error: "Something went wrong!"
  353. });
  354. }
  355. Old = State.data;
  356. }else{
  357. console.log(State.data,Old);
  358. console.warn('Stopped double load of '+Old.type+'-'+Old.id);
  359. $('#loading').hide();
  360. }
  361. });
  362. $('#content').niceScroll({
  363. cursorwidth: 10,
  364. nativeparentscrolling: false,
  365. preservenativescrolling: false
  366. });
  367. $('#content,#topbar').click(function(){
  368. $('.menu').hide();
  369. });
  370. document.addEventListener('touchmove',function(e){
  371. e.preventDefault();
  372. });
  373. $(window).resize(function(){
  374. if($(window).width()>767){
  375. $('#topbar div.topbar-right, #topbar div.topbar-left').css({
  376. 'display': ''
  377. });
  378. }
  379. $('#content').height($('body').height()-$('#topbar').height());
  380. $('#content').getNiceScroll().resize();
  381. render.form('#content');
  382. });
  383. var data = {
  384. get: 'settings',
  385. timestamp: +new Date
  386. };
  387. $.get(location.href,data,function(d){
  388. settings = d;
  389. apiState(location.href);
  390. },'json');
  391. });
  392. shortcut.add('f12',function(){
  393. if(!flag('firebug-lite')){
  394. $('head').append(
  395. $('<script>').attr({
  396. 'type': 'text/javascript',
  397. 'src': 'https://getfirebug.com/firebug-lite.js#startOpened',
  398. 'id': 'FirebugLite'
  399. })
  400. );
  401. $('<image>').attr('src','https://getfirebug.com/releases/lite/latest/skin/xp/sprite.png');
  402. flag('firebug-lite',true);
  403. }
  404. });
  405. shortcut.add('Ctrl+f12',function(){
  406. if(!flag('manifesto')){
  407. if(window.applicationCache){
  408. if(window.applicationCache.status==window.applicationCache.UNCACHED){
  409. $('head').append(
  410. $('<script>').attr({
  411. 'type': 'text/javascript',
  412. 'src': 'http://manifesto.ericdelabar.com/manifesto.js?x="+(Math.random())'
  413. })
  414. );
  415. (function wait(){
  416. if($('#cacheStatus').length == 0){
  417. setTimeout(wait,10);
  418. }else{
  419. $('#cacheStatus').niceScroll();
  420. }
  421. })();
  422. }else{
  423. alert("Manifest file is valid.");
  424. }
  425. }else{
  426. alert("This browser does not support HTML5 Offline Application Cache.");
  427. }
  428. flag('manifesto',true);
  429. }
  430. });
  431. shortcut.add('Shift+f12',function(){
  432. templates = [];
  433. $.localStorage('templates',null);
  434. console.log('Templates cleared.');
  435. });
  436. })(jQuery,History);