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 17KB

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