app.js 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  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. $(selector).zclip({
  254. path: "/js/ZeroClipboard.swf",
  255. copy: function () {
  256. var t = $(this).data("copy-val");
  257. var to = $($(this).data("copy-from"));
  258. var str = "";
  259. if (t == "txt") {
  260. str = to.text();
  261. }
  262. if (t == 'val') {
  263. str = to.val();
  264. }
  265. if (t == 'html') {
  266. str = to.html();
  267. }
  268. return str;
  269. },
  270. afterCopy: function () {
  271. var $this = $(this);
  272. $this.tooltip('hide')
  273. .attr('data-original-title', 'Copied OK');
  274. setTimeout(function () {
  275. $this.tooltip("show");
  276. }, 200);
  277. setTimeout(function () {
  278. $this.tooltip('hide')
  279. .attr('data-original-title', 'Copy to Clipboard');
  280. }, 3000);
  281. }
  282. }).addClass("js-copy-bind");
  283. }
  284. // api working
  285. Gogits.getUsers = function (val, $target) {
  286. $.ajax({
  287. url: '/api/v1/users/search?q=' + val,
  288. dataType: "json",
  289. success: function (json) {
  290. if (json.ok && json.data.length) {
  291. var html = '';
  292. $.each(json.data, function (i, item) {
  293. html += '<li><img src="' + item.avatar + '">' + item.username + '</li>';
  294. });
  295. $target.toggleShow();
  296. $target.find('ul').html(html);
  297. } else {
  298. $target.toggleHide();
  299. }
  300. }
  301. });
  302. }
  303. })(jQuery);
  304. // ajax utils
  305. (function ($) {
  306. Gogits.ajaxDelete = function (url, data, success) {
  307. data = data || {};
  308. data._method = "DELETE";
  309. $.ajax({
  310. url: url,
  311. data: data,
  312. method: "POST",
  313. dataType: "json",
  314. success: function (json) {
  315. if (success) {
  316. success(json);
  317. }
  318. }
  319. })
  320. }
  321. })(jQuery);
  322. function initCore() {
  323. Gogits.initTooltips();
  324. Gogits.initPopovers();
  325. Gogits.initTabs();
  326. Gogits.initModals();
  327. Gogits.initDropDown();
  328. Gogits.renderMarkdown();
  329. Gogits.renderCodeView();
  330. }
  331. function initUserSetting() {
  332. // ssh confirmation
  333. $('#ssh-keys .delete').confirmation({
  334. singleton: true,
  335. onConfirm: function (e, $this) {
  336. Gogits.ajaxDelete("", {"id": $this.data("del")}, function (json) {
  337. if (json.ok) {
  338. window.location.reload();
  339. } else {
  340. alert(json.err);
  341. }
  342. });
  343. }
  344. });
  345. // profile form
  346. (function () {
  347. $('#user-setting-username').on("keyup", function () {
  348. var $this = $(this);
  349. if ($this.val() != $this.attr('title')) {
  350. $this.next('.help-block').toggleShow();
  351. } else {
  352. $this.next('.help-block').toggleHide();
  353. }
  354. });
  355. }())
  356. }
  357. function initRepository() {
  358. // clone group button script
  359. (function () {
  360. var $clone = $('.clone-group-btn');
  361. if ($clone.length) {
  362. var $url = $('.clone-group-url');
  363. $clone.find('button[data-link]').on("click", function (e) {
  364. var $this = $(this);
  365. if (!$this.hasClass('btn-primary')) {
  366. $clone.find('.input-group-btn .btn-primary').removeClass('btn-primary').addClass("btn-default");
  367. $(this).addClass('btn-primary').removeClass('btn-default');
  368. $url.val($this.data("link"));
  369. $clone.find('span.clone-url').text($this.data('link'));
  370. }
  371. }).eq(0).trigger("click");
  372. $("#repo-clone").on("shown.bs.dropdown", function () {
  373. Gogits.bindCopy("[data-init=copy]");
  374. });
  375. Gogits.bindCopy("[data-init=copy]:visible");
  376. }
  377. })();
  378. // watching script
  379. (function () {
  380. var $watch = $('#repo-watching'),
  381. watchLink = $watch.attr("data-watch"),
  382. // Use $.attr() to work around jQuery not finding $.data("unwatch") in Firefox,
  383. // which has a method "unwatch" on `Object` that gets returned instead.
  384. unwatchLink = $watch.attr("data-unwatch");
  385. $watch.on('click', '.to-watch', function () {
  386. if ($watch.hasClass("watching")) {
  387. return false;
  388. }
  389. $.get(watchLink, function (json) {
  390. if (json.ok) {
  391. $watch.find('.text-primary').removeClass('text-primary');
  392. $watch.find('.to-watch h4').addClass('text-primary');
  393. $watch.find('.fa-eye-slash').removeClass('fa-eye-slash').addClass('fa-eye');
  394. $watch.removeClass("no-watching").addClass("watching");
  395. }
  396. });
  397. return false;
  398. }).on('click', '.to-unwatch', function () {
  399. if ($watch.hasClass("no-watching")) {
  400. return false;
  401. }
  402. $.get(unwatchLink, function (json) {
  403. if (json.ok) {
  404. $watch.find('.text-primary').removeClass('text-primary');
  405. $watch.find('.to-unwatch h4').addClass('text-primary');
  406. $watch.find('.fa-eye').removeClass('fa-eye').addClass('fa-eye-slash');
  407. $watch.removeClass("watching").addClass("no-watching");
  408. }
  409. });
  410. return false;
  411. });
  412. })();
  413. // repo diff counter
  414. (function () {
  415. var $counter = $('.diff-counter');
  416. if ($counter.length < 1) {
  417. return;
  418. }
  419. $counter.each(function (i, item) {
  420. var $item = $(item);
  421. var addLine = $item.find('span[data-line].add').data("line");
  422. var delLine = $item.find('span[data-line].del').data("line");
  423. var addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  424. $item.find(".bar .add").css("width", addPercent + "%");
  425. });
  426. }());
  427. // repo setting form
  428. (function () {
  429. $('#repo-setting-name').on("keyup", function () {
  430. var $this = $(this);
  431. if ($this.val() != $this.attr('title')) {
  432. $this.next('.help-block').toggleShow();
  433. } else {
  434. $this.next('.help-block').toggleHide();
  435. }
  436. });
  437. }())
  438. }
  439. function initInstall() {
  440. // database type change
  441. (function () {
  442. var mysql_default = '127.0.0.1:3306';
  443. var postgres_default = '127.0.0.1:5432';
  444. $('#install-database').on("change", function () {
  445. var val = $(this).val();
  446. if (val != "SQLite3") {
  447. $('.server-sql').show();
  448. $('.sqlite-setting').addClass("hide");
  449. if (val == "PostgreSQL") {
  450. $('.pgsql-setting').removeClass("hide");
  451. // Change the host value to the Postgres default, but only
  452. // if the user hasn't already changed it from the MySQL
  453. // default.
  454. if ($('#database-host').val() == mysql_default) {
  455. $('#database-host').val(postgres_default);
  456. }
  457. } else if (val == 'MySQL') {
  458. $('.pgsql-setting').addClass("hide");
  459. if ($('#database-host').val() == postgres_default) {
  460. $('#database-host').val(mysql_default);
  461. }
  462. } else {
  463. $('.pgsql-setting').addClass("hide");
  464. }
  465. } else {
  466. $('.server-sql').hide();
  467. $('.sqlite-setting').removeClass("hide");
  468. }
  469. });
  470. }());
  471. }
  472. function initIssue() {
  473. // close button
  474. (function () {
  475. var $closeBtn = $('#issue-close-btn');
  476. var $openBtn = $('#issue-open-btn');
  477. $('#issue-reply-content').on("keyup", function () {
  478. if ($(this).val().length) {
  479. $closeBtn.val($closeBtn.data("text"));
  480. $openBtn.val($openBtn.data("text"));
  481. } else {
  482. $closeBtn.val($closeBtn.data("origin"));
  483. $openBtn.val($openBtn.data("origin"));
  484. }
  485. });
  486. }());
  487. // store unsend text in session storage.
  488. (function() {
  489. var $textArea = $("#issue-content,#issue-reply-content");
  490. var current = "";
  491. if ($textArea == null || !('sessionStorage' in window)) {
  492. return;
  493. }
  494. var path = location.pathname.split("/");
  495. var key = "issue-" + path[1] + "-" + path[2] + "-";
  496. if (/\/issues\/\d+$/.test(location.pathname)) {
  497. key = key + path[4];
  498. } else {
  499. key = key + "new";
  500. }
  501. if ($textArea.val() !== undefined && $textArea.val() !== "") {
  502. sessionStorage.setItem(key, $textArea.val());
  503. } else {
  504. $textArea.val(sessionStorage.getItem(key) || "");
  505. if ($textArea.attr("id") == "issue-reply-content") {
  506. var $closeBtn = $('#issue-close-btn');
  507. var $openBtn = $('#issue-open-btn');
  508. if ($textArea.val().length) {
  509. $closeBtn.val($closeBtn.data("text"));
  510. $openBtn.val($openBtn.data("text"));
  511. } else {
  512. $closeBtn.val($closeBtn.data("origin"));
  513. $openBtn.val($openBtn.data("origin"));
  514. }
  515. }
  516. }
  517. $textArea.on("keyup", function() {
  518. if ($textArea.val() !== current) {
  519. sessionStorage.setItem(key, current = $textArea.val());
  520. }
  521. });
  522. }());
  523. // Preview for images.
  524. (function() {
  525. var $hoverElement = $("<div></div>");
  526. var $hoverImage = $("<img />");
  527. $hoverElement.addClass("attachment-preview");
  528. $hoverElement.hide();
  529. $hoverImage.addClass("attachment-preview-img");
  530. $hoverElement.append($hoverImage);
  531. $(document.body).append($hoverElement);
  532. var over = function() {
  533. var $this = $(this);
  534. if ((/\.(png|jpg|jpeg|gif)$/i).test($this.text()) == false) {
  535. return;
  536. }
  537. if ($hoverImage.attr("src") != $this.attr("href")) {
  538. $hoverImage.attr("src", $this.attr("href"));
  539. $hoverImage.load(function() {
  540. var height = this.height;
  541. var width = this.width;
  542. if (height > 300) {
  543. var factor = 300 / height;
  544. height = factor * height;
  545. width = factor * width;
  546. }
  547. $hoverImage.css({"height": height, "width": width});
  548. var offset = $this.offset();
  549. var left = offset.left, top = offset.top + $this.height() + 5;
  550. $hoverElement.css({"top": top + "px", "left": left + "px"});
  551. $hoverElement.css({"height": height + 16, "width": width + 16});
  552. $hoverElement.show();
  553. });
  554. } else {
  555. $hoverElement.show();
  556. }
  557. };
  558. var out = function() {
  559. $hoverElement.hide();
  560. };
  561. $(".issue-main .attachments .attachment").hover(over, out);
  562. }());
  563. // Upload.
  564. (function() {
  565. var $attachedList = $("#attached-list");
  566. var $addButton = $("#attachments-button");
  567. var files = [];
  568. var fileInput = document.getElementById("attachments-input");
  569. if (fileInput === null) {
  570. return;
  571. }
  572. $attachedList.on("click", "span.attachment-remove", function(event) {
  573. var $parent = $(this).parent();
  574. files.splice($parent.data("index"), 1);
  575. $parent.remove();
  576. });
  577. var clickedButton;
  578. $('input[type="submit"],input[type="button"],button.btn-success', fileInput.form).on('click', function() {
  579. clickedButton = this;
  580. var $button = $(this);
  581. $button.removeClass("btn-success btn-default");
  582. $button.addClass("btn-warning");
  583. $button.html("Submitting&hellip;");
  584. });
  585. fileInput.form.addEventListener("submit", function(event) {
  586. event.stopImmediatePropagation();
  587. event.preventDefault();
  588. //var data = new FormData(this);
  589. // Internet Explorer ... -_-
  590. var data = new FormData();
  591. $.each($("[name]", this), function(i, e) {
  592. if (e.name == "attachments" || e.type == "submit") {
  593. return;
  594. }
  595. data.append(e.name, $(e).val());
  596. });
  597. data.append(clickedButton.name, $(clickedButton).val());
  598. files.forEach(function(file) {
  599. data.append("attachments", file);
  600. });
  601. var xhr = new XMLHttpRequest();
  602. xhr.addEventListener("error", function() {
  603. console.log("Issue submit request failed. xhr.status: " + xhr.status);
  604. });
  605. xhr.addEventListener("load", function() {
  606. var response = xhr.response;
  607. if (typeof response == "string") {
  608. try {
  609. response = JSON.parse(response);
  610. } catch (err) {
  611. response = { ok: false, error: "Could not parse JSON" };
  612. }
  613. }
  614. if (response.ok === false) {
  615. $("#submit-error").text(response.error);
  616. $("#submit-error").show();
  617. var $button = $(clickedButton);
  618. $button.removeClass("btn-warning");
  619. $button.addClass("btn-danger");
  620. $button.text("An error occurred!");
  621. return;
  622. }
  623. if (!('sessionStorage' in window)) {
  624. return;
  625. }
  626. var path = location.pathname.split("/");
  627. var key = "issue-" + path[1] + "-" + path[2] + "-";
  628. if (/\/issues\/\d+$/.test(location.pathname)) {
  629. key = key + path[4];
  630. } else {
  631. key = key + "new";
  632. }
  633. sessionStorage.removeItem(key);
  634. window.location.href = response.data;
  635. });
  636. xhr.open("POST", this.action, true);
  637. xhr.send(data);
  638. return false;
  639. });
  640. fileInput.addEventListener("change", function() {
  641. for (var index = 0; index < fileInput.files.length; index++) {
  642. var file = fileInput.files[index];
  643. if (files.indexOf(file) > -1) {
  644. continue;
  645. }
  646. var $span = $("<span></span>");
  647. $span.addClass("label");
  648. $span.addClass("label-default");
  649. $span.data("index", files.length);
  650. $span.append(file.name);
  651. $span.append(" <span class=\"attachment-remove fa fa-times-circle\"></span>");
  652. $attachedList.append($span);
  653. files.push(file);
  654. }
  655. this.value = "";
  656. });
  657. $addButton.on("click", function(evt) {
  658. fileInput.click();
  659. evt.preventDefault();
  660. });
  661. }());
  662. // issue edit mode
  663. (function () {
  664. $("#issue-edit-btn").on("click", function () {
  665. $('#issue h1.title,#issue .issue-main > .issue-content .content,#issue-edit-btn').toggleHide();
  666. $('#issue-edit-title,.issue-edit-content,.issue-edit-cancel,.issue-edit-save').toggleShow();
  667. });
  668. $('.issue-edit-cancel').on("click", function () {
  669. $('#issue h1.title,#issue .issue-main > .issue-content .content,#issue-edit-btn').toggleShow();
  670. $('#issue-edit-title,.issue-edit-content,.issue-edit-cancel,.issue-edit-save').toggleHide();
  671. });
  672. }());
  673. // issue ajax update
  674. (function () {
  675. var $cnt = $('#issue-edit-content');
  676. $('.issue-edit-save').on("click", function () {
  677. $cnt.attr('data-ajax-rel', 'issue-edit-save');
  678. $(this).toggleAjax(function (json) {
  679. if (json.ok) {
  680. $('.issue-head h1.title').text(json.title);
  681. $('.issue-main > .issue-content .content').html(json.content);
  682. $('.issue-edit-cancel').trigger("click");
  683. }
  684. });
  685. setTimeout(function () {
  686. $cnt.attr('data-ajax-rel', 'issue-edit-preview');
  687. }, 200)
  688. });
  689. }());
  690. // issue ajax preview
  691. (function () {
  692. $('[data-ajax-name=issue-preview],[data-ajax-name=issue-edit-preview]').on("click", function () {
  693. var $this = $(this);
  694. $this.toggleAjax(function (resp) {
  695. $($this.data("preview")).html(resp);
  696. }, function () {
  697. $($this.data("preview")).html("no content");
  698. })
  699. });
  700. $('.issue-write a[data-toggle]').on("click", function () {
  701. var selector = $(this).parent().next(".issue-preview").find('a').data('preview');
  702. $(selector).html("loading...");
  703. });
  704. }());
  705. // assignee
  706. var is_issue_bar = $('.issue-bar').length > 0;
  707. var $a = $('.assignee');
  708. if ($a.data("assigned") > 0) {
  709. $('.clear-assignee').toggleShow();
  710. }
  711. $('.assignee', '#issue').on('click', 'li', function () {
  712. var uid = $(this).data("uid");
  713. if (is_issue_bar) {
  714. var assignee = $a.data("assigned");
  715. if (uid != assignee) {
  716. var text = $(this).text();
  717. var img = $("img", this).attr("src");
  718. $.post($a.data("ajax"), {
  719. issue: $('#issue').data("id"),
  720. assigneeid: uid
  721. }, function (json) {
  722. if (json.ok) {
  723. //window.location.reload();
  724. $a.data("assigned", uid);
  725. if (uid > 0) {
  726. $('.clear-assignee').toggleShow();
  727. $(".assignee > p").html('<img src="' + img + '"><strong>' + text + '</strong>');
  728. } else {
  729. $('.clear-assignee').toggleHide();
  730. $(".assignee > p").text("No one assigned");
  731. }
  732. }
  733. })
  734. }
  735. return;
  736. }
  737. $('#assignee').val(uid);
  738. if (uid > 0) {
  739. $('.clear-assignee').toggleShow();
  740. $('#assigned').text($(this).find("strong").text())
  741. } else {
  742. $('.clear-assignee').toggleHide();
  743. $('#assigned').text($('#assigned').data("no-assigned"));
  744. }
  745. });
  746. // milestone
  747. $('#issue .dropdown-menu a[data-toggle="tab"]').on("click", function (e) {
  748. e.stopPropagation();
  749. $(this).tab('show');
  750. return false;
  751. });
  752. var $m = $('.milestone');
  753. if ($m.data("milestone") > 0) {
  754. $('.clear-milestone').toggleShow();
  755. }
  756. $('.milestone', '#issue').on('click', 'li.milestone-item', function () {
  757. var id = $(this).data("id");
  758. if (is_issue_bar) {
  759. var m = $m.data("milestone");
  760. if (id != m) {
  761. var text = $(this).text();
  762. $.post($m.data("ajax"), {
  763. issue: $('#issue').data("id"),
  764. milestone: id
  765. }, function (json) {
  766. if (json.ok) {
  767. //window.location.reload();
  768. $m.data("milestone", id);
  769. if (id > 0) {
  770. $('.clear-milestone').toggleShow();
  771. $(".milestone > .name").html('<a href="' + location.pathname + '?milestone=' + id + '"><strong>' + text + '</strong></a>');
  772. } else {
  773. $('.clear-milestone').toggleHide();
  774. $(".milestone > .name").text("No milestone");
  775. }
  776. }
  777. });
  778. }
  779. return;
  780. }
  781. $('#milestone-id').val(id);
  782. if (id > 0) {
  783. $('.clear-milestone').toggleShow();
  784. $('#milestone').text($(this).find("strong").text())
  785. } else {
  786. $('.clear-milestone').toggleHide();
  787. $('#milestone').text($('#milestone').data("no-milestone"));
  788. }
  789. });
  790. // labels
  791. var removeLabels = [];
  792. $('#label-manage-btn').on("click", function () {
  793. var $list = $('#label-list');
  794. if ($list.hasClass("managing")) {
  795. var ids = [];
  796. $list.find('li').each(function (i, item) {
  797. var id = $(item).data("id");
  798. if (id > 0) {
  799. ids.push(id);
  800. }
  801. });
  802. $.post($list.data("ajax"), {"ids": ids.join(","), "remove": removeLabels.join(",")}, function (json) {
  803. if (json.ok) {
  804. window.location.reload();
  805. }
  806. })
  807. } else {
  808. $list.addClass("managing");
  809. $list.find(".count").hide();
  810. $list.find(".del").show();
  811. $(this).text("Save Labels");
  812. $list.on('click', 'li.label-item', function () {
  813. var $this = $(this);
  814. $this.after($('.label-change-li').detach().show());
  815. $('#label-name-change-ipt').val($this.find('.name').text());
  816. var color = $this.find('.color').data("color");
  817. $('.label-change-color-picker').colorpicker("setValue", color);
  818. $('#label-color-change-ipt,#label-color-change-ipt2').val(color);
  819. $('#label-change-id-ipt').val($this.data("id"));
  820. return false;
  821. });
  822. }
  823. });
  824. var colorRegex = new RegExp("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$");
  825. $('#label-color-ipt2').on('keyup', function () {
  826. var val = $(this).val();
  827. if (val.length > 7) {
  828. $(this).val(val.substr(0, 7));
  829. }
  830. if (colorRegex.test(val)) {
  831. $('.label-color-picker').colorpicker("setValue", val);
  832. }
  833. return true;
  834. });
  835. $('#label-color-change-ipt2').on('keyup', function () {
  836. var val = $(this).val();
  837. console.log(val);
  838. if (val.length > 7) {
  839. $(this).val(val.substr(0, 7));
  840. }
  841. if (colorRegex.test(val)) {
  842. $('.label-change-color-picker').colorpicker("setValue", val);
  843. }
  844. return true;
  845. });
  846. $("#label-list").on('click', '.del', function () {
  847. var $p = $(this).parent();
  848. removeLabels.push($p.data('id'));
  849. $p.remove();
  850. return false;
  851. });
  852. $('.label-selected').each(function (i, item) {
  853. var $item = $(item);
  854. var color = $item.find('.color').data('color');
  855. $item.css('background-color', color);
  856. });
  857. $('.issue-bar .labels .dropdown-menu').on('click', 'li', function (e) {
  858. var $labels = $('.issue-bar .labels');
  859. var url = $labels.data("ajax");
  860. var id = $(this).data('id');
  861. var check = $(this).hasClass("checked");
  862. var item = this;
  863. $.post(url, {id: id, action: check ? 'detach' : "attach", issue: $('#issue').data('id')}, function (json) {
  864. if (json.ok) {
  865. if (check) {
  866. $("span.check.pull-left", item).remove();
  867. $(item).removeClass("checked");
  868. $(item).addClass("no-checked");
  869. $("#label-" + id, $labels).remove();
  870. if ($labels.children(".label-item").length == 0) {
  871. $labels.append("<p>None yet</p>");
  872. }
  873. } else {
  874. $(item).prepend('<span class="check pull-left"><i class="fa fa-check"></i></span>');
  875. $(item).removeClass("no-checked");
  876. $(item).addClass("checked");
  877. $("p:not([class])", $labels).remove();
  878. var $l = $("<p></p>");
  879. var c = $("span.color", item).css("background-color");
  880. $l.attr("id", "label-" + id);
  881. $l.attr("class", "label-item label-white");
  882. $l.css("background-color", c);
  883. $l.append("<strong>" + $(item).text() + "</strong>");
  884. $labels.append($l);
  885. }
  886. }
  887. });
  888. e.stopPropagation();
  889. return false;
  890. })
  891. }
  892. function initRelease() {
  893. // release new ajax preview
  894. (function () {
  895. $('[data-ajax-name=release-preview]').on("click", function () {
  896. var $this = $(this);
  897. $this.toggleAjax(function (resp) {
  898. $($this.data("preview")).html(resp);
  899. }, function () {
  900. $($this.data("preview")).html("no content");
  901. })
  902. });
  903. $('.release-write a[data-toggle]').on("click", function () {
  904. $('.release-preview-content').html("loading...");
  905. });
  906. }());
  907. // release new target selection
  908. (function () {
  909. $('#release-new-target-branch-list').on('click', 'a', function () {
  910. $('#tag-target').val($(this).text());
  911. $('#release-new-target-name').text(" " + $(this).text());
  912. });
  913. }());
  914. }
  915. function initRepoSetting() {
  916. // repo member add
  917. $('#repo-collaborator').on('keyup', function () {
  918. var $this = $(this);
  919. if (!$this.val()) {
  920. $this.next().toggleHide();
  921. return;
  922. }
  923. Gogits.getUsers($this.val(), $this.next());
  924. /*$.ajax({
  925. url: '/api/v1/users/search?q=' + $this.val(),
  926. dataType: "json",
  927. success: function (json) {
  928. if (json.ok && json.data.length) {
  929. var html = '';
  930. $.each(json.data, function (i, item) {
  931. html += '<li><img src="' + item.avatar + '">' + item.username + '</li>';
  932. });
  933. $this.next().toggleShow();
  934. $this.next().find('ul').html(html);
  935. } else {
  936. $this.next().toggleHide();
  937. }
  938. }
  939. });*/
  940. }).on('focus', function () {
  941. if (!$(this).val()) {
  942. $(this).next().toggleHide();
  943. }
  944. }).next().on("click", 'li', function () {
  945. $('#repo-collaborator').val($(this).text());
  946. });
  947. }
  948. function initRepoCreating() {
  949. // owner switch menu click
  950. (function () {
  951. $('#repo-owner-switch .dropdown-menu').on("click", "li", function () {
  952. var uid = $(this).data('uid');
  953. // set to input
  954. $('#repo-owner-id').val(uid);
  955. // set checked class
  956. if (!$(this).hasClass("checked")) {
  957. $(this).parent().find(".checked").removeClass("checked");
  958. $(this).addClass("checked");
  959. }
  960. // set button group to show clicked owner
  961. $('#repo-owner-avatar').attr("src", $(this).find('img').attr("src"));
  962. $('#repo-owner-name').text($(this).text().trim());
  963. console.log("set repo owner to uid :", uid, $(this).text().trim());
  964. });
  965. }());
  966. console.log("init repo-creating scripts");
  967. }
  968. function initOrganization() {
  969. (function(){
  970. $('#org-team-add-user').on('keyup', function () {
  971. var $this = $(this);
  972. if (!$this.val()) {
  973. $this.next().toggleHide();
  974. return;
  975. }
  976. Gogits.getUsers($this.val(), $this.next());
  977. }).on('focus', function () {
  978. if (!$(this).val()) {
  979. $(this).next().toggleHide();
  980. }
  981. }).next().on("click", 'li', function () {
  982. $('#org-team-add-user').val($(this).text());
  983. $('#org-team-add-user-form').submit();
  984. }).toggleHide();
  985. console.log("init script : add user to team");
  986. }());
  987. (function(){
  988. $('#org-team-add-repo').next().toggleHide();
  989. console.log("init script : add repository to team");
  990. }());
  991. console.log("init script : organization done");
  992. }
  993. function initTimeSwitch() {
  994. $(".time-since[title]").on("click", function() {
  995. var $this = $(this);
  996. var title = $this.attr("title");
  997. var text = $this.text();
  998. $this.text(title);
  999. $this.attr("title", text);
  1000. });
  1001. }
  1002. (function ($) {
  1003. $(function () {
  1004. initCore();
  1005. var body = $("#body");
  1006. if (body.data("page") == "user") {
  1007. initUserSetting();
  1008. }
  1009. if ($('.repo-nav').length) {
  1010. initRepository();
  1011. }
  1012. if ($('#install-card').length) {
  1013. initInstall();
  1014. }
  1015. if ($('#issue').length) {
  1016. initIssue();
  1017. }
  1018. if ($('#release').length) {
  1019. initRelease();
  1020. }
  1021. if ($('#repo-setting-container').length) {
  1022. initRepoSetting();
  1023. }
  1024. if ($('#repo-create').length) {
  1025. initRepoCreating();
  1026. }
  1027. if ($('#body-nav').hasClass("org-nav")) {
  1028. initOrganization();
  1029. }
  1030. initTimeSwitch();
  1031. });
  1032. })(jQuery);
  1033. String.prototype.endsWith = function (suffix) {
  1034. return this.indexOf(suffix, this.length - suffix.length) !== -1;
  1035. };