all.js 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042
  1. /* ---- lib/Animation.coffee ---- */
  2. (function() {
  3. var Animation;
  4. Animation = (function() {
  5. function Animation() {}
  6. Animation.prototype.slideDown = function(elem, props) {
  7. var cstyle, h, margin_bottom, margin_top, padding_bottom, padding_top, transition;
  8. if (elem.offsetTop > 2000) {
  9. return;
  10. }
  11. h = elem.offsetHeight;
  12. cstyle = window.getComputedStyle(elem);
  13. margin_top = cstyle.marginTop;
  14. margin_bottom = cstyle.marginBottom;
  15. padding_top = cstyle.paddingTop;
  16. padding_bottom = cstyle.paddingBottom;
  17. transition = cstyle.transition;
  18. elem.style.boxSizing = "border-box";
  19. elem.style.overflow = "hidden";
  20. elem.style.transform = "scale(0.6)";
  21. elem.style.opacity = "0";
  22. elem.style.height = "0px";
  23. elem.style.marginTop = "0px";
  24. elem.style.marginBottom = "0px";
  25. elem.style.paddingTop = "0px";
  26. elem.style.paddingBottom = "0px";
  27. elem.style.transition = "none";
  28. setTimeout((function() {
  29. elem.className += " animate-inout";
  30. elem.style.height = h + "px";
  31. elem.style.transform = "scale(1)";
  32. elem.style.opacity = "1";
  33. elem.style.marginTop = margin_top;
  34. elem.style.marginBottom = margin_bottom;
  35. elem.style.paddingTop = padding_top;
  36. return elem.style.paddingBottom = padding_bottom;
  37. }), 1);
  38. return elem.addEventListener("transitionend", function() {
  39. elem.classList.remove("animate-inout");
  40. elem.style.transition = elem.style.transform = elem.style.opacity = elem.style.height = null;
  41. elem.style.boxSizing = elem.style.marginTop = elem.style.marginBottom = null;
  42. elem.style.paddingTop = elem.style.paddingBottom = elem.style.overflow = null;
  43. return elem.removeEventListener("transitionend", arguments.callee, false);
  44. });
  45. };
  46. Animation.prototype.slideUp = function(elem, remove_func, props) {
  47. if (elem.offsetTop > 1000) {
  48. return remove_func();
  49. }
  50. elem.className += " animate-back";
  51. elem.style.boxSizing = "border-box";
  52. elem.style.height = elem.offsetHeight + "px";
  53. elem.style.overflow = "hidden";
  54. elem.style.transform = "scale(1)";
  55. elem.style.opacity = "1";
  56. elem.style.pointerEvents = "none";
  57. setTimeout((function() {
  58. elem.style.height = "0px";
  59. elem.style.marginTop = "0px";
  60. elem.style.marginBottom = "0px";
  61. elem.style.paddingTop = "0px";
  62. elem.style.paddingBottom = "0px";
  63. elem.style.transform = "scale(0.8)";
  64. elem.style.borderTopWidth = "0px";
  65. elem.style.borderBottomWidth = "0px";
  66. return elem.style.opacity = "0";
  67. }), 1);
  68. return elem.addEventListener("transitionend", function(e) {
  69. if (e.propertyName === "opacity" || e.elapsedTime >= 0.6) {
  70. elem.removeEventListener("transitionend", arguments.callee, false);
  71. return remove_func();
  72. }
  73. });
  74. };
  75. Animation.prototype.slideUpInout = function(elem, remove_func, props) {
  76. elem.className += " animate-inout";
  77. elem.style.boxSizing = "border-box";
  78. elem.style.height = elem.offsetHeight + "px";
  79. elem.style.overflow = "hidden";
  80. elem.style.transform = "scale(1)";
  81. elem.style.opacity = "1";
  82. elem.style.pointerEvents = "none";
  83. setTimeout((function() {
  84. elem.style.height = "0px";
  85. elem.style.marginTop = "0px";
  86. elem.style.marginBottom = "0px";
  87. elem.style.paddingTop = "0px";
  88. elem.style.paddingBottom = "0px";
  89. elem.style.transform = "scale(0.8)";
  90. elem.style.borderTopWidth = "0px";
  91. elem.style.borderBottomWidth = "0px";
  92. return elem.style.opacity = "0";
  93. }), 1);
  94. return elem.addEventListener("transitionend", function(e) {
  95. if (e.propertyName === "opacity" || e.elapsedTime >= 0.6) {
  96. elem.removeEventListener("transitionend", arguments.callee, false);
  97. return remove_func();
  98. }
  99. });
  100. };
  101. Animation.prototype.showRight = function(elem, props) {
  102. elem.className += " animate";
  103. elem.style.opacity = 0;
  104. elem.style.transform = "TranslateX(-20px) Scale(1.01)";
  105. setTimeout((function() {
  106. elem.style.opacity = 1;
  107. return elem.style.transform = "TranslateX(0px) Scale(1)";
  108. }), 1);
  109. return elem.addEventListener("transitionend", function() {
  110. elem.classList.remove("animate");
  111. return elem.style.transform = elem.style.opacity = null;
  112. });
  113. };
  114. Animation.prototype.show = function(elem, props) {
  115. var delay, ref;
  116. delay = ((ref = arguments[arguments.length - 2]) != null ? ref.delay : void 0) * 1000 || 1;
  117. elem.style.opacity = 0;
  118. setTimeout((function() {
  119. return elem.className += " animate";
  120. }), 1);
  121. setTimeout((function() {
  122. return elem.style.opacity = 1;
  123. }), delay);
  124. return elem.addEventListener("transitionend", function() {
  125. elem.classList.remove("animate");
  126. elem.style.opacity = null;
  127. return elem.removeEventListener("transitionend", arguments.callee, false);
  128. });
  129. };
  130. Animation.prototype.hide = function(elem, remove_func, props) {
  131. var delay, ref;
  132. delay = ((ref = arguments[arguments.length - 2]) != null ? ref.delay : void 0) * 1000 || 1;
  133. elem.className += " animate";
  134. setTimeout((function() {
  135. return elem.style.opacity = 0;
  136. }), delay);
  137. return elem.addEventListener("transitionend", function(e) {
  138. if (e.propertyName === "opacity") {
  139. return remove_func();
  140. }
  141. });
  142. };
  143. Animation.prototype.addVisibleClass = function(elem, props) {
  144. return setTimeout(function() {
  145. return elem.classList.add("visible");
  146. });
  147. };
  148. return Animation;
  149. })();
  150. window.Animation = new Animation();
  151. }).call(this);
  152. /* ---- lib/Class.coffee ---- */
  153. (function() {
  154. var Class,
  155. slice = [].slice;
  156. Class = (function() {
  157. function Class() {}
  158. Class.prototype.trace = true;
  159. Class.prototype.log = function() {
  160. var args;
  161. args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  162. if (!this.trace) {
  163. return;
  164. }
  165. if (typeof console === 'undefined') {
  166. return;
  167. }
  168. args.unshift("[" + this.constructor.name + "]");
  169. console.log.apply(console, args);
  170. return this;
  171. };
  172. Class.prototype.logStart = function() {
  173. var args, name;
  174. name = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  175. if (!this.trace) {
  176. return;
  177. }
  178. this.logtimers || (this.logtimers = {});
  179. this.logtimers[name] = +(new Date);
  180. if (args.length > 0) {
  181. this.log.apply(this, ["" + name].concat(slice.call(args), ["(started)"]));
  182. }
  183. return this;
  184. };
  185. Class.prototype.logEnd = function() {
  186. var args, ms, name;
  187. name = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
  188. ms = +(new Date) - this.logtimers[name];
  189. this.log.apply(this, ["" + name].concat(slice.call(args), ["(Done in " + ms + "ms)"]));
  190. return this;
  191. };
  192. return Class;
  193. })();
  194. window.Class = Class;
  195. }).call(this);
  196. /* ---- lib/Dollar.coffee ---- */
  197. (function() {
  198. window.$ = function(selector) {
  199. if (selector.startsWith("#")) {
  200. return document.getElementById(selector.replace("#", ""));
  201. }
  202. };
  203. }).call(this);
  204. /* ---- lib/ItemList.coffee ---- */
  205. (function() {
  206. var ItemList;
  207. ItemList = (function() {
  208. function ItemList(item_class1, key1) {
  209. this.item_class = item_class1;
  210. this.key = key1;
  211. this.items = [];
  212. this.items_bykey = {};
  213. }
  214. ItemList.prototype.sync = function(rows, item_class, key) {
  215. var current_obj, i, item, len, results, row;
  216. this.items.splice(0, this.items.length);
  217. results = [];
  218. for (i = 0, len = rows.length; i < len; i++) {
  219. row = rows[i];
  220. current_obj = this.items_bykey[row[this.key]];
  221. if (current_obj) {
  222. current_obj.row = row;
  223. results.push(this.items.push(current_obj));
  224. } else {
  225. item = new this.item_class(row, this);
  226. this.items_bykey[row[this.key]] = item;
  227. results.push(this.items.push(item));
  228. }
  229. }
  230. return results;
  231. };
  232. ItemList.prototype.deleteItem = function(item) {
  233. var index;
  234. index = this.items.indexOf(item);
  235. if (index > -1) {
  236. this.items.splice(index, 1);
  237. } else {
  238. console.log("Can't delete item", item);
  239. }
  240. return delete this.items_bykey[item.row[this.key]];
  241. };
  242. return ItemList;
  243. })();
  244. window.ItemList = ItemList;
  245. }).call(this);
  246. /* ---- lib/Menu.coffee ---- */
  247. (function() {
  248. var Menu,
  249. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  250. 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; };
  251. Menu = (function() {
  252. function Menu() {
  253. this.render = bind(this.render, this);
  254. this.getStyle = bind(this.getStyle, this);
  255. this.renderItem = bind(this.renderItem, this);
  256. this.handleClick = bind(this.handleClick, this);
  257. this.getDirection = bind(this.getDirection, this);
  258. this.storeNode = bind(this.storeNode, this);
  259. this.toggle = bind(this.toggle, this);
  260. this.hide = bind(this.hide, this);
  261. this.show = bind(this.show, this);
  262. this.visible = false;
  263. this.items = [];
  264. this.node = null;
  265. this.height = 0;
  266. this.direction = "bottom";
  267. }
  268. Menu.prototype.show = function() {
  269. var ref;
  270. if ((ref = window.visible_menu) != null) {
  271. ref.hide();
  272. }
  273. this.visible = true;
  274. window.visible_menu = this;
  275. return this.direction = this.getDirection();
  276. };
  277. Menu.prototype.hide = function() {
  278. return this.visible = false;
  279. };
  280. Menu.prototype.toggle = function() {
  281. if (this.visible) {
  282. this.hide();
  283. } else {
  284. this.show();
  285. }
  286. return Page.projector.scheduleRender();
  287. };
  288. Menu.prototype.addItem = function(title, cb, selected) {
  289. if (selected == null) {
  290. selected = false;
  291. }
  292. return this.items.push([title, cb, selected]);
  293. };
  294. Menu.prototype.storeNode = function(node) {
  295. this.node = node;
  296. if (this.visible) {
  297. node.className = node.className.replace("visible", "");
  298. setTimeout(((function(_this) {
  299. return function() {
  300. node.className += " visible";
  301. return node.attributes.style.value = _this.getStyle();
  302. };
  303. })(this)), 20);
  304. node.style.maxHeight = "none";
  305. this.height = node.offsetHeight;
  306. node.style.maxHeight = "0px";
  307. return this.direction = this.getDirection();
  308. }
  309. };
  310. Menu.prototype.getDirection = function() {
  311. if (this.node && this.node.parentNode.getBoundingClientRect().top + this.height + 60 > document.body.clientHeight && this.node.parentNode.getBoundingClientRect().top - this.height > 0) {
  312. return "top";
  313. } else {
  314. return "bottom";
  315. }
  316. };
  317. Menu.prototype.handleClick = function(e) {
  318. var cb, i, item, keep_menu, len, ref, selected, title;
  319. keep_menu = false;
  320. ref = this.items;
  321. for (i = 0, len = ref.length; i < len; i++) {
  322. item = ref[i];
  323. title = item[0], cb = item[1], selected = item[2];
  324. if (title === e.currentTarget.textContent || e.currentTarget["data-title"] === title) {
  325. keep_menu = typeof cb === "function" ? cb(item) : void 0;
  326. break;
  327. }
  328. }
  329. if (keep_menu !== true && cb !== null) {
  330. this.hide();
  331. }
  332. return false;
  333. };
  334. Menu.prototype.renderItem = function(item) {
  335. var cb, classes, href, onclick, selected, title;
  336. title = item[0], cb = item[1], selected = item[2];
  337. if (typeof selected === "function") {
  338. selected = selected();
  339. }
  340. if (title === "---") {
  341. return h("div.menu-item-separator", {
  342. key: Time.timestamp()
  343. });
  344. } else {
  345. if (cb === null) {
  346. href = void 0;
  347. onclick = this.handleClick;
  348. } else if (typeof cb === "string") {
  349. href = cb;
  350. onclick = true;
  351. } else {
  352. href = "#" + title;
  353. onclick = this.handleClick;
  354. }
  355. classes = {
  356. "selected": selected,
  357. "noaction": cb === null
  358. };
  359. return h("a.menu-item", {
  360. href: href,
  361. onclick: onclick,
  362. "data-title": title,
  363. key: title,
  364. classes: classes
  365. }, title);
  366. }
  367. };
  368. Menu.prototype.getStyle = function() {
  369. var max_height, style;
  370. if (this.visible) {
  371. max_height = this.height;
  372. } else {
  373. max_height = 0;
  374. }
  375. style = "max-height: " + max_height + "px";
  376. if (this.direction === "top") {
  377. style += ";margin-top: " + (0 - this.height - 50) + "px";
  378. } else {
  379. style += ";margin-top: 0px";
  380. }
  381. return style;
  382. };
  383. Menu.prototype.render = function(class_name) {
  384. if (class_name == null) {
  385. class_name = "";
  386. }
  387. if (this.visible || this.node) {
  388. return h("div.menu" + class_name, {
  389. classes: {
  390. "visible": this.visible
  391. },
  392. style: this.getStyle(),
  393. afterCreate: this.storeNode
  394. }, this.items.map(this.renderItem));
  395. }
  396. };
  397. return Menu;
  398. })();
  399. window.Menu = Menu;
  400. document.body.addEventListener("mouseup", function(e) {
  401. var menu_node, menu_parents, ref, ref1;
  402. if (!window.visible_menu || !window.visible_menu.node) {
  403. return false;
  404. }
  405. menu_node = window.visible_menu.node;
  406. menu_parents = [menu_node, menu_node.parentNode];
  407. if ((ref = e.target.parentNode, indexOf.call(menu_parents, ref) < 0) && (ref1 = e.target.parentNode.parentNode, indexOf.call(menu_parents, ref1) < 0)) {
  408. window.visible_menu.hide();
  409. return Page.projector.scheduleRender();
  410. }
  411. });
  412. }).call(this);
  413. /* ---- lib/Promise.coffee ---- */
  414. (function() {
  415. var Promise,
  416. slice = [].slice;
  417. Promise = (function() {
  418. Promise.when = function() {
  419. var args, fn, i, len, num_uncompleted, promise, task, task_id, tasks;
  420. tasks = 1 <= arguments.length ? slice.call(arguments, 0) : [];
  421. num_uncompleted = tasks.length;
  422. args = new Array(num_uncompleted);
  423. promise = new Promise();
  424. fn = function(task_id) {
  425. return task.then(function() {
  426. args[task_id] = Array.prototype.slice.call(arguments);
  427. num_uncompleted--;
  428. if (num_uncompleted === 0) {
  429. return promise.complete.apply(promise, args);
  430. }
  431. });
  432. };
  433. for (task_id = i = 0, len = tasks.length; i < len; task_id = ++i) {
  434. task = tasks[task_id];
  435. fn(task_id);
  436. }
  437. return promise;
  438. };
  439. function Promise() {
  440. this.resolved = false;
  441. this.end_promise = null;
  442. this.result = null;
  443. this.callbacks = [];
  444. }
  445. Promise.prototype.resolve = function() {
  446. var back, callback, i, len, ref;
  447. if (this.resolved) {
  448. return false;
  449. }
  450. this.resolved = true;
  451. this.data = arguments;
  452. if (!arguments.length) {
  453. this.data = [true];
  454. }
  455. this.result = this.data[0];
  456. ref = this.callbacks;
  457. for (i = 0, len = ref.length; i < len; i++) {
  458. callback = ref[i];
  459. back = callback.apply(callback, this.data);
  460. }
  461. if (this.end_promise) {
  462. return this.end_promise.resolve(back);
  463. }
  464. };
  465. Promise.prototype.fail = function() {
  466. return this.resolve(false);
  467. };
  468. Promise.prototype.then = function(callback) {
  469. if (this.resolved === true) {
  470. callback.apply(callback, this.data);
  471. return;
  472. }
  473. this.callbacks.push(callback);
  474. return this.end_promise = new Promise();
  475. };
  476. return Promise;
  477. })();
  478. window.Promise = Promise;
  479. /*
  480. s = Date.now()
  481. log = (text) ->
  482. console.log Date.now()-s, Array.prototype.slice.call(arguments).join(", ")
  483. log "Started"
  484. cmd = (query) ->
  485. p = new Promise()
  486. setTimeout ( ->
  487. p.resolve query+" Result"
  488. ), 100
  489. return p
  490. back = cmd("SELECT * FROM message").then (res) ->
  491. log res
  492. return "Return from query"
  493. .then (res) ->
  494. log "Back then", res
  495. log "Query started", back
  496. */
  497. }).call(this);
  498. /* ---- lib/Prototypes.coffee ---- */
  499. (function() {
  500. String.prototype.startsWith = function(s) {
  501. return this.slice(0, s.length) === s;
  502. };
  503. String.prototype.endsWith = function(s) {
  504. return s === '' || this.slice(-s.length) === s;
  505. };
  506. String.prototype.repeat = function(count) {
  507. return new Array(count + 1).join(this);
  508. };
  509. window.isEmpty = function(obj) {
  510. var key;
  511. for (key in obj) {
  512. return false;
  513. }
  514. return true;
  515. };
  516. }).call(this);
  517. /* ---- lib/RateLimitCb.coffee ---- */
  518. (function() {
  519. var call_after_interval, calling, calling_iterval, last_time,
  520. slice = [].slice;
  521. last_time = {};
  522. calling = {};
  523. calling_iterval = {};
  524. call_after_interval = {};
  525. window.RateLimitCb = function(interval, fn, args) {
  526. var cb;
  527. if (args == null) {
  528. args = [];
  529. }
  530. cb = function() {
  531. var left;
  532. left = interval - (Date.now() - last_time[fn]);
  533. if (left <= 0) {
  534. delete last_time[fn];
  535. if (calling[fn]) {
  536. RateLimitCb(interval, fn, calling[fn]);
  537. }
  538. return delete calling[fn];
  539. } else {
  540. return setTimeout((function() {
  541. delete last_time[fn];
  542. if (calling[fn]) {
  543. RateLimitCb(interval, fn, calling[fn]);
  544. }
  545. return delete calling[fn];
  546. }), left);
  547. }
  548. };
  549. if (last_time[fn]) {
  550. return calling[fn] = args;
  551. } else {
  552. last_time[fn] = Date.now();
  553. return fn.apply(this, [cb].concat(slice.call(args)));
  554. }
  555. };
  556. window.RateLimit = function(interval, fn) {
  557. if (calling_iterval[fn] > interval) {
  558. clearInterval(calling[fn]);
  559. delete calling[fn];
  560. }
  561. if (!calling[fn]) {
  562. call_after_interval[fn] = false;
  563. fn();
  564. calling_iterval[fn] = interval;
  565. return calling[fn] = setTimeout((function() {
  566. if (call_after_interval[fn]) {
  567. fn();
  568. }
  569. delete calling[fn];
  570. return delete call_after_interval[fn];
  571. }), interval);
  572. } else {
  573. return call_after_interval[fn] = true;
  574. }
  575. };
  576. /*
  577. window.s = Date.now()
  578. window.load = (done, num) ->
  579. console.log "Loading #{num}...", Date.now()-window.s
  580. setTimeout (-> done()), 1000
  581. RateLimit 500, window.load, [0] # Called instantly
  582. RateLimit 500, window.load, [1]
  583. setTimeout (-> RateLimit 500, window.load, [300]), 300
  584. setTimeout (-> RateLimit 500, window.load, [600]), 600 # Called after 1000ms
  585. setTimeout (-> RateLimit 500, window.load, [1000]), 1000
  586. setTimeout (-> RateLimit 500, window.load, [1200]), 1200 # Called after 2000ms
  587. setTimeout (-> RateLimit 500, window.load, [3000]), 3000 # Called after 3000ms
  588. */
  589. }).call(this);
  590. /* ---- lib/Text.coffee ---- */
  591. (function() {
  592. var Text,
  593. 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; };
  594. Text = (function() {
  595. function Text() {}
  596. Text.prototype.toColor = function(text, saturation, lightness) {
  597. var hash, i, j, ref;
  598. if (saturation == null) {
  599. saturation = 30;
  600. }
  601. if (lightness == null) {
  602. lightness = 50;
  603. }
  604. hash = 0;
  605. for (i = j = 0, ref = text.length - 1; 0 <= ref ? j <= ref : j >= ref; i = 0 <= ref ? ++j : --j) {
  606. hash += text.charCodeAt(i) * i;
  607. hash = hash % 1777;
  608. }
  609. return "hsl(" + (hash % 360) + ("," + saturation + "%," + lightness + "%)");
  610. };
  611. Text.prototype.renderMarked = function(text, options) {
  612. if (options == null) {
  613. options = {};
  614. }
  615. options["gfm"] = true;
  616. options["breaks"] = true;
  617. options["sanitize"] = true;
  618. options["renderer"] = marked_renderer;
  619. text = marked(text, options);
  620. return this.fixHtmlLinks(text);
  621. };
  622. Text.prototype.emailLinks = function(text) {
  623. return text.replace(/([a-zA-Z0-9]+)@zeroid.bit/g, "<a href='?to=$1' onclick='return Page.message_create.show(\"$1\")'>$1@zeroid.bit</a>");
  624. };
  625. Text.prototype.fixHtmlLinks = function(text) {
  626. if (window.is_proxy) {
  627. return text.replace(/href="http:\/\/(127.0.0.1|localhost):43110/g, 'href="http://zero');
  628. } else {
  629. return text.replace(/href="http:\/\/(127.0.0.1|localhost):43110/g, 'href="');
  630. }
  631. };
  632. Text.prototype.fixLink = function(link) {
  633. var back;
  634. if (window.is_proxy) {
  635. back = link.replace(/http:\/\/(127.0.0.1|localhost):43110/, 'http://zero');
  636. return back.replace(/http:\/\/zero\/([^\/]+\.bit)/, "http://$1");
  637. } else {
  638. return link.replace(/http:\/\/(127.0.0.1|localhost):43110/, '');
  639. }
  640. };
  641. Text.prototype.toUrl = function(text) {
  642. return text.replace(/[^A-Za-z0-9]/g, "+").replace(/[+]+/g, "+").replace(/[+]+$/, "");
  643. };
  644. Text.prototype.getSiteUrl = function(address) {
  645. if (window.is_proxy) {
  646. if (indexOf.call(address, ".") >= 0) {
  647. return "http://" + address + "/";
  648. } else {
  649. return "http://zero/" + address + "/";
  650. }
  651. } else {
  652. return "/" + address + "/";
  653. }
  654. };
  655. Text.prototype.fixReply = function(text) {
  656. return text.replace(/(>.*\n)([^\n>])/gm, "$1\n$2");
  657. };
  658. Text.prototype.toBitcoinAddress = function(text) {
  659. return text.replace(/[^A-Za-z0-9]/g, "");
  660. };
  661. Text.prototype.jsonEncode = function(obj) {
  662. return unescape(encodeURIComponent(JSON.stringify(obj)));
  663. };
  664. Text.prototype.jsonDecode = function(obj) {
  665. return JSON.parse(decodeURIComponent(escape(obj)));
  666. };
  667. Text.prototype.fileEncode = function(obj) {
  668. if (typeof obj === "string") {
  669. return btoa(unescape(encodeURIComponent(obj)));
  670. } else {
  671. return btoa(unescape(encodeURIComponent(JSON.stringify(obj, void 0, '\t'))));
  672. }
  673. };
  674. Text.prototype.utf8Encode = function(s) {
  675. return unescape(encodeURIComponent(s));
  676. };
  677. Text.prototype.utf8Decode = function(s) {
  678. return decodeURIComponent(escape(s));
  679. };
  680. Text.prototype.distance = function(s1, s2) {
  681. var char, extra_parts, j, key, len, match, next_find, next_find_i, val;
  682. s1 = s1.toLocaleLowerCase();
  683. s2 = s2.toLocaleLowerCase();
  684. next_find_i = 0;
  685. next_find = s2[0];
  686. match = true;
  687. extra_parts = {};
  688. for (j = 0, len = s1.length; j < len; j++) {
  689. char = s1[j];
  690. if (char !== next_find) {
  691. if (extra_parts[next_find_i]) {
  692. extra_parts[next_find_i] += char;
  693. } else {
  694. extra_parts[next_find_i] = char;
  695. }
  696. } else {
  697. next_find_i++;
  698. next_find = s2[next_find_i];
  699. }
  700. }
  701. if (extra_parts[next_find_i]) {
  702. extra_parts[next_find_i] = "";
  703. }
  704. extra_parts = (function() {
  705. var results;
  706. results = [];
  707. for (key in extra_parts) {
  708. val = extra_parts[key];
  709. results.push(val);
  710. }
  711. return results;
  712. })();
  713. if (next_find_i >= s2.length) {
  714. return extra_parts.length + extra_parts.join("").length;
  715. } else {
  716. return false;
  717. }
  718. };
  719. Text.prototype.parseQuery = function(query) {
  720. var j, key, len, params, part, parts, ref, val;
  721. params = {};
  722. parts = query.split('&');
  723. for (j = 0, len = parts.length; j < len; j++) {
  724. part = parts[j];
  725. ref = part.split("="), key = ref[0], val = ref[1];
  726. if (val) {
  727. params[decodeURIComponent(key)] = decodeURIComponent(val);
  728. } else {
  729. params["url"] = decodeURIComponent(key);
  730. }
  731. }
  732. return params;
  733. };
  734. Text.prototype.encodeQuery = function(params) {
  735. var back, key, val;
  736. back = [];
  737. if (params.url) {
  738. back.push(params.url);
  739. }
  740. for (key in params) {
  741. val = params[key];
  742. if (!val || key === "url") {
  743. continue;
  744. }
  745. back.push((encodeURIComponent(key)) + "=" + (encodeURIComponent(val)));
  746. }
  747. return back.join("&");
  748. };
  749. Text.prototype.highlight = function(text, search) {
  750. var back, i, j, len, part, parts;
  751. if (!text) {
  752. return [""];
  753. }
  754. parts = text.split(RegExp(search, "i"));
  755. back = [];
  756. for (i = j = 0, len = parts.length; j < len; i = ++j) {
  757. part = parts[i];
  758. back.push(part);
  759. if (i < parts.length - 1) {
  760. back.push(h("span.highlight", {
  761. key: i
  762. }, search));
  763. }
  764. }
  765. return back;
  766. };
  767. Text.prototype.formatSize = function(size) {
  768. var size_mb;
  769. if (isNaN(parseInt(size))) {
  770. return "";
  771. }
  772. size_mb = size / 1024 / 1024;
  773. if (size_mb >= 1000) {
  774. return (size_mb / 1024).toFixed(1) + " GB";
  775. } else if (size_mb >= 100) {
  776. return size_mb.toFixed(0) + " MB";
  777. } else if (size / 1024 >= 1000) {
  778. return size_mb.toFixed(2) + " MB";
  779. } else {
  780. return (parseInt(size) / 1024).toFixed(2) + " KB";
  781. }
  782. };
  783. return Text;
  784. })();
  785. window.is_proxy = document.location.host === "zero" || window.location.pathname === "/";
  786. window.Text = new Text();
  787. }).call(this);
  788. /* ---- lib/Time.coffee ---- */
  789. (function() {
  790. var Time;
  791. Time = (function() {
  792. function Time() {}
  793. Time.prototype.since = function(timestamp) {
  794. var back, minutes, now, secs;
  795. now = +(new Date) / 1000;
  796. if (timestamp > 1000000000000) {
  797. timestamp = timestamp / 1000;
  798. }
  799. secs = now - timestamp;
  800. if (secs < 60) {
  801. back = "Just now";
  802. } else if (secs < 60 * 60) {
  803. minutes = Math.round(secs / 60);
  804. back = "" + minutes + " minutes ago";
  805. } else if (secs < 60 * 60 * 24) {
  806. back = (Math.round(secs / 60 / 60)) + " hours ago";
  807. } else if (secs < 60 * 60 * 24 * 3) {
  808. back = (Math.round(secs / 60 / 60 / 24)) + " days ago";
  809. } else {
  810. back = "on " + this.date(timestamp);
  811. }
  812. back = back.replace(/^1 ([a-z]+)s/, "1 $1");
  813. return back;
  814. };
  815. Time.prototype.dateIso = function(timestamp) {
  816. var tzoffset;
  817. if (timestamp == null) {
  818. timestamp = null;
  819. }
  820. if (!timestamp) {
  821. timestamp = window.Time.timestamp();
  822. }
  823. if (timestamp > 1000000000000) {
  824. timestamp = timestamp / 1000;
  825. }
  826. tzoffset = (new Date()).getTimezoneOffset() * 60;
  827. return (new Date((timestamp - tzoffset) * 1000)).toISOString().split("T")[0];
  828. };
  829. Time.prototype.date = function(timestamp, format) {
  830. var display, parts;
  831. if (timestamp == null) {
  832. timestamp = null;
  833. }
  834. if (format == null) {
  835. format = "short";
  836. }
  837. if (!timestamp) {
  838. timestamp = window.Time.timestamp();
  839. }
  840. if (timestamp > 1000000000000) {
  841. timestamp = timestamp / 1000;
  842. }
  843. parts = (new Date(timestamp * 1000)).toString().split(" ");
  844. if (format === "short") {
  845. display = parts.slice(1, 4);
  846. } else if (format === "day") {
  847. display = parts.slice(1, 3);
  848. } else if (format === "month") {
  849. display = [parts[1], parts[3]];
  850. } else if (format === "long") {
  851. display = parts.slice(1, 5);
  852. }
  853. return display.join(" ").replace(/( [0-9]{4})/, ",$1");
  854. };
  855. Time.prototype.weekDay = function(timestamp) {
  856. if (timestamp > 1000000000000) {
  857. timestamp = timestamp / 1000;
  858. }
  859. return ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][(new Date(timestamp * 1000)).getDay()];
  860. };
  861. Time.prototype.timestamp = function(date) {
  862. if (date == null) {
  863. date = "";
  864. }
  865. if (date === "now" || date === "") {
  866. return parseInt(+(new Date) / 1000);
  867. } else {
  868. return parseInt(Date.parse(date) / 1000);
  869. }
  870. };
  871. return Time;
  872. })();
  873. window.Time = new Time;
  874. }).call(this);
  875. /* ---- lib/ZeroFrame.coffee ---- */
  876. (function() {
  877. var ZeroFrame,
  878. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  879. extend = 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; },
  880. hasProp = {}.hasOwnProperty;
  881. ZeroFrame = (function(superClass) {
  882. extend(ZeroFrame, superClass);
  883. function ZeroFrame(url) {
  884. this.onCloseWebsocket = bind(this.onCloseWebsocket, this);
  885. this.onOpenWebsocket = bind(this.onOpenWebsocket, this);
  886. this.onRequest = bind(this.onRequest, this);
  887. this.onMessage = bind(this.onMessage, this);
  888. this.url = url;
  889. this.waiting_cb = {};
  890. this.wrapper_nonce = document.location.href.replace(/.*wrapper_nonce=([A-Za-z0-9]+).*/, "$1");
  891. this.connect();
  892. this.next_message_id = 1;
  893. this.history_state = {};
  894. this.init();
  895. }
  896. ZeroFrame.prototype.init = function() {
  897. return this;
  898. };
  899. ZeroFrame.prototype.connect = function() {
  900. this.target = window.parent;
  901. window.addEventListener("message", this.onMessage, false);
  902. this.cmd("innerReady");
  903. window.addEventListener("beforeunload", (function(_this) {
  904. return function(e) {
  905. _this.log("save scrollTop", window.pageYOffset);
  906. _this.history_state["scrollTop"] = window.pageYOffset;
  907. return _this.cmd("wrapperReplaceState", [_this.history_state, null]);
  908. };
  909. })(this));
  910. return this.cmd("wrapperGetState", [], (function(_this) {
  911. return function(state) {
  912. if (state != null) {
  913. _this.history_state = state;
  914. }
  915. _this.log("restore scrollTop", state, window.pageYOffset);
  916. if (window.pageYOffset === 0 && state) {
  917. return window.scroll(window.pageXOffset, state.scrollTop);
  918. }
  919. };
  920. })(this));
  921. };
  922. ZeroFrame.prototype.onMessage = function(e) {
  923. var cmd, message;
  924. message = e.data;
  925. cmd = message.cmd;
  926. if (cmd === "response") {
  927. if (this.waiting_cb[message.to] != null) {
  928. return this.waiting_cb[message.to](message.result);
  929. } else {
  930. return this.log("Websocket callback not found:", message);
  931. }
  932. } else if (cmd === "wrapperReady") {
  933. return this.cmd("innerReady");
  934. } else if (cmd === "ping") {
  935. return this.response(message.id, "pong");
  936. } else if (cmd === "wrapperOpenedWebsocket") {
  937. return this.onOpenWebsocket();
  938. } else if (cmd === "wrapperClosedWebsocket") {
  939. return this.onCloseWebsocket();
  940. } else {
  941. return this.onRequest(cmd, message.params);
  942. }
  943. };
  944. ZeroFrame.prototype.onRequest = function(cmd, message) {
  945. return this.log("Unknown request", message);
  946. };
  947. ZeroFrame.prototype.response = function(to, result) {
  948. return this.send({
  949. "cmd": "response",
  950. "to": to,
  951. "result": result
  952. });
  953. };
  954. ZeroFrame.prototype.cmd = function(cmd, params, cb) {
  955. if (params == null) {
  956. params = {};
  957. }
  958. if (cb == null) {
  959. cb = null;
  960. }
  961. return this.send({
  962. "cmd": cmd,
  963. "params": params
  964. }, cb);
  965. };
  966. ZeroFrame.prototype.send = function(message, cb) {
  967. if (cb == null) {
  968. cb = null;
  969. }
  970. message.wrapper_nonce = this.wrapper_nonce;
  971. message.id = this.next_message_id;
  972. this.next_message_id += 1;
  973. this.target.postMessage(message, "*");
  974. if (cb) {
  975. return this.waiting_cb[message.id] = cb;
  976. }
  977. };
  978. ZeroFrame.prototype.onOpenWebsocket = function() {
  979. return this.log("Websocket open");
  980. };
  981. ZeroFrame.prototype.onCloseWebsocket = function() {
  982. return this.log("Websocket close");
  983. };
  984. return ZeroFrame;
  985. })(Class);
  986. window.ZeroFrame = ZeroFrame;
  987. }).call(this);
  988. /* ---- lib/maquette.js ---- */
  989. (function (root, factory) {
  990. if (typeof define === 'function' && define.amd) {
  991. // AMD. Register as an anonymous module.
  992. define(['exports'], factory);
  993. } else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
  994. // CommonJS
  995. factory(exports);
  996. } else {
  997. // Browser globals
  998. factory(root.maquette = {});
  999. }
  1000. }(this, function (exports) {
  1001. 'use strict';
  1002. ;
  1003. ;
  1004. ;
  1005. ;
  1006. var NAMESPACE_W3 = 'http://www.w3.org/';
  1007. var NAMESPACE_SVG = NAMESPACE_W3 + '2000/svg';
  1008. var NAMESPACE_XLINK = NAMESPACE_W3 + '1999/xlink';
  1009. // Utilities
  1010. var emptyArray = [];
  1011. var extend = function (base, overrides) {
  1012. var result = {};
  1013. Object.keys(base).forEach(function (key) {
  1014. result[key] = base[key];
  1015. });
  1016. if (overrides) {
  1017. Object.keys(overrides).forEach(function (key) {
  1018. result[key] = overrides[key];
  1019. });
  1020. }
  1021. return result;
  1022. };
  1023. // Hyperscript helper functions
  1024. var same = function (vnode1, vnode2) {
  1025. if (vnode1.vnodeSelector !== vnode2.vnodeSelector) {
  1026. return false;
  1027. }
  1028. if (vnode1.properties && vnode2.properties) {
  1029. if (vnode1.properties.key !== vnode2.properties.key) {
  1030. return false;
  1031. }
  1032. return vnode1.properties.bind === vnode2.properties.bind;
  1033. }
  1034. return !vnode1.properties && !vnode2.properties;
  1035. };
  1036. var toTextVNode = function (data) {
  1037. return {
  1038. vnodeSelector: '',
  1039. properties: undefined,
  1040. children: undefined,
  1041. text: data.toString(),
  1042. domNode: null
  1043. };
  1044. };
  1045. var appendChildren = function (parentSelector, insertions, main) {
  1046. for (var i = 0; i < insertions.length; i++) {
  1047. var item = insertions[i];
  1048. if (Array.isArray(item)) {
  1049. appendChildren(parentSelector, item, main);
  1050. } else {
  1051. if (item !== null && item !== undefined) {
  1052. if (!item.hasOwnProperty('vnodeSelector')) {
  1053. item = toTextVNode(item);
  1054. }
  1055. main.push(item);
  1056. }
  1057. }
  1058. }
  1059. };
  1060. // Render helper functions
  1061. var missingTransition = function () {
  1062. throw new Error('Provide a transitions object to the projectionOptions to do animations');
  1063. };
  1064. var DEFAULT_PROJECTION_OPTIONS = {
  1065. namespace: undefined,
  1066. eventHandlerInterceptor: undefined,
  1067. styleApplyer: function (domNode, styleName, value) {
  1068. // Provides a hook to add vendor prefixes for browsers that still need it.
  1069. domNode.style[styleName] = value;
  1070. },
  1071. transitions: {
  1072. enter: missingTransition,
  1073. exit: missingTransition
  1074. }
  1075. };
  1076. var applyDefaultProjectionOptions = function (projectorOptions) {
  1077. return extend(DEFAULT_PROJECTION_OPTIONS, projectorOptions);
  1078. };
  1079. var checkStyleValue = function (styleValue) {
  1080. if (typeof styleValue !== 'string') {
  1081. throw new Error('Style values must be strings');
  1082. }
  1083. };
  1084. var setProperties = function (domNode, properties, projectionOptions) {
  1085. if (!properties) {
  1086. return;
  1087. }
  1088. var eventHandlerInterceptor = projectionOptions.eventHandlerInterceptor;
  1089. var propNames = Object.keys(properties);
  1090. var propCount = propNames.length;
  1091. for (var i = 0; i < propCount; i++) {
  1092. var propName = propNames[i];
  1093. /* tslint:disable:no-var-keyword: edge case */
  1094. var propValue = properties[propName];
  1095. /* tslint:enable:no-var-keyword */
  1096. if (propName === 'className') {
  1097. throw new Error('Property "className" is not supported, use "class".');
  1098. } else if (propName === 'class') {
  1099. if (domNode.className) {
  1100. // May happen if classes is specified before class
  1101. domNode.className += ' ' + propValue;
  1102. } else {
  1103. domNode.className = propValue;
  1104. }
  1105. } else if (propName === 'classes') {
  1106. // object with string keys and boolean values
  1107. var classNames = Object.keys(propValue);
  1108. var classNameCount = classNames.length;
  1109. for (var j = 0; j < classNameCount; j++) {
  1110. var className = classNames[j];
  1111. if (propValue[className]) {
  1112. domNode.classList.add(className);
  1113. }
  1114. }
  1115. } else if (propName === 'styles') {
  1116. // object with string keys and string (!) values
  1117. var styleNames = Object.keys(propValue);
  1118. var styleCount = styleNames.length;
  1119. for (var j = 0; j < styleCount; j++) {
  1120. var styleName = styleNames[j];
  1121. var styleValue = propValue[styleName];
  1122. if (styleValue) {
  1123. checkStyleValue(styleValue);
  1124. projectionOptions.styleApplyer(domNode, styleName, styleValue);
  1125. }
  1126. }
  1127. } else if (propName === 'key') {
  1128. continue;
  1129. } else if (propValue === null || propValue === undefined) {
  1130. continue;
  1131. } else {
  1132. var type = typeof propValue;
  1133. if (type === 'function') {
  1134. if (propName.lastIndexOf('on', 0) === 0) {
  1135. if (eventHandlerInterceptor) {
  1136. propValue = eventHandlerInterceptor(propName, propValue, domNode, properties); // intercept eventhandlers
  1137. }
  1138. if (propName === 'oninput') {
  1139. (function () {
  1140. // record the evt.target.value, because IE and Edge sometimes do a requestAnimationFrame between changing value and running oninput
  1141. var oldPropValue = propValue;
  1142. propValue = function (evt) {
  1143. evt.target['oninput-value'] = evt.target.value;
  1144. // may be HTMLTextAreaElement as well
  1145. oldPropValue.apply(this, [evt]);
  1146. };
  1147. }());
  1148. }
  1149. domNode[propName] = propValue;
  1150. }
  1151. } else if (type === 'string' && propName !== 'value' && propName !== 'innerHTML') {
  1152. if (projectionOptions.namespace === NAMESPACE_SVG && propName === 'href') {
  1153. domNode.setAttributeNS(NAMESPACE_XLINK, propName, propValue);
  1154. } else {
  1155. domNode.setAttribute(propName, propValue);
  1156. }
  1157. } else {
  1158. domNode[propName] = propValue;
  1159. }
  1160. }
  1161. }
  1162. };
  1163. var updateProperties = function (domNode, previousProperties, properties, projectionOptions) {
  1164. if (!properties) {
  1165. return;
  1166. }
  1167. var propertiesUpdated = false;
  1168. var propNames = Object.keys(properties);
  1169. var propCount = propNames.length;
  1170. for (var i = 0; i < propCount; i++) {
  1171. var propName = propNames[i];
  1172. // assuming that properties will be nullified instead of missing is by design
  1173. var propValue = properties[propName];
  1174. var previousValue = previousProperties[propName];
  1175. if (propName === 'class') {
  1176. if (previousValue !== propValue) {
  1177. throw new Error('"class" property may not be updated. Use the "classes" property for conditional css classes.');
  1178. }
  1179. } else if (propName === 'classes') {
  1180. var classList = domNode.classList;
  1181. var classNames = Object.keys(propValue);
  1182. var classNameCount = classNames.length;
  1183. for (var j = 0; j < classNameCount; j++) {
  1184. var className = classNames[j];
  1185. var on = !!propValue[className];
  1186. var previousOn = !!previousValue[className];
  1187. if (on === previousOn) {
  1188. continue;
  1189. }
  1190. propertiesUpdated = true;
  1191. if (on) {
  1192. classList.add(className);
  1193. } else {
  1194. classList.remove(className);
  1195. }
  1196. }
  1197. } else if (propName === 'styles') {
  1198. var styleNames = Object.keys(propValue);
  1199. var styleCount = styleNames.length;
  1200. for (var j = 0; j < styleCount; j++) {
  1201. var styleName = styleNames[j];
  1202. var newStyleValue = propValue[styleName];
  1203. var oldStyleValue = previousValue[styleName];
  1204. if (newStyleValue === oldStyleValue) {
  1205. continue;
  1206. }
  1207. propertiesUpdated = true;
  1208. if (newStyleValue) {
  1209. checkStyleValue(newStyleValue);
  1210. projectionOptions.styleApplyer(domNode, styleName, newStyleValue);
  1211. } else {
  1212. projectionOptions.styleApplyer(domNode, styleName, '');
  1213. }
  1214. }
  1215. } else {
  1216. if (!propValue && typeof previousValue === 'string') {
  1217. propValue = '';
  1218. }
  1219. if (propName === 'value') {
  1220. if (domNode[propName] !== propValue && domNode['oninput-value'] !== propValue) {
  1221. domNode[propName] = propValue;
  1222. // Reset the value, even if the virtual DOM did not change
  1223. domNode['oninput-value'] = undefined;
  1224. }
  1225. // else do not update the domNode, otherwise the cursor position would be changed
  1226. if (propValue !== previousValue) {
  1227. propertiesUpdated = true;
  1228. }
  1229. } else if (propValue !== previousValue) {
  1230. var type = typeof propValue;
  1231. if (type === 'function') {
  1232. throw new Error('Functions may not be updated on subsequent renders (property: ' + propName + '). Hint: declare event handler functions outside the render() function.');
  1233. }
  1234. if (type === 'string' && propName !== 'innerHTML') {
  1235. if (projectionOptions.namespace === NAMESPACE_SVG && propName === 'href') {
  1236. domNode.setAttributeNS(NAMESPACE_XLINK, propName, propValue);
  1237. } else {
  1238. domNode.setAttribute(propName, propValue);
  1239. }
  1240. } else {
  1241. if (domNode[propName] !== propValue) {
  1242. domNode[propName] = propValue;
  1243. }
  1244. }
  1245. propertiesUpdated = true;
  1246. }
  1247. }
  1248. }
  1249. return propertiesUpdated;
  1250. };
  1251. var findIndexOfChild = function (children, sameAs, start) {
  1252. if (sameAs.vnodeSelector !== '') {
  1253. // Never scan for text-nodes
  1254. for (var i = start; i < children.length; i++) {
  1255. if (same(children[i], sameAs)) {
  1256. return i;
  1257. }
  1258. }
  1259. }
  1260. return -1;
  1261. };
  1262. var nodeAdded = function (vNode, transitions) {
  1263. if (vNode.properties) {
  1264. var enterAnimation = vNode.properties.enterAnimation;
  1265. if (enterAnimation) {
  1266. if (typeof enterAnimation === 'function') {
  1267. enterAnimation(vNode.domNode, vNode.properties);
  1268. } else {
  1269. transitions.enter(vNode.domNode, vNode.properties, enterAnimation);
  1270. }
  1271. }
  1272. }
  1273. };
  1274. var nodeToRemove = function (vNode, transitions) {
  1275. var domNode = vNode.domNode;
  1276. if (vNode.properties) {
  1277. var exitAnimation = vNode.properties.exitAnimation;
  1278. if (exitAnimation) {
  1279. domNode.style.pointerEvents = 'none';
  1280. var removeDomNode = function () {
  1281. if (domNode.parentNode) {
  1282. domNode.parentNode.removeChild(domNode);
  1283. }
  1284. };
  1285. if (typeof exitAnimation === 'function') {
  1286. exitAnimation(domNode, removeDomNode, vNode.properties);
  1287. return;
  1288. } else {
  1289. transitions.exit(vNode.domNode, vNode.properties, exitAnimation, removeDomNode);
  1290. return;
  1291. }
  1292. }
  1293. }
  1294. if (domNode.parentNode) {
  1295. domNode.parentNode.removeChild(domNode);
  1296. }
  1297. };
  1298. var checkDistinguishable = function (childNodes, indexToCheck, parentVNode, operation) {
  1299. var childNode = childNodes[indexToCheck];
  1300. if (childNode.vnodeSelector === '') {
  1301. return; // Text nodes need not be distinguishable
  1302. }
  1303. var properties = childNode.properties;
  1304. var key = properties ? properties.key === undefined ? properties.bind : properties.key : undefined;
  1305. if (!key) {
  1306. for (var i = 0; i < childNodes.length; i++) {
  1307. if (i !== indexToCheck) {
  1308. var node = childNodes[i];
  1309. if (same(node, childNode)) {
  1310. if (operation === 'added') {
  1311. throw new Error(parentVNode.vnodeSelector + ' had a ' + childNode.vnodeSelector + ' child ' + 'added, but there is now more than one. You must add unique key properties to make them distinguishable.');
  1312. } else {
  1313. throw new Error(parentVNode.vnodeSelector + ' had a ' + childNode.vnodeSelector + ' child ' + 'removed, but there were more than one. You must add unique key properties to make them distinguishable.');
  1314. }
  1315. }
  1316. }
  1317. }
  1318. }
  1319. };
  1320. var createDom;
  1321. var updateDom;
  1322. var updateChildren = function (vnode, domNode, oldChildren, newChildren, projectionOptions) {
  1323. if (oldChildren === newChildren) {
  1324. return false;
  1325. }
  1326. oldChildren = oldChildren || emptyArray;
  1327. newChildren = newChildren || emptyArray;
  1328. var oldChildrenLength = oldChildren.length;
  1329. var newChildrenLength = newChildren.length;
  1330. var transitions = projectionOptions.transitions;
  1331. var oldIndex = 0;
  1332. var newIndex = 0;
  1333. var i;
  1334. var textUpdated = false;
  1335. while (newIndex < newChildrenLength) {
  1336. var oldChild = oldIndex < oldChildrenLength ? oldChildren[oldIndex] : undefined;
  1337. var newChild = newChildren[newIndex];
  1338. if (oldChild !== undefined && same(oldChild, newChild)) {
  1339. textUpdated = updateDom(oldChild, newChild, projectionOptions) || textUpdated;
  1340. oldIndex++;
  1341. } else {
  1342. var findOldIndex = findIndexOfChild(oldChildren, newChild, oldIndex + 1);
  1343. if (findOldIndex >= 0) {
  1344. // Remove preceding missing children
  1345. for (i = oldIndex; i < findOldIndex; i++) {
  1346. nodeToRemove(oldChildren[i], transitions);
  1347. checkDistinguishable(oldChildren, i, vnode, 'removed');
  1348. }
  1349. textUpdated = updateDom(oldChildren[findOldIndex], newChild, projectionOptions) || textUpdated;
  1350. oldIndex = findOldIndex + 1;
  1351. } else {
  1352. // New child
  1353. createDom(newChild, domNode, oldIndex < oldChildrenLength ? oldChildren[oldIndex].domNode : undefined, projectionOptions);
  1354. nodeAdded(newChild, transitions);
  1355. checkDistinguishable(newChildren, newIndex, vnode, 'added');
  1356. }
  1357. }
  1358. newIndex++;
  1359. }
  1360. if (oldChildrenLength > oldIndex) {
  1361. // Remove child fragments
  1362. for (i = oldIndex; i < oldChildrenLength; i++) {
  1363. nodeToRemove(oldChildren[i], transitions);
  1364. checkDistinguishable(oldChildren, i, vnode, 'removed');
  1365. }
  1366. }
  1367. return textUpdated;
  1368. };
  1369. var addChildren = function (domNode, children, projectionOptions) {
  1370. if (!children) {
  1371. return;
  1372. }
  1373. for (var i = 0; i < children.length; i++) {
  1374. createDom(children[i], domNode, undefined, projectionOptions);
  1375. }
  1376. };
  1377. var initPropertiesAndChildren = function (domNode, vnode, projectionOptions) {
  1378. addChildren(domNode, vnode.children, projectionOptions);
  1379. // children before properties, needed for value property of <select>.
  1380. if (vnode.text) {
  1381. domNode.textContent = vnode.text;
  1382. }
  1383. setProperties(domNode, vnode.properties, projectionOptions);
  1384. if (vnode.properties && vnode.properties.afterCreate) {
  1385. vnode.properties.afterCreate(domNode, projectionOptions, vnode.vnodeSelector, vnode.properties, vnode.children);
  1386. }
  1387. };
  1388. createDom = function (vnode, parentNode, insertBefore, projectionOptions) {
  1389. var domNode, i, c, start = 0, type, found;
  1390. var vnodeSelector = vnode.vnodeSelector;
  1391. if (vnodeSelector === '') {
  1392. domNode = vnode.domNode = document.createTextNode(vnode.text);
  1393. if (insertBefore !== undefined) {
  1394. parentNode.insertBefore(domNode, insertBefore);
  1395. } else {
  1396. parentNode.appendChild(domNode);
  1397. }
  1398. } else {
  1399. for (i = 0; i <= vnodeSelector.length; ++i) {
  1400. c = vnodeSelector.charAt(i);
  1401. if (i === vnodeSelector.length || c === '.' || c === '#') {
  1402. type = vnodeSelector.charAt(start - 1);
  1403. found = vnodeSelector.slice(start, i);
  1404. if (type === '.') {
  1405. domNode.classList.add(found);
  1406. } else if (type === '#') {
  1407. domNode.id = found;
  1408. } else {
  1409. if (found === 'svg') {
  1410. projectionOptions = extend(projectionOptions, { namespace: NAMESPACE_SVG });
  1411. }
  1412. if (projectionOptions.namespace !== undefined) {
  1413. domNode = vnode.domNode = document.createElementNS(projectionOptions.namespace, found);
  1414. } else {
  1415. domNode = vnode.domNode = document.createElement(found);
  1416. }
  1417. if (insertBefore !== undefined) {
  1418. parentNode.insertBefore(domNode, insertBefore);
  1419. } else {
  1420. parentNode.appendChild(domNode);
  1421. }
  1422. }
  1423. start = i + 1;
  1424. }
  1425. }
  1426. initPropertiesAndChildren(domNode, vnode, projectionOptions);
  1427. }
  1428. };
  1429. updateDom = function (previous, vnode, projectionOptions) {
  1430. var domNode = previous.domNode;
  1431. var textUpdated = false;
  1432. if (previous === vnode) {
  1433. return false; // By contract, VNode objects may not be modified anymore after passing them to maquette
  1434. }
  1435. var updated = false;
  1436. if (vnode.vnodeSelector === '') {
  1437. if (vnode.text !== previous.text) {
  1438. var newVNode = document.createTextNode(vnode.text);
  1439. domNode.parentNode.replaceChild(newVNode, domNode);
  1440. vnode.domNode = newVNode;
  1441. textUpdated = true;
  1442. return textUpdated;
  1443. }
  1444. } else {
  1445. if (vnode.vnodeSelector.lastIndexOf('svg', 0) === 0) {
  1446. projectionOptions = extend(projectionOptions, { namespace: NAMESPACE_SVG });
  1447. }
  1448. if (previous.text !== vnode.text) {
  1449. updated = true;
  1450. if (vnode.text === undefined) {
  1451. domNode.removeChild(domNode.firstChild); // the only textnode presumably
  1452. } else {
  1453. domNode.textContent = vnode.text;
  1454. }
  1455. }
  1456. updated = updateChildren(vnode, domNode, previous.children, vnode.children, projectionOptions) || updated;
  1457. updated = updateProperties(domNode, previous.properties, vnode.properties, projectionOptions) || updated;
  1458. if (vnode.properties && vnode.properties.afterUpdate) {
  1459. vnode.properties.afterUpdate(domNode, projectionOptions, vnode.vnodeSelector, vnode.properties, vnode.children);
  1460. }
  1461. }
  1462. if (updated && vnode.properties && vnode.properties.updateAnimation) {
  1463. vnode.properties.updateAnimation(domNode, vnode.properties, previous.properties);
  1464. }
  1465. vnode.domNode = previous.domNode;
  1466. return textUpdated;
  1467. };
  1468. var createProjection = function (vnode, projectionOptions) {
  1469. return {
  1470. update: function (updatedVnode) {
  1471. if (vnode.vnodeSelector !== updatedVnode.vnodeSelector) {
  1472. throw new Error('The selector for the root VNode may not be changed. (consider using dom.merge and add one extra level to the virtual DOM)');
  1473. }
  1474. updateDom(vnode, updatedVnode, projectionOptions);
  1475. vnode = updatedVnode;
  1476. },
  1477. domNode: vnode.domNode
  1478. };
  1479. };
  1480. ;
  1481. // The other two parameters are not added here, because the Typescript compiler creates surrogate code for desctructuring 'children'.
  1482. exports.h = function (selector) {
  1483. var properties = arguments[1];
  1484. if (typeof selector !== 'string') {
  1485. throw new Error();
  1486. }
  1487. var childIndex = 1;
  1488. if (properties && !properties.hasOwnProperty('vnodeSelector') && !Array.isArray(properties) && typeof properties === 'object') {
  1489. childIndex = 2;
  1490. } else {
  1491. // Optional properties argument was omitted
  1492. properties = undefined;
  1493. }
  1494. var text = undefined;
  1495. var children = undefined;
  1496. var argsLength = arguments.length;
  1497. // Recognize a common special case where there is only a single text node
  1498. if (argsLength === childIndex + 1) {
  1499. var onlyChild = arguments[childIndex];
  1500. if (typeof onlyChild === 'string') {
  1501. text = onlyChild;
  1502. } else if (onlyChild !== undefined && onlyChild.length === 1 && typeof onlyChild[0] === 'string') {
  1503. text = onlyChild[0];
  1504. }
  1505. }
  1506. if (text === undefined) {
  1507. children = [];
  1508. for (; childIndex < arguments.length; childIndex++) {
  1509. var child = arguments[childIndex];
  1510. if (child === null || child === undefined) {
  1511. continue;
  1512. } else if (Array.isArray(child)) {
  1513. appendChildren(selector, child, children);
  1514. } else if (child.hasOwnProperty('vnodeSelector')) {
  1515. children.push(child);
  1516. } else {
  1517. children.push(toTextVNode(child));
  1518. }
  1519. }
  1520. }
  1521. return {
  1522. vnodeSelector: selector,
  1523. properties: properties,
  1524. children: children,
  1525. text: text === '' ? undefined : text,
  1526. domNode: null
  1527. };
  1528. };
  1529. /**
  1530. * Contains simple low-level utility functions to manipulate the real DOM.
  1531. */
  1532. exports.dom = {
  1533. /**
  1534. * Creates a real DOM tree from `vnode`. The [[Projection]] object returned will contain the resulting DOM Node in
  1535. * its [[Projection.domNode|domNode]] property.
  1536. * This is a low-level method. Users wil typically use a [[Projector]] instead.
  1537. * @param vnode - The root of the virtual DOM tree that was created using the [[h]] function. NOTE: [[VNode]]
  1538. * objects may only be rendered once.
  1539. * @param projectionOptions - Options to be used to create and update the projection.
  1540. * @returns The [[Projection]] which also contains the DOM Node that was created.
  1541. */
  1542. create: function (vnode, projectionOptions) {
  1543. projectionOptions = applyDefaultProjectionOptions(projectionOptions);
  1544. createDom(vnode, document.createElement('div'), undefined, projectionOptions);
  1545. return createProjection(vnode, projectionOptions);
  1546. },
  1547. /**
  1548. * Appends a new childnode to the DOM which is generated from a [[VNode]].
  1549. * This is a low-level method. Users wil typically use a [[Projector]] instead.
  1550. * @param parentNode - The parent node for the new childNode.
  1551. * @param vnode - The root of the virtual DOM tree that was created using the [[h]] function. NOTE: [[VNode]]
  1552. * objects may only be rendered once.
  1553. * @param projectionOptions - Options to be used to create and update the [[Projection]].
  1554. * @returns The [[Projection]] that was created.
  1555. */
  1556. append: function (parentNode, vnode, projectionOptions) {
  1557. projectionOptions = applyDefaultProjectionOptions(projectionOptions);
  1558. createDom(vnode, parentNode, undefined, projectionOptions);
  1559. return createProjection(vnode, projectionOptions);
  1560. },
  1561. /**
  1562. * Inserts a new DOM node which is generated from a [[VNode]].
  1563. * This is a low-level method. Users wil typically use a [[Projector]] instead.
  1564. * @param beforeNode - The node that the DOM Node is inserted before.
  1565. * @param vnode - The root of the virtual DOM tree that was created using the [[h]] function.
  1566. * NOTE: [[VNode]] objects may only be rendered once.
  1567. * @param projectionOptions - Options to be used to create and update the projection, see [[createProjector]].
  1568. * @returns The [[Projection]] that was created.
  1569. */
  1570. insertBefore: function (beforeNode, vnode, projectionOptions) {
  1571. projectionOptions = applyDefaultProjectionOptions(projectionOptions);
  1572. createDom(vnode, beforeNode.parentNode, beforeNode, projectionOptions);
  1573. return createProjection(vnode, projectionOptions);
  1574. },
  1575. /**
  1576. * Merges a new DOM node which is generated from a [[VNode]] with an existing DOM Node.
  1577. * This means that the virtual DOM and the real DOM will have one overlapping element.
  1578. * Therefore the selector for the root [[VNode]] will be ignored, but its properties and children will be applied to the Element provided.
  1579. * This is a low-level method. Users wil typically use a [[Projector]] instead.
  1580. * @param domNode - The existing element to adopt as the root of the new virtual DOM. Existing attributes and childnodes are preserved.
  1581. * @param vnode - The root of the virtual DOM tree that was created using the [[h]] function. NOTE: [[VNode]] objects
  1582. * may only be rendered once.
  1583. * @param projectionOptions - Options to be used to create and update the projection, see [[createProjector]].
  1584. * @returns The [[Projection]] that was created.
  1585. */
  1586. merge: function (element, vnode, projectionOptions) {
  1587. projectionOptions = applyDefaultProjectionOptions(projectionOptions);
  1588. vnode.domNode = element;
  1589. initPropertiesAndChildren(element, vnode, projectionOptions);
  1590. return createProjection(vnode, projectionOptions);
  1591. }
  1592. };
  1593. /**
  1594. * Creates a [[CalculationCache]] object, useful for caching [[VNode]] trees.
  1595. * In practice, caching of [[VNode]] trees is not needed, because achieving 60 frames per second is almost never a problem.
  1596. * For more information, see [[CalculationCache]].
  1597. *
  1598. * @param <Result> The type of the value that is cached.
  1599. */
  1600. exports.createCache = function () {
  1601. var cachedInputs = undefined;
  1602. var cachedOutcome = undefined;
  1603. var result = {
  1604. invalidate: function () {
  1605. cachedOutcome = undefined;
  1606. cachedInputs = undefined;
  1607. },
  1608. result: function (inputs, calculation) {
  1609. if (cachedInputs) {
  1610. for (var i = 0; i < inputs.length; i++) {
  1611. if (cachedInputs[i] !== inputs[i]) {
  1612. cachedOutcome = undefined;
  1613. }
  1614. }
  1615. }
  1616. if (!cachedOutcome) {
  1617. cachedOutcome = calculation();
  1618. cachedInputs = inputs;
  1619. }
  1620. return cachedOutcome;
  1621. }
  1622. };
  1623. return result;
  1624. };
  1625. /**
  1626. * Creates a {@link Mapping} instance that keeps an array of result objects synchronized with an array of source objects.
  1627. * See {@link http://maquettejs.org/docs/arrays.html|Working with arrays}.
  1628. *
  1629. * @param <Source> The type of source items. A database-record for instance.
  1630. * @param <Target> The type of target items. A [[Component]] for instance.
  1631. * @param getSourceKey `function(source)` that must return a key to identify each source object. The result must either be a string or a number.
  1632. * @param createResult `function(source, index)` that must create a new result object from a given source. This function is identical
  1633. * to the `callback` argument in `Array.map(callback)`.
  1634. * @param updateResult `function(source, target, index)` that updates a result to an updated source.
  1635. */
  1636. exports.createMapping = function (getSourceKey, createResult, updateResult) {
  1637. var keys = [];
  1638. var results = [];
  1639. return {
  1640. results: results,
  1641. map: function (newSources) {
  1642. var newKeys = newSources.map(getSourceKey);
  1643. var oldTargets = results.slice();
  1644. var oldIndex = 0;
  1645. for (var i = 0; i < newSources.length; i++) {
  1646. var source = newSources[i];
  1647. var sourceKey = newKeys[i];
  1648. if (sourceKey === keys[oldIndex]) {
  1649. results[i] = oldTargets[oldIndex];
  1650. updateResult(source, oldTargets[oldIndex], i);
  1651. oldIndex++;
  1652. } else {
  1653. var found = false;
  1654. for (var j = 1; j < keys.length; j++) {
  1655. var searchIndex = (oldIndex + j) % keys.length;
  1656. if (keys[searchIndex] === sourceKey) {
  1657. results[i] = oldTargets[searchIndex];
  1658. updateResult(newSources[i], oldTargets[searchIndex], i);
  1659. oldIndex = searchIndex + 1;
  1660. found = true;
  1661. break;
  1662. }
  1663. }
  1664. if (!found) {
  1665. results[i] = createResult(source, i);
  1666. }
  1667. }
  1668. }
  1669. results.length = newSources.length;
  1670. keys = newKeys;
  1671. }
  1672. };
  1673. };
  1674. /**
  1675. * Creates a [[Projector]] instance using the provided projectionOptions.
  1676. *
  1677. * For more information, see [[Projector]].
  1678. *
  1679. * @param projectionOptions Options that influence how the DOM is rendered and updated.
  1680. */
  1681. exports.createProjector = function (projectorOptions) {
  1682. var projector;
  1683. var projectionOptions = applyDefaultProjectionOptions(projectorOptions);
  1684. projectionOptions.eventHandlerInterceptor = function (propertyName, eventHandler, domNode, properties) {
  1685. return function () {
  1686. // intercept function calls (event handlers) to do a render afterwards.
  1687. projector.scheduleRender();
  1688. return eventHandler.apply(properties.bind || this, arguments);
  1689. };
  1690. };
  1691. var renderCompleted = true;
  1692. var scheduled;
  1693. var stopped = false;
  1694. var projections = [];
  1695. var renderFunctions = [];
  1696. // matches the projections array
  1697. var doRender = function () {
  1698. scheduled = undefined;
  1699. if (!renderCompleted) {
  1700. return; // The last render threw an error, it should be logged in the browser console.
  1701. }
  1702. renderCompleted = false;
  1703. for (var i = 0; i < projections.length; i++) {
  1704. var updatedVnode = renderFunctions[i]();
  1705. projections[i].update(updatedVnode);
  1706. }
  1707. renderCompleted = true;
  1708. };
  1709. projector = {
  1710. scheduleRender: function () {
  1711. if (!scheduled && !stopped) {
  1712. scheduled = requestAnimationFrame(doRender);
  1713. }
  1714. },
  1715. stop: function () {
  1716. if (scheduled) {
  1717. cancelAnimationFrame(scheduled);
  1718. scheduled = undefined;
  1719. }
  1720. stopped = true;
  1721. },
  1722. resume: function () {
  1723. stopped = false;
  1724. renderCompleted = true;
  1725. projector.scheduleRender();
  1726. },
  1727. append: function (parentNode, renderMaquetteFunction) {
  1728. projections.push(exports.dom.append(parentNode, renderMaquetteFunction(), projectionOptions));
  1729. renderFunctions.push(renderMaquetteFunction);
  1730. },
  1731. insertBefore: function (beforeNode, renderMaquetteFunction) {
  1732. projections.push(exports.dom.insertBefore(beforeNode, renderMaquetteFunction(), projectionOptions));
  1733. renderFunctions.push(renderMaquetteFunction);
  1734. },
  1735. merge: function (domNode, renderMaquetteFunction) {
  1736. projections.push(exports.dom.merge(domNode, renderMaquetteFunction(), projectionOptions));
  1737. renderFunctions.push(renderMaquetteFunction);
  1738. },
  1739. replace: function (domNode, renderMaquetteFunction) {
  1740. var vnode = renderMaquetteFunction();
  1741. createDom(vnode, domNode.parentNode, domNode, projectionOptions);
  1742. domNode.parentNode.removeChild(domNode);
  1743. projections.push(createProjection(vnode, projectionOptions));
  1744. renderFunctions.push(renderMaquetteFunction);
  1745. },
  1746. detach: function (renderMaquetteFunction) {
  1747. for (var i = 0; i < renderFunctions.length; i++) {
  1748. if (renderFunctions[i] === renderMaquetteFunction) {
  1749. renderFunctions.splice(i, 1);
  1750. return projections.splice(i, 1)[0];
  1751. }
  1752. }
  1753. throw new Error('renderMaquetteFunction was not found');
  1754. }
  1755. };
  1756. return projector;
  1757. };
  1758. }));
  1759. /* ---- Config.coffee ---- */
  1760. (function() {
  1761. window.BINARY_EXTENSIONS = ["3dm", "3ds", "3g2", "3gp", "7z", "a", "aac", "adp", "ai", "aif", "aiff", "alz", "ape", "apk", "appimage", "ar", "arj", "asc", "asf", "au", "avi", "bak", "baml", "bh", "bin", "bk", "bmp", "btif", "bz2", "bzip2", "cab", "caf", "cgm", "class", "cmx", "cpio", "cr2", "cur", "dat", "dcm", "deb", "dex", "djvu", "dll", "dmg", "dng", "doc", "docm", "docx", "dot", "dotm", "dra", "DS_Store", "dsk", "dts", "dtshd", "dvb", "dwg", "dxf", "ecelp4800", "ecelp7470", "ecelp9600", "egg", "eol", "eot", "epub", "exe", "f4v", "fbs", "fh", "fla", "flac", "flatpak", "fli", "flv", "fpx", "fst", "fvt", "g3", "gh", "gif", "gpg", "graffle", "gz", "gzip", "h261", "h263", "h264", "icns", "ico", "ief", "img", "ipa", "iso", "jar", "jpeg", "jpg", "jpgv", "jpm", "jxr", "key", "ktx", "lha", "lib", "lvp", "lz", "lzh", "lzma", "lzo", "m3u", "m4a", "m4v", "mar", "mdi", "mht", "mid", "midi", "mj2", "mka", "mkv", "mmr", "mng", "mobi", "mov", "movie", "mp3", "mp4", "mp4a", "mpeg", "mpg", "mpga", "msgpack", "mxu", "nef", "npx", "numbers", "nupkg", "o", "oga", "ogg", "ogv", "otf", "pages", "pbm", "pcx", "pdb", "pdf", "pea", "pgm", "pic", "png", "pnm", "pot", "potm", "potx", "ppa", "ppam", "ppm", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx", "psd", "pya", "pyc", "pyo", "pyv", "qt", "rar", "ras", "raw", "resources", "rgb", "rip", "rlc", "rmf", "rmvb", "rpm", "rtf", "rz", "s3m", "s7z", "scpt", "sgi", "shar", "sig", "sil", "sketch", "slk", "smv", "snap", "snk", "so", "stl", "sub", "suo", "swf", "tar", "tbz2", "tbz", "tga", "tgz", "thmx", "tif", "tiff", "tlz", "ttc", "ttf", "txz", "udf", "uvh", "uvi", "uvm", "uvp", "uvs", "uvu", "viv", "vob", "war", "wav", "wax", "wbmp", "wdp", "weba", "webm", "webp", "whl", "wim", "wm", "wma", "wmv", "wmx", "woff2", "woff", "wrm", "wvx", "xbm", "xif", "xla", "xlam", "xls", "xlsb", "xlsm", "xlsx", "xlt", "xltm", "xltx", "xm", "xmind", "xpi", "xpm", "xwd", "xz", "z", "zip", "zipx"];
  1762. }).call(this);
  1763. /* ---- FileEditor.coffee ---- */
  1764. (function() {
  1765. var FileEditor,
  1766. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  1767. extend = 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; },
  1768. hasProp = {}.hasOwnProperty;
  1769. FileEditor = (function(superClass) {
  1770. extend(FileEditor, superClass);
  1771. function FileEditor(inner_path1) {
  1772. this.inner_path = inner_path1;
  1773. this.save = bind(this.save, this);
  1774. this.handleSaveClick = bind(this.handleSaveClick, this);
  1775. this.handleSidebarButtonClick = bind(this.handleSidebarButtonClick, this);
  1776. this.foldJson = bind(this.foldJson, this);
  1777. this.storeCmNode = bind(this.storeCmNode, this);
  1778. this.isModified = bind(this.isModified, this);
  1779. this.need_update = true;
  1780. this.on_loaded = new Promise();
  1781. this.is_loading = false;
  1782. this.content = "";
  1783. this.node_cm = null;
  1784. this.cm = null;
  1785. this.error = null;
  1786. this.is_loaded = false;
  1787. this.is_modified = false;
  1788. this.is_saving = false;
  1789. this.mode = "Loading";
  1790. }
  1791. FileEditor.prototype.update = function() {
  1792. var is_required;
  1793. is_required = Page.url_params.get("edit_mode") !== "new";
  1794. return Page.cmd("fileGet", {
  1795. inner_path: this.inner_path,
  1796. required: is_required
  1797. }, (function(_this) {
  1798. return function(res) {
  1799. if (res != null ? res.error : void 0) {
  1800. _this.error = res.error;
  1801. _this.content = res.error;
  1802. _this.log("Error loading: " + _this.error);
  1803. } else {
  1804. if (res) {
  1805. _this.content = res;
  1806. } else {
  1807. _this.content = "";
  1808. _this.mode = "Create";
  1809. }
  1810. }
  1811. if (!_this.content) {
  1812. _this.cm.getDoc().clearHistory();
  1813. }
  1814. _this.cm.setValue(_this.content);
  1815. if (!_this.error) {
  1816. _this.is_loaded = true;
  1817. }
  1818. return Page.projector.scheduleRender();
  1819. };
  1820. })(this));
  1821. };
  1822. FileEditor.prototype.isModified = function() {
  1823. return this.content !== this.cm.getValue();
  1824. };
  1825. FileEditor.prototype.storeCmNode = function(node) {
  1826. return this.node_cm = node;
  1827. };
  1828. FileEditor.prototype.getMode = function(inner_path) {
  1829. var ext, types;
  1830. ext = inner_path.split(".").pop();
  1831. types = {
  1832. "py": "python",
  1833. "json": "application/json",
  1834. "js": "javascript",
  1835. "coffee": "coffeescript",
  1836. "html": "htmlmixed",
  1837. "htm": "htmlmixed",
  1838. "php": "htmlmixed",
  1839. "rs": "rust",
  1840. "css": "css",
  1841. "md": "markdown",
  1842. "xml": "xml",
  1843. "svg": "xml"
  1844. };
  1845. return types[ext];
  1846. };
  1847. FileEditor.prototype.foldJson = function(from, to) {
  1848. var count, e, endToken, internal, parsed, prevLine, startToken, toParse;
  1849. this.log("foldJson", from, to);
  1850. startToken = '{';
  1851. endToken = '}';
  1852. prevLine = this.cm.getLine(from.line);
  1853. if (prevLine.lastIndexOf('[') > prevLine.lastIndexOf('{')) {
  1854. startToken = '[';
  1855. endToken = ']';
  1856. }
  1857. internal = this.cm.getRange(from, to);
  1858. toParse = startToken + internal + endToken;
  1859. try {
  1860. parsed = JSON.parse(toParse);
  1861. count = Object.keys(parsed).length;
  1862. } catch (error) {
  1863. e = error;
  1864. null;
  1865. }
  1866. if (count) {
  1867. return "\u21A4" + count + "\u21A6";
  1868. } else {
  1869. return "\u2194";
  1870. }
  1871. };
  1872. FileEditor.prototype.createCodeMirror = function() {
  1873. var mode, options;
  1874. mode = this.getMode(this.inner_path);
  1875. this.log("Creating CodeMirror", this.inner_path, mode);
  1876. options = {
  1877. value: "Loading...",
  1878. mode: mode,
  1879. lineNumbers: true,
  1880. styleActiveLine: true,
  1881. matchBrackets: true,
  1882. keyMap: "sublime",
  1883. theme: "mdn-like",
  1884. extraKeys: {
  1885. "Ctrl-Space": "autocomplete"
  1886. },
  1887. foldGutter: true,
  1888. gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"]
  1889. };
  1890. if (mode === "application/json") {
  1891. options.gutters.unshift("CodeMirror-lint-markers");
  1892. options.lint = true;
  1893. options.foldOptions = {
  1894. widget: this.foldJson
  1895. };
  1896. }
  1897. this.cm = CodeMirror(this.node_cm, options);
  1898. return this.cm.on("changes", (function(_this) {
  1899. return function(changes) {
  1900. if (_this.is_loaded && !_this.is_modified) {
  1901. _this.is_modified = true;
  1902. return Page.projector.scheduleRender();
  1903. }
  1904. };
  1905. })(this));
  1906. };
  1907. FileEditor.prototype.loadEditor = function() {
  1908. var script;
  1909. if (!this.is_loading) {
  1910. document.getElementsByTagName("head")[0].insertAdjacentHTML("beforeend", "<link rel=\"stylesheet\" href=\"codemirror/all.css\" />");
  1911. script = document.createElement('script');
  1912. script.src = "codemirror/all.js";
  1913. script.onload = (function(_this) {
  1914. return function() {
  1915. _this.createCodeMirror();
  1916. return _this.on_loaded.resolve();
  1917. };
  1918. })(this);
  1919. document.head.appendChild(script);
  1920. }
  1921. return this.on_loaded;
  1922. };
  1923. FileEditor.prototype.handleSidebarButtonClick = function() {
  1924. Page.is_sidebar_closed = !Page.is_sidebar_closed;
  1925. return false;
  1926. };
  1927. FileEditor.prototype.handleSaveClick = function() {
  1928. var mark, num_errors;
  1929. num_errors = ((function() {
  1930. var i, len, ref, results;
  1931. ref = Page.file_editor.cm.getAllMarks();
  1932. results = [];
  1933. for (i = 0, len = ref.length; i < len; i++) {
  1934. mark = ref[i];
  1935. if (mark.className === "CodeMirror-lint-mark-error") {
  1936. results.push(mark);
  1937. }
  1938. }
  1939. return results;
  1940. })()).length;
  1941. if (num_errors > 0) {
  1942. Page.cmd("wrapperConfirm", ["<b>Warning:</b> The file looks invalid.", "Save anyway"], this.save);
  1943. } else {
  1944. this.save();
  1945. }
  1946. return false;
  1947. };
  1948. FileEditor.prototype.save = function() {
  1949. Page.projector.scheduleRender();
  1950. this.is_saving = true;
  1951. return Page.cmd("fileWrite", [this.inner_path, Text.fileEncode(this.cm.getValue())], (function(_this) {
  1952. return function(res) {
  1953. _this.is_saving = false;
  1954. if (res.error) {
  1955. Page.cmd("wrapperNotification", ["error", "Error saving " + res.error]);
  1956. } else {
  1957. _this.is_save_done = true;
  1958. setTimeout((function() {
  1959. _this.is_save_done = false;
  1960. return Page.projector.scheduleRender();
  1961. }), 2000);
  1962. _this.content = _this.cm.getValue();
  1963. _this.is_modified = false;
  1964. if (_this.mode === "Create") {
  1965. _this.mode = "Edit";
  1966. }
  1967. Page.file_list.need_update = true;
  1968. }
  1969. return Page.projector.scheduleRender();
  1970. };
  1971. })(this));
  1972. };
  1973. FileEditor.prototype.render = function() {
  1974. var ref;
  1975. if (this.need_update) {
  1976. this.loadEditor().then((function(_this) {
  1977. return function() {
  1978. return _this.update();
  1979. };
  1980. })(this));
  1981. this.need_update = false;
  1982. }
  1983. return h("div.editor", {
  1984. afterCreate: this.storeCmNode,
  1985. classes: {
  1986. error: this.error,
  1987. loaded: this.is_loaded
  1988. }
  1989. }, [
  1990. h("a.sidebar-button", {
  1991. href: "#Sidebar",
  1992. onclick: this.handleSidebarButtonClick
  1993. }, h("span", "\u2039")), h("div.editor-head", [
  1994. (ref = this.mode) === "Edit" || ref === "Create" ? h("a.save.button", {
  1995. href: "#Save",
  1996. classes: {
  1997. loading: this.is_saving,
  1998. done: this.is_save_done,
  1999. disabled: !this.is_modified
  2000. },
  2001. onclick: this.handleSaveClick
  2002. }, this.is_save_done ? "Save: done!" : "Save") : void 0, h("span.title", this.mode, ": ", this.inner_path)
  2003. ]), this.error ? h("div.error-message", h("h2", "Unable to load the file: " + this.error), h("a", {
  2004. href: Page.file_list.getHref(this.inner_path)
  2005. }, "View in browser")) : void 0
  2006. ]);
  2007. };
  2008. return FileEditor;
  2009. })(Class);
  2010. window.FileEditor = FileEditor;
  2011. }).call(this);
  2012. /* ---- FileItemList.coffee ---- */
  2013. (function() {
  2014. var FileItemList,
  2015. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  2016. extend = 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; },
  2017. hasProp = {}.hasOwnProperty;
  2018. FileItemList = (function(superClass) {
  2019. extend(FileItemList, superClass);
  2020. function FileItemList(inner_path1) {
  2021. this.inner_path = inner_path1;
  2022. this.sort = bind(this.sort, this);
  2023. this.getOptionalInfo = bind(this.getOptionalInfo, this);
  2024. this.hasPermissionDelete = bind(this.hasPermissionDelete, this);
  2025. this.isAdded = bind(this.isAdded, this);
  2026. this.isModified = bind(this.isModified, this);
  2027. this.getFileType = bind(this.getFileType, this);
  2028. this.addOptionalFilesToItems = bind(this.addOptionalFilesToItems, this);
  2029. this.updateOptionalFiles = bind(this.updateOptionalFiles, this);
  2030. this.updateAddedFiles = bind(this.updateAddedFiles, this);
  2031. this.updateModifiedFiles = bind(this.updateModifiedFiles, this);
  2032. this.items = [];
  2033. this.updating = false;
  2034. this.files_modified = {};
  2035. this.dirs_modified = {};
  2036. this.files_added = {};
  2037. this.dirs_added = {};
  2038. this.files_optional = {};
  2039. this.items_by_name = {};
  2040. }
  2041. FileItemList.prototype.update = function(cb) {
  2042. this.updating = true;
  2043. this.logStart("Updating dirlist");
  2044. return Page.cmd("dirList", {
  2045. inner_path: this.inner_path,
  2046. stats: true
  2047. }, (function(_this) {
  2048. return function(res) {
  2049. var i, len, pattern_ignore, ref, ref1, ref2, ref3, row;
  2050. if (res.error) {
  2051. _this.error = res.error;
  2052. } else {
  2053. _this.error = null;
  2054. pattern_ignore = RegExp("^" + ((ref = Page.site_info.content) != null ? ref.ignore : void 0));
  2055. _this.items.splice(0, _this.items.length);
  2056. _this.items_by_name = {};
  2057. for (i = 0, len = res.length; i < len; i++) {
  2058. row = res[i];
  2059. row.type = _this.getFileType(row);
  2060. row.inner_path = _this.inner_path + row.name;
  2061. if (((ref1 = Page.site_info.content) != null ? ref1.ignore : void 0) && row.inner_path.match(pattern_ignore)) {
  2062. row.ignored = true;
  2063. }
  2064. _this.items.push(row);
  2065. _this.items_by_name[row.name] = row;
  2066. }
  2067. _this.sort();
  2068. }
  2069. if ((ref2 = Page.site_info) != null ? (ref3 = ref2.settings) != null ? ref3.own : void 0 : void 0) {
  2070. _this.updateAddedFiles();
  2071. }
  2072. return _this.updateOptionalFiles(function() {
  2073. _this.updating = false;
  2074. if (typeof cb === "function") {
  2075. cb();
  2076. }
  2077. _this.logEnd("Updating dirlist", _this.inner_path);
  2078. Page.projector.scheduleRender();
  2079. return _this.updateModifiedFiles(function() {
  2080. return Page.projector.scheduleRender();
  2081. });
  2082. });
  2083. };
  2084. })(this));
  2085. };
  2086. FileItemList.prototype.updateModifiedFiles = function(cb) {
  2087. return Page.cmd("siteListModifiedFiles", [], (function(_this) {
  2088. return function(res) {
  2089. var dir_inner_path, dir_part, dir_parts, i, inner_path, j, len, len1, ref, ref1;
  2090. _this.files_modified = {};
  2091. _this.dirs_modified = {};
  2092. ref = res.modified_files;
  2093. for (i = 0, len = ref.length; i < len; i++) {
  2094. inner_path = ref[i];
  2095. _this.files_modified[inner_path] = true;
  2096. dir_inner_path = "";
  2097. dir_parts = inner_path.split("/");
  2098. ref1 = dir_parts.slice(0, -1);
  2099. for (j = 0, len1 = ref1.length; j < len1; j++) {
  2100. dir_part = ref1[j];
  2101. if (dir_inner_path) {
  2102. dir_inner_path += "/" + dir_part;
  2103. } else {
  2104. dir_inner_path = dir_part;
  2105. }
  2106. _this.dirs_modified[dir_inner_path] = true;
  2107. }
  2108. }
  2109. return typeof cb === "function" ? cb() : void 0;
  2110. };
  2111. })(this));
  2112. };
  2113. FileItemList.prototype.updateAddedFiles = function() {
  2114. return Page.cmd("fileGet", "content.json", (function(_this) {
  2115. return function(res) {
  2116. var content, dirs_content, file, file_name, i, j, len, len1, match, pattern, ref, ref1, results;
  2117. if (!res) {
  2118. return false;
  2119. }
  2120. content = JSON.parse(res);
  2121. if (content.files == null) {
  2122. return false;
  2123. }
  2124. _this.files_added = {};
  2125. ref = _this.items;
  2126. for (i = 0, len = ref.length; i < len; i++) {
  2127. file = ref[i];
  2128. if (file.name === "content.json" || file.is_dir) {
  2129. continue;
  2130. }
  2131. if (!content.files[_this.inner_path + file.name]) {
  2132. _this.files_added[_this.inner_path + file.name] = true;
  2133. }
  2134. }
  2135. _this.dirs_added = {};
  2136. dirs_content = {};
  2137. for (file_name in Object.assign({}, content.files, content.files_optional)) {
  2138. if (!file_name.startsWith(_this.inner_path)) {
  2139. continue;
  2140. }
  2141. pattern = new RegExp(_this.inner_path + "(.*?)/");
  2142. match = file_name.match(pattern);
  2143. if (!match) {
  2144. continue;
  2145. }
  2146. dirs_content[match[1]] = true;
  2147. }
  2148. ref1 = _this.items;
  2149. results = [];
  2150. for (j = 0, len1 = ref1.length; j < len1; j++) {
  2151. file = ref1[j];
  2152. if (!file.is_dir) {
  2153. continue;
  2154. }
  2155. if (!dirs_content[file.name]) {
  2156. results.push(_this.dirs_added[_this.inner_path + file.name] = true);
  2157. } else {
  2158. results.push(void 0);
  2159. }
  2160. }
  2161. return results;
  2162. };
  2163. })(this));
  2164. };
  2165. FileItemList.prototype.updateOptionalFiles = function(cb) {
  2166. return Page.cmd("optionalFileList", {
  2167. filter: ""
  2168. }, (function(_this) {
  2169. return function(res) {
  2170. var i, len, optional_file;
  2171. _this.files_optional = {};
  2172. for (i = 0, len = res.length; i < len; i++) {
  2173. optional_file = res[i];
  2174. _this.files_optional[optional_file.inner_path] = optional_file;
  2175. }
  2176. _this.addOptionalFilesToItems();
  2177. return typeof cb === "function" ? cb() : void 0;
  2178. };
  2179. })(this));
  2180. };
  2181. FileItemList.prototype.addOptionalFilesToItems = function() {
  2182. var dir_name, file_name, inner_path, is_added, optional_file, ref, ref1, row;
  2183. is_added = false;
  2184. ref = this.files_optional;
  2185. for (inner_path in ref) {
  2186. optional_file = ref[inner_path];
  2187. if (optional_file.inner_path.startsWith(this.inner_path)) {
  2188. if (this.getDirectory(optional_file.inner_path) === this.inner_path) {
  2189. file_name = this.getFileName(optional_file.inner_path);
  2190. if (!this.items_by_name[file_name]) {
  2191. row = {
  2192. "name": file_name,
  2193. "type": "file",
  2194. "optional_empty": true,
  2195. "size": optional_file.size,
  2196. "is_dir": false,
  2197. "inner_path": optional_file.inner_path
  2198. };
  2199. this.items.push(row);
  2200. this.items_by_name[file_name] = row;
  2201. is_added = true;
  2202. }
  2203. } else {
  2204. dir_name = (ref1 = optional_file.inner_path.replace(this.inner_path, "").match(/(.*?)\//, "")) != null ? ref1[1] : void 0;
  2205. if (dir_name && !this.items_by_name[dir_name]) {
  2206. row = {
  2207. "name": dir_name,
  2208. "type": "dir",
  2209. "optional_empty": true,
  2210. "size": 0,
  2211. "is_dir": true,
  2212. "inner_path": optional_file.inner_path
  2213. };
  2214. this.items.push(row);
  2215. this.items_by_name[dir_name] = row;
  2216. is_added = true;
  2217. }
  2218. }
  2219. }
  2220. }
  2221. if (is_added) {
  2222. return this.sort();
  2223. }
  2224. };
  2225. FileItemList.prototype.getFileType = function(file) {
  2226. if (file.is_dir) {
  2227. return "dir";
  2228. } else {
  2229. return "unknown";
  2230. }
  2231. };
  2232. FileItemList.prototype.getDirectory = function(inner_path) {
  2233. if (inner_path.indexOf("/") !== -1) {
  2234. return inner_path.replace(/^(.*\/)(.*?)$/, "$1");
  2235. } else {
  2236. return "";
  2237. }
  2238. };
  2239. FileItemList.prototype.getFileName = function(inner_path) {
  2240. return inner_path.replace(/^(.*\/)(.*?)$/, "$2");
  2241. };
  2242. FileItemList.prototype.isModified = function(inner_path) {
  2243. return this.files_modified[inner_path] || this.dirs_modified[inner_path];
  2244. };
  2245. FileItemList.prototype.isAdded = function(inner_path) {
  2246. return this.files_added[inner_path] || this.dirs_added[inner_path];
  2247. };
  2248. FileItemList.prototype.hasPermissionDelete = function(file) {
  2249. var optional_info, ref, ref1, ref2;
  2250. if ((ref = file.type) === "dir" || ref === "parent") {
  2251. return false;
  2252. }
  2253. if (file.inner_path === "content.json") {
  2254. return false;
  2255. }
  2256. optional_info = this.getOptionalInfo(file.inner_path);
  2257. if (optional_info && optional_info.downloaded_percent > 0) {
  2258. return true;
  2259. } else {
  2260. return (ref1 = Page.site_info) != null ? (ref2 = ref1.settings) != null ? ref2.own : void 0 : void 0;
  2261. }
  2262. };
  2263. FileItemList.prototype.getOptionalInfo = function(inner_path) {
  2264. return this.files_optional[inner_path];
  2265. };
  2266. FileItemList.prototype.sort = function() {
  2267. return this.items.sort(function(a, b) {
  2268. return (b.is_dir - a.is_dir) || a.name.localeCompare(b.name);
  2269. });
  2270. };
  2271. return FileItemList;
  2272. })(Class);
  2273. window.FileItemList = FileItemList;
  2274. }).call(this);
  2275. /* ---- FileList.coffee ---- */
  2276. (function() {
  2277. var FileList,
  2278. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  2279. extend = 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; },
  2280. hasProp = {}.hasOwnProperty,
  2281. 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; };
  2282. FileList = (function(superClass) {
  2283. extend(FileList, superClass);
  2284. function FileList(site, inner_path1, is_owner) {
  2285. this.site = site;
  2286. this.inner_path = inner_path1;
  2287. this.is_owner = is_owner != null ? is_owner : false;
  2288. this.render = bind(this.render, this);
  2289. this.renderFoot = bind(this.renderFoot, this);
  2290. this.renderItems = bind(this.renderItems, this);
  2291. this.renderItem = bind(this.renderItem, this);
  2292. this.renderItemCheckbox = bind(this.renderItemCheckbox, this);
  2293. this.renderHead = bind(this.renderHead, this);
  2294. this.renderSelectbar = bind(this.renderSelectbar, this);
  2295. this.handleSelectbarRemoveOptional = bind(this.handleSelectbarRemoveOptional, this);
  2296. this.handleSelectbarDelete = bind(this.handleSelectbarDelete, this);
  2297. this.handleSelectbarCancel = bind(this.handleSelectbarCancel, this);
  2298. this.handleRowMouseenter = bind(this.handleRowMouseenter, this);
  2299. this.handleSelectMousedown = bind(this.handleSelectMousedown, this);
  2300. this.handleSelectEnd = bind(this.handleSelectEnd, this);
  2301. this.handleSelectClick = bind(this.handleSelectClick, this);
  2302. this.handleNewDirectoryClick = bind(this.handleNewDirectoryClick, this);
  2303. this.handleNewFileClick = bind(this.handleNewFileClick, this);
  2304. this.handleMenuCreateClick = bind(this.handleMenuCreateClick, this);
  2305. this.checkSelectedItems = bind(this.checkSelectedItems, this);
  2306. this.getEditHref = bind(this.getEditHref, this);
  2307. this.getListHref = bind(this.getListHref, this);
  2308. this.getHref = bind(this.getHref, this);
  2309. this.update = bind(this.update, this);
  2310. this.need_update = true;
  2311. this.error = null;
  2312. this.url_root = "/list/" + this.site + "/";
  2313. if (this.inner_path) {
  2314. this.inner_path += "/";
  2315. this.url_root += this.inner_path;
  2316. }
  2317. this.log("inited", this.url_root);
  2318. this.item_list = new FileItemList(this.inner_path);
  2319. this.item_list.items = this.item_list.items;
  2320. this.menu_create = new Menu();
  2321. this.select_action = null;
  2322. this.selected = {};
  2323. this.selected_items_num = 0;
  2324. this.selected_items_size = 0;
  2325. this.selected_optional_empty_num = 0;
  2326. }
  2327. FileList.prototype.isSelectedAll = function() {
  2328. return false;
  2329. };
  2330. FileList.prototype.update = function() {
  2331. return this.item_list.update((function(_this) {
  2332. return function() {
  2333. return document.body.classList.add("loaded");
  2334. };
  2335. })(this));
  2336. };
  2337. FileList.prototype.getHref = function(inner_path) {
  2338. return "/" + this.site + "/" + inner_path;
  2339. };
  2340. FileList.prototype.getListHref = function(inner_path) {
  2341. return "/list/" + this.site + "/" + inner_path;
  2342. };
  2343. FileList.prototype.getEditHref = function(inner_path, mode) {
  2344. var href;
  2345. if (mode == null) {
  2346. mode = null;
  2347. }
  2348. href = this.url_root + "?file=" + inner_path;
  2349. if (mode) {
  2350. href += "&edit_mode=" + mode;
  2351. }
  2352. return href;
  2353. };
  2354. FileList.prototype.checkSelectedItems = function() {
  2355. var i, item, len, optional_info, ref, results;
  2356. this.selected_items_num = 0;
  2357. this.selected_items_size = 0;
  2358. this.selected_optional_empty_num = 0;
  2359. ref = this.item_list.items;
  2360. results = [];
  2361. for (i = 0, len = ref.length; i < len; i++) {
  2362. item = ref[i];
  2363. if (this.selected[item.inner_path]) {
  2364. this.selected_items_num += 1;
  2365. this.selected_items_size += item.size;
  2366. optional_info = this.item_list.getOptionalInfo(item.inner_path);
  2367. if (optional_info && !optional_info.downloaded_percent > 0) {
  2368. results.push(this.selected_optional_empty_num += 1);
  2369. } else {
  2370. results.push(void 0);
  2371. }
  2372. } else {
  2373. results.push(void 0);
  2374. }
  2375. }
  2376. return results;
  2377. };
  2378. FileList.prototype.handleMenuCreateClick = function() {
  2379. this.menu_create.items = [];
  2380. this.menu_create.items.push(["File", this.handleNewFileClick]);
  2381. this.menu_create.items.push(["Directory", this.handleNewDirectoryClick]);
  2382. this.menu_create.toggle();
  2383. return false;
  2384. };
  2385. FileList.prototype.handleNewFileClick = function() {
  2386. Page.cmd("wrapperPrompt", "New file name:", (function(_this) {
  2387. return function(file_name) {
  2388. return window.top.location.href = _this.getEditHref(_this.inner_path + file_name, "new");
  2389. };
  2390. })(this));
  2391. return false;
  2392. };
  2393. FileList.prototype.handleNewDirectoryClick = function() {
  2394. Page.cmd("wrapperPrompt", "New directory name:", (function(_this) {
  2395. return function(res) {
  2396. return alert("directory name " + res);
  2397. };
  2398. })(this));
  2399. return false;
  2400. };
  2401. FileList.prototype.handleSelectClick = function(e) {
  2402. return false;
  2403. };
  2404. FileList.prototype.handleSelectEnd = function(e) {
  2405. document.body.removeEventListener('mouseup', this.handleSelectEnd);
  2406. return this.select_action = null;
  2407. };
  2408. FileList.prototype.handleSelectMousedown = function(e) {
  2409. var inner_path;
  2410. inner_path = e.currentTarget.attributes.inner_path.value;
  2411. if (this.selected[inner_path]) {
  2412. delete this.selected[inner_path];
  2413. this.select_action = "deselect";
  2414. } else {
  2415. this.selected[inner_path] = true;
  2416. this.select_action = "select";
  2417. }
  2418. this.checkSelectedItems();
  2419. document.body.addEventListener('mouseup', this.handleSelectEnd);
  2420. e.stopPropagation();
  2421. Page.projector.scheduleRender();
  2422. return false;
  2423. };
  2424. FileList.prototype.handleRowMouseenter = function(e) {
  2425. var inner_path;
  2426. if (e.buttons && this.select_action) {
  2427. inner_path = e.target.attributes.inner_path.value;
  2428. if (this.select_action === "select") {
  2429. this.selected[inner_path] = true;
  2430. } else {
  2431. delete this.selected[inner_path];
  2432. }
  2433. this.checkSelectedItems();
  2434. Page.projector.scheduleRender();
  2435. }
  2436. return false;
  2437. };
  2438. FileList.prototype.handleSelectbarCancel = function() {
  2439. this.selected = {};
  2440. this.checkSelectedItems();
  2441. Page.projector.scheduleRender();
  2442. return false;
  2443. };
  2444. FileList.prototype.handleSelectbarDelete = function(e, remove_optional) {
  2445. var inner_path, optional_info;
  2446. if (remove_optional == null) {
  2447. remove_optional = false;
  2448. }
  2449. for (inner_path in this.selected) {
  2450. optional_info = this.item_list.getOptionalInfo(inner_path);
  2451. delete this.selected[inner_path];
  2452. if (optional_info && !remove_optional) {
  2453. Page.cmd("optionalFileDelete", inner_path);
  2454. } else {
  2455. Page.cmd("fileDelete", inner_path);
  2456. }
  2457. }
  2458. this.need_update = true;
  2459. Page.projector.scheduleRender();
  2460. this.checkSelectedItems();
  2461. return false;
  2462. };
  2463. FileList.prototype.handleSelectbarRemoveOptional = function(e) {
  2464. return this.handleSelectbarDelete(e, true);
  2465. };
  2466. FileList.prototype.renderSelectbar = function() {
  2467. return h("div.selectbar", {
  2468. classes: {
  2469. visible: this.selected_items_num > 0
  2470. }
  2471. }, [
  2472. "Selected:", h("span.info", [h("span.num", this.selected_items_num + " files"), h("span.size", "(" + (Text.formatSize(this.selected_items_size)) + ")")]), h("div.actions", [
  2473. this.selected_optional_empty_num > 0 ? h("a.action.delete.remove_optional", {
  2474. href: "#",
  2475. onclick: this.handleSelectbarRemoveOptional
  2476. }, "Delete and remove optional") : h("a.action.delete", {
  2477. href: "#",
  2478. onclick: this.handleSelectbarDelete
  2479. }, "Delete")
  2480. ]), h("a.cancel.link", {
  2481. href: "#",
  2482. onclick: this.handleSelectbarCancel
  2483. }, "Cancel")
  2484. ]);
  2485. };
  2486. FileList.prototype.renderHead = function() {
  2487. var i, inner_path_parent, len, parent_dir, parent_links, ref;
  2488. parent_links = [];
  2489. inner_path_parent = "";
  2490. ref = this.inner_path.split("/");
  2491. for (i = 0, len = ref.length; i < len; i++) {
  2492. parent_dir = ref[i];
  2493. if (!parent_dir) {
  2494. continue;
  2495. }
  2496. if (inner_path_parent) {
  2497. inner_path_parent += "/";
  2498. }
  2499. inner_path_parent += "" + parent_dir;
  2500. parent_links.push([
  2501. " / ", h("a", {
  2502. href: this.getListHref(inner_path_parent)
  2503. }, parent_dir)
  2504. ]);
  2505. }
  2506. return h("div.tr.thead", h("div.td.full", h("a", {
  2507. href: this.getListHref("")
  2508. }, "root"), parent_links));
  2509. };
  2510. FileList.prototype.renderItemCheckbox = function(item) {
  2511. if (!this.item_list.hasPermissionDelete(item)) {
  2512. return [" "];
  2513. }
  2514. return h("a.checkbox-outer", {
  2515. href: "#Select",
  2516. onmousedown: this.handleSelectMousedown,
  2517. onclick: this.handleSelectClick,
  2518. inner_path: item.inner_path
  2519. }, h("span.checkbox"));
  2520. };
  2521. FileList.prototype.renderItem = function(item) {
  2522. var classes, downloaded_percent, ext, href, href_edit, inner_path, is_added, is_dir, is_editable, is_editing, is_modified, obj, optional_info, ref, ref1, style, title;
  2523. if (item.type === "parent") {
  2524. href = this.url_root.replace(/^(.*)\/.{2,255}?$/, "$1/");
  2525. } else if (item.type === "dir") {
  2526. href = this.url_root + item.name;
  2527. } else {
  2528. href = this.url_root.replace(/^\/list\//, "/") + item.name;
  2529. }
  2530. inner_path = this.inner_path + item.name;
  2531. href_edit = this.getEditHref(inner_path);
  2532. is_dir = (ref = item.type) === "dir" || ref === "parent";
  2533. ext = item.name.split(".").pop();
  2534. is_editing = inner_path === ((ref1 = Page.file_editor) != null ? ref1.inner_path : void 0);
  2535. is_editable = !is_dir && item.size < 1024 * 1024 && indexOf.call(window.BINARY_EXTENSIONS, ext) < 0;
  2536. is_modified = this.item_list.isModified(inner_path);
  2537. is_added = this.item_list.isAdded(inner_path);
  2538. optional_info = this.item_list.getOptionalInfo(inner_path);
  2539. style = "";
  2540. title = "";
  2541. if (optional_info) {
  2542. downloaded_percent = optional_info.downloaded_percent;
  2543. if (!downloaded_percent) {
  2544. downloaded_percent = 0;
  2545. }
  2546. style += "background: linear-gradient(90deg, #fff6dd, " + downloaded_percent + "%, white, " + downloaded_percent + "%, white);";
  2547. is_added = false;
  2548. }
  2549. if (item.ignored) {
  2550. is_added = false;
  2551. }
  2552. if (is_modified) {
  2553. title += " (modified)";
  2554. }
  2555. if (is_added) {
  2556. title += " (new)";
  2557. }
  2558. if (optional_info || item.optional_empty) {
  2559. title += " (optional)";
  2560. }
  2561. if (item.ignored) {
  2562. title += " (ignored from content.json)";
  2563. }
  2564. classes = (
  2565. obj = {},
  2566. obj["type-" + item.type] = true,
  2567. obj.editing = is_editing,
  2568. obj.nobuttons = !is_editable,
  2569. obj.selected = this.selected[inner_path],
  2570. obj.modified = is_modified,
  2571. obj.added = is_added,
  2572. obj.ignored = item.ignored,
  2573. obj.optional = optional_info,
  2574. obj.optional_empty = item.optional_empty,
  2575. obj
  2576. );
  2577. return h("div.tr", {
  2578. key: item.name,
  2579. classes: classes,
  2580. style: style,
  2581. onmouseenter: this.handleRowMouseenter,
  2582. inner_path: inner_path
  2583. }, [
  2584. h("div.td.pre", {
  2585. title: title
  2586. }, this.renderItemCheckbox(item)), h("div.td.name", h("a.link", {
  2587. href: href
  2588. }, item.name)), h("div.td.buttons", is_editable ? h("a.edit", {
  2589. href: href_edit
  2590. }, Page.site_info.settings.own ? "Edit" : "View") : void 0), h("div.td.size", is_dir ? "[DIR]" : Text.formatSize(item.size))
  2591. ]);
  2592. };
  2593. FileList.prototype.renderItems = function() {
  2594. return [
  2595. this.item_list.error && !this.item_list.items.length && !this.item_list.updating ? [
  2596. h("div.tr", {
  2597. key: "error"
  2598. }, h("div.td.full.error", this.item_list.error))
  2599. ] : void 0, this.inner_path ? this.renderItem({
  2600. "name": "..",
  2601. type: "parent",
  2602. size: 0
  2603. }) : void 0, this.item_list.items.map(this.renderItem)
  2604. ];
  2605. };
  2606. FileList.prototype.renderFoot = function() {
  2607. var dirs, file, files, foot_text, item, ref, ref1, ref2, ref3, total_size;
  2608. files = (function() {
  2609. var i, len, ref, ref1, results;
  2610. ref = this.item_list.items;
  2611. results = [];
  2612. for (i = 0, len = ref.length; i < len; i++) {
  2613. item = ref[i];
  2614. if ((ref1 = item.type) !== "parent" && ref1 !== "dir") {
  2615. results.push(item);
  2616. }
  2617. }
  2618. return results;
  2619. }).call(this);
  2620. dirs = (function() {
  2621. var i, len, ref, results;
  2622. ref = this.item_list.items;
  2623. results = [];
  2624. for (i = 0, len = ref.length; i < len; i++) {
  2625. item = ref[i];
  2626. if (item.type === "dir") {
  2627. results.push(item);
  2628. }
  2629. }
  2630. return results;
  2631. }).call(this);
  2632. if (files.length) {
  2633. total_size = ((function() {
  2634. var i, len, results;
  2635. results = [];
  2636. for (i = 0, len = files.length; i < len; i++) {
  2637. file = files[i];
  2638. results.push(item.size);
  2639. }
  2640. return results;
  2641. })()).reduce(function(a, b) {
  2642. return a + b;
  2643. });
  2644. } else {
  2645. total_size = 0;
  2646. }
  2647. foot_text = "Total: ";
  2648. foot_text += dirs.length + " dir, " + files.length + " file in " + (Text.formatSize(total_size));
  2649. return [
  2650. dirs.length || files.length || ((ref = Page.site_info) != null ? (ref1 = ref.settings) != null ? ref1.own : void 0 : void 0) ? h("div.tr.foot-info.foot", h("div.td.full", [
  2651. this.item_list.updating ? "Updating file list..." : dirs.length || files.length ? foot_text : void 0, ((ref2 = Page.site_info) != null ? (ref3 = ref2.settings) != null ? ref3.own : void 0 : void 0) ? h("div.create", [
  2652. h("a.link", {
  2653. href: "#Create+new+file",
  2654. onclick: this.handleNewFileClick
  2655. }, "+ New"), this.menu_create.render()
  2656. ]) : void 0
  2657. ])) : void 0
  2658. ];
  2659. };
  2660. FileList.prototype.render = function() {
  2661. if (this.need_update) {
  2662. this.update();
  2663. this.need_update = false;
  2664. if (!this.item_list.items) {
  2665. return [];
  2666. }
  2667. }
  2668. return h("div.files", [this.renderSelectbar(), this.renderHead(), h("div.tbody", this.renderItems()), this.renderFoot()]);
  2669. };
  2670. return FileList;
  2671. })(Class);
  2672. window.FileList = FileList;
  2673. }).call(this);
  2674. /* ---- UiFileManager.coffee ---- */
  2675. (function() {
  2676. var UiFileManager,
  2677. bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
  2678. extend = 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; },
  2679. hasProp = {}.hasOwnProperty;
  2680. window.h = maquette.h;
  2681. UiFileManager = (function(superClass) {
  2682. extend(UiFileManager, superClass);
  2683. function UiFileManager() {
  2684. this.render = bind(this.render, this);
  2685. this.createProjector = bind(this.createProjector, this);
  2686. this.onRequest = bind(this.onRequest, this);
  2687. this.checkBodyWidth = bind(this.checkBodyWidth, this);
  2688. return UiFileManager.__super__.constructor.apply(this, arguments);
  2689. }
  2690. UiFileManager.prototype.init = function() {
  2691. this.url_params = new URLSearchParams(window.location.search);
  2692. this.list_site = this.url_params.get("site");
  2693. this.list_address = this.url_params.get("address");
  2694. this.list_inner_path = this.url_params.get("inner_path");
  2695. this.editor_inner_path = this.url_params.get("file");
  2696. this.file_list = new FileList(this.list_site, this.list_inner_path);
  2697. this.site_info = null;
  2698. this.server_info = null;
  2699. this.is_sidebar_closed = false;
  2700. if (this.editor_inner_path) {
  2701. this.file_editor = new FileEditor(this.editor_inner_path);
  2702. }
  2703. window.onbeforeunload = (function(_this) {
  2704. return function() {
  2705. var ref;
  2706. if ((ref = _this.file_editor) != null ? ref.isModified() : void 0) {
  2707. return true;
  2708. } else {
  2709. return null;
  2710. }
  2711. };
  2712. })(this);
  2713. window.onresize = (function(_this) {
  2714. return function() {
  2715. return _this.checkBodyWidth();
  2716. };
  2717. })(this);
  2718. this.checkBodyWidth();
  2719. this.cmd("wrapperSetViewport", "width=device-width, initial-scale=0.8");
  2720. this.cmd("serverInfo", {}, (function(_this) {
  2721. return function(server_info) {
  2722. return _this.server_info = server_info;
  2723. };
  2724. })(this));
  2725. return this.cmd("siteInfo", {}, (function(_this) {
  2726. return function(site_info) {
  2727. _this.cmd("wrapperSetTitle", "List: /" + _this.list_inner_path + " - " + site_info.content.title + " - ZeroNet");
  2728. _this.site_info = site_info;
  2729. if (_this.file_editor) {
  2730. _this.file_editor.on_loaded.then(function() {
  2731. _this.file_editor.cm.setOption("readOnly", !site_info.settings.own);
  2732. return _this.file_editor.mode = site_info.settings.own ? "Edit" : "View";
  2733. });
  2734. }
  2735. return _this.projector.scheduleRender();
  2736. };
  2737. })(this));
  2738. };
  2739. UiFileManager.prototype.checkBodyWidth = function() {
  2740. var ref, ref1;
  2741. if (!this.file_editor) {
  2742. return false;
  2743. }
  2744. if (document.body.offsetWidth < 960 && !this.is_sidebar_closed) {
  2745. this.is_sidebar_closed = true;
  2746. return (ref = this.projector) != null ? ref.scheduleRender() : void 0;
  2747. } else if (document.body.offsetWidth > 960 && this.is_sidebar_closed) {
  2748. this.is_sidebar_closed = false;
  2749. return (ref1 = this.projector) != null ? ref1.scheduleRender() : void 0;
  2750. }
  2751. };
  2752. UiFileManager.prototype.onRequest = function(cmd, message) {
  2753. if (cmd === "setSiteInfo") {
  2754. this.site_info = message;
  2755. RateLimitCb(1000, (function(_this) {
  2756. return function(cb_done) {
  2757. return _this.file_list.update(cb_done);
  2758. };
  2759. })(this));
  2760. return this.projector.scheduleRender();
  2761. } else if (cmd === "setServerInfo") {
  2762. this.server_info = message;
  2763. return this.projector.scheduleRender();
  2764. } else {
  2765. return this.log("Unknown incoming message:", cmd);
  2766. }
  2767. };
  2768. UiFileManager.prototype.createProjector = function() {
  2769. this.projector = maquette.createProjector();
  2770. return this.projector.replace($("#content"), this.render);
  2771. };
  2772. UiFileManager.prototype.render = function() {
  2773. return h("div.content#content", [
  2774. h("div.manager", {
  2775. classes: {
  2776. editing: this.file_editor,
  2777. sidebar_closed: this.is_sidebar_closed
  2778. }
  2779. }, [this.file_list.render(), this.file_editor ? this.file_editor.render() : void 0])
  2780. ]);
  2781. };
  2782. return UiFileManager;
  2783. })(ZeroFrame);
  2784. window.Page = new UiFileManager();
  2785. window.Page.createProjector();
  2786. }).call(this);