app.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. var Gogits = {};
  2. (function ($) {
  3. // extend jQuery ajax, set csrf token value
  4. var ajax = $.ajax;
  5. $.extend({
  6. ajax: function (url, options) {
  7. if (typeof url === 'object') {
  8. options = url;
  9. url = undefined;
  10. }
  11. options = options || {};
  12. url = options.url;
  13. var csrftoken = $('meta[name=_csrf]').attr('content');
  14. var headers = options.headers || {};
  15. var domain = document.domain.replace(/\./ig, '\\.');
  16. if (!/^(http:|https:).*/.test(url) || eval('/^(http:|https:)\\/\\/(.+\\.)*' + domain + '.*/').test(url)) {
  17. headers = $.extend(headers, {'X-Csrf-Token': csrftoken});
  18. }
  19. options.headers = headers;
  20. var callback = options.success;
  21. options.success = function (data) {
  22. if (data.once) {
  23. // change all _once value if ajax data.once exist
  24. $('[name=_once]').val(data.once);
  25. }
  26. if (callback) {
  27. callback.apply(this, arguments);
  28. }
  29. };
  30. return ajax(url, options);
  31. },
  32. changeHash: function (hash) {
  33. if (history.pushState) {
  34. history.pushState(null, null, hash);
  35. }
  36. else {
  37. location.hash = hash;
  38. }
  39. },
  40. deSelect: function () {
  41. if (window.getSelection) {
  42. window.getSelection().removeAllRanges();
  43. } else {
  44. document.selection.empty();
  45. }
  46. }
  47. });
  48. $.fn.extend({
  49. toggleHide: function () {
  50. $(this).addClass("hidden");
  51. },
  52. toggleShow: function () {
  53. $(this).removeClass("hidden");
  54. },
  55. toggleAjax: function (successCallback, errorCallback) {
  56. var url = $(this).data("ajax");
  57. var method = $(this).data('ajax-method') || 'get';
  58. var ajaxName = $(this).data('ajax-name');
  59. var data = {};
  60. if (ajaxName.endsWith("preview")) {
  61. data["mode"] = "gfm";
  62. data["context"] = $(this).data('ajax-context');
  63. }
  64. $('[data-ajax-rel=' + ajaxName + ']').each(function () {
  65. var field = $(this).data("ajax-field");
  66. var t = $(this).data("ajax-val");
  67. if (t == "val") {
  68. data[field] = $(this).val();
  69. return true;
  70. }
  71. if (t == "txt") {
  72. data[field] = $(this).text();
  73. return true;
  74. }
  75. if (t == "html") {
  76. data[field] = $(this).html();
  77. return true;
  78. }
  79. if (t == "data") {
  80. data[field] = $(this).data("ajax-data");
  81. return true;
  82. }
  83. return true;
  84. });
  85. console.log("toggleAjax:", method, url, data);
  86. $.ajax({
  87. url: url,
  88. method: method.toUpperCase(),
  89. data: data,
  90. error: errorCallback,
  91. success: function (d) {
  92. if (successCallback) {
  93. successCallback(d);
  94. }
  95. }
  96. })
  97. }
  98. })
  99. }(jQuery));
  100. (function ($) {
  101. Gogits.showTab = function (selector, index) {
  102. if (!index) {
  103. index = 0;
  104. }
  105. $(selector).tab("show");
  106. $(selector).find("li:eq(" + index + ") a").tab("show");
  107. };
  108. Gogits.validateForm = function (selector, options) {
  109. var $form = $(selector);
  110. options = options || {};
  111. options.showErrors = function (map, list) {
  112. var $error = $form.find('.form-error').addClass('hidden');
  113. $('.has-error').removeClass("has-error");
  114. $error.text(list[0].message).show().removeClass("hidden");
  115. $(list[0].element).parents(".form-group").addClass("has-error");
  116. };
  117. $form.validate(options);
  118. };
  119. // ----- init elements
  120. Gogits.initModals = function () {
  121. var modals = $("[data-toggle=modal]");
  122. if (modals.length < 1) {
  123. return;
  124. }
  125. $.each(modals, function (i, item) {
  126. var hide = $(item).data('modal');
  127. $(item).modal(hide ? hide : "hide");
  128. });
  129. };
  130. Gogits.initTooltips = function () {
  131. $("body").tooltip({
  132. selector: "[data-toggle=tooltip]"
  133. //container: "body"
  134. });
  135. };
  136. Gogits.initPopovers = function () {
  137. var hideAllPopovers = function () {
  138. $('[data-toggle=popover]').each(function () {
  139. $(this).popover('hide');
  140. });
  141. };
  142. $(document).on('click', function (e) {
  143. var $e = $(e.target);
  144. if ($e.data('toggle') == 'popover' || $e.parents("[data-toggle=popover], .popover").length > 0) {
  145. return;
  146. }
  147. hideAllPopovers();
  148. });
  149. $("body").popover({
  150. selector: "[data-toggle=popover]"
  151. });
  152. };
  153. Gogits.initTabs = function () {
  154. var $tabs = $('[data-init=tabs]');
  155. $tabs.tab("show");
  156. $tabs.find("li:eq(0) a").tab("show");
  157. };
  158. // fix dropdown inside click
  159. Gogits.initDropDown = function () {
  160. $('.dropdown-menu.no-propagation').on('click', function (e) {
  161. e.stopPropagation();
  162. });
  163. };
  164. // render markdown
  165. Gogits.renderMarkdown = function () {
  166. var $md = $('.markdown');
  167. var $pre = $md.find('pre > code').parent();
  168. $pre.addClass('prettyprint linenums');
  169. prettyPrint();
  170. // Set anchor.
  171. var headers = {};
  172. $md.find('h1, h2, h3, h4, h5, h6').each(function () {
  173. var node = $(this);
  174. var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\w\- ]/g, '').replace(/[ ]/g, '-'));
  175. var name = val;
  176. if (headers[val] > 0) {
  177. name = val + '-' + headers[val];
  178. }
  179. if (headers[val] == undefined) {
  180. headers[val] = 1;
  181. } else {
  182. headers[val] += 1;
  183. }
  184. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  185. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  186. });
  187. };
  188. // render code view
  189. Gogits.renderCodeView = function () {
  190. function selectRange($list, $select, $from) {
  191. $list.removeClass('active');
  192. if ($from) {
  193. var a = parseInt($select.attr('rel').substr(1));
  194. var b = parseInt($from.attr('rel').substr(1));
  195. var c;
  196. if (a != b) {
  197. if (a > b) {
  198. c = a;
  199. a = b;
  200. b = c;
  201. }
  202. var classes = [];
  203. for (i = a; i <= b; i++) {
  204. classes.push('.L' + i);
  205. }
  206. $list.filter(classes.join(',')).addClass('active');
  207. $.changeHash('#L' + a + '-' + 'L' + b);
  208. return
  209. }
  210. }
  211. $select.addClass('active');
  212. $.changeHash('#' + $select.attr('rel'));
  213. }
  214. $(document).on('click', '.lines-num span', function (e) {
  215. var $select = $(this);
  216. var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  217. selectRange($list, $list.filter('[rel=' + $select.attr('rel') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  218. $.deSelect();
  219. });
  220. $('.code-view .lines-code > pre').each(function () {
  221. var $pre = $(this);
  222. var $lineCode = $pre.parent();
  223. var $lineNums = $lineCode.siblings('.lines-num');
  224. if ($lineNums.length > 0) {
  225. var nums = $pre.find('ol.linenums > li').length;
  226. for (var i = 1; i <= nums; i++) {
  227. $lineNums.append('<span id="L' + i + '" rel="L' + i + '">' + i + '</span>');
  228. }
  229. }
  230. });
  231. $(window).on('hashchange', function (e) {
  232. var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/);
  233. var $list = $('.code-view ol.linenums > li');
  234. if (m) {
  235. var $first = $list.filter('.' + m[1]);
  236. selectRange($list, $first, $list.filter('.' + m[2]));
  237. $("html, body").scrollTop($first.offset().top - 200);
  238. return;
  239. }
  240. m = window.location.hash.match(/^#(L\d+)$/);
  241. if (m) {
  242. var $first = $list.filter('.' + m[1]);
  243. selectRange($list, $first);
  244. $("html, body").scrollTop($first.offset().top - 200);
  245. }
  246. }).trigger('hashchange');
  247. };
  248. // copy utils
  249. Gogits.bindCopy = function (selector) {
  250. if ($(selector).hasClass('js-copy-bind')) {
  251. return;
  252. }
  253. if ( document.documentElement.classList.contains("is-copy-enabled") ) {
  254. $(selector).click(function(event) {
  255. var $this = $(this);
  256. var cfrom = $this.attr('data-copy-from');
  257. $(cfrom).select();
  258. document.execCommand('copy');
  259. getSelection().removeAllRanges();
  260. $this.tipsy("hide").attr('original-title', $this.data('after-title'));
  261. setTimeout(function () {
  262. $this.tipsy("show");
  263. }, 200);
  264. setTimeout(function () {
  265. $this.tipsy('hide').attr('original-title', $this.data('original-title'));
  266. }, 2000);
  267. this.blur();
  268. return;
  269. });
  270. $(selector).addClass("js-copy-bind");
  271. } else {
  272. $(selector).zclip({
  273. path: Gogits.AppSubUrl + "/js/ZeroClipboard.swf",
  274. copy: function () {
  275. var t = $(this).data("copy-val");
  276. var to = $($(this).data("copy-from"));
  277. var str = "";
  278. if (t == "txt") {
  279. str = to.text();
  280. }
  281. if (t == 'val') {
  282. str = to.val();
  283. }
  284. if (t == 'html') {
  285. str = to.html();
  286. }
  287. return str;
  288. },
  289. afterCopy: function () {
  290. var $this = $(this);
  291. $this.tipsy("hide").attr('original-title', $this.data('after-title'));
  292. setTimeout(function () {
  293. $this.tipsy("show");
  294. }, 200);
  295. setTimeout(function () {
  296. $this.tipsy('hide').attr('original-title', $this.data('original-title'));
  297. }, 2000);
  298. }
  299. }).addClass("js-copy-bind");
  300. }
  301. }
  302. // api working
  303. Gogits.getUsers = function (val, $target) {
  304. var notEmpty = function (str) {
  305. return str && str.length > 0;
  306. }
  307. $.ajax({
  308. url: '/api/v1/users/search?q=' + val,
  309. dataType: "json",
  310. success: function (json) {
  311. if (json.ok && json.data.length) {
  312. var html = '';
  313. $.each(json.data, function (i, item) {
  314. html += '<li><img src="' + item.avatar + '">' + item.username;
  315. if (notEmpty(item.full_name)) {
  316. html += ' (' + item.full_name + ')';
  317. }
  318. html += '</li>';
  319. });
  320. $target.toggleShow();
  321. $target.find('ul').html(html);
  322. } else {
  323. $target.toggleHide();
  324. }
  325. }
  326. });
  327. }
  328. })(jQuery);
  329. // ajax utils
  330. (function ($) {
  331. Gogits.ajaxDelete = function (url, data, success) {
  332. data = data || {};
  333. data._method = "DELETE";
  334. $.ajax({
  335. url: url,
  336. data: data,
  337. method: "POST",
  338. dataType: "json",
  339. success: function (json) {
  340. if (success) {
  341. success(json);
  342. }
  343. }
  344. })
  345. }
  346. })(jQuery);
  347. function initCore() {
  348. Gogits.initTooltips();
  349. Gogits.initPopovers();
  350. Gogits.initTabs();
  351. Gogits.initModals();
  352. Gogits.initDropDown();
  353. Gogits.renderMarkdown();
  354. Gogits.renderCodeView();
  355. }
  356. function initUserSetting() {
  357. // ssh confirmation
  358. $('#ssh-keys .delete').confirmation({
  359. singleton: true,
  360. onConfirm: function (e, $this) {
  361. Gogits.ajaxDelete("", {"id": $this.data("del")}, function (json) {
  362. if (json.ok) {
  363. window.location.reload();
  364. } else {
  365. alert(json.err);
  366. }
  367. });
  368. }
  369. });
  370. // profile form
  371. (function () {
  372. $('#user-setting-username').on("keyup", function () {
  373. var $this = $(this);
  374. if ($this.val() != $this.attr('title')) {
  375. $this.next('.help-block').toggleShow();
  376. } else {
  377. $this.next('.help-block').toggleHide();
  378. }
  379. });
  380. }())
  381. }
  382. function initRepository() {
  383. // clone group button script
  384. (function () {
  385. var $clone = $('.clone-group-btn');
  386. if ($clone.length) {
  387. var $url = $('.clone-group-url');
  388. $clone.find('button[data-link]').on("click", function (e) {
  389. var $this = $(this);
  390. if (!$this.hasClass('btn-primary')) {
  391. $clone.find('.input-group-btn .btn-primary').removeClass('btn-primary').addClass("btn-default");
  392. $(this).addClass('btn-primary').removeClass('btn-default');
  393. $url.val($this.data("link"));
  394. $clone.find('span.clone-url').text($this.data('link'));
  395. }
  396. }).eq(0).trigger("click");
  397. $("#repo-clone").on("shown.bs.dropdown", function () {
  398. Gogits.bindCopy("[data-init=copy]");
  399. });
  400. Gogits.bindCopy("[data-init=copy]:visible");
  401. }
  402. })();
  403. // watching script
  404. (function () {
  405. var $watch = $('#repo-watching'),
  406. watchLink = $watch.attr("data-watch"),
  407. // Use $.attr() to work around jQuery not finding $.data("unwatch") in Firefox,
  408. // which has a method "unwatch" on `Object` that gets returned instead.
  409. unwatchLink = $watch.attr("data-unwatch");
  410. $watch.on('click', '.to-watch', function () {
  411. if ($watch.hasClass("watching")) {
  412. return false;
  413. }
  414. $.get(watchLink, function (json) {
  415. if (json.ok) {
  416. $watch.find('.text-primary').removeClass('text-primary');
  417. $watch.find('.to-watch h4').addClass('text-primary');
  418. $watch.find('.fa-eye-slash').removeClass('fa-eye-slash').addClass('fa-eye');
  419. $watch.removeClass("no-watching").addClass("watching");
  420. }
  421. });
  422. return false;
  423. }).on('click', '.to-unwatch', function () {
  424. if ($watch.hasClass("no-watching")) {
  425. return false;
  426. }
  427. $.get(unwatchLink, function (json) {
  428. if (json.ok) {
  429. $watch.find('.text-primary').removeClass('text-primary');
  430. $watch.find('.to-unwatch h4').addClass('text-primary');
  431. $watch.find('.fa-eye').removeClass('fa-eye').addClass('fa-eye-slash');
  432. $watch.removeClass("watching").addClass("no-watching");
  433. }
  434. });
  435. return false;
  436. });
  437. })();
  438. // repo diff counter
  439. (function () {
  440. var $counter = $('.diff-counter');
  441. if ($counter.length < 1) {
  442. return;
  443. }
  444. $counter.each(function (i, item) {
  445. var $item = $(item);
  446. var addLine = $item.find('span[data-line].add').data("line");
  447. var delLine = $item.find('span[data-line].del').data("line");
  448. var addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  449. $item.find(".bar .add").css("width", addPercent + "%");
  450. });
  451. }());
  452. // repo setting form
  453. (function () {
  454. $('#repo-setting-name').on("keyup", function () {
  455. var $this = $(this);
  456. if ($this.val() != $this.attr('title')) {
  457. $this.next('.help-block').toggleShow();
  458. } else {
  459. $this.next('.help-block').toggleHide();
  460. }
  461. });
  462. }())
  463. }
  464. function initInstall() {
  465. // database type change
  466. (function () {
  467. var mysql_default = '127.0.0.1:3306';
  468. var postgres_default = '127.0.0.1:5432';
  469. $('#install-database').on("change", function () {
  470. var val = $(this).val();
  471. if (val != "SQLite3") {
  472. $('.server-sql').show();
  473. $('.sqlite-setting').addClass("hide");
  474. if (val == "PostgreSQL") {
  475. $('.pgsql-setting').removeClass("hide");
  476. // Change the host value to the Postgres default, but only
  477. // if the user hasn't already changed it from the MySQL
  478. // default.
  479. if ($('#database-host').val() == mysql_default) {
  480. $('#database-host').val(postgres_default);
  481. }
  482. } else if (val == 'MySQL') {
  483. $('.pgsql-setting').addClass("hide");
  484. if ($('#database-host').val() == postgres_default) {
  485. $('#database-host').val(mysql_default);
  486. }
  487. } else {
  488. $('.pgsql-setting').addClass("hide");
  489. }
  490. } else {
  491. $('.server-sql').hide();
  492. $('.sqlite-setting').removeClass("hide");
  493. }
  494. });
  495. }());
  496. }
  497. function initIssue() {
  498. // close button
  499. (function () {
  500. var $closeBtn = $('#issue-close-btn');
  501. var $openBtn = $('#issue-open-btn');
  502. $('#issue-reply-content').on("keyup", function () {
  503. if ($(this).val().length) {
  504. $closeBtn.val($closeBtn.data("text"));
  505. $openBtn.val($openBtn.data("text"));
  506. } else {
  507. $closeBtn.val($closeBtn.data("origin"));
  508. $openBtn.val($openBtn.data("origin"));
  509. }
  510. });
  511. }());
  512. // store unsend text in session storage.
  513. (function() {
  514. var $textArea = $("#issue-content,#issue-reply-content");
  515. var current = "";
  516. if ($textArea == null || !('sessionStorage' in window)) {
  517. return;
  518. }
  519. var path = location.pathname.split("/");
  520. var key = "issue-" + path[1] + "-" + path[2] + "-";
  521. if (/\/issues\/\d+$/.test(location.pathname)) {
  522. key = key + path[4];
  523. } else {
  524. key = key + "new";
  525. }
  526. if ($textArea.val() !== undefined && $textArea.val() !== "") {
  527. sessionStorage.setItem(key, $textArea.val());
  528. } else {
  529. $textArea.val(sessionStorage.getItem(key) || "");
  530. if ($textArea.attr("id") == "issue-reply-content") {
  531. var $closeBtn = $('#issue-close-btn');
  532. var $openBtn = $('#issue-open-btn');
  533. if ($textArea.val().length) {
  534. $closeBtn.val($closeBtn.data("text"));
  535. $openBtn.val($openBtn.data("text"));
  536. } else {
  537. $closeBtn.val($closeBtn.data("origin"));
  538. $openBtn.val($openBtn.data("origin"));
  539. }
  540. }
  541. }
  542. $textArea.on("keyup", function() {
  543. if ($textArea.val() !== current) {
  544. sessionStorage.setItem(key, current = $textArea.val());
  545. }
  546. });
  547. }());
  548. // Preview for images.
  549. (function() {
  550. var $hoverElement = $("<div></div>");
  551. var $hoverImage = $("<img />");
  552. $hoverElement.addClass("attachment-preview");
  553. $hoverElement.hide();
  554. $hoverImage.addClass("attachment-preview-img");
  555. $hoverElement.append($hoverImage);
  556. $(document.body).append($hoverElement);
  557. var over = function() {
  558. var $this = $(this);
  559. if ((/\.(png|jpg|jpeg|gif)$/i).test($this.text()) == false) {
  560. return;
  561. }
  562. if ($hoverImage.attr("src") != $this.attr("href")) {
  563. $hoverImage.attr("src", $this.attr("href"));
  564. $hoverImage.load(function() {
  565. var height = this.height;
  566. var width = this.width;
  567. if (height > 300) {
  568. var factor = 300 / height;
  569. height = factor * height;
  570. width = factor * width;
  571. }
  572. $hoverImage.css({"height": height, "width": width});
  573. var offset = $this.offset();
  574. var left = offset.left, top = offset.top + $this.height() + 5;
  575. $hoverElement.css({"top": top + "px", "left": left + "px"});
  576. $hoverElement.css({"height": height + 16, "width": width + 16});
  577. $hoverElement.show();
  578. });
  579. } else {
  580. $hoverElement.show();
  581. }
  582. };
  583. var out = function() {
  584. $hoverElement.hide();
  585. };
  586. $(".issue-main .attachments .attachment").hover(over, out);
  587. }());
  588. // Upload.
  589. (function() {
  590. var $attachedList = $("#attached-list");
  591. var $addButton = $("#attachments-button");
  592. var files = [];
  593. var fileInput = document.getElementById("attachments-input");
  594. if (fileInput === null) {
  595. return;
  596. }
  597. $attachedList.on("click", "span.attachment-remove", function(event) {
  598. var $parent = $(this).parent();
  599. files.splice($parent.data("index"), 1);
  600. $parent.remove();
  601. });
  602. var clickedButton;
  603. $('input[type="submit"],input[type="button"],button.btn-success', fileInput.form).on('click', function() {
  604. clickedButton = this;
  605. var $button = $(this);
  606. $button.removeClass("btn-success btn-default");
  607. $button.addClass("btn-warning");
  608. $button.html("Submitting&hellip;");
  609. });
  610. fileInput.form.addEventListener("submit", function(event) {
  611. event.stopImmediatePropagation();
  612. event.preventDefault();
  613. //var data = new FormData(this);
  614. // Internet Explorer ... -_-
  615. var data = new FormData();
  616. $.each($("[name]", this), function(i, e) {
  617. if (e.name == "attachments" || e.type == "submit") {
  618. return;
  619. }
  620. data.append(e.name, $(e).val());
  621. });
  622. data.append(clickedButton.name, $(clickedButton).val());
  623. files.forEach(function(file) {
  624. data.append("attachments", file);
  625. });
  626. var xhr = new XMLHttpRequest();
  627. xhr.addEventListener("error", function() {
  628. console.log("Issue submit request failed. xhr.status: " + xhr.status);
  629. });
  630. xhr.addEventListener("load", function() {
  631. var response = xhr.response;
  632. if (typeof response == "string") {
  633. try {
  634. response = JSON.parse(response);
  635. } catch (err) {
  636. response = { ok: false, error: "Could not parse JSON" };
  637. }
  638. }
  639. if (response.ok === false) {
  640. $("#submit-error").text(response.error);
  641. $("#submit-error").show();
  642. var $button = $(clickedButton);
  643. $button.removeClass("btn-warning");
  644. $button.addClass("btn-danger");
  645. $button.text("An error occurred!");
  646. return;
  647. }
  648. if (!('sessionStorage' in window)) {
  649. return;
  650. }
  651. var path = location.pathname.split("/");
  652. var key = "issue-" + path[1] + "-" + path[2] + "-";
  653. if (/\/issues\/\d+$/.test(location.pathname)) {
  654. key = key + path[4];
  655. } else {
  656. key = key + "new";
  657. }
  658. sessionStorage.removeItem(key);
  659. window.location.href = response.data;
  660. });
  661. xhr.open("POST", this.action, true);
  662. xhr.send(data);
  663. return false;
  664. });
  665. fileInput.addEventListener("change", function() {
  666. for (var index = 0; index < fileInput.files.length; index++) {
  667. var file = fileInput.files[index];
  668. if (files.indexOf(file) > -1) {
  669. continue;
  670. }
  671. var $span = $("<span></span>");
  672. $span.addClass("label");
  673. $span.addClass("label-default");
  674. $span.data("index", files.length);
  675. $span.append(file.name);
  676. $span.append(" <span class=\"attachment-remove fa fa-times-circle\"></span>");
  677. $attachedList.append($span);
  678. files.push(file);
  679. }
  680. this.value = "";
  681. });
  682. $addButton.on("click", function(evt) {
  683. fileInput.click();
  684. evt.preventDefault();
  685. });
  686. }());
  687. // issue edit mode
  688. (function () {
  689. $("#issue-edit-btn").on("click", function () {
  690. $('#issue h1.title,#issue .issue-main > .issue-content .content,#issue-edit-btn').toggleHide();
  691. $('#issue-edit-title,.issue-edit-content,.issue-edit-cancel,.issue-edit-save').toggleShow();
  692. $('#issue-edit-content').focus();
  693. });
  694. $('.issue-edit-cancel').on("click", function () {
  695. $('#issue h1.title,#issue .issue-main > .issue-content .content,#issue-edit-btn').toggleShow();
  696. $('#issue-edit-title,.issue-edit-content,.issue-edit-cancel,.issue-edit-save').toggleHide();
  697. });
  698. }());
  699. // issue ajax update
  700. (function () {
  701. var $cnt = $('#issue-edit-content');
  702. $('.issue-edit-save').on("click", function () {
  703. $cnt.attr('data-ajax-rel', 'issue-edit-save');
  704. $(this).toggleAjax(function (json) {
  705. if (json.ok) {
  706. $('.issue-head h1.title').text(json.title);
  707. $('.issue-main > .issue-content .content').html(json.content);
  708. $('.issue-edit-cancel').trigger("click");
  709. }
  710. });
  711. setTimeout(function () {
  712. $cnt.attr('data-ajax-rel', 'issue-edit-preview');
  713. }, 200)
  714. });
  715. }());
  716. // issue ajax preview
  717. (function () {
  718. $('[data-ajax-name=issue-preview],[data-ajax-name=issue-edit-preview]').on("click", function () {
  719. var $this = $(this);
  720. $this.toggleAjax(function (resp) {
  721. $($this.data("preview")).html(resp);
  722. }, function () {
  723. $($this.data("preview")).html("no content");
  724. })
  725. });
  726. $('.issue-write a[data-toggle]').on("click", function () {
  727. var selector = $(this).parent().next(".issue-preview").find('a').data('preview');
  728. $(selector).html("loading...");
  729. });
  730. }());
  731. // assignee
  732. var is_issue_bar = $('.issue-bar').length > 0;
  733. var $a = $('.assignee');
  734. if ($a.data("assigned") > 0) {
  735. $('.clear-assignee').toggleShow();
  736. }
  737. $('.assignee', '#issue').on('click', 'li', function () {
  738. var uid = $(this).data("uid");
  739. if (is_issue_bar) {
  740. var assignee = $a.data("assigned");
  741. if (uid != assignee) {
  742. var text = $(this).text();
  743. var img = $("img", this).attr("src");
  744. $.post($a.data("ajax"), {
  745. issue: $('#issue').data("id"),
  746. assigneeid: uid
  747. }, function (json) {
  748. if (json.ok) {
  749. //window.location.reload();
  750. $a.data("assigned", uid);
  751. if (uid > 0) {
  752. $('.clear-assignee').toggleShow();
  753. $(".assignee > p").html('<img src="' + img + '"><strong>' + text + '</strong>');
  754. } else {
  755. $('.clear-assignee').toggleHide();
  756. $(".assignee > p").text("No one assigned");
  757. }
  758. }
  759. })
  760. }
  761. return;
  762. }
  763. $('#assignee').val(uid);
  764. if (uid > 0) {
  765. $('.clear-assignee').toggleShow();
  766. $('#assigned').text($(this).find("strong").text())
  767. } else {
  768. $('.clear-assignee').toggleHide();
  769. $('#assigned').text($('#assigned').data("no-assigned"));
  770. }
  771. });
  772. // milestone
  773. $('#issue .dropdown-menu a[data-toggle="tab"]').on("click", function (e) {
  774. e.stopPropagation();
  775. $(this).tab('show');
  776. return false;
  777. });
  778. var $m = $('.milestone');
  779. if ($m.data("milestone") > 0) {
  780. $('.clear-milestone').toggleShow();
  781. }
  782. $('.milestone', '#issue').on('click', 'li.milestone-item', function () {
  783. var id = $(this).data("id");
  784. if (is_issue_bar) {
  785. var m = $m.data("milestone");
  786. if (id != m) {
  787. var text = $(this).text();
  788. $.post($m.data("ajax"), {
  789. issue: $('#issue').data("id"),
  790. milestoneid: id
  791. }, function (json) {
  792. if (json.ok) {
  793. //window.location.reload();
  794. $m.data("milestone", id);
  795. if (id > 0) {
  796. $('.clear-milestone').toggleShow();
  797. $(".milestone > .name").html('<a href="' + location.pathname + '?milestone=' + id + '"><strong>' + text + '</strong></a>');
  798. } else {
  799. $('.clear-milestone').toggleHide();
  800. $(".milestone > .name").text("No milestone");
  801. }
  802. }
  803. });
  804. }
  805. return;
  806. }
  807. $('#milestone-id').val(id);
  808. if (id > 0) {
  809. $('.clear-milestone').toggleShow();
  810. $('#milestone').text($(this).find("strong").text())
  811. } else {
  812. $('.clear-milestone').toggleHide();
  813. $('#milestone').text($('#milestone').data("no-milestone"));
  814. }
  815. });
  816. // labels
  817. var removeLabels = [];
  818. $('#label-manage-btn').on("click", function () {
  819. var $list = $('#label-list');
  820. if ($list.hasClass("managing")) {
  821. var ids = [];
  822. $list.find('li').each(function (i, item) {
  823. var id = $(item).data("id");
  824. if (id > 0) {
  825. ids.push(id);
  826. }
  827. });
  828. $.post($list.data("ajax"), {"ids": ids.join(","), "remove": removeLabels.join(",")}, function (json) {
  829. if (json.ok) {
  830. window.location.reload();
  831. }
  832. })
  833. } else {
  834. $list.addClass("managing");
  835. $list.find(".count").hide();
  836. $list.find(".del").show();
  837. $(this).text("Save Labels");
  838. $list.on('click', 'li.label-item', function () {
  839. var $this = $(this);
  840. $this.after($('.label-change-li').detach().show());
  841. $('#label-name-change-ipt').val($this.find('.name').text());
  842. var color = $this.find('.color').data("color");
  843. $('.label-change-color-picker').colorpicker("setValue", color);
  844. $('#label-color-change-ipt,#label-color-change-ipt2').val(color);
  845. $('#label-change-id-ipt').val($this.data("id"));
  846. return false;
  847. });
  848. }
  849. });
  850. var colorRegex = new RegExp("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$");
  851. $('#label-color-ipt2').on('keyup', function () {
  852. var val = $(this).val();
  853. if (val.length > 7) {
  854. $(this).val(val.substr(0, 7));
  855. }
  856. if (colorRegex.test(val)) {
  857. $('.label-color-picker').colorpicker("setValue", val);
  858. }
  859. return true;
  860. });
  861. $('#label-color-change-ipt2').on('keyup', function () {
  862. var val = $(this).val();
  863. console.log(val);
  864. if (val.length > 7) {
  865. $(this).val(val.substr(0, 7));
  866. }
  867. if (colorRegex.test(val)) {
  868. $('.label-change-color-picker').colorpicker("setValue", val);
  869. }
  870. return true;
  871. });
  872. $("#label-list").on('click', '.del', function () {
  873. var $p = $(this).parent();
  874. removeLabels.push($p.data('id'));
  875. $p.remove();
  876. return false;
  877. });
  878. $('.label-selected').each(function (i, item) {
  879. var $item = $(item);
  880. var color = $item.find('.color').data('color');
  881. $item.css('background-color', color);
  882. });
  883. $('.issue-bar .labels .dropdown-menu').on('click', 'li', function (e) {
  884. var $labels = $('.issue-bar .labels');
  885. var url = $labels.data("ajax");
  886. var id = $(this).data('id');
  887. var check = $(this).hasClass("checked");
  888. var item = this;
  889. $.post(url, {id: id, action: check ? 'detach' : "attach", issue: $('#issue').data('id')}, function (json) {
  890. if (json.ok) {
  891. if (check) {
  892. $("span.check.pull-left", item).remove();
  893. $(item).removeClass("checked");
  894. $(item).addClass("no-checked");
  895. $("#label-" + id, $labels).remove();
  896. if ($labels.children(".label-item").length == 0) {
  897. $labels.append("<p>None yet</p>");
  898. }
  899. } else {
  900. $(item).prepend('<span class="check pull-left"><i class="fa fa-check"></i></span>');
  901. $(item).removeClass("no-checked");
  902. $(item).addClass("checked");
  903. $("p:not([class])", $labels).remove();
  904. var $l = $("<p></p>");
  905. var c = $("span.color", item).css("background-color");
  906. $l.attr("id", "label-" + id);
  907. $l.attr("class", "label-item label-white");
  908. $l.css("background-color", c);
  909. $l.append("<strong>" + $(item).text() + "</strong>");
  910. $labels.append($l);
  911. }
  912. }
  913. });
  914. e.stopPropagation();
  915. return false;
  916. })
  917. }
  918. function initRelease() {
  919. // release new ajax preview
  920. (function () {
  921. $('[data-ajax-name=release-preview]').on("click", function () {
  922. var $this = $(this);
  923. $this.toggleAjax(function (resp) {
  924. $($this.data("preview")).html(resp);
  925. }, function () {
  926. $($this.data("preview")).html("no content");
  927. })
  928. });
  929. $('.release-write a[data-toggle]').on("click", function () {
  930. $('.release-preview-content').html("loading...");
  931. });
  932. }());
  933. // release new target selection
  934. (function () {
  935. $('#release-new-target-branch-list').on('click', 'a', function () {
  936. $('#tag-target').val($(this).text());
  937. $('#release-new-target-name').text(" " + $(this).text());
  938. });
  939. }());
  940. }
  941. function initRepoSetting() {
  942. // repo member add
  943. $('#repo-collaborator').on('keyup', function () {
  944. var $this = $(this);
  945. if (!$this.val()) {
  946. $this.next().toggleHide();
  947. return;
  948. }
  949. Gogits.getUsers($this.val(), $this.next());
  950. }).on('focus', function () {
  951. if (!$(this).val()) {
  952. $(this).next().toggleHide();
  953. }
  954. }).next().on("click", 'li', function () {
  955. $('#repo-collaborator').val($(this).text());
  956. });
  957. }
  958. function initRepoCreating() {
  959. // owner switch menu click
  960. (function () {
  961. $('#repo-owner-switch .dropdown-menu').on("click", "li", function () {
  962. var uid = $(this).data('uid');
  963. // set to input
  964. $('#repo-owner-id').val(uid);
  965. // set checked class
  966. if (!$(this).hasClass("checked")) {
  967. $(this).parent().find(".checked").removeClass("checked");
  968. $(this).addClass("checked");
  969. }
  970. // set button group to show clicked owner
  971. $('#repo-owner-avatar').attr("src", $(this).find('img').attr("src"));
  972. $('#repo-owner-name').text($(this).text().trim());
  973. console.log("set repo owner to uid :", uid, $(this).text().trim());
  974. });
  975. }());
  976. console.log("init repo-creating scripts");
  977. }
  978. function initOrganization() {
  979. (function(){
  980. $('#org-team-add-user').on('keyup', function () {
  981. var $this = $(this);
  982. if (!$this.val()) {
  983. $this.next().toggleHide();
  984. return;
  985. }
  986. Gogits.getUsers($this.val(), $this.next());
  987. }).on('focus', function () {
  988. if (!$(this).val()) {
  989. $(this).next().toggleHide();
  990. }
  991. }).next().on("click", 'li', function () {
  992. $('#org-team-add-user').val($(this).text());
  993. $('#org-team-add-user-form').submit();
  994. }).toggleHide();
  995. console.log("init script : add user to team");
  996. }());
  997. (function(){
  998. $('#org-team-add-repo').next().toggleHide();
  999. console.log("init script : add repository to team");
  1000. }());
  1001. console.log("init script : organization done");
  1002. }
  1003. function initTimeSwitch() {
  1004. $(".time-since[title]").on("click", function() {
  1005. var $this = $(this);
  1006. var title = $this.attr("title");
  1007. var text = $this.text();
  1008. $this.text(title);
  1009. $this.attr("title", text);
  1010. });
  1011. }
  1012. (function ($) {
  1013. $(function () {
  1014. initCore();
  1015. var body = $("#body");
  1016. if (body.data("page") == "user") {
  1017. initUserSetting();
  1018. }
  1019. if ($('.repo-nav').length) {
  1020. initRepository();
  1021. }
  1022. if ($('#install-card').length) {
  1023. initInstall();
  1024. }
  1025. if ($('#issue').length) {
  1026. initIssue();
  1027. }
  1028. if ($('#release').length) {
  1029. initRelease();
  1030. }
  1031. if ($('#repo-setting-container').length) {
  1032. initRepoSetting();
  1033. }
  1034. if ($('#repo-create').length) {
  1035. initRepoCreating();
  1036. }
  1037. if ($('#body-nav').hasClass("org-nav")) {
  1038. initOrganization();
  1039. }
  1040. initTimeSwitch();
  1041. });
  1042. })(jQuery);
  1043. String.prototype.endsWith = function (suffix) {
  1044. return this.indexOf(suffix, this.length - suffix.length) !== -1;
  1045. };