You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 123 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424
  1. /* globals wipPrefixes, issuesTribute, emojiTribute */
  2. /* exported timeAddManual, toggleStopwatch, cancelStopwatch, initHeatmap */
  3. /* exported toggleDeadlineForm, setDeadline, updateDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */
  4. 'use strict';
  5. function htmlEncode(text) {
  6. return jQuery('<div />').text(text).html()
  7. }
  8. let csrf;
  9. let suburl;
  10. let previewFileModes;
  11. let simpleMDEditor;
  12. let codeMirrorEditor;
  13. // Disable Dropzone auto-discover because it's manually initialized
  14. if (typeof(Dropzone) !== "undefined") {
  15. Dropzone.autoDiscover = false;
  16. }
  17. // Polyfill for IE9+ support (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
  18. if (!Array.from) {
  19. Array.from = (function () {
  20. const toStr = Object.prototype.toString;
  21. const isCallable = function (fn) {
  22. return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
  23. };
  24. const toInteger = function (value) {
  25. const number = Number(value);
  26. if (isNaN(number)) { return 0; }
  27. if (number === 0 || !isFinite(number)) { return number; }
  28. return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
  29. };
  30. const maxSafeInteger = Math.pow(2, 53) - 1;
  31. const toLength = function (value) {
  32. const len = toInteger(value);
  33. return Math.min(Math.max(len, 0), maxSafeInteger);
  34. };
  35. // The length property of the from method is 1.
  36. return function from(arrayLike/*, mapFn, thisArg */) {
  37. // 1. Let C be the this value.
  38. const C = this;
  39. // 2. Let items be ToObject(arrayLike).
  40. const items = Object(arrayLike);
  41. // 3. ReturnIfAbrupt(items).
  42. if (arrayLike == null) {
  43. throw new TypeError("Array.from requires an array-like object - not null or undefined");
  44. }
  45. // 4. If mapfn is undefined, then let mapping be false.
  46. const mapFn = arguments.length > 1 ? arguments[1] : void undefined;
  47. let T;
  48. if (typeof mapFn !== 'undefined') {
  49. // 5. else
  50. // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
  51. if (!isCallable(mapFn)) {
  52. throw new TypeError('Array.from: when provided, the second argument must be a function');
  53. }
  54. // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
  55. if (arguments.length > 2) {
  56. T = arguments[2];
  57. }
  58. }
  59. // 10. Let lenValue be Get(items, "length").
  60. // 11. Let len be ToLength(lenValue).
  61. const len = toLength(items.length);
  62. // 13. If IsConstructor(C) is true, then
  63. // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
  64. // 14. a. Else, Let A be ArrayCreate(len).
  65. const A = isCallable(C) ? Object(new C(len)) : new Array(len);
  66. // 16. Let k be 0.
  67. let k = 0;
  68. // 17. Repeat, while k < len… (also steps a - h)
  69. let kValue;
  70. while (k < len) {
  71. kValue = items[k];
  72. if (mapFn) {
  73. A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
  74. } else {
  75. A[k] = kValue;
  76. }
  77. k += 1;
  78. }
  79. // 18. Let putStatus be Put(A, "length", len, true).
  80. A.length = len;
  81. // 20. Return A.
  82. return A;
  83. };
  84. }());
  85. }
  86. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  87. if (typeof Object.assign != 'function') {
  88. // Must be writable: true, enumerable: false, configurable: true
  89. Object.defineProperty(Object, "assign", {
  90. value: function assign(target, _varArgs) { // .length of function is 2
  91. 'use strict';
  92. if (target == null) { // TypeError if undefined or null
  93. throw new TypeError('Cannot convert undefined or null to object');
  94. }
  95. const to = Object(target);
  96. for (let index = 1; index < arguments.length; index++) {
  97. const nextSource = arguments[index];
  98. if (nextSource != null) { // Skip over if undefined or null
  99. for (const nextKey in nextSource) {
  100. // Avoid bugs when hasOwnProperty is shadowed
  101. if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
  102. to[nextKey] = nextSource[nextKey];
  103. }
  104. }
  105. }
  106. }
  107. return to;
  108. },
  109. writable: true,
  110. configurable: true
  111. });
  112. }
  113. function initCommentPreviewTab($form) {
  114. const $tabMenu = $form.find('.tabular.menu');
  115. $tabMenu.find('.item').tab();
  116. $tabMenu.find('.item[data-tab="' + $tabMenu.data('preview') + '"]').click(function () {
  117. const $this = $(this);
  118. $.post($this.data('url'), {
  119. "_csrf": csrf,
  120. "mode": "gfm",
  121. "context": $this.data('context'),
  122. "text": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  123. },
  124. function (data) {
  125. const $previewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('preview') + '"]');
  126. $previewPanel.html(data);
  127. emojify.run($previewPanel[0]);
  128. $('pre code', $previewPanel[0]).each(function () {
  129. hljs.highlightBlock(this);
  130. });
  131. }
  132. );
  133. });
  134. buttonsClickOnEnter();
  135. }
  136. function initEditPreviewTab($form) {
  137. const $tabMenu = $form.find('.tabular.menu');
  138. $tabMenu.find('.item').tab();
  139. const $previewTab = $tabMenu.find('.item[data-tab="' + $tabMenu.data('preview') + '"]');
  140. if ($previewTab.length) {
  141. previewFileModes = $previewTab.data('preview-file-modes').split(',');
  142. $previewTab.click(function () {
  143. const $this = $(this);
  144. $.post($this.data('url'), {
  145. "_csrf": csrf,
  146. "mode": "gfm",
  147. "context": $this.data('context'),
  148. "text": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  149. },
  150. function (data) {
  151. const $previewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('preview') + '"]');
  152. $previewPanel.html(data);
  153. emojify.run($previewPanel[0]);
  154. $('pre code', $previewPanel[0]).each(function () {
  155. hljs.highlightBlock(this);
  156. });
  157. }
  158. );
  159. });
  160. }
  161. }
  162. function initEditDiffTab($form) {
  163. const $tabMenu = $form.find('.tabular.menu');
  164. $tabMenu.find('.item').tab();
  165. $tabMenu.find('.item[data-tab="' + $tabMenu.data('diff') + '"]').click(function () {
  166. const $this = $(this);
  167. $.post($this.data('url'), {
  168. "_csrf": csrf,
  169. "context": $this.data('context'),
  170. "content": $form.find('.tab.segment[data-tab="' + $tabMenu.data('write') + '"] textarea').val()
  171. },
  172. function (data) {
  173. const $diffPreviewPanel = $form.find('.tab.segment[data-tab="' + $tabMenu.data('diff') + '"]');
  174. $diffPreviewPanel.html(data);
  175. emojify.run($diffPreviewPanel[0]);
  176. }
  177. );
  178. });
  179. }
  180. function initEditForm() {
  181. if ($('.edit.form').length == 0) {
  182. return;
  183. }
  184. initEditPreviewTab($('.edit.form'));
  185. initEditDiffTab($('.edit.form'));
  186. }
  187. function initBranchSelector() {
  188. const $selectBranch = $('.ui.select-branch')
  189. const $branchMenu = $selectBranch.find('.reference-list-menu');
  190. $branchMenu.find('.item:not(.no-select)').click(function () {
  191. const selectedValue = $(this).data('id');
  192. $($(this).data('id-selector')).val(selectedValue);
  193. $selectBranch.find('.ui .branch-name').text(selectedValue);
  194. });
  195. $selectBranch.find('.reference.column').click(function () {
  196. $selectBranch.find('.scrolling.reference-list-menu').css('display', 'none');
  197. $selectBranch.find('.reference .text').removeClass('black');
  198. $($(this).data('target')).css('display', 'block');
  199. $(this).find('.text').addClass('black');
  200. return false;
  201. });
  202. }
  203. function updateIssuesMeta(url, action, issueIds, elementId) {
  204. return new Promise(function(resolve) {
  205. $.ajax({
  206. type: "POST",
  207. url: url,
  208. data: {
  209. "_csrf": csrf,
  210. "action": action,
  211. "issue_ids": issueIds,
  212. "id": elementId
  213. },
  214. success: resolve
  215. })
  216. })
  217. }
  218. function initRepoStatusChecker() {
  219. const migrating = $("#repo_migrating");
  220. $('#repo_migrating_failed').hide();
  221. if (migrating) {
  222. const repo_name = migrating.attr('repo');
  223. if (typeof repo_name === 'undefined') {
  224. return
  225. }
  226. $.ajax({
  227. type: "GET",
  228. url: suburl +"/"+repo_name+"/status",
  229. data: {
  230. "_csrf": csrf,
  231. },
  232. complete: function(xhr) {
  233. if (xhr.status == 200) {
  234. if (xhr.responseJSON) {
  235. if (xhr.responseJSON["status"] == 0) {
  236. location.reload();
  237. return
  238. }
  239. setTimeout(function () {
  240. initRepoStatusChecker()
  241. }, 2000);
  242. return
  243. }
  244. }
  245. $('#repo_migrating_progress').hide();
  246. $('#repo_migrating_failed').show();
  247. }
  248. })
  249. }
  250. }
  251. function initReactionSelector(parent) {
  252. let reactions = '';
  253. if (!parent) {
  254. parent = $(document);
  255. reactions = '.reactions > ';
  256. }
  257. parent.find(reactions + 'a.label').popup({'position': 'bottom left', 'metadata': {'content': 'title', 'title': 'none'}});
  258. parent.find('.select-reaction > .menu > .item, ' + reactions + 'a.label').on('click', function(e){
  259. const vm = this;
  260. e.preventDefault();
  261. if ($(this).hasClass('disabled')) return;
  262. const actionURL = $(this).hasClass('item') ?
  263. $(this).closest('.select-reaction').data('action-url') :
  264. $(this).data('action-url');
  265. const url = actionURL + '/' + ($(this).hasClass('blue') ? 'unreact' : 'react');
  266. $.ajax({
  267. type: 'POST',
  268. url: url,
  269. data: {
  270. '_csrf': csrf,
  271. 'content': $(this).data('content')
  272. }
  273. }).done(function(resp) {
  274. if (resp && (resp.html || resp.empty)) {
  275. const content = $(vm).closest('.content');
  276. let react = content.find('.segment.reactions');
  277. if (!resp.empty && react.length > 0) {
  278. react.remove();
  279. }
  280. if (!resp.empty) {
  281. react = $('<div class="ui attached segment reactions"></div>');
  282. const attachments = content.find('.segment.bottom:first');
  283. if (attachments.length > 0) {
  284. react.insertBefore(attachments);
  285. } else {
  286. react.appendTo(content);
  287. }
  288. react.html(resp.html);
  289. const hasEmoji = react.find('.has-emoji');
  290. for (let i = 0; i < hasEmoji.length; i++) {
  291. emojify.run(hasEmoji.get(i));
  292. }
  293. react.find('.dropdown').dropdown();
  294. initReactionSelector(react);
  295. }
  296. }
  297. });
  298. });
  299. }
  300. function insertAtCursor(field, value) {
  301. if (field.selectionStart || field.selectionStart === 0) {
  302. const startPos = field.selectionStart;
  303. const endPos = field.selectionEnd;
  304. field.value = field.value.substring(0, startPos)
  305. + value
  306. + field.value.substring(endPos, field.value.length);
  307. field.selectionStart = startPos + value.length;
  308. field.selectionEnd = startPos + value.length;
  309. } else {
  310. field.value += value;
  311. }
  312. }
  313. function replaceAndKeepCursor(field, oldval, newval) {
  314. if (field.selectionStart || field.selectionStart === 0) {
  315. const startPos = field.selectionStart;
  316. const endPos = field.selectionEnd;
  317. field.value = field.value.replace(oldval, newval);
  318. field.selectionStart = startPos + newval.length - oldval.length;
  319. field.selectionEnd = endPos + newval.length - oldval.length;
  320. } else {
  321. field.value = field.value.replace(oldval, newval);
  322. }
  323. }
  324. function retrieveImageFromClipboardAsBlob(pasteEvent, callback){
  325. if (!pasteEvent.clipboardData) {
  326. return;
  327. }
  328. const items = pasteEvent.clipboardData.items;
  329. if (typeof(items) === "undefined") {
  330. return;
  331. }
  332. for (let i = 0; i < items.length; i++) {
  333. if (items[i].type.indexOf("image") === -1) continue;
  334. const blob = items[i].getAsFile();
  335. if (typeof(callback) === "function") {
  336. pasteEvent.preventDefault();
  337. pasteEvent.stopPropagation();
  338. callback(blob);
  339. }
  340. }
  341. }
  342. function uploadFile(file, callback) {
  343. const xhr = new XMLHttpRequest();
  344. xhr.onload = function() {
  345. if (xhr.status == 200) {
  346. callback(xhr.responseText);
  347. }
  348. };
  349. xhr.open("post", suburl + "/attachments", true);
  350. xhr.setRequestHeader("X-Csrf-Token", csrf);
  351. const formData = new FormData();
  352. formData.append('file', file, file.name);
  353. xhr.send(formData);
  354. }
  355. function reload() {
  356. window.location.reload();
  357. }
  358. function initImagePaste(target) {
  359. target.each(function() {
  360. const field = this;
  361. field.addEventListener('paste', function(event){
  362. retrieveImageFromClipboardAsBlob(event, function(img) {
  363. const name = img.name.substr(0, img.name.lastIndexOf('.'));
  364. insertAtCursor(field, '![' + name + ']()');
  365. uploadFile(img, function(res) {
  366. const data = JSON.parse(res);
  367. replaceAndKeepCursor(field, '![' + name + ']()', '![' + name + '](' + suburl + '/attachments/' + data.uuid + ')');
  368. const input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  369. $('.files').append(input);
  370. });
  371. });
  372. }, false);
  373. });
  374. }
  375. function initCommentForm() {
  376. if ($('.comment.form').length == 0) {
  377. return
  378. }
  379. initBranchSelector();
  380. initCommentPreviewTab($('.comment.form'));
  381. initImagePaste($('.comment.form textarea'));
  382. // Listsubmit
  383. function initListSubmits(selector, outerSelector) {
  384. const $list = $('.ui.' + outerSelector + '.list');
  385. const $noSelect = $list.find('.no-select');
  386. const $listMenu = $('.' + selector + ' .menu');
  387. let hasLabelUpdateAction = $listMenu.data('action') == 'update';
  388. const labels = {};
  389. $('.' + selector).dropdown('setting', 'onHide', function(){
  390. hasLabelUpdateAction = $listMenu.data('action') == 'update'; // Update the var
  391. if (hasLabelUpdateAction) {
  392. const promises = [];
  393. Object.keys(labels).forEach(function(elementId) {
  394. const label = labels[elementId];
  395. const promise = updateIssuesMeta(
  396. label["update-url"],
  397. label["action"],
  398. label["issue-id"],
  399. elementId
  400. );
  401. promises.push(promise);
  402. });
  403. Promise.all(promises).then(reload);
  404. }
  405. });
  406. $listMenu.find('.item:not(.no-select)').click(function () {
  407. // we don't need the action attribute when updating assignees
  408. if (selector == 'select-assignees-modify') {
  409. // UI magic. We need to do this here, otherwise it would destroy the functionality of
  410. // adding/removing labels
  411. if ($(this).hasClass('checked')) {
  412. $(this).removeClass('checked');
  413. $(this).find('.octicon').removeClass('octicon-check');
  414. } else {
  415. $(this).addClass('checked');
  416. $(this).find('.octicon').addClass('octicon-check');
  417. }
  418. updateIssuesMeta(
  419. $listMenu.data('update-url'),
  420. "",
  421. $listMenu.data('issue-id'),
  422. $(this).data('id')
  423. );
  424. $listMenu.data('action', 'update'); // Update to reload the page when we updated items
  425. return false;
  426. }
  427. if ($(this).hasClass('checked')) {
  428. $(this).removeClass('checked');
  429. $(this).find('.octicon').removeClass('octicon-check');
  430. if (hasLabelUpdateAction) {
  431. if (!($(this).data('id') in labels)) {
  432. labels[$(this).data('id')] = {
  433. "update-url": $listMenu.data('update-url'),
  434. "action": "detach",
  435. "issue-id": $listMenu.data('issue-id'),
  436. };
  437. } else {
  438. delete labels[$(this).data('id')];
  439. }
  440. }
  441. } else {
  442. $(this).addClass('checked');
  443. $(this).find('.octicon').addClass('octicon-check');
  444. if (hasLabelUpdateAction) {
  445. if (!($(this).data('id') in labels)) {
  446. labels[$(this).data('id')] = {
  447. "update-url": $listMenu.data('update-url'),
  448. "action": "attach",
  449. "issue-id": $listMenu.data('issue-id'),
  450. };
  451. } else {
  452. delete labels[$(this).data('id')];
  453. }
  454. }
  455. }
  456. const listIds = [];
  457. $(this).parent().find('.item').each(function () {
  458. if ($(this).hasClass('checked')) {
  459. listIds.push($(this).data('id'));
  460. $($(this).data('id-selector')).removeClass('hide');
  461. } else {
  462. $($(this).data('id-selector')).addClass('hide');
  463. }
  464. });
  465. if (listIds.length == 0) {
  466. $noSelect.removeClass('hide');
  467. } else {
  468. $noSelect.addClass('hide');
  469. }
  470. $($(this).parent().data('id')).val(listIds.join(","));
  471. return false;
  472. });
  473. $listMenu.find('.no-select.item').click(function () {
  474. if (hasLabelUpdateAction || selector == 'select-assignees-modify') {
  475. updateIssuesMeta(
  476. $listMenu.data('update-url'),
  477. "clear",
  478. $listMenu.data('issue-id'),
  479. ""
  480. ).then(reload);
  481. }
  482. $(this).parent().find('.item').each(function () {
  483. $(this).removeClass('checked');
  484. $(this).find('.octicon').removeClass('octicon-check');
  485. });
  486. $list.find('.item').each(function () {
  487. $(this).addClass('hide');
  488. });
  489. $noSelect.removeClass('hide');
  490. $($(this).parent().data('id')).val('');
  491. });
  492. }
  493. // Init labels and assignees
  494. initListSubmits('select-label', 'labels');
  495. initListSubmits('select-assignees', 'assignees');
  496. initListSubmits('select-assignees-modify', 'assignees');
  497. function selectItem(select_id, input_id) {
  498. const $menu = $(select_id + ' .menu');
  499. const $list = $('.ui' + select_id + '.list');
  500. const hasUpdateAction = $menu.data('action') == 'update';
  501. $menu.find('.item:not(.no-select)').click(function () {
  502. $(this).parent().find('.item').each(function () {
  503. $(this).removeClass('selected active')
  504. });
  505. $(this).addClass('selected active');
  506. if (hasUpdateAction) {
  507. updateIssuesMeta(
  508. $menu.data('update-url'),
  509. "",
  510. $menu.data('issue-id'),
  511. $(this).data('id')
  512. ).then(reload);
  513. }
  514. switch (input_id) {
  515. case '#milestone_id':
  516. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  517. htmlEncode($(this).text()) + '</a>');
  518. break;
  519. case '#assignee_id':
  520. $list.find('.selected').html('<a class="item" href=' + $(this).data('href') + '>' +
  521. '<img class="ui avatar image" src=' + $(this).data('avatar') + '>' +
  522. htmlEncode($(this).text()) + '</a>');
  523. }
  524. $('.ui' + select_id + '.list .no-select').addClass('hide');
  525. $(input_id).val($(this).data('id'));
  526. });
  527. $menu.find('.no-select.item').click(function () {
  528. $(this).parent().find('.item:not(.no-select)').each(function () {
  529. $(this).removeClass('selected active')
  530. });
  531. if (hasUpdateAction) {
  532. updateIssuesMeta(
  533. $menu.data('update-url'),
  534. "",
  535. $menu.data('issue-id'),
  536. $(this).data('id')
  537. ).then(reload);
  538. }
  539. $list.find('.selected').html('');
  540. $list.find('.no-select').removeClass('hide');
  541. $(input_id).val('');
  542. });
  543. }
  544. // Milestone and assignee
  545. selectItem('.select-milestone', '#milestone_id');
  546. selectItem('.select-assignee', '#assignee_id');
  547. }
  548. function initInstall() {
  549. if ($('.install').length == 0) {
  550. return;
  551. }
  552. if ($('#db_host').val()=="") {
  553. $('#db_host').val("127.0.0.1:3306");
  554. $('#db_user').val("gitea");
  555. $('#db_name').val("gitea");
  556. }
  557. // Database type change detection.
  558. $("#db_type").change(function () {
  559. const sqliteDefault = 'data/gitea.db';
  560. const tidbDefault = 'data/gitea_tidb';
  561. const dbType = $(this).val();
  562. if (dbType === "SQLite3") {
  563. $('#sql_settings').hide();
  564. $('#pgsql_settings').hide();
  565. $('#mysql_settings').hide();
  566. $('#sqlite_settings').show();
  567. if (dbType === "SQLite3" && $('#db_path').val() == tidbDefault) {
  568. $('#db_path').val(sqliteDefault);
  569. }
  570. return;
  571. }
  572. const dbDefaults = {
  573. "MySQL": "127.0.0.1:3306",
  574. "PostgreSQL": "127.0.0.1:5432",
  575. "MSSQL": "127.0.0.1:1433"
  576. };
  577. $('#sqlite_settings').hide();
  578. $('#sql_settings').show();
  579. $('#pgsql_settings').toggle(dbType === "PostgreSQL");
  580. $('#mysql_settings').toggle(dbType === "MySQL");
  581. $.each(dbDefaults, function(_type, defaultHost) {
  582. if ($('#db_host').val() == defaultHost) {
  583. $('#db_host').val(dbDefaults[dbType]);
  584. return false;
  585. }
  586. });
  587. });
  588. // TODO: better handling of exclusive relations.
  589. $('#offline-mode input').change(function () {
  590. if ($(this).is(':checked')) {
  591. $('#disable-gravatar').checkbox('check');
  592. $('#federated-avatar-lookup').checkbox('uncheck');
  593. }
  594. });
  595. $('#disable-gravatar input').change(function () {
  596. if ($(this).is(':checked')) {
  597. $('#federated-avatar-lookup').checkbox('uncheck');
  598. } else {
  599. $('#offline-mode').checkbox('uncheck');
  600. }
  601. });
  602. $('#federated-avatar-lookup input').change(function () {
  603. if ($(this).is(':checked')) {
  604. $('#disable-gravatar').checkbox('uncheck');
  605. $('#offline-mode').checkbox('uncheck');
  606. }
  607. });
  608. $('#enable-openid-signin input').change(function () {
  609. if ($(this).is(':checked')) {
  610. if (!$('#disable-registration input').is(':checked')) {
  611. $('#enable-openid-signup').checkbox('check');
  612. }
  613. } else {
  614. $('#enable-openid-signup').checkbox('uncheck');
  615. }
  616. });
  617. $('#disable-registration input').change(function () {
  618. if ($(this).is(':checked')) {
  619. $('#enable-captcha').checkbox('uncheck');
  620. $('#enable-openid-signup').checkbox('uncheck');
  621. } else {
  622. $('#enable-openid-signup').checkbox('check');
  623. }
  624. });
  625. $('#enable-captcha input').change(function () {
  626. if ($(this).is(':checked')) {
  627. $('#disable-registration').checkbox('uncheck');
  628. }
  629. });
  630. }
  631. function initRepository() {
  632. if ($('.repository').length == 0) {
  633. return;
  634. }
  635. function initFilterSearchDropdown(selector) {
  636. const $dropdown = $(selector);
  637. $dropdown.dropdown({
  638. fullTextSearch: true,
  639. selectOnKeydown: false,
  640. onChange: function (_text, _value, $choice) {
  641. if ($choice.data('url')) {
  642. window.location.href = $choice.data('url');
  643. }
  644. },
  645. message: {noResults: $dropdown.data('no-results')}
  646. });
  647. }
  648. // File list and commits
  649. if ($('.repository.file.list').length > 0 ||
  650. ('.repository.commits').length > 0) {
  651. initFilterBranchTagDropdown('.choose.reference .dropdown');
  652. }
  653. // Wiki
  654. if ($('.repository.wiki.view').length > 0) {
  655. initFilterSearchDropdown('.choose.page .dropdown');
  656. }
  657. // Options
  658. if ($('.repository.settings.options').length > 0) {
  659. $('#repo_name').keyup(function () {
  660. const $prompt = $('#repo-name-change-prompt');
  661. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  662. $prompt.show();
  663. } else {
  664. $prompt.hide();
  665. }
  666. });
  667. // Enable or select internal/external wiki system and issue tracker.
  668. $('.enable-system').change(function () {
  669. if (this.checked) {
  670. $($(this).data('target')).removeClass('disabled');
  671. if (!$(this).data('context')) $($(this).data('context')).addClass('disabled');
  672. } else {
  673. $($(this).data('target')).addClass('disabled');
  674. if (!$(this).data('context')) $($(this).data('context')).removeClass('disabled');
  675. }
  676. });
  677. $('.enable-system-radio').change(function () {
  678. if (this.value == 'false') {
  679. $($(this).data('target')).addClass('disabled');
  680. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).removeClass('disabled');
  681. } else if (this.value == 'true') {
  682. $($(this).data('target')).removeClass('disabled');
  683. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).addClass('disabled');
  684. }
  685. });
  686. }
  687. // Labels
  688. if ($('.repository.labels').length > 0) {
  689. // Create label
  690. const $newLabelPanel = $('.new-label.segment');
  691. $('.new-label.button').click(function () {
  692. $newLabelPanel.show();
  693. });
  694. $('.new-label.segment .cancel').click(function () {
  695. $newLabelPanel.hide();
  696. });
  697. $('.color-picker').each(function () {
  698. $(this).minicolors();
  699. });
  700. $('.precolors .color').click(function () {
  701. const color_hex = $(this).data('color-hex');
  702. $('.color-picker').val(color_hex);
  703. $('.minicolors-swatch-color').css("background-color", color_hex);
  704. });
  705. $('.edit-label-button').click(function () {
  706. $('#label-modal-id').val($(this).data('id'));
  707. $('.edit-label .new-label-input').val($(this).data('title'));
  708. $('.edit-label .new-label-desc-input').val($(this).data('description'));
  709. $('.edit-label .color-picker').val($(this).data('color'));
  710. $('.minicolors-swatch-color').css("background-color", $(this).data('color'));
  711. $('.edit-label.modal').modal({
  712. onApprove: function () {
  713. $('.edit-label.form').submit();
  714. }
  715. }).modal('show');
  716. return false;
  717. });
  718. }
  719. // Milestones
  720. if ($('.repository.new.milestone').length > 0) {
  721. const $datepicker = $('.milestone.datepicker');
  722. $datepicker.datetimepicker({
  723. lang: $datepicker.data('lang'),
  724. inline: true,
  725. timepicker: false,
  726. startDate: $datepicker.data('start-date'),
  727. formatDate: 'Y-m-d',
  728. onSelectDate: function (ct) {
  729. $('#deadline').val(ct.dateFormat('Y-m-d'));
  730. }
  731. });
  732. $('#clear-date').click(function () {
  733. $('#deadline').val('');
  734. return false;
  735. });
  736. }
  737. // Issues
  738. if ($('.repository.view.issue').length > 0) {
  739. // Edit issue title
  740. const $issueTitle = $('#issue-title');
  741. const $editInput = $('#edit-title-input input');
  742. const editTitleToggle = function () {
  743. $issueTitle.toggle();
  744. $('.not-in-edit').toggle();
  745. $('#edit-title-input').toggle();
  746. $('.in-edit').toggle();
  747. $editInput.focus();
  748. return false;
  749. };
  750. $('#edit-title').click(editTitleToggle);
  751. $('#cancel-edit-title').click(editTitleToggle);
  752. $('#save-edit-title').click(editTitleToggle).click(function () {
  753. if ($editInput.val().length == 0 ||
  754. $editInput.val() == $issueTitle.text()) {
  755. $editInput.val($issueTitle.text());
  756. return false;
  757. }
  758. $.post($(this).data('update-url'), {
  759. "_csrf": csrf,
  760. "title": $editInput.val()
  761. },
  762. function (data) {
  763. $editInput.val(data.title);
  764. $issueTitle.text(data.title);
  765. reload();
  766. });
  767. return false;
  768. });
  769. // Edit issue or comment content
  770. $('.edit-content').click(function () {
  771. const $segment = $(this).parent().parent().parent().next();
  772. const $editContentZone = $segment.find('.edit-content-zone');
  773. const $renderContent = $segment.find('.render-content');
  774. const $rawContent = $segment.find('.raw-content');
  775. let $textarea;
  776. // Setup new form
  777. if ($editContentZone.html().length == 0) {
  778. $editContentZone.html($('#edit-content-form').html());
  779. $textarea = $editContentZone.find('textarea');
  780. issuesTribute.attach($textarea.get());
  781. emojiTribute.attach($textarea.get());
  782. const $dropzone = $editContentZone.find('.dropzone');
  783. $dropzone.data("saved", false);
  784. const $files = $editContentZone.find('.comment-files');
  785. if ($dropzone.length > 0) {
  786. const filenameDict = {};
  787. $dropzone.dropzone({
  788. url: $dropzone.data('upload-url'),
  789. headers: {"X-Csrf-Token": csrf},
  790. maxFiles: $dropzone.data('max-file'),
  791. maxFilesize: $dropzone.data('max-size'),
  792. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  793. addRemoveLinks: true,
  794. dictDefaultMessage: $dropzone.data('default-message'),
  795. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  796. dictFileTooBig: $dropzone.data('file-too-big'),
  797. dictRemoveFile: $dropzone.data('remove-file'),
  798. init: function () {
  799. this.on("success", function (file, data) {
  800. filenameDict[file.name] = {
  801. "uuid": data.uuid,
  802. "submitted": false
  803. }
  804. const input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  805. $files.append(input);
  806. });
  807. this.on("removedfile", function (file) {
  808. if (!(file.name in filenameDict)) {
  809. return;
  810. }
  811. $('#' + filenameDict[file.name].uuid).remove();
  812. if ($dropzone.data('remove-url') && $dropzone.data('csrf') && !filenameDict[file.name].submitted) {
  813. $.post($dropzone.data('remove-url'), {
  814. file: filenameDict[file.name].uuid,
  815. _csrf: $dropzone.data('csrf')
  816. });
  817. }
  818. });
  819. this.on("submit", function () {
  820. $.each(filenameDict, function(name){
  821. filenameDict[name].submitted = true;
  822. });
  823. });
  824. this.on("reload", function (){
  825. $.getJSON($editContentZone.data('attachment-url'), function(data){
  826. const drop = $dropzone.get(0).dropzone;
  827. drop.removeAllFiles(true);
  828. $files.empty();
  829. $.each(data, function(){
  830. const imgSrc = $dropzone.data('upload-url') + "/" + this.uuid;
  831. drop.emit("addedfile", this);
  832. drop.emit("thumbnail", this, imgSrc);
  833. drop.emit("complete", this);
  834. drop.files.push(this);
  835. filenameDict[this.name] = {
  836. "submitted": true,
  837. "uuid": this.uuid
  838. }
  839. $dropzone.find("img[src='" + imgSrc + "']").css("max-width", "100%");
  840. const input = $('<input id="' + this.uuid + '" name="files" type="hidden">').val(this.uuid);
  841. $files.append(input);
  842. });
  843. });
  844. });
  845. }
  846. });
  847. $dropzone.get(0).dropzone.emit("reload");
  848. }
  849. // Give new write/preview data-tab name to distinguish from others
  850. const $editContentForm = $editContentZone.find('.ui.comment.form');
  851. const $tabMenu = $editContentForm.find('.tabular.menu');
  852. $tabMenu.attr('data-write', $editContentZone.data('write'));
  853. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  854. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  855. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  856. $editContentForm.find('.write.segment').attr('data-tab', $editContentZone.data('write'));
  857. $editContentForm.find('.preview.segment').attr('data-tab', $editContentZone.data('preview'));
  858. initCommentPreviewTab($editContentForm);
  859. $editContentZone.find('.cancel.button').click(function () {
  860. $renderContent.show();
  861. $editContentZone.hide();
  862. $dropzone.get(0).dropzone.emit("reload");
  863. });
  864. $editContentZone.find('.save.button').click(function () {
  865. $renderContent.show();
  866. $editContentZone.hide();
  867. const $attachments = $files.find("[name=files]").map(function(){
  868. return $(this).val();
  869. }).get();
  870. $.post($editContentZone.data('update-url'), {
  871. "_csrf": csrf,
  872. "content": $textarea.val(),
  873. "context": $editContentZone.data('context'),
  874. "files": $attachments
  875. },
  876. function (data) {
  877. if (data.length == 0) {
  878. $renderContent.html($('#no-content').html());
  879. } else {
  880. $renderContent.html(data.content);
  881. emojify.run($renderContent[0]);
  882. $('pre code', $renderContent[0]).each(function () {
  883. hljs.highlightBlock(this);
  884. });
  885. }
  886. const $content = $segment.parent();
  887. if(!$content.find(".ui.small.images").length){
  888. if(data.attachments != ""){
  889. $content.append(
  890. '<div class="ui bottom attached segment">' +
  891. ' <div class="ui small images">' +
  892. ' </div>' +
  893. '</div>'
  894. );
  895. $content.find(".ui.small.images").html(data.attachments);
  896. }
  897. } else if (data.attachments == "") {
  898. $content.find(".ui.small.images").parent().remove();
  899. } else {
  900. $content.find(".ui.small.images").html(data.attachments);
  901. }
  902. $dropzone.get(0).dropzone.emit("submit");
  903. $dropzone.get(0).dropzone.emit("reload");
  904. });
  905. });
  906. } else {
  907. $textarea = $segment.find('textarea');
  908. }
  909. // Show write/preview tab and copy raw content as needed
  910. $editContentZone.show();
  911. $renderContent.hide();
  912. if ($textarea.val().length == 0) {
  913. $textarea.val($rawContent.text());
  914. }
  915. $textarea.focus();
  916. return false;
  917. });
  918. // Delete comment
  919. $('.delete-comment').click(function () {
  920. const $this = $(this);
  921. if (confirm($this.data('locale'))) {
  922. $.post($this.data('url'), {
  923. "_csrf": csrf
  924. }).success(function () {
  925. $('#' + $this.data('comment-id')).remove();
  926. });
  927. }
  928. return false;
  929. });
  930. // Change status
  931. const $statusButton = $('#status-button');
  932. $('#comment-form .edit_area').keyup(function () {
  933. if ($(this).val().length == 0) {
  934. $statusButton.text($statusButton.data('status'))
  935. } else {
  936. $statusButton.text($statusButton.data('status-and-comment'))
  937. }
  938. });
  939. $statusButton.click(function () {
  940. $('#status').val($statusButton.data('status-val'));
  941. $('#comment-form').submit();
  942. });
  943. // Pull Request merge button
  944. const $mergeButton = $('.merge-button > button');
  945. $mergeButton.on('click', function(e) {
  946. e.preventDefault();
  947. $('.' + $(this).data('do') + '-fields').show();
  948. $(this).parent().hide();
  949. });
  950. $('.merge-button > .dropdown').dropdown({
  951. onChange: function (_text, _value, $choice) {
  952. if ($choice.data('do')) {
  953. $mergeButton.find('.button-text').text($choice.text());
  954. $mergeButton.data('do', $choice.data('do'));
  955. }
  956. }
  957. });
  958. $('.merge-cancel').on('click', function(e) {
  959. e.preventDefault();
  960. $(this).closest('.form').hide();
  961. $mergeButton.parent().show();
  962. });
  963. initReactionSelector();
  964. }
  965. // Diff
  966. if ($('.repository.diff').length > 0) {
  967. $('.diff-counter').each(function () {
  968. const $item = $(this);
  969. const addLine = $item.find('span[data-line].add').data("line");
  970. const delLine = $item.find('span[data-line].del').data("line");
  971. const addPercent = parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine)) * 100;
  972. $item.find(".bar .add").css("width", addPercent + "%");
  973. });
  974. }
  975. // Quick start and repository home
  976. $('#repo-clone-ssh').click(function () {
  977. $('.clone-url').text($(this).data('link'));
  978. $('#repo-clone-url').val($(this).data('link'));
  979. $(this).addClass('blue');
  980. $('#repo-clone-https').removeClass('blue');
  981. localStorage.setItem('repo-clone-protocol', 'ssh');
  982. });
  983. $('#repo-clone-https').click(function () {
  984. $('.clone-url').text($(this).data('link'));
  985. $('#repo-clone-url').val($(this).data('link'));
  986. $(this).addClass('blue');
  987. $('#repo-clone-ssh').removeClass('blue');
  988. localStorage.setItem('repo-clone-protocol', 'https');
  989. });
  990. $('#repo-clone-url').click(function () {
  991. $(this).select();
  992. });
  993. // Pull request
  994. const $repoComparePull = $('.repository.compare.pull');
  995. if ($repoComparePull.length > 0) {
  996. initFilterSearchDropdown('.choose.branch .dropdown');
  997. // show pull request form
  998. $repoComparePull.find('button.show-form').on('click', function(e) {
  999. e.preventDefault();
  1000. $repoComparePull.find('.pullrequest-form').show();
  1001. $(this).parent().hide();
  1002. });
  1003. }
  1004. // Branches
  1005. if ($('.repository.settings.branches').length > 0) {
  1006. initFilterSearchDropdown('.protected-branches .dropdown');
  1007. $('.enable-protection, .enable-whitelist').change(function () {
  1008. if (this.checked) {
  1009. $($(this).data('target')).removeClass('disabled');
  1010. } else {
  1011. $($(this).data('target')).addClass('disabled');
  1012. }
  1013. });
  1014. }
  1015. }
  1016. function initMigration() {
  1017. const toggleMigrations = function() {
  1018. const authUserName = $('#auth_username').val();
  1019. const cloneAddr = $('#clone_addr').val();
  1020. if (!$('#mirror').is(":checked") && (authUserName!=undefined && authUserName.length > 0)
  1021. && (cloneAddr!=undefined && (cloneAddr.startsWith("https://github.com") || cloneAddr.startsWith("http://github.com")))) {
  1022. $('#migrate_items').show();
  1023. } else {
  1024. $('#migrate_items').hide();
  1025. }
  1026. }
  1027. toggleMigrations();
  1028. $('#clone_addr').on('input', toggleMigrations)
  1029. $('#auth_username').on('input', toggleMigrations)
  1030. $('#mirror').on('change', toggleMigrations)
  1031. }
  1032. function initPullRequestReview() {
  1033. $('.show-outdated').on('click', function (e) {
  1034. e.preventDefault();
  1035. const id = $(this).data('comment');
  1036. $(this).addClass("hide");
  1037. $("#code-comments-" + id).removeClass('hide');
  1038. $("#code-preview-" + id).removeClass('hide');
  1039. $("#hide-outdated-" + id).removeClass('hide');
  1040. });
  1041. $('.hide-outdated').on('click', function (e) {
  1042. e.preventDefault();
  1043. const id = $(this).data('comment');
  1044. $(this).addClass("hide");
  1045. $("#code-comments-" + id).addClass('hide');
  1046. $("#code-preview-" + id).addClass('hide');
  1047. $("#show-outdated-" + id).removeClass('hide');
  1048. });
  1049. $('button.comment-form-reply').on('click', function (e) {
  1050. e.preventDefault();
  1051. $(this).hide();
  1052. const form = $(this).parent().find('.comment-form')
  1053. form.removeClass('hide');
  1054. assingMenuAttributes(form.find('.menu'));
  1055. });
  1056. // The following part is only for diff views
  1057. if ($('.repository.pull.diff').length == 0) {
  1058. return;
  1059. }
  1060. $('.diff-detail-box.ui.sticky').sticky();
  1061. $('.btn-review').on('click', function(e) {
  1062. e.preventDefault();
  1063. $(this).closest('.dropdown').find('.menu').toggle('visible');
  1064. }).closest('.dropdown').find('.link.close').on('click', function(e) {
  1065. e.preventDefault();
  1066. $(this).closest('.menu').toggle('visible');
  1067. });
  1068. $('.code-view .lines-code,.code-view .lines-num')
  1069. .on('mouseenter', function() {
  1070. const parent = $(this).closest('td');
  1071. $(this).closest('tr').addClass(
  1072. parent.hasClass('lines-num-old') || parent.hasClass('lines-code-old')
  1073. ? 'focus-lines-old' : 'focus-lines-new'
  1074. );
  1075. })
  1076. .on('mouseleave', function() {
  1077. $(this).closest('tr').removeClass('focus-lines-new focus-lines-old');
  1078. });
  1079. $('.add-code-comment').on('click', function(e) {
  1080. // https://github.com/go-gitea/gitea/issues/4745
  1081. if ($(e.target).hasClass('btn-add-single')) {
  1082. return;
  1083. }
  1084. e.preventDefault();
  1085. const isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  1086. const side = $(this).data('side');
  1087. const idx = $(this).data('idx');
  1088. const path = $(this).data('path');
  1089. const form = $('#pull_review_add_comment').html();
  1090. const tr = $(this).closest('tr');
  1091. let ntr = tr.next();
  1092. if (!ntr.hasClass('add-comment')) {
  1093. ntr = $('<tr class="add-comment">'
  1094. + (isSplit ? '<td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-left"></td><td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-right"></td>'
  1095. : '<td class="lines-num"></td><td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-left add-comment-right"></td>')
  1096. + '</tr>');
  1097. tr.after(ntr);
  1098. }
  1099. const td = ntr.find('.add-comment-' + side);
  1100. let commentCloud = td.find('.comment-code-cloud');
  1101. if (commentCloud.length === 0) {
  1102. td.html(form);
  1103. commentCloud = td.find('.comment-code-cloud');
  1104. assingMenuAttributes(commentCloud.find('.menu'));
  1105. td.find("input[name='line']").val(idx);
  1106. td.find("input[name='side']").val(side === "left" ? "previous":"proposed");
  1107. td.find("input[name='path']").val(path);
  1108. }
  1109. commentCloud.find('textarea').focus();
  1110. });
  1111. }
  1112. function assingMenuAttributes(menu) {
  1113. const id = Math.floor(Math.random() * Math.floor(1000000));
  1114. menu.attr('data-write', menu.attr('data-write') + id);
  1115. menu.attr('data-preview', menu.attr('data-preview') + id);
  1116. menu.find('.item').each(function() {
  1117. const tab = $(this).attr('data-tab') + id;
  1118. $(this).attr('data-tab', tab);
  1119. });
  1120. menu.parent().find("*[data-tab='write']").attr('data-tab', 'write' + id);
  1121. menu.parent().find("*[data-tab='preview']").attr('data-tab', 'preview' + id);
  1122. initCommentPreviewTab(menu.parent(".form"));
  1123. return id;
  1124. }
  1125. function initRepositoryCollaboration() {
  1126. // Change collaborator access mode
  1127. $('.access-mode.menu .item').click(function () {
  1128. const $menu = $(this).parent();
  1129. $.post($menu.data('url'), {
  1130. "_csrf": csrf,
  1131. "uid": $menu.data('uid'),
  1132. "mode": $(this).data('value')
  1133. })
  1134. });
  1135. }
  1136. function initTeamSettings() {
  1137. // Change team access mode
  1138. $('.organization.new.team input[name=permission]').change(function () {
  1139. const val = $('input[name=permission]:checked', '.organization.new.team').val()
  1140. if (val === 'admin') {
  1141. $('.organization.new.team .team-units').hide();
  1142. } else {
  1143. $('.organization.new.team .team-units').show();
  1144. }
  1145. });
  1146. }
  1147. function initWikiForm() {
  1148. const $editArea = $('.repository.wiki textarea#edit_area');
  1149. if ($editArea.length > 0) {
  1150. const simplemde = new SimpleMDE({
  1151. autoDownloadFontAwesome: false,
  1152. element: $editArea[0],
  1153. forceSync: true,
  1154. previewRender: function (plainText, preview) { // Async method
  1155. setTimeout(function () {
  1156. // FIXME: still send render request when return back to edit mode
  1157. $.post($editArea.data('url'), {
  1158. "_csrf": csrf,
  1159. "mode": "gfm",
  1160. "context": $editArea.data('context'),
  1161. "text": plainText
  1162. },
  1163. function (data) {
  1164. preview.innerHTML = '<div class="markdown ui segment">' + data + '</div>';
  1165. emojify.run($('.editor-preview')[0]);
  1166. }
  1167. );
  1168. }, 0);
  1169. return "Loading...";
  1170. },
  1171. renderingConfig: {
  1172. singleLineBreaks: false
  1173. },
  1174. indentWithTabs: false,
  1175. tabSize: 4,
  1176. spellChecker: false,
  1177. toolbar: ["bold", "italic", "strikethrough", "|",
  1178. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  1179. {
  1180. name: "code-inline",
  1181. action: function(e){
  1182. const cm = e.codemirror;
  1183. const selection = cm.getSelection();
  1184. cm.replaceSelection("`" + selection + "`");
  1185. if (!selection) {
  1186. const cursorPos = cm.getCursor();
  1187. cm.setCursor(cursorPos.line, cursorPos.ch - 1);
  1188. }
  1189. cm.focus();
  1190. },
  1191. className: "fa fa-angle-right",
  1192. title: "Add Inline Code",
  1193. },"code", "quote", "|", {
  1194. name: "checkbox-empty",
  1195. action: function(e){
  1196. const cm = e.codemirror;
  1197. cm.replaceSelection("\n- [ ] " + cm.getSelection());
  1198. cm.focus();
  1199. },
  1200. className: "fa fa-square-o",
  1201. title: "Add Checkbox (empty)",
  1202. },
  1203. {
  1204. name: "checkbox-checked",
  1205. action: function(e){
  1206. const cm = e.codemirror;
  1207. cm.replaceSelection("\n- [x] " + cm.getSelection());
  1208. cm.focus();
  1209. },
  1210. className: "fa fa-check-square-o",
  1211. title: "Add Checkbox (checked)",
  1212. }, "|",
  1213. "unordered-list", "ordered-list", "|",
  1214. "link", "image", "table", "horizontal-rule", "|",
  1215. "clean-block", "preview", "fullscreen"]
  1216. })
  1217. $(simplemde.codemirror.getInputField()).addClass("js-quick-submit");
  1218. }
  1219. }
  1220. // For IE
  1221. String.prototype.endsWith = function (pattern) {
  1222. const d = this.length - pattern.length;
  1223. return d >= 0 && this.lastIndexOf(pattern) === d;
  1224. };
  1225. // Adding function to get the cursor position in a text field to jQuery object.
  1226. $.fn.getCursorPosition = function () {
  1227. const el = $(this).get(0);
  1228. let pos = 0;
  1229. if ('selectionStart' in el) {
  1230. pos = el.selectionStart;
  1231. } else if ('selection' in document) {
  1232. el.focus();
  1233. const Sel = document.selection.createRange();
  1234. const SelLength = document.selection.createRange().text.length;
  1235. Sel.moveStart('character', -el.value.length);
  1236. pos = Sel.text.length - SelLength;
  1237. }
  1238. return pos;
  1239. }
  1240. function setSimpleMDE($editArea) {
  1241. if (codeMirrorEditor) {
  1242. codeMirrorEditor.toTextArea();
  1243. codeMirrorEditor = null;
  1244. }
  1245. if (simpleMDEditor) {
  1246. return true;
  1247. }
  1248. simpleMDEditor = new SimpleMDE({
  1249. autoDownloadFontAwesome: false,
  1250. element: $editArea[0],
  1251. forceSync: true,
  1252. renderingConfig: {
  1253. singleLineBreaks: false
  1254. },
  1255. indentWithTabs: false,
  1256. tabSize: 4,
  1257. spellChecker: false,
  1258. previewRender: function (plainText, preview) { // Async method
  1259. setTimeout(function () {
  1260. // FIXME: still send render request when return back to edit mode
  1261. $.post($editArea.data('url'), {
  1262. "_csrf": csrf,
  1263. "mode": "gfm",
  1264. "context": $editArea.data('context'),
  1265. "text": plainText
  1266. },
  1267. function (data) {
  1268. preview.innerHTML = '<div class="markdown ui segment">' + data + '</div>';
  1269. emojify.run($('.editor-preview')[0]);
  1270. }
  1271. );
  1272. }, 0);
  1273. return "Loading...";
  1274. },
  1275. toolbar: ["bold", "italic", "strikethrough", "|",
  1276. "heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
  1277. "code", "quote", "|",
  1278. "unordered-list", "ordered-list", "|",
  1279. "link", "image", "table", "horizontal-rule", "|",
  1280. "clean-block", "preview", "fullscreen", "side-by-side"]
  1281. });
  1282. return true;
  1283. }
  1284. function setCodeMirror($editArea) {
  1285. if (simpleMDEditor) {
  1286. simpleMDEditor.toTextArea();
  1287. simpleMDEditor = null;
  1288. }
  1289. if (codeMirrorEditor) {
  1290. return true;
  1291. }
  1292. codeMirrorEditor = CodeMirror.fromTextArea($editArea[0], {
  1293. lineNumbers: true
  1294. });
  1295. codeMirrorEditor.on("change", function (cm, _change) {
  1296. $editArea.val(cm.getValue());
  1297. });
  1298. return true;
  1299. }
  1300. function initEditor() {
  1301. $('.js-quick-pull-choice-option').change(function () {
  1302. if ($(this).val() == 'commit-to-new-branch') {
  1303. $('.quick-pull-branch-name').show();
  1304. $('.quick-pull-branch-name input').prop('required',true);
  1305. } else {
  1306. $('.quick-pull-branch-name').hide();
  1307. $('.quick-pull-branch-name input').prop('required',false);
  1308. }
  1309. $('#commit-button').text($(this).attr('button_text'));
  1310. });
  1311. const $editFilename = $("#file-name");
  1312. $editFilename.keyup(function (e) {
  1313. const $section = $('.breadcrumb span.section');
  1314. const $divider = $('.breadcrumb div.divider');
  1315. let value;
  1316. let parts;
  1317. if (e.keyCode == 8) {
  1318. if ($(this).getCursorPosition() == 0) {
  1319. if ($section.length > 0) {
  1320. value = $section.last().find('a').text();
  1321. $(this).val(value + $(this).val());
  1322. $(this)[0].setSelectionRange(value.length, value.length);
  1323. $section.last().remove();
  1324. $divider.last().remove();
  1325. }
  1326. }
  1327. }
  1328. if (e.keyCode == 191) {
  1329. parts = $(this).val().split('/');
  1330. for (let i = 0; i < parts.length; ++i) {
  1331. value = parts[i];
  1332. if (i < parts.length - 1) {
  1333. if (value.length) {
  1334. $('<span class="section"><a href="#">' + value + '</a></span>').insertBefore($(this));
  1335. $('<div class="divider"> / </div>').insertBefore($(this));
  1336. }
  1337. }
  1338. else {
  1339. $(this).val(value);
  1340. }
  1341. $(this)[0].setSelectionRange(0, 0);
  1342. }
  1343. }
  1344. parts = [];
  1345. $('.breadcrumb span.section').each(function () {
  1346. const element = $(this);
  1347. if (element.find('a').length) {
  1348. parts.push(element.find('a').text());
  1349. } else {
  1350. parts.push(element.text());
  1351. }
  1352. });
  1353. if ($(this).val())
  1354. parts.push($(this).val());
  1355. $('#tree_path').val(parts.join('/'));
  1356. }).trigger('keyup');
  1357. const $editArea = $('.repository.editor textarea#edit_area');
  1358. if (!$editArea.length)
  1359. return;
  1360. const markdownFileExts = $editArea.data("markdown-file-exts").split(",");
  1361. const lineWrapExtensions = $editArea.data("line-wrap-extensions").split(",");
  1362. $editFilename.on("keyup", function () {
  1363. const val = $editFilename.val();
  1364. let mode, spec, extension, extWithDot, dataUrl, apiCall;
  1365. extension = extWithDot = "";
  1366. const m = /.+\.([^.]+)$/.exec(val);
  1367. if (m) {
  1368. extension = m[1];
  1369. extWithDot = "." + extension;
  1370. }
  1371. const info = CodeMirror.findModeByExtension(extension);
  1372. const previewLink = $('a[data-tab=preview]');
  1373. if (info) {
  1374. mode = info.mode;
  1375. spec = info.mime;
  1376. apiCall = mode;
  1377. }
  1378. else {
  1379. apiCall = extension
  1380. }
  1381. if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
  1382. dataUrl = previewLink.data('url');
  1383. previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
  1384. previewLink.show();
  1385. }
  1386. else {
  1387. previewLink.hide();
  1388. }
  1389. // If this file is a Markdown extensions, we will load that editor and return
  1390. if (markdownFileExts.indexOf(extWithDot) >= 0) {
  1391. if (setSimpleMDE($editArea)) {
  1392. return;
  1393. }
  1394. }
  1395. // Else we are going to use CodeMirror
  1396. if (!codeMirrorEditor && !setCodeMirror($editArea)) {
  1397. return;
  1398. }
  1399. if (mode) {
  1400. codeMirrorEditor.setOption("mode", spec);
  1401. CodeMirror.autoLoadMode(codeMirrorEditor, mode);
  1402. }
  1403. if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
  1404. codeMirrorEditor.setOption("lineWrapping", true);
  1405. }
  1406. else {
  1407. codeMirrorEditor.setOption("lineWrapping", false);
  1408. }
  1409. // get the filename without any folder
  1410. let value = $editFilename.val();
  1411. if (value.length === 0) {
  1412. return;
  1413. }
  1414. value = value.split('/');
  1415. value = value[value.length - 1];
  1416. $.getJSON($editFilename.data('ec-url-prefix')+value, function(editorconfig) {
  1417. if (editorconfig.indent_style === 'tab') {
  1418. codeMirrorEditor.setOption("indentWithTabs", true);
  1419. codeMirrorEditor.setOption('extraKeys', {});
  1420. } else {
  1421. codeMirrorEditor.setOption("indentWithTabs", false);
  1422. // required because CodeMirror doesn't seems to use spaces correctly for {"indentWithTabs": false}:
  1423. // - https://github.com/codemirror/CodeMirror/issues/988
  1424. // - https://codemirror.net/doc/manual.html#keymaps
  1425. codeMirrorEditor.setOption('extraKeys', {
  1426. Tab: function(cm) {
  1427. const spaces = Array(parseInt(cm.getOption("indentUnit")) + 1).join(" ");
  1428. cm.replaceSelection(spaces);
  1429. }
  1430. });
  1431. }
  1432. codeMirrorEditor.setOption("indentUnit", editorconfig.indent_size || 4);
  1433. codeMirrorEditor.setOption("tabSize", editorconfig.tab_width || 4);
  1434. });
  1435. }).trigger('keyup');
  1436. // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
  1437. // to enable or disable the commit button
  1438. const $commitButton = $('#commit-button');
  1439. const $editForm = $('.ui.edit.form');
  1440. const dirtyFileClass = 'dirty-file';
  1441. // Disabling the button at the start
  1442. $commitButton.prop('disabled', true);
  1443. // Registering a custom listener for the file path and the file content
  1444. $editForm.areYouSure({
  1445. silent: true,
  1446. dirtyClass: dirtyFileClass,
  1447. fieldSelector: ':input:not(.commit-form-wrapper :input)',
  1448. change: function () {
  1449. const dirty = $(this).hasClass(dirtyFileClass);
  1450. $commitButton.prop('disabled', !dirty);
  1451. }
  1452. });
  1453. $commitButton.click(function (event) {
  1454. // A modal which asks if an empty file should be committed
  1455. if ($editArea.val().length === 0) {
  1456. $('#edit-empty-content-modal').modal({
  1457. onApprove: function () {
  1458. $('.edit.form').submit();
  1459. }
  1460. }).modal('show');
  1461. event.preventDefault();
  1462. }
  1463. });
  1464. }
  1465. function initOrganization() {
  1466. if ($('.organization').length == 0) {
  1467. return;
  1468. }
  1469. // Options
  1470. if ($('.organization.settings.options').length > 0) {
  1471. $('#org_name').keyup(function () {
  1472. const $prompt = $('#org-name-change-prompt');
  1473. if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
  1474. $prompt.show();
  1475. } else {
  1476. $prompt.hide();
  1477. }
  1478. });
  1479. }
  1480. }
  1481. function initUserSettings() {
  1482. // Options
  1483. if ($('.user.settings.profile').length > 0) {
  1484. $('#username').keyup(function () {
  1485. const $prompt = $('#name-change-prompt');
  1486. if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
  1487. $prompt.show();
  1488. } else {
  1489. $prompt.hide();
  1490. }
  1491. });
  1492. }
  1493. }
  1494. function initWebhook() {
  1495. if ($('.new.webhook').length == 0) {
  1496. return;
  1497. }
  1498. $('.events.checkbox input').change(function () {
  1499. if ($(this).is(':checked')) {
  1500. $('.events.fields').show();
  1501. }
  1502. });
  1503. $('.non-events.checkbox input').change(function () {
  1504. if ($(this).is(':checked')) {
  1505. $('.events.fields').hide();
  1506. }
  1507. });
  1508. const updateContentType = function () {
  1509. const visible = $('#http_method').val() === 'POST';
  1510. $('#content_type').parent().parent()[visible ? 'show' : 'hide']();
  1511. };
  1512. updateContentType();
  1513. $('#http_method').change(function () {
  1514. updateContentType();
  1515. });
  1516. // Test delivery
  1517. $('#test-delivery').click(function () {
  1518. const $this = $(this);
  1519. $this.addClass('loading disabled');
  1520. $.post($this.data('link'), {
  1521. "_csrf": csrf
  1522. }).done(
  1523. setTimeout(function () {
  1524. window.location.href = $this.data('redirect');
  1525. }, 5000)
  1526. )
  1527. });
  1528. }
  1529. function initAdmin() {
  1530. if ($('.admin').length == 0) {
  1531. return;
  1532. }
  1533. // New user
  1534. if ($('.admin.new.user').length > 0 ||
  1535. $('.admin.edit.user').length > 0) {
  1536. $('#login_type').change(function () {
  1537. if ($(this).val().substring(0, 1) == '0') {
  1538. $('#login_name').removeAttr('required');
  1539. $('.non-local').hide();
  1540. $('.local').show();
  1541. $('#user_name').focus();
  1542. if ($(this).data('password') == "required") {
  1543. $('#password').attr('required', 'required');
  1544. }
  1545. } else {
  1546. $('#login_name').attr('required', 'required');
  1547. $('.non-local').show();
  1548. $('.local').hide();
  1549. $('#login_name').focus();
  1550. $('#password').removeAttr('required');
  1551. }
  1552. });
  1553. }
  1554. function onSecurityProtocolChange() {
  1555. if ($('#security_protocol').val() > 0) {
  1556. $('.has-tls').show();
  1557. } else {
  1558. $('.has-tls').hide();
  1559. }
  1560. }
  1561. function onUsePagedSearchChange() {
  1562. if ($('#use_paged_search').prop('checked')) {
  1563. $('.search-page-size').show()
  1564. .find('input').attr('required', 'required');
  1565. } else {
  1566. $('.search-page-size').hide()
  1567. .find('input').removeAttr('required');
  1568. }
  1569. }
  1570. function onOAuth2Change() {
  1571. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1572. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1573. const provider = $('#oauth2_provider').val();
  1574. switch (provider) {
  1575. case 'github':
  1576. case 'gitlab':
  1577. case 'gitea':
  1578. $('.oauth2_use_custom_url').show();
  1579. break;
  1580. case 'openidConnect':
  1581. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1582. $('.open_id_connect_auto_discovery_url').show();
  1583. break;
  1584. }
  1585. onOAuth2UseCustomURLChange();
  1586. }
  1587. function onOAuth2UseCustomURLChange() {
  1588. const provider = $('#oauth2_provider').val();
  1589. $('.oauth2_use_custom_url_field').hide();
  1590. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1591. if ($('#oauth2_use_custom_url').is(':checked')) {
  1592. if (!$('#oauth2_token_url').val()) {
  1593. $('#oauth2_token_url').val($('#' + provider + '_token_url').val());
  1594. }
  1595. if (!$('#oauth2_auth_url').val()) {
  1596. $('#oauth2_auth_url').val($('#' + provider + '_auth_url').val());
  1597. }
  1598. if (!$('#oauth2_profile_url').val()) {
  1599. $('#oauth2_profile_url').val($('#' + provider + '_profile_url').val());
  1600. }
  1601. if (!$('#oauth2_email_url').val()) {
  1602. $('#oauth2_email_url').val($('#' + provider + '_email_url').val());
  1603. }
  1604. switch (provider) {
  1605. case 'github':
  1606. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1607. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1608. break;
  1609. case 'gitea':
  1610. case 'gitlab':
  1611. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1612. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1613. $('#oauth2_email_url').val('');
  1614. break;
  1615. }
  1616. }
  1617. }
  1618. // New authentication
  1619. if ($('.admin.new.authentication').length > 0) {
  1620. $('#auth_type').change(function () {
  1621. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls .search-page-size').hide();
  1622. $('.ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required]').removeAttr('required');
  1623. $('.binddnrequired').removeClass("required");
  1624. const authType = $(this).val();
  1625. switch (authType) {
  1626. case '2': // LDAP
  1627. $('.ldap').show();
  1628. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr('required', 'required');
  1629. $('.binddnrequired').addClass("required");
  1630. break;
  1631. case '3': // SMTP
  1632. $('.smtp').show();
  1633. $('.has-tls').show();
  1634. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1635. break;
  1636. case '4': // PAM
  1637. $('.pam').show();
  1638. $('.pam input').attr('required', 'required');
  1639. break;
  1640. case '5': // LDAP
  1641. $('.dldap').show();
  1642. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1643. break;
  1644. case '6': // OAuth2
  1645. $('.oauth2').show();
  1646. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1647. onOAuth2Change();
  1648. break;
  1649. }
  1650. if (authType == '2' || authType == '5') {
  1651. onSecurityProtocolChange()
  1652. }
  1653. if (authType == '2') {
  1654. onUsePagedSearchChange();
  1655. }
  1656. });
  1657. $('#auth_type').change();
  1658. $('#security_protocol').change(onSecurityProtocolChange);
  1659. $('#use_paged_search').change(onUsePagedSearchChange);
  1660. $('#oauth2_provider').change(onOAuth2Change);
  1661. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1662. }
  1663. // Edit authentication
  1664. if ($('.admin.edit.authentication').length > 0) {
  1665. const authType = $('#auth_type').val();
  1666. if (authType == '2' || authType == '5') {
  1667. $('#security_protocol').change(onSecurityProtocolChange);
  1668. if (authType == '2') {
  1669. $('#use_paged_search').change(onUsePagedSearchChange);
  1670. }
  1671. } else if (authType == '6') {
  1672. $('#oauth2_provider').change(onOAuth2Change);
  1673. $('#oauth2_use_custom_url').change(onOAuth2UseCustomURLChange);
  1674. onOAuth2Change();
  1675. }
  1676. }
  1677. // Notice
  1678. if ($('.admin.notice')) {
  1679. const $detailModal = $('#detail-modal');
  1680. // Attach view detail modals
  1681. $('.view-detail').click(function () {
  1682. $detailModal.find('.content p').text($(this).data('content'));
  1683. $detailModal.modal('show');
  1684. return false;
  1685. });
  1686. // Select actions
  1687. const $checkboxes = $('.select.table .ui.checkbox');
  1688. $('.select.action').click(function () {
  1689. switch ($(this).data('action')) {
  1690. case 'select-all':
  1691. $checkboxes.checkbox('check');
  1692. break;
  1693. case 'deselect-all':
  1694. $checkboxes.checkbox('uncheck');
  1695. break;
  1696. case 'inverse':
  1697. $checkboxes.checkbox('toggle');
  1698. break;
  1699. }
  1700. });
  1701. $('#delete-selection').click(function () {
  1702. const $this = $(this);
  1703. $this.addClass("loading disabled");
  1704. const ids = [];
  1705. $checkboxes.each(function () {
  1706. if ($(this).checkbox('is checked')) {
  1707. ids.push($(this).data('id'));
  1708. }
  1709. });
  1710. $.post($this.data('link'), {
  1711. "_csrf": csrf,
  1712. "ids": ids
  1713. }).done(function () {
  1714. window.location.href = $this.data('redirect');
  1715. });
  1716. });
  1717. }
  1718. }
  1719. function buttonsClickOnEnter() {
  1720. $('.ui.button').keypress(function (e) {
  1721. if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
  1722. $(this).click();
  1723. });
  1724. }
  1725. function searchUsers() {
  1726. const $searchUserBox = $('#search-user-box');
  1727. $searchUserBox.search({
  1728. minCharacters: 2,
  1729. apiSettings: {
  1730. url: suburl + '/api/v1/users/search?q={query}',
  1731. onResponse: function(response) {
  1732. const items = [];
  1733. $.each(response.data, function (_i, item) {
  1734. let title = item.login;
  1735. if (item.full_name && item.full_name.length > 0) {
  1736. title += ' (' + htmlEncode(item.full_name) + ')';
  1737. }
  1738. items.push({
  1739. title: title,
  1740. image: item.avatar_url
  1741. })
  1742. });
  1743. return { results: items }
  1744. }
  1745. },
  1746. searchFields: ['login', 'full_name'],
  1747. showNoResults: false
  1748. });
  1749. }
  1750. function searchTeams() {
  1751. const $searchTeamBox = $('#search-team-box');
  1752. $searchTeamBox.search({
  1753. minCharacters: 2,
  1754. apiSettings: {
  1755. url: suburl + '/api/v1/orgs/' + $searchTeamBox.data('org') + '/teams/search?q={query}',
  1756. headers: {"X-Csrf-Token": csrf},
  1757. onResponse: function(response) {
  1758. const items = [];
  1759. $.each(response.data, function (_i, item) {
  1760. const title = item.name + ' (' + item.permission + ' access)';
  1761. items.push({
  1762. title: title,
  1763. })
  1764. });
  1765. return { results: items }
  1766. }
  1767. },
  1768. searchFields: ['name', 'description'],
  1769. showNoResults: false
  1770. });
  1771. }
  1772. function searchRepositories() {
  1773. const $searchRepoBox = $('#search-repo-box');
  1774. $searchRepoBox.search({
  1775. minCharacters: 2,
  1776. apiSettings: {
  1777. url: suburl + '/api/v1/repos/search?q={query}&uid=' + $searchRepoBox.data('uid'),
  1778. onResponse: function(response) {
  1779. const items = [];
  1780. $.each(response.data, function (_i, item) {
  1781. items.push({
  1782. title: item.full_name.split("/")[1],
  1783. description: item.full_name
  1784. })
  1785. });
  1786. return { results: items }
  1787. }
  1788. },
  1789. searchFields: ['full_name'],
  1790. showNoResults: false
  1791. });
  1792. }
  1793. function initCodeView() {
  1794. if ($('.code-view .linenums').length > 0) {
  1795. $(document).on('click', '.lines-num span', function (e) {
  1796. const $select = $(this);
  1797. const $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
  1798. selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1799. deSelect();
  1800. });
  1801. $(window).on('hashchange', function () {
  1802. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  1803. const $list = $('.code-view ol.linenums > li');
  1804. let $first;
  1805. if (m) {
  1806. $first = $list.filter('.' + m[1]);
  1807. selectRange($list, $first, $list.filter('.' + m[2]));
  1808. $("html, body").scrollTop($first.offset().top - 200);
  1809. return;
  1810. }
  1811. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  1812. if (m) {
  1813. $first = $list.filter('.L' + m[2]);
  1814. selectRange($list, $first);
  1815. $("html, body").scrollTop($first.offset().top - 200);
  1816. }
  1817. }).trigger('hashchange');
  1818. }
  1819. }
  1820. function initU2FAuth() {
  1821. if($('#wait-for-key').length === 0) {
  1822. return
  1823. }
  1824. u2fApi.ensureSupport()
  1825. .then(function () {
  1826. $.getJSON(suburl + '/user/u2f/challenge').success(function(req) {
  1827. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  1828. .then(u2fSigned)
  1829. .catch(function (err) {
  1830. if(err === undefined) {
  1831. u2fError(1);
  1832. return
  1833. }
  1834. u2fError(err.metaData.code);
  1835. });
  1836. });
  1837. }).catch(function () {
  1838. // Fallback in case browser do not support U2F
  1839. window.location.href = suburl + "/user/two_factor"
  1840. })
  1841. }
  1842. function u2fSigned(resp) {
  1843. $.ajax({
  1844. url: suburl + '/user/u2f/sign',
  1845. type: "POST",
  1846. headers: {"X-Csrf-Token": csrf},
  1847. data: JSON.stringify(resp),
  1848. contentType: "application/json; charset=utf-8",
  1849. }).done(function(res){
  1850. window.location.replace(res);
  1851. }).fail(function () {
  1852. u2fError(1);
  1853. });
  1854. }
  1855. function u2fRegistered(resp) {
  1856. if (checkError(resp)) {
  1857. return;
  1858. }
  1859. $.ajax({
  1860. url: suburl + '/user/settings/security/u2f/register',
  1861. type: "POST",
  1862. headers: {"X-Csrf-Token": csrf},
  1863. data: JSON.stringify(resp),
  1864. contentType: "application/json; charset=utf-8",
  1865. success: function(){
  1866. reload();
  1867. },
  1868. fail: function () {
  1869. u2fError(1);
  1870. }
  1871. });
  1872. }
  1873. function checkError(resp) {
  1874. if (!('errorCode' in resp)) {
  1875. return false;
  1876. }
  1877. if (resp.errorCode === 0) {
  1878. return false;
  1879. }
  1880. u2fError(resp.errorCode);
  1881. return true;
  1882. }
  1883. function u2fError(errorType) {
  1884. const u2fErrors = {
  1885. 'browser': $('#unsupported-browser'),
  1886. 1: $('#u2f-error-1'),
  1887. 2: $('#u2f-error-2'),
  1888. 3: $('#u2f-error-3'),
  1889. 4: $('#u2f-error-4'),
  1890. 5: $('.u2f-error-5')
  1891. };
  1892. u2fErrors[errorType].removeClass('hide');
  1893. for(const type in u2fErrors){
  1894. if(type != errorType){
  1895. u2fErrors[type].addClass('hide');
  1896. }
  1897. }
  1898. $('#u2f-error').modal('show');
  1899. }
  1900. function initU2FRegister() {
  1901. $('#register-device').modal({allowMultiple: false});
  1902. $('#u2f-error').modal({allowMultiple: false});
  1903. $('#register-security-key').on('click', function(e) {
  1904. e.preventDefault();
  1905. u2fApi.ensureSupport()
  1906. .then(u2fRegisterRequest)
  1907. .catch(function() {
  1908. u2fError('browser');
  1909. })
  1910. })
  1911. }
  1912. function u2fRegisterRequest() {
  1913. $.post(suburl + "/user/settings/security/u2f/request_register", {
  1914. "_csrf": csrf,
  1915. "name": $('#nickname').val()
  1916. }).success(function(req) {
  1917. $("#nickname").closest("div.field").removeClass("error");
  1918. $('#register-device').modal('show');
  1919. if(req.registeredKeys === null) {
  1920. req.registeredKeys = []
  1921. }
  1922. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  1923. .then(u2fRegistered)
  1924. .catch(function (reason) {
  1925. if(reason === undefined) {
  1926. u2fError(1);
  1927. return
  1928. }
  1929. u2fError(reason.metaData.code);
  1930. });
  1931. }).fail(function(xhr) {
  1932. if(xhr.status === 409) {
  1933. $("#nickname").closest("div.field").addClass("error");
  1934. }
  1935. });
  1936. }
  1937. function initWipTitle() {
  1938. $(".title_wip_desc > a").click(function (e) {
  1939. e.preventDefault();
  1940. const $issueTitle = $("#issue_title");
  1941. $issueTitle.focus();
  1942. const value = $issueTitle.val().trim().toUpperCase();
  1943. for (const i in wipPrefixes) {
  1944. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  1945. return;
  1946. }
  1947. }
  1948. $issueTitle.val(wipPrefixes[0] + " " + $issueTitle.val());
  1949. });
  1950. }
  1951. function initTemplateSearch() {
  1952. const $repoTemplate = $("#repo_template");
  1953. const checkTemplate = function() {
  1954. const $templateUnits = $("#template_units");
  1955. const $nonTemplate = $("#non_template");
  1956. if ($repoTemplate.val() !== "") {
  1957. $templateUnits.show();
  1958. $nonTemplate.hide();
  1959. } else {
  1960. $templateUnits.hide();
  1961. $nonTemplate.show();
  1962. }
  1963. };
  1964. $repoTemplate.change(checkTemplate);
  1965. checkTemplate();
  1966. const changeOwner = function() {
  1967. $("#repo_template_search")
  1968. .dropdown({
  1969. apiSettings: {
  1970. url: suburl + '/api/v1/repos/search?q={query}&template=true&priority_owner_id=' + $("#uid").val(),
  1971. onResponse: function(response) {
  1972. const filteredResponse = {'success': true, 'results': []};
  1973. filteredResponse.results.push({
  1974. 'name': '',
  1975. 'value': ''
  1976. });
  1977. // Parse the response from the api to work with our dropdown
  1978. $.each(response.data, function(_r, repo) {
  1979. filteredResponse.results.push({
  1980. 'name' : htmlEncode(repo.full_name) ,
  1981. 'value' : repo.id
  1982. });
  1983. });
  1984. return filteredResponse;
  1985. },
  1986. cache: false,
  1987. },
  1988. fullTextSearch: true
  1989. });
  1990. };
  1991. $("#uid").change(changeOwner);
  1992. changeOwner();
  1993. }
  1994. $(document).ready(function () {
  1995. csrf = $('meta[name=_csrf]').attr("content");
  1996. suburl = $('meta[name=_suburl]').attr("content");
  1997. // Show exact time
  1998. $('.time-since').each(function () {
  1999. $(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
  2000. });
  2001. // Semantic UI modules.
  2002. $('.dropdown:not(.custom)').dropdown();
  2003. $('.jump.dropdown').dropdown({
  2004. action: 'hide',
  2005. onShow: function () {
  2006. $('.poping.up').popup('hide');
  2007. }
  2008. });
  2009. $('.slide.up.dropdown').dropdown({
  2010. transition: 'slide up'
  2011. });
  2012. $('.upward.dropdown').dropdown({
  2013. direction: 'upward'
  2014. });
  2015. $('.ui.accordion').accordion();
  2016. $('.ui.checkbox').checkbox();
  2017. $('.ui.progress').progress({
  2018. showActivity: false
  2019. });
  2020. $('.poping.up').popup();
  2021. $('.top.menu .poping.up').popup({
  2022. onShow: function () {
  2023. if ($('.top.menu .menu.transition').hasClass('visible')) {
  2024. return false;
  2025. }
  2026. }
  2027. });
  2028. $('.tabular.menu .item').tab();
  2029. $('.tabable.menu .item').tab();
  2030. $('.toggle.button').click(function () {
  2031. $($(this).data('target')).slideToggle(100);
  2032. });
  2033. // make table <tr> element clickable like a link
  2034. $('tr[data-href]').click(function() {
  2035. window.location = $(this).data('href');
  2036. });
  2037. // Highlight JS
  2038. if (typeof hljs != 'undefined') {
  2039. const nodes = [].slice.call(document.querySelectorAll('pre code') || []);
  2040. for (let i = 0; i < nodes.length; i++) {
  2041. hljs.highlightBlock(nodes[i]);
  2042. }
  2043. }
  2044. // Dropzone
  2045. const $dropzone = $('#dropzone');
  2046. if ($dropzone.length > 0) {
  2047. const filenameDict = {};
  2048. new Dropzone("#dropzone", {
  2049. url: $dropzone.data('upload-url'),
  2050. headers: {"X-Csrf-Token": csrf},
  2051. maxFiles: $dropzone.data('max-file'),
  2052. maxFilesize: $dropzone.data('max-size'),
  2053. acceptedFiles: ($dropzone.data('accepts') === '*/*') ? null : $dropzone.data('accepts'),
  2054. addRemoveLinks: true,
  2055. dictDefaultMessage: $dropzone.data('default-message'),
  2056. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  2057. dictFileTooBig: $dropzone.data('file-too-big'),
  2058. dictRemoveFile: $dropzone.data('remove-file'),
  2059. init: function () {
  2060. this.on("success", function (file, data) {
  2061. filenameDict[file.name] = data.uuid;
  2062. const input = $('<input id="' + data.uuid + '" name="files" type="hidden">').val(data.uuid);
  2063. $('.files').append(input);
  2064. });
  2065. this.on("removedfile", function (file) {
  2066. if (file.name in filenameDict) {
  2067. $('#' + filenameDict[file.name]).remove();
  2068. }
  2069. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  2070. $.post($dropzone.data('remove-url'), {
  2071. file: filenameDict[file.name],
  2072. _csrf: $dropzone.data('csrf')
  2073. });
  2074. }
  2075. })
  2076. },
  2077. });
  2078. }
  2079. // Emojify
  2080. emojify.setConfig({
  2081. img_dir: suburl + '/vendor/plugins/emojify/images',
  2082. ignore_emoticons: true
  2083. });
  2084. const hasEmoji = document.getElementsByClassName('has-emoji');
  2085. for (let i = 0; i < hasEmoji.length; i++) {
  2086. emojify.run(hasEmoji[i]);
  2087. for (let j = 0; j < hasEmoji[i].childNodes.length; j++) {
  2088. if (hasEmoji[i].childNodes[j].nodeName === "A") {
  2089. emojify.run(hasEmoji[i].childNodes[j])
  2090. }
  2091. }
  2092. }
  2093. // Clipboard JS
  2094. const clipboard = new Clipboard('.clipboard');
  2095. clipboard.on('success', function (e) {
  2096. e.clearSelection();
  2097. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  2098. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
  2099. $('#' + e.trigger.getAttribute('id')).popup('show');
  2100. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  2101. });
  2102. clipboard.on('error', function (e) {
  2103. $('#' + e.trigger.getAttribute('id')).popup('destroy');
  2104. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
  2105. $('#' + e.trigger.getAttribute('id')).popup('show');
  2106. e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
  2107. });
  2108. // Helpers.
  2109. $('.delete-button').click(showDeletePopup);
  2110. $('.add-all-button').click(showAddAllPopup);
  2111. $('.delete-branch-button').click(showDeletePopup);
  2112. $('.undo-button').click(function() {
  2113. const $this = $(this);
  2114. $.post($this.data('url'), {
  2115. "_csrf": csrf,
  2116. "id": $this.data("id")
  2117. }).done(function(data) {
  2118. window.location.href = data.redirect;
  2119. });
  2120. });
  2121. $('.show-panel.button').click(function () {
  2122. $($(this).data('panel')).show();
  2123. });
  2124. $('.show-modal.button').click(function () {
  2125. $($(this).data('modal')).modal('show');
  2126. });
  2127. $('.delete-post.button').click(function () {
  2128. const $this = $(this);
  2129. $.post($this.data('request-url'), {
  2130. "_csrf": csrf
  2131. }).done(function () {
  2132. window.location.href = $this.data('done-url');
  2133. });
  2134. });
  2135. // Set anchor.
  2136. $('.markdown').each(function () {
  2137. const headers = {};
  2138. $(this).find('h1, h2, h3, h4, h5, h6').each(function () {
  2139. let node = $(this);
  2140. const val = encodeURIComponent(node.text().toLowerCase().replace(/[^\u00C0-\u1FFF\u2C00-\uD7FF\w\- ]/g, '').replace(/[ ]/g, '-'));
  2141. let name = val;
  2142. if (headers[val] > 0) {
  2143. name = val + '-' + headers[val];
  2144. }
  2145. if (headers[val] == undefined) {
  2146. headers[val] = 1;
  2147. } else {
  2148. headers[val] += 1;
  2149. }
  2150. node = node.wrap('<div id="' + name + '" class="anchor-wrap" ></div>');
  2151. node.append('<a class="anchor" href="#' + name + '"><span class="octicon octicon-link"></span></a>');
  2152. });
  2153. });
  2154. $('.issue-checkbox').click(function() {
  2155. const numChecked = $('.issue-checkbox').children('input:checked').length;
  2156. if (numChecked > 0) {
  2157. $('#issue-filters').addClass("hide");
  2158. $('#issue-actions').removeClass("hide");
  2159. } else {
  2160. $('#issue-filters').removeClass("hide");
  2161. $('#issue-actions').addClass("hide");
  2162. }
  2163. });
  2164. $('.issue-action').click(function () {
  2165. let action = this.dataset.action;
  2166. let elementId = this.dataset.elementId;
  2167. const issueIDs = $('.issue-checkbox').children('input:checked').map(function() {
  2168. return this.dataset.issueId;
  2169. }).get().join();
  2170. const url = this.dataset.url;
  2171. if (elementId === '0' && url.substr(-9) === '/assignee'){
  2172. elementId = '';
  2173. action = 'clear';
  2174. }
  2175. updateIssuesMeta(url, action, issueIDs, elementId).then(function() {
  2176. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2177. if (action === "close" || action === "open" ){
  2178. //uncheck all checkboxes
  2179. $('.issue-checkbox input[type="checkbox"]').each(function(_,e){ e.checked = false; });
  2180. }
  2181. reload();
  2182. });
  2183. });
  2184. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2185. // trigger ckecked event, if checkboxes are checked on load
  2186. $('.issue-checkbox input[type="checkbox"]:checked').first().each(function(_,e) {
  2187. e.checked = false;
  2188. $(e).click();
  2189. });
  2190. buttonsClickOnEnter();
  2191. searchUsers();
  2192. searchTeams();
  2193. searchRepositories();
  2194. initCommentForm();
  2195. initInstall();
  2196. initRepository();
  2197. initMigration();
  2198. initWikiForm();
  2199. initEditForm();
  2200. initEditor();
  2201. initOrganization();
  2202. initWebhook();
  2203. initAdmin();
  2204. initCodeView();
  2205. initVueApp();
  2206. initTeamSettings();
  2207. initCtrlEnterSubmit();
  2208. initNavbarContentToggle();
  2209. initTopicbar();
  2210. initU2FAuth();
  2211. initU2FRegister();
  2212. initIssueList();
  2213. initWipTitle();
  2214. initPullRequestReview();
  2215. initRepoStatusChecker();
  2216. initTemplateSearch();
  2217. // Repo clone url.
  2218. if ($('#repo-clone-url').length > 0) {
  2219. switch (localStorage.getItem('repo-clone-protocol')) {
  2220. case 'ssh':
  2221. if ($('#repo-clone-ssh').click().length === 0) {
  2222. $('#repo-clone-https').click();
  2223. }
  2224. break;
  2225. default:
  2226. $('#repo-clone-https').click();
  2227. break;
  2228. }
  2229. }
  2230. const routes = {
  2231. 'div.user.settings': initUserSettings,
  2232. 'div.repository.settings.collaboration': initRepositoryCollaboration
  2233. };
  2234. let selector;
  2235. for (selector in routes) {
  2236. if ($(selector).length > 0) {
  2237. routes[selector]();
  2238. break;
  2239. }
  2240. }
  2241. const $cloneAddr = $('#clone_addr');
  2242. $cloneAddr.change(function() {
  2243. const $repoName = $('#repo_name');
  2244. if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) { // Only modify if repo_name input is blank
  2245. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  2246. }
  2247. });
  2248. });
  2249. function changeHash(hash) {
  2250. if (history.pushState) {
  2251. history.pushState(null, null, hash);
  2252. }
  2253. else {
  2254. location.hash = hash;
  2255. }
  2256. }
  2257. function deSelect() {
  2258. if (window.getSelection) {
  2259. window.getSelection().removeAllRanges();
  2260. } else {
  2261. document.selection.empty();
  2262. }
  2263. }
  2264. function selectRange($list, $select, $from) {
  2265. $list.removeClass('active');
  2266. if ($from) {
  2267. let a = parseInt($select.attr('rel').substr(1));
  2268. let b = parseInt($from.attr('rel').substr(1));
  2269. let c;
  2270. if (a != b) {
  2271. if (a > b) {
  2272. c = a;
  2273. a = b;
  2274. b = c;
  2275. }
  2276. const classes = [];
  2277. for (let i = a; i <= b; i++) {
  2278. classes.push('.L' + i);
  2279. }
  2280. $list.filter(classes.join(',')).addClass('active');
  2281. changeHash('#L' + a + '-' + 'L' + b);
  2282. return
  2283. }
  2284. }
  2285. $select.addClass('active');
  2286. changeHash('#' + $select.attr('rel'));
  2287. }
  2288. $(function () {
  2289. // Warn users that try to leave a page after entering data into a form.
  2290. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2291. if ($('.user.signin').length === 0) {
  2292. $('form:not(.ignore-dirty)').areYouSure();
  2293. }
  2294. // Parse SSH Key
  2295. $("#ssh-key-content").on('change paste keyup',function(){
  2296. const arrays = $(this).val().split(" ");
  2297. const $title = $("#ssh-key-title")
  2298. if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") {
  2299. $title.val(arrays[2]);
  2300. }
  2301. });
  2302. });
  2303. function showDeletePopup() {
  2304. const $this = $(this);
  2305. let filter = "";
  2306. if ($this.attr("id")) {
  2307. filter += "#" + $this.attr("id")
  2308. }
  2309. const dialog = $('.delete.modal' + filter);
  2310. dialog.find('.name').text($this.data('name'));
  2311. dialog.modal({
  2312. closable: false,
  2313. onApprove: function() {
  2314. if ($this.data('type') == "form") {
  2315. $($this.data('form')).submit();
  2316. return;
  2317. }
  2318. $.post($this.data('url'), {
  2319. "_csrf": csrf,
  2320. "id": $this.data("id")
  2321. }).done(function(data) {
  2322. window.location.href = data.redirect;
  2323. });
  2324. }
  2325. }).modal('show');
  2326. return false;
  2327. }
  2328. function showAddAllPopup() {
  2329. const $this = $(this);
  2330. let filter = "";
  2331. if ($this.attr("id")) {
  2332. filter += "#" + $this.attr("id")
  2333. }
  2334. const dialog = $('.addall.modal' + filter);
  2335. dialog.find('.name').text($this.data('name'));
  2336. dialog.modal({
  2337. closable: false,
  2338. onApprove: function() {
  2339. if ($this.data('type') == "form") {
  2340. $($this.data('form')).submit();
  2341. return;
  2342. }
  2343. $.post($this.data('url'), {
  2344. "_csrf": csrf,
  2345. "id": $this.data("id")
  2346. }).done(function(data) {
  2347. window.location.href = data.redirect;
  2348. });
  2349. }
  2350. }).modal('show');
  2351. return false;
  2352. }
  2353. function initVueComponents(){
  2354. const vueDelimeters = ['${', '}'];
  2355. Vue.component('repo-search', {
  2356. delimiters: vueDelimeters,
  2357. props: {
  2358. searchLimit: {
  2359. type: Number,
  2360. default: 10
  2361. },
  2362. suburl: {
  2363. type: String,
  2364. required: true
  2365. },
  2366. uid: {
  2367. type: Number,
  2368. required: true
  2369. },
  2370. organizations: {
  2371. type: Array,
  2372. default: []
  2373. },
  2374. isOrganization: {
  2375. type: Boolean,
  2376. default: true
  2377. },
  2378. canCreateOrganization: {
  2379. type: Boolean,
  2380. default: false
  2381. },
  2382. organizationsTotalCount: {
  2383. type: Number,
  2384. default: 0
  2385. },
  2386. moreReposLink: {
  2387. type: String,
  2388. default: ''
  2389. }
  2390. },
  2391. data: function() {
  2392. return {
  2393. tab: 'repos',
  2394. repos: [],
  2395. reposTotalCount: 0,
  2396. reposFilter: 'all',
  2397. searchQuery: '',
  2398. isLoading: false,
  2399. repoTypes: {
  2400. 'all': {
  2401. count: 0,
  2402. searchMode: '',
  2403. },
  2404. 'forks': {
  2405. count: 0,
  2406. searchMode: 'fork',
  2407. },
  2408. 'mirrors': {
  2409. count: 0,
  2410. searchMode: 'mirror',
  2411. },
  2412. 'sources': {
  2413. count: 0,
  2414. searchMode: 'source',
  2415. },
  2416. 'collaborative': {
  2417. count: 0,
  2418. searchMode: 'collaborative',
  2419. },
  2420. }
  2421. }
  2422. },
  2423. computed: {
  2424. showMoreReposLink: function() {
  2425. return this.repos.length > 0 && this.repos.length < this.repoTypes[this.reposFilter].count;
  2426. },
  2427. searchURL: function() {
  2428. return this.suburl + '/api/v1/repos/search?sort=updated&order=desc&uid=' + this.uid + '&q=' + this.searchQuery
  2429. + '&limit=' + this.searchLimit + '&mode=' + this.repoTypes[this.reposFilter].searchMode
  2430. + (this.reposFilter !== 'all' ? '&exclusive=1' : '');
  2431. },
  2432. repoTypeCount: function() {
  2433. return this.repoTypes[this.reposFilter].count;
  2434. }
  2435. },
  2436. mounted: function() {
  2437. this.searchRepos(this.reposFilter);
  2438. const self = this;
  2439. Vue.nextTick(function() {
  2440. self.$refs.search.focus();
  2441. });
  2442. },
  2443. methods: {
  2444. changeTab: function(t) {
  2445. this.tab = t;
  2446. },
  2447. changeReposFilter: function(filter) {
  2448. this.reposFilter = filter;
  2449. this.repos = [];
  2450. this.repoTypes[filter].count = 0;
  2451. this.searchRepos(filter);
  2452. },
  2453. showRepo: function(repo, filter) {
  2454. switch (filter) {
  2455. case 'sources':
  2456. return repo.owner.id == this.uid && !repo.mirror && !repo.fork;
  2457. case 'forks':
  2458. return repo.owner.id == this.uid && !repo.mirror && repo.fork;
  2459. case 'mirrors':
  2460. return repo.mirror;
  2461. case 'collaborative':
  2462. return repo.owner.id != this.uid && !repo.mirror;
  2463. default:
  2464. return true;
  2465. }
  2466. },
  2467. searchRepos: function(reposFilter) {
  2468. const self = this;
  2469. this.isLoading = true;
  2470. const searchedMode = this.repoTypes[reposFilter].searchMode;
  2471. const searchedURL = this.searchURL;
  2472. const searchedQuery = this.searchQuery;
  2473. $.getJSON(searchedURL, function(result, _textStatus, request) {
  2474. if (searchedURL == self.searchURL) {
  2475. self.repos = result.data;
  2476. const count = request.getResponseHeader('X-Total-Count');
  2477. if (searchedQuery === '' && searchedMode === '') {
  2478. self.reposTotalCount = count;
  2479. }
  2480. self.repoTypes[reposFilter].count = count;
  2481. }
  2482. }).always(function() {
  2483. if (searchedURL == self.searchURL) {
  2484. self.isLoading = false;
  2485. }
  2486. });
  2487. },
  2488. repoClass: function(repo) {
  2489. if (repo.fork) {
  2490. return 'octicon octicon-repo-forked';
  2491. } else if (repo.mirror) {
  2492. return 'octicon octicon-repo-clone';
  2493. } else if (repo.private) {
  2494. return 'octicon octicon-lock';
  2495. } else {
  2496. return 'octicon octicon-repo';
  2497. }
  2498. }
  2499. }
  2500. })
  2501. }
  2502. function initCtrlEnterSubmit() {
  2503. $(".js-quick-submit").keydown(function(e) {
  2504. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
  2505. $(this).closest("form").submit();
  2506. }
  2507. });
  2508. }
  2509. function initVueApp() {
  2510. const el = document.getElementById('app');
  2511. if (!el) {
  2512. return;
  2513. }
  2514. initVueComponents();
  2515. new Vue({
  2516. delimiters: ['${', '}'],
  2517. el: el,
  2518. data: {
  2519. searchLimit: document.querySelector('meta[name=_search_limit]').content,
  2520. suburl: document.querySelector('meta[name=_suburl]').content,
  2521. uid: document.querySelector('meta[name=_context_uid]').content,
  2522. },
  2523. });
  2524. }
  2525. window.timeAddManual = function() {
  2526. $('.mini.modal')
  2527. .modal({
  2528. duration: 200,
  2529. onApprove: function() {
  2530. $('#add_time_manual_form').submit();
  2531. }
  2532. }).modal('show')
  2533. ;
  2534. }
  2535. window.toggleStopwatch = function() {
  2536. $("#toggle_stopwatch_form").submit();
  2537. }
  2538. window.cancelStopwatch = function() {
  2539. $("#cancel_stopwatch_form").submit();
  2540. }
  2541. window.initHeatmap = function(appElementId, heatmapUser, locale) {
  2542. const el = document.getElementById(appElementId);
  2543. if (!el) {
  2544. return;
  2545. }
  2546. locale = locale || {};
  2547. locale.contributions = locale.contributions || 'contributions';
  2548. locale.no_contributions = locale.no_contributions || 'No contributions';
  2549. const vueDelimeters = ['${', '}'];
  2550. Vue.component('activity-heatmap', {
  2551. delimiters: vueDelimeters,
  2552. props: {
  2553. user: {
  2554. type: String,
  2555. required: true
  2556. },
  2557. suburl: {
  2558. type: String,
  2559. required: true
  2560. },
  2561. locale: {
  2562. type: Object,
  2563. required: true
  2564. }
  2565. },
  2566. data: function () {
  2567. return {
  2568. isLoading: true,
  2569. colorRange: [],
  2570. endDate: null,
  2571. values: [],
  2572. totalContributions: 0,
  2573. };
  2574. },
  2575. mounted: function() {
  2576. this.colorRange = [
  2577. this.getColor(0),
  2578. this.getColor(1),
  2579. this.getColor(2),
  2580. this.getColor(3),
  2581. this.getColor(4),
  2582. this.getColor(5)
  2583. ];
  2584. this.endDate = new Date();
  2585. this.loadHeatmap(this.user);
  2586. },
  2587. methods: {
  2588. loadHeatmap: function(userName) {
  2589. const self = this;
  2590. $.get(this.suburl + '/api/v1/users/' + userName + '/heatmap', function(chartRawData) {
  2591. const chartData = [];
  2592. for (let i = 0; i < chartRawData.length; i++) {
  2593. self.totalContributions += chartRawData[i].contributions;
  2594. chartData[i] = { date: new Date(chartRawData[i].timestamp * 1000), count: chartRawData[i].contributions };
  2595. }
  2596. self.values = chartData;
  2597. self.isLoading = false;
  2598. });
  2599. },
  2600. getColor: function(idx) {
  2601. const el = document.createElement('div');
  2602. el.className = 'heatmap-color-' + idx;
  2603. document.body.appendChild(el);
  2604. const color = getComputedStyle(el).backgroundColor;
  2605. document.body.removeChild(el);
  2606. return color;
  2607. }
  2608. },
  2609. template: '<div><div v-show="isLoading"><slot name="loading"></slot></div><h4 class="total-contributions" v-if="!isLoading"><span v-html="totalContributions"></span> total contributions in the last 12 months</h4><calendar-heatmap v-show="!isLoading" :locale="locale" :no-data-text="locale.no_contributions" :tooltip-unit="locale.contributions" :end-date="endDate" :values="values" :range-color="colorRange" />'
  2610. });
  2611. new Vue({
  2612. delimiters: vueDelimeters,
  2613. el: el,
  2614. data: {
  2615. suburl: document.querySelector('meta[name=_suburl]').content,
  2616. heatmapUser: heatmapUser,
  2617. locale: locale
  2618. },
  2619. });
  2620. }
  2621. function initFilterBranchTagDropdown(selector) {
  2622. $(selector).each(function() {
  2623. const $dropdown = $(this);
  2624. const $data = $dropdown.find('.data');
  2625. const data = {
  2626. items: [],
  2627. mode: $data.data('mode'),
  2628. searchTerm: '',
  2629. noResults: '',
  2630. canCreateBranch: false,
  2631. menuVisible: false,
  2632. active: 0
  2633. };
  2634. $data.find('.item').each(function() {
  2635. data.items.push({
  2636. name: $(this).text(),
  2637. url: $(this).data('url'),
  2638. branch: $(this).hasClass('branch'),
  2639. tag: $(this).hasClass('tag'),
  2640. selected: $(this).hasClass('selected')
  2641. });
  2642. });
  2643. $data.remove();
  2644. new Vue({
  2645. delimiters: ['${', '}'],
  2646. el: this,
  2647. data: data,
  2648. beforeMount: function () {
  2649. const vm = this;
  2650. this.noResults = vm.$el.getAttribute('data-no-results');
  2651. this.canCreateBranch = vm.$el.getAttribute('data-can-create-branch') === 'true';
  2652. document.body.addEventListener('click', function(event) {
  2653. if (vm.$el.contains(event.target)) {
  2654. return;
  2655. }
  2656. if (vm.menuVisible) {
  2657. Vue.set(vm, 'menuVisible', false);
  2658. }
  2659. });
  2660. },
  2661. watch: {
  2662. menuVisible: function(visible) {
  2663. if (visible) {
  2664. this.focusSearchField();
  2665. }
  2666. }
  2667. },
  2668. computed: {
  2669. filteredItems: function() {
  2670. const vm = this;
  2671. const items = vm.items.filter(function (item) {
  2672. return ((vm.mode === 'branches' && item.branch)
  2673. || (vm.mode === 'tags' && item.tag))
  2674. && (!vm.searchTerm
  2675. || item.name.toLowerCase().indexOf(vm.searchTerm.toLowerCase()) >= 0);
  2676. });
  2677. vm.active = (items.length === 0 && vm.showCreateNewBranch ? 0 : -1);
  2678. return items;
  2679. },
  2680. showNoResults: function() {
  2681. return this.filteredItems.length === 0
  2682. && !this.showCreateNewBranch;
  2683. },
  2684. showCreateNewBranch: function() {
  2685. const vm = this;
  2686. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  2687. return false;
  2688. }
  2689. return vm.items.filter(function (item) {
  2690. return item.name.toLowerCase() === vm.searchTerm.toLowerCase()
  2691. }).length === 0;
  2692. }
  2693. },
  2694. methods: {
  2695. selectItem: function(item) {
  2696. const prev = this.getSelected();
  2697. if (prev !== null) {
  2698. prev.selected = false;
  2699. }
  2700. item.selected = true;
  2701. window.location.href = item.url;
  2702. },
  2703. createNewBranch: function() {
  2704. if (!this.showCreateNewBranch) {
  2705. return;
  2706. }
  2707. this.$refs.newBranchForm.submit();
  2708. },
  2709. focusSearchField: function() {
  2710. const vm = this;
  2711. Vue.nextTick(function() {
  2712. vm.$refs.searchField.focus();
  2713. });
  2714. },
  2715. getSelected: function() {
  2716. for (let i = 0, j = this.items.length; i < j; ++i) {
  2717. if (this.items[i].selected)
  2718. return this.items[i];
  2719. }
  2720. return null;
  2721. },
  2722. getSelectedIndexInFiltered: function() {
  2723. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  2724. if (this.filteredItems[i].selected)
  2725. return i;
  2726. }
  2727. return -1;
  2728. },
  2729. scrollToActive: function() {
  2730. let el = this.$refs['listItem' + this.active];
  2731. if (!el || el.length === 0) {
  2732. return;
  2733. }
  2734. if (Array.isArray(el)) {
  2735. el = el[0];
  2736. }
  2737. const cont = this.$refs.scrollContainer;
  2738. if (el.offsetTop < cont.scrollTop) {
  2739. cont.scrollTop = el.offsetTop;
  2740. }
  2741. else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  2742. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  2743. }
  2744. },
  2745. keydown: function(event) {
  2746. const vm = this;
  2747. if (event.keyCode === 40) {
  2748. // arrow down
  2749. event.preventDefault();
  2750. if (vm.active === -1) {
  2751. vm.active = vm.getSelectedIndexInFiltered();
  2752. }
  2753. if (vm.active + (vm.showCreateNewBranch ? 0 : 1) >= vm.filteredItems.length) {
  2754. return;
  2755. }
  2756. vm.active++;
  2757. vm.scrollToActive();
  2758. }
  2759. if (event.keyCode === 38) {
  2760. // arrow up
  2761. event.preventDefault();
  2762. if (vm.active === -1) {
  2763. vm.active = vm.getSelectedIndexInFiltered();
  2764. }
  2765. if (vm.active <= 0) {
  2766. return;
  2767. }
  2768. vm.active--;
  2769. vm.scrollToActive();
  2770. }
  2771. if (event.keyCode == 13) {
  2772. // enter
  2773. event.preventDefault();
  2774. if (vm.active >= vm.filteredItems.length) {
  2775. vm.createNewBranch();
  2776. } else if (vm.active >= 0) {
  2777. vm.selectItem(vm.filteredItems[vm.active]);
  2778. }
  2779. }
  2780. if (event.keyCode == 27) {
  2781. // escape
  2782. event.preventDefault();
  2783. vm.menuVisible = false;
  2784. }
  2785. }
  2786. }
  2787. });
  2788. });
  2789. }
  2790. $(".commit-button").click(function(e) {
  2791. e.preventDefault();
  2792. $(this).parent().find('.commit-body').toggle();
  2793. });
  2794. function initNavbarContentToggle() {
  2795. const content = $('#navbar');
  2796. const toggle = $('#navbar-expand-toggle');
  2797. let isExpanded = false;
  2798. toggle.click(function() {
  2799. isExpanded = !isExpanded;
  2800. if (isExpanded) {
  2801. content.addClass('shown');
  2802. toggle.addClass('active');
  2803. }
  2804. else {
  2805. content.removeClass('shown');
  2806. toggle.removeClass('active');
  2807. }
  2808. });
  2809. }
  2810. function initTopicbar() {
  2811. const mgrBtn = $("#manage_topic");
  2812. const editDiv = $("#topic_edit");
  2813. const viewDiv = $("#repo-topics");
  2814. const saveBtn = $("#save_topic");
  2815. const topicDropdown = $('#topic_edit .dropdown');
  2816. const topicForm = $('#topic_edit.ui.form');
  2817. const topicPrompts = getPrompts();
  2818. mgrBtn.click(function() {
  2819. viewDiv.hide();
  2820. editDiv.css('display', ''); // show Semantic UI Grid
  2821. });
  2822. function getPrompts() {
  2823. const hidePrompt = $("div.hide#validate_prompt"),
  2824. prompts = {
  2825. countPrompt: hidePrompt.children('#count_prompt').text(),
  2826. formatPrompt: hidePrompt.children('#format_prompt').text()
  2827. };
  2828. hidePrompt.remove();
  2829. return prompts;
  2830. }
  2831. saveBtn.click(function() {
  2832. const topics = $("input[name=topics]").val();
  2833. $.post(saveBtn.data('link'), {
  2834. "_csrf": csrf,
  2835. "topics": topics
  2836. }, function(_data, _textStatus, xhr){
  2837. if (xhr.responseJSON.status === 'ok') {
  2838. viewDiv.children(".topic").remove();
  2839. if (topics.length) {
  2840. const topicArray = topics.split(",");
  2841. const last = viewDiv.children("a").last();
  2842. for (let i=0; i < topicArray.length; i++) {
  2843. $('<div class="ui small label topic" style="cursor:pointer;">'+topicArray[i]+'</div>').insertBefore(last)
  2844. }
  2845. }
  2846. editDiv.css('display', 'none');
  2847. viewDiv.show();
  2848. }
  2849. }).fail(function(xhr){
  2850. if (xhr.status === 422) {
  2851. if (xhr.responseJSON.invalidTopics.length > 0) {
  2852. topicPrompts.formatPrompt = xhr.responseJSON.message;
  2853. const invalidTopics = xhr.responseJSON.invalidTopics,
  2854. topicLables = topicDropdown.children('a.ui.label');
  2855. topics.split(',').forEach(function(value, index) {
  2856. for (let i=0; i < invalidTopics.length; i++) {
  2857. if (invalidTopics[i] === value) {
  2858. topicLables.eq(index).removeClass("green").addClass("red");
  2859. }
  2860. }
  2861. });
  2862. } else {
  2863. topicPrompts.countPrompt = xhr.responseJSON.message;
  2864. }
  2865. }
  2866. }).always(function() {
  2867. topicForm.form('validate form');
  2868. });
  2869. });
  2870. topicDropdown.dropdown({
  2871. allowAdditions: true,
  2872. forceSelection: false,
  2873. fields: { name: "description", value: "data-value" },
  2874. saveRemoteData: false,
  2875. label: {
  2876. transition : 'horizontal flip',
  2877. duration : 200,
  2878. variation : false,
  2879. blue : true,
  2880. basic: true,
  2881. },
  2882. className: {
  2883. label: 'ui small label'
  2884. },
  2885. apiSettings: {
  2886. url: suburl + '/api/v1/topics/search?q={query}',
  2887. throttle: 500,
  2888. cache: false,
  2889. onResponse: function(res) {
  2890. const formattedResponse = {
  2891. success: false,
  2892. results: [],
  2893. };
  2894. const stripTags = function (text) {
  2895. return text.replace(/<[^>]*>?/gm, "");
  2896. };
  2897. const query = stripTags(this.urlData.query.trim());
  2898. let found_query = false;
  2899. const current_topics = [];
  2900. topicDropdown.find('div.label.visible.topic,a.label.visible').each(function(_,e){ current_topics.push(e.dataset.value); });
  2901. if (res.topics) {
  2902. let found = false;
  2903. for (let i=0;i < res.topics.length;i++) {
  2904. // skip currently added tags
  2905. if (current_topics.indexOf(res.topics[i].topic_name) != -1){
  2906. continue;
  2907. }
  2908. if (res.topics[i].topic_name.toLowerCase() === query.toLowerCase()){
  2909. found_query = true;
  2910. }
  2911. formattedResponse.results.push({"description": res.topics[i].topic_name, "data-value": res.topics[i].topic_name});
  2912. found = true;
  2913. }
  2914. formattedResponse.success = found;
  2915. }
  2916. if (query.length > 0 && !found_query){
  2917. formattedResponse.success = true;
  2918. formattedResponse.results.unshift({"description": query, "data-value": query});
  2919. } else if (query.length > 0 && found_query) {
  2920. formattedResponse.results.sort(function(a, b){
  2921. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  2922. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  2923. if (a.description > b.description) return -1;
  2924. if (a.description < b.description) return 1;
  2925. return 0;
  2926. });
  2927. }
  2928. return formattedResponse;
  2929. },
  2930. },
  2931. onLabelCreate: function(value) {
  2932. value = value.toLowerCase().trim();
  2933. this.attr("data-value", value).contents().first().replaceWith(value);
  2934. return $(this);
  2935. },
  2936. onAdd: function(addedValue, _addedText, $addedChoice) {
  2937. addedValue = addedValue.toLowerCase().trim();
  2938. $($addedChoice).attr('data-value', addedValue);
  2939. $($addedChoice).attr('data-text', addedValue);
  2940. }
  2941. });
  2942. $.fn.form.settings.rules.validateTopic = function(_values, regExp) {
  2943. const topics = topicDropdown.children('a.ui.label'),
  2944. status = topics.length === 0 || topics.last().attr("data-value").match(regExp);
  2945. if (!status) {
  2946. topics.last().removeClass("green").addClass("red");
  2947. }
  2948. return status && topicDropdown.children('a.ui.label.red').length === 0;
  2949. };
  2950. topicForm.form({
  2951. on: 'change',
  2952. inline : true,
  2953. fields: {
  2954. topics: {
  2955. identifier: 'topics',
  2956. rules: [
  2957. {
  2958. type: 'validateTopic',
  2959. value: /^[a-z0-9][a-z0-9-]{1,35}$/,
  2960. prompt: topicPrompts.formatPrompt
  2961. },
  2962. {
  2963. type: 'maxCount[25]',
  2964. prompt: topicPrompts.countPrompt
  2965. }
  2966. ]
  2967. },
  2968. }
  2969. });
  2970. }
  2971. window.toggleDeadlineForm = function() {
  2972. $('#deadlineForm').fadeToggle(150);
  2973. }
  2974. window.setDeadline = function() {
  2975. const deadline = $('#deadlineDate').val();
  2976. window.updateDeadline(deadline);
  2977. }
  2978. window.updateDeadline = function(deadlineString) {
  2979. $('#deadline-err-invalid-date').hide();
  2980. $('#deadline-loader').addClass('loading');
  2981. let realDeadline = null;
  2982. if (deadlineString !== '') {
  2983. const newDate = Date.parse(deadlineString)
  2984. if (isNaN(newDate)) {
  2985. $('#deadline-loader').removeClass('loading');
  2986. $('#deadline-err-invalid-date').show();
  2987. return false;
  2988. }
  2989. realDeadline = new Date(newDate);
  2990. }
  2991. $.ajax($('#update-issue-deadline-form').attr('action') + '/deadline', {
  2992. data: JSON.stringify({
  2993. 'due_date': realDeadline,
  2994. }),
  2995. headers: {
  2996. 'X-Csrf-Token': csrf,
  2997. 'X-Remote': true,
  2998. },
  2999. contentType: 'application/json',
  3000. type: 'POST',
  3001. success: function () {
  3002. reload();
  3003. },
  3004. error: function () {
  3005. $('#deadline-loader').removeClass('loading');
  3006. $('#deadline-err-invalid-date').show();
  3007. }
  3008. });
  3009. }
  3010. window.deleteDependencyModal = function(id, type) {
  3011. $('.remove-dependency')
  3012. .modal({
  3013. closable: false,
  3014. duration: 200,
  3015. onApprove: function () {
  3016. $('#removeDependencyID').val(id);
  3017. $('#dependencyType').val(type);
  3018. $('#removeDependencyForm').submit();
  3019. }
  3020. }).modal('show')
  3021. ;
  3022. }
  3023. function initIssueList() {
  3024. const repolink = $('#repolink').val();
  3025. const repoId = $('#repoId').val();
  3026. const crossRepoSearch = $('#crossRepoSearch').val();
  3027. let issueSearchUrl = suburl + '/api/v1/repos/' + repolink + '/issues?q={query}';
  3028. if (crossRepoSearch === 'true') {
  3029. issueSearchUrl = suburl + '/api/v1/repos/issues/search?q={query}&priority_repo_id=' + repoId;
  3030. }
  3031. $('#new-dependency-drop-list')
  3032. .dropdown({
  3033. apiSettings: {
  3034. url: issueSearchUrl,
  3035. onResponse: function(response) {
  3036. const filteredResponse = {'success': true, 'results': []};
  3037. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  3038. // Parse the response from the api to work with our dropdown
  3039. $.each(response, function(_i, issue) {
  3040. // Don't list current issue in the dependency list.
  3041. if(issue.id === currIssueId) {
  3042. return;
  3043. }
  3044. filteredResponse.results.push({
  3045. 'name' : '#' + issue.number + ' ' + htmlEncode(issue.title) +
  3046. '<div class="text small dont-break-out">' + htmlEncode(issue.repository.full_name) + '</div>',
  3047. 'value' : issue.id
  3048. });
  3049. });
  3050. return filteredResponse;
  3051. },
  3052. cache: false,
  3053. },
  3054. fullTextSearch: true
  3055. });
  3056. $(".menu a.label-filter-item").each(function() {
  3057. $(this).click(function(e) {
  3058. if (e.altKey) {
  3059. e.preventDefault();
  3060. const href = $(this).attr("href");
  3061. const id = $(this).data("label-id");
  3062. const regStr = "labels=(-?[0-9]+%2c)*(" + id + ")(%2c-?[0-9]+)*&";
  3063. const newStr = "labels=$1-$2$3&";
  3064. window.location = href.replace(new RegExp(regStr), newStr);
  3065. }
  3066. });
  3067. });
  3068. $(".menu .ui.dropdown.label-filter").keydown(function(e) {
  3069. if (e.altKey && e.keyCode == 13) {
  3070. const selectedItems = $(".menu .ui.dropdown.label-filter .menu .item.selected");
  3071. if (selectedItems.length > 0) {
  3072. const item = $(selectedItems[0]);
  3073. const href = item.attr("href");
  3074. const id = item.data("label-id");
  3075. const regStr = "labels=(-?[0-9]+%2c)*(" + id + ")(%2c-?[0-9]+)*&";
  3076. const newStr = "labels=$1-$2$3&";
  3077. window.location = href.replace(new RegExp(regStr), newStr);
  3078. }
  3079. }
  3080. });
  3081. }
  3082. window.cancelCodeComment = function(btn) {
  3083. const form = $(btn).closest("form");
  3084. if(form.length > 0 && form.hasClass('comment-form')) {
  3085. form.addClass('hide');
  3086. form.parent().find('button.comment-form-reply').show();
  3087. } else {
  3088. form.closest('.comment-code-cloud').remove()
  3089. }
  3090. }
  3091. window.onOAuthLoginClick = function() {
  3092. const oauthLoader = $('#oauth2-login-loader');
  3093. const oauthNav = $('#oauth2-login-navigator');
  3094. oauthNav.hide();
  3095. oauthLoader.removeClass('disabled');
  3096. setTimeout(function(){
  3097. // recover previous content to let user try again
  3098. // usually redirection will be performed before this action
  3099. oauthLoader.addClass('disabled');
  3100. oauthNav.show();
  3101. },5000);
  3102. }