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

common-global.js 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. import $ from 'jquery';
  2. import '../vendor/jquery.are-you-sure.js';
  3. import {clippie} from 'clippie';
  4. import {createDropzone} from './dropzone.js';
  5. import {initCompColorPicker} from './comp/ColorPicker.js';
  6. import {showGlobalErrorMessage} from '../bootstrap.js';
  7. import {handleGlobalEnterQuickSubmit} from './comp/QuickSubmit.js';
  8. import {svg} from '../svg.js';
  9. import {hideElem, showElem, toggleElem, initSubmitEventPolyfill, submitEventSubmitter} from '../utils/dom.js';
  10. import {htmlEscape} from 'escape-goat';
  11. import {showTemporaryTooltip} from '../modules/tippy.js';
  12. import {confirmModal} from './comp/ConfirmModal.js';
  13. import {showErrorToast} from '../modules/toast.js';
  14. import {request, POST} from '../modules/fetch.js';
  15. const {appUrl, appSubUrl, csrfToken, i18n} = window.config;
  16. export function initGlobalFormDirtyLeaveConfirm() {
  17. // Warn users that try to leave a page after entering data into a form.
  18. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  19. if ($('.user.signin').length === 0) {
  20. $('form:not(.ignore-dirty)').areYouSure();
  21. }
  22. }
  23. export function initHeadNavbarContentToggle() {
  24. const navbar = document.getElementById('navbar');
  25. const btn = document.getElementById('navbar-expand-toggle');
  26. if (!navbar || !btn) return;
  27. btn.addEventListener('click', () => {
  28. const isExpanded = btn.classList.contains('active');
  29. navbar.classList.toggle('navbar-menu-open', !isExpanded);
  30. btn.classList.toggle('active', !isExpanded);
  31. });
  32. }
  33. export function initFootLanguageMenu() {
  34. function linkLanguageAction() {
  35. const $this = $(this);
  36. $.get($this.data('url')).always(() => {
  37. window.location.reload();
  38. });
  39. }
  40. $('.language-menu a[lang]').on('click', linkLanguageAction);
  41. }
  42. export function initGlobalEnterQuickSubmit() {
  43. $(document).on('keydown', '.js-quick-submit', (e) => {
  44. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.key === 'Enter')) {
  45. handleGlobalEnterQuickSubmit(e.target);
  46. return false;
  47. }
  48. });
  49. }
  50. export function initGlobalButtonClickOnEnter() {
  51. $(document).on('keypress', 'div.ui.button,span.ui.button', (e) => {
  52. if (e.code === ' ' || e.code === 'Enter') {
  53. $(e.target).trigger('click');
  54. e.preventDefault();
  55. }
  56. });
  57. }
  58. // fetchActionDoRedirect does real redirection to bypass the browser's limitations of "location"
  59. // more details are in the backend's fetch-redirect handler
  60. function fetchActionDoRedirect(redirect) {
  61. const form = document.createElement('form');
  62. const input = document.createElement('input');
  63. form.method = 'post';
  64. form.action = `${appSubUrl}/-/fetch-redirect`;
  65. input.type = 'hidden';
  66. input.name = 'redirect';
  67. input.value = redirect;
  68. form.append(input);
  69. document.body.append(form);
  70. form.submit();
  71. }
  72. async function fetchActionDoRequest(actionElem, url, opt) {
  73. try {
  74. const resp = await request(url, opt);
  75. if (resp.status === 200) {
  76. let {redirect} = await resp.json();
  77. redirect = redirect || actionElem.getAttribute('data-redirect');
  78. actionElem.classList.remove('dirty'); // remove the areYouSure check before reloading
  79. if (redirect) {
  80. fetchActionDoRedirect(redirect);
  81. } else {
  82. window.location.reload();
  83. }
  84. } else if (resp.status >= 400 && resp.status < 500) {
  85. const data = await resp.json();
  86. // the code was quite messy, sometimes the backend uses "err", sometimes it uses "error", and even "user_error"
  87. // but at the moment, as a new approach, we only use "errorMessage" here, backend can use JSONError() to respond.
  88. showErrorToast(data.errorMessage || `server error: ${resp.status}`);
  89. } else {
  90. showErrorToast(`server error: ${resp.status}`);
  91. }
  92. } catch (e) {
  93. console.error('error when doRequest', e);
  94. actionElem.classList.remove('is-loading', 'small-loading-icon');
  95. showErrorToast(i18n.network_error);
  96. }
  97. }
  98. async function formFetchAction(e) {
  99. if (!e.target.classList.contains('form-fetch-action')) return;
  100. e.preventDefault();
  101. const formEl = e.target;
  102. if (formEl.classList.contains('is-loading')) return;
  103. formEl.classList.add('is-loading');
  104. if (formEl.clientHeight < 50) {
  105. formEl.classList.add('small-loading-icon');
  106. }
  107. const formMethod = formEl.getAttribute('method') || 'get';
  108. const formActionUrl = formEl.getAttribute('action');
  109. const formData = new FormData(formEl);
  110. const formSubmitter = submitEventSubmitter(e);
  111. const [submitterName, submitterValue] = [formSubmitter?.getAttribute('name'), formSubmitter?.getAttribute('value')];
  112. if (submitterName) {
  113. formData.append(submitterName, submitterValue || '');
  114. }
  115. let reqUrl = formActionUrl;
  116. const reqOpt = {method: formMethod.toUpperCase()};
  117. if (formMethod.toLowerCase() === 'get') {
  118. const params = new URLSearchParams();
  119. for (const [key, value] of formData) {
  120. params.append(key, value.toString());
  121. }
  122. const pos = reqUrl.indexOf('?');
  123. if (pos !== -1) {
  124. reqUrl = reqUrl.slice(0, pos);
  125. }
  126. reqUrl += `?${params.toString()}`;
  127. } else {
  128. reqOpt.body = formData;
  129. }
  130. await fetchActionDoRequest(formEl, reqUrl, reqOpt);
  131. }
  132. export function initGlobalCommon() {
  133. // Semantic UI modules.
  134. const $uiDropdowns = $('.ui.dropdown');
  135. // do not init "custom" dropdowns, "custom" dropdowns are managed by their own code.
  136. $uiDropdowns.filter(':not(.custom)').dropdown();
  137. // The "jump" means this dropdown is mainly used for "menu" purpose,
  138. // clicking an item will jump to somewhere else or trigger an action/function.
  139. // When a dropdown is used for non-refresh actions with tippy,
  140. // it must have this "jump" class to hide the tippy when dropdown is closed.
  141. $uiDropdowns.filter('.jump').dropdown({
  142. action: 'hide',
  143. onShow() {
  144. // hide associated tooltip while dropdown is open
  145. this._tippy?.hide();
  146. this._tippy?.disable();
  147. },
  148. onHide() {
  149. this._tippy?.enable();
  150. // hide all tippy elements of items after a while. eg: use Enter to click "Copy Link" in the Issue Context Menu
  151. setTimeout(() => {
  152. const $dropdown = $(this);
  153. if ($dropdown.dropdown('is hidden')) {
  154. $(this).find('.menu > .item').each((_, item) => {
  155. item._tippy?.hide();
  156. });
  157. }
  158. }, 2000);
  159. },
  160. });
  161. // Special popup-directions, prevent Fomantic from guessing the popup direction.
  162. // With default "direction: auto", if the viewport height is small, Fomantic would show the popup upward,
  163. // if the dropdown is at the beginning of the page, then the top part would be clipped by the window view.
  164. // eg: Issue List "Sort" dropdown
  165. // But we can not set "direction: downward" for all dropdowns, because there is a bug in dropdown menu positioning when calculating the "left" position,
  166. // which would make some dropdown popups slightly shift out of the right viewport edge in some cases.
  167. // eg: the "Create New Repo" menu on the navbar.
  168. $uiDropdowns.filter('.upward').dropdown('setting', 'direction', 'upward');
  169. $uiDropdowns.filter('.downward').dropdown('setting', 'direction', 'downward');
  170. $('.ui.checkbox').checkbox();
  171. $('.tabular.menu .item').tab();
  172. initSubmitEventPolyfill();
  173. document.addEventListener('submit', formFetchAction);
  174. document.addEventListener('click', linkAction);
  175. }
  176. export function initGlobalDropzone() {
  177. // Dropzone
  178. for (const el of document.querySelectorAll('.dropzone')) {
  179. const $dropzone = $(el);
  180. const _promise = createDropzone(el, {
  181. url: $dropzone.data('upload-url'),
  182. headers: {'X-Csrf-Token': csrfToken},
  183. maxFiles: $dropzone.data('max-file'),
  184. maxFilesize: $dropzone.data('max-size'),
  185. acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'),
  186. addRemoveLinks: true,
  187. dictDefaultMessage: $dropzone.data('default-message'),
  188. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  189. dictFileTooBig: $dropzone.data('file-too-big'),
  190. dictRemoveFile: $dropzone.data('remove-file'),
  191. timeout: 0,
  192. thumbnailMethod: 'contain',
  193. thumbnailWidth: 480,
  194. thumbnailHeight: 480,
  195. init() {
  196. this.on('success', (file, data) => {
  197. file.uuid = data.uuid;
  198. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  199. $dropzone.find('.files').append(input);
  200. // Create a "Copy Link" element, to conveniently copy the image
  201. // or file link as Markdown to the clipboard
  202. const copyLinkElement = document.createElement('div');
  203. copyLinkElement.className = 'gt-text-center';
  204. // The a element has a hardcoded cursor: pointer because the default is overridden by .dropzone
  205. copyLinkElement.innerHTML = `<a href="#" style="cursor: pointer;">${svg('octicon-copy', 14, 'copy link')} Copy link</a>`;
  206. copyLinkElement.addEventListener('click', async (e) => {
  207. e.preventDefault();
  208. let fileMarkdown = `[${file.name}](/attachments/${file.uuid})`;
  209. if (file.type.startsWith('image/')) {
  210. fileMarkdown = `!${fileMarkdown}`;
  211. } else if (file.type.startsWith('video/')) {
  212. fileMarkdown = `<video src="/attachments/${file.uuid}" title="${htmlEscape(file.name)}" controls></video>`;
  213. }
  214. const success = await clippie(fileMarkdown);
  215. showTemporaryTooltip(e.target, success ? i18n.copy_success : i18n.copy_error);
  216. });
  217. file.previewTemplate.append(copyLinkElement);
  218. });
  219. this.on('removedfile', (file) => {
  220. $(`#${file.uuid}`).remove();
  221. if ($dropzone.data('remove-url')) {
  222. POST($dropzone.data('remove-url'), {
  223. data: new URLSearchParams({file: file.uuid}),
  224. });
  225. }
  226. });
  227. this.on('error', function (file, message) {
  228. showErrorToast(message);
  229. this.removeFile(file);
  230. });
  231. },
  232. });
  233. }
  234. }
  235. async function linkAction(e) {
  236. // A "link-action" can post AJAX request to its "data-url"
  237. // Then the browser is redirected to: the "redirect" in response, or "data-redirect" attribute, or current URL by reloading.
  238. // If the "link-action" has "data-modal-confirm" attribute, a confirm modal dialog will be shown before taking action.
  239. const el = e.target.closest('.link-action');
  240. if (!el) return;
  241. e.preventDefault();
  242. const url = el.getAttribute('data-url');
  243. const doRequest = async () => {
  244. el.disabled = true;
  245. await fetchActionDoRequest(el, url, {method: 'POST'});
  246. el.disabled = false;
  247. };
  248. const modalConfirmContent = htmlEscape(el.getAttribute('data-modal-confirm') || '');
  249. if (!modalConfirmContent) {
  250. await doRequest();
  251. return;
  252. }
  253. const isRisky = el.classList.contains('red') || el.classList.contains('yellow') || el.classList.contains('orange') || el.classList.contains('negative');
  254. if (await confirmModal({content: modalConfirmContent, buttonColor: isRisky ? 'orange' : 'primary'})) {
  255. await doRequest();
  256. }
  257. }
  258. export function initGlobalLinkActions() {
  259. function showDeletePopup(e) {
  260. e.preventDefault();
  261. const $this = $(this);
  262. const dataArray = $this.data();
  263. let filter = '';
  264. if ($this.attr('data-modal-id')) {
  265. filter += `#${$this.attr('data-modal-id')}`;
  266. }
  267. const dialog = $(`.delete.modal${filter}`);
  268. dialog.find('.name').text($this.data('name'));
  269. for (const [key, value] of Object.entries(dataArray)) {
  270. if (key && key.startsWith('data')) {
  271. dialog.find(`.${key}`).text(value);
  272. }
  273. }
  274. dialog.modal({
  275. closable: false,
  276. onApprove() {
  277. if ($this.data('type') === 'form') {
  278. $($this.data('form')).trigger('submit');
  279. return;
  280. }
  281. const postData = {
  282. _csrf: csrfToken,
  283. };
  284. for (const [key, value] of Object.entries(dataArray)) {
  285. if (key && key.startsWith('data')) {
  286. postData[key.slice(4)] = value;
  287. }
  288. if (key === 'id') {
  289. postData['id'] = value;
  290. }
  291. }
  292. $.post($this.data('url'), postData).done((data) => {
  293. window.location.href = data.redirect;
  294. });
  295. }
  296. }).modal('show');
  297. }
  298. // Helpers.
  299. $('.delete-button').on('click', showDeletePopup);
  300. }
  301. function initGlobalShowModal() {
  302. // A ".show-modal" button will show a modal dialog defined by its "data-modal" attribute.
  303. // Each "data-modal-{target}" attribute will be filled to target element's value or text-content.
  304. // * First, try to query '#target'
  305. // * Then, try to query '.target'
  306. // * Then, try to query 'target' as HTML tag
  307. // If there is a ".{attr}" part like "data-modal-form.action", then the form's "action" attribute will be set.
  308. $('.show-modal').on('click', function (e) {
  309. e.preventDefault();
  310. const $el = $(this);
  311. const modalSelector = $el.attr('data-modal');
  312. const $modal = $(modalSelector);
  313. if (!$modal.length) {
  314. throw new Error('no modal for this action');
  315. }
  316. const modalAttrPrefix = 'data-modal-';
  317. for (const attrib of this.attributes) {
  318. if (!attrib.name.startsWith(modalAttrPrefix)) {
  319. continue;
  320. }
  321. const attrTargetCombo = attrib.name.substring(modalAttrPrefix.length);
  322. const [attrTargetName, attrTargetAttr] = attrTargetCombo.split('.');
  323. // try to find target by: "#target" -> ".target" -> "target tag"
  324. let $attrTarget = $modal.find(`#${attrTargetName}`);
  325. if (!$attrTarget.length) $attrTarget = $modal.find(`.${attrTargetName}`);
  326. if (!$attrTarget.length) $attrTarget = $modal.find(`${attrTargetName}`);
  327. if (!$attrTarget.length) continue; // TODO: show errors in dev mode to remind developers that there is a bug
  328. if (attrTargetAttr) {
  329. $attrTarget[0][attrTargetAttr] = attrib.value;
  330. } else if ($attrTarget.is('input') || $attrTarget.is('textarea')) {
  331. $attrTarget.val(attrib.value); // FIXME: add more supports like checkbox
  332. } else {
  333. $attrTarget.text(attrib.value); // FIXME: it should be more strict here, only handle div/span/p
  334. }
  335. }
  336. const colorPickers = $modal.find('.color-picker');
  337. if (colorPickers.length > 0) {
  338. initCompColorPicker(); // FIXME: this might cause duplicate init
  339. }
  340. $modal.modal('setting', {
  341. onApprove: () => {
  342. // "form-fetch-action" can handle network errors gracefully,
  343. // so keep the modal dialog to make users can re-submit the form if anything wrong happens.
  344. if ($modal.find('.form-fetch-action').length) return false;
  345. },
  346. }).modal('show');
  347. });
  348. }
  349. export function initGlobalButtons() {
  350. // There are many "cancel button" elements in modal dialogs, Fomantic UI expects they are button-like elements but never submit a form.
  351. // However, Gitea misuses the modal dialog and put the cancel buttons inside forms, so we must prevent the form submission.
  352. // There are a few cancel buttons in non-modal forms, and there are some dynamically created forms (eg: the "Edit Issue Content")
  353. $(document).on('click', 'form button.ui.cancel.button', (e) => {
  354. e.preventDefault();
  355. });
  356. $('.show-panel').on('click', function (e) {
  357. // a '.show-panel' element can show a panel, by `data-panel="selector"`
  358. // if it has "toggle" class, it toggles the panel
  359. e.preventDefault();
  360. const sel = $(this).attr('data-panel');
  361. if (this.classList.contains('toggle')) {
  362. toggleElem(sel);
  363. } else {
  364. showElem(sel);
  365. }
  366. });
  367. $('.hide-panel').on('click', function (e) {
  368. // a `.hide-panel` element can hide a panel, by `data-panel="selector"` or `data-panel-closest="selector"`
  369. e.preventDefault();
  370. let sel = $(this).attr('data-panel');
  371. if (sel) {
  372. hideElem($(sel));
  373. return;
  374. }
  375. sel = $(this).attr('data-panel-closest');
  376. if (sel) {
  377. hideElem($(this).closest(sel));
  378. return;
  379. }
  380. // should never happen, otherwise there is a bug in code
  381. showErrorToast('Nothing to hide');
  382. });
  383. initGlobalShowModal();
  384. }
  385. /**
  386. * Too many users set their ROOT_URL to wrong value, and it causes a lot of problems:
  387. * * Cross-origin API request without correct cookie
  388. * * Incorrect href in <a>
  389. * * ...
  390. * So we check whether current URL starts with AppUrl(ROOT_URL).
  391. * If they don't match, show a warning to users.
  392. */
  393. export function checkAppUrl() {
  394. const curUrl = window.location.href;
  395. // some users visit "https://domain/gitea" while appUrl is "https://domain/gitea/", there should be no warning
  396. if (curUrl.startsWith(appUrl) || `${curUrl}/` === appUrl) {
  397. return;
  398. }
  399. showGlobalErrorMessage(`Your ROOT_URL in app.ini is "${appUrl}", it's unlikely matching the site you are visiting.
  400. Mismatched ROOT_URL config causes wrong URL links for web UI/mail content/webhook notification/OAuth2 sign-in.`);
  401. }