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

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