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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. $('.ui.checkbox').checkbox();
  177. $('.tabular.menu .item').tab();
  178. initSubmitEventPolyfill();
  179. document.addEventListener('submit', formFetchAction);
  180. document.addEventListener('click', linkAction);
  181. }
  182. export function initGlobalDropzone() {
  183. for (const el of document.querySelectorAll('.dropzone')) {
  184. initDropzone(el);
  185. }
  186. }
  187. export function initDropzone(el) {
  188. const $dropzone = $(el);
  189. const _promise = createDropzone(el, {
  190. url: $dropzone.data('upload-url'),
  191. headers: {'X-Csrf-Token': csrfToken},
  192. maxFiles: $dropzone.data('max-file'),
  193. maxFilesize: $dropzone.data('max-size'),
  194. acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'),
  195. addRemoveLinks: true,
  196. dictDefaultMessage: $dropzone.data('default-message'),
  197. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  198. dictFileTooBig: $dropzone.data('file-too-big'),
  199. dictRemoveFile: $dropzone.data('remove-file'),
  200. timeout: 0,
  201. thumbnailMethod: 'contain',
  202. thumbnailWidth: 480,
  203. thumbnailHeight: 480,
  204. init() {
  205. this.on('success', (file, data) => {
  206. file.uuid = data.uuid;
  207. const $input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  208. $dropzone.find('.files').append($input);
  209. // Create a "Copy Link" element, to conveniently copy the image
  210. // or file link as Markdown to the clipboard
  211. const copyLinkElement = document.createElement('div');
  212. copyLinkElement.className = 'tw-text-center';
  213. // The a element has a hardcoded cursor: pointer because the default is overridden by .dropzone
  214. copyLinkElement.innerHTML = `<a href="#" style="cursor: pointer;">${svg('octicon-copy', 14, 'copy link')} Copy link</a>`;
  215. copyLinkElement.addEventListener('click', async (e) => {
  216. e.preventDefault();
  217. let fileMarkdown = `[${file.name}](/attachments/${file.uuid})`;
  218. if (file.type.startsWith('image/')) {
  219. fileMarkdown = `!${fileMarkdown}`;
  220. } else if (file.type.startsWith('video/')) {
  221. fileMarkdown = `<video src="/attachments/${file.uuid}" title="${htmlEscape(file.name)}" controls></video>`;
  222. }
  223. const success = await clippie(fileMarkdown);
  224. showTemporaryTooltip(e.target, success ? i18n.copy_success : i18n.copy_error);
  225. });
  226. file.previewTemplate.append(copyLinkElement);
  227. });
  228. this.on('removedfile', (file) => {
  229. $(`#${file.uuid}`).remove();
  230. if ($dropzone.data('remove-url')) {
  231. POST($dropzone.data('remove-url'), {
  232. data: new URLSearchParams({file: file.uuid}),
  233. });
  234. }
  235. });
  236. this.on('error', function (file, message) {
  237. showErrorToast(message);
  238. this.removeFile(file);
  239. });
  240. },
  241. });
  242. }
  243. async function linkAction(e) {
  244. // A "link-action" can post AJAX request to its "data-url"
  245. // Then the browser is redirected to: the "redirect" in response, or "data-redirect" attribute, or current URL by reloading.
  246. // If the "link-action" has "data-modal-confirm" attribute, a confirm modal dialog will be shown before taking action.
  247. const el = e.target.closest('.link-action');
  248. if (!el) return;
  249. e.preventDefault();
  250. const url = el.getAttribute('data-url');
  251. const doRequest = async () => {
  252. el.disabled = true;
  253. await fetchActionDoRequest(el, url, {method: 'POST'});
  254. el.disabled = false;
  255. };
  256. const modalConfirmContent = htmlEscape(el.getAttribute('data-modal-confirm') || '');
  257. if (!modalConfirmContent) {
  258. await doRequest();
  259. return;
  260. }
  261. const isRisky = el.classList.contains('red') || el.classList.contains('yellow') || el.classList.contains('orange') || el.classList.contains('negative');
  262. if (await confirmModal({content: modalConfirmContent, buttonColor: isRisky ? 'orange' : 'primary'})) {
  263. await doRequest();
  264. }
  265. }
  266. export function initGlobalLinkActions() {
  267. function showDeletePopup(e) {
  268. e.preventDefault();
  269. const $this = $(this);
  270. const dataArray = $this.data();
  271. let filter = '';
  272. if (this.getAttribute('data-modal-id')) {
  273. filter += `#${this.getAttribute('data-modal-id')}`;
  274. }
  275. const $dialog = $(`.delete.modal${filter}`);
  276. $dialog.find('.name').text($this.data('name'));
  277. for (const [key, value] of Object.entries(dataArray)) {
  278. if (key && key.startsWith('data')) {
  279. $dialog.find(`.${key}`).text(value);
  280. }
  281. }
  282. $dialog.modal({
  283. closable: false,
  284. onApprove: async () => {
  285. if ($this.data('type') === 'form') {
  286. $($this.data('form')).trigger('submit');
  287. return;
  288. }
  289. const postData = new FormData();
  290. for (const [key, value] of Object.entries(dataArray)) {
  291. if (key && key.startsWith('data')) {
  292. postData.append(key.slice(4), value);
  293. }
  294. if (key === 'id') {
  295. postData.append('id', value);
  296. }
  297. }
  298. const response = await POST($this.data('url'), {data: postData});
  299. if (response.ok) {
  300. const data = await response.json();
  301. window.location.href = data.redirect;
  302. }
  303. },
  304. }).modal('show');
  305. }
  306. // Helpers.
  307. $('.delete-button').on('click', showDeletePopup);
  308. }
  309. function initGlobalShowModal() {
  310. // A ".show-modal" button will show a modal dialog defined by its "data-modal" attribute.
  311. // Each "data-modal-{target}" attribute will be filled to target element's value or text-content.
  312. // * First, try to query '#target'
  313. // * Then, try to query '.target'
  314. // * Then, try to query 'target' as HTML tag
  315. // If there is a ".{attr}" part like "data-modal-form.action", then the form's "action" attribute will be set.
  316. $('.show-modal').on('click', function (e) {
  317. e.preventDefault();
  318. const modalSelector = this.getAttribute('data-modal');
  319. const $modal = $(modalSelector);
  320. if (!$modal.length) {
  321. throw new Error('no modal for this action');
  322. }
  323. const modalAttrPrefix = 'data-modal-';
  324. for (const attrib of this.attributes) {
  325. if (!attrib.name.startsWith(modalAttrPrefix)) {
  326. continue;
  327. }
  328. const attrTargetCombo = attrib.name.substring(modalAttrPrefix.length);
  329. const [attrTargetName, attrTargetAttr] = attrTargetCombo.split('.');
  330. // try to find target by: "#target" -> ".target" -> "target tag"
  331. let $attrTarget = $modal.find(`#${attrTargetName}`);
  332. if (!$attrTarget.length) $attrTarget = $modal.find(`.${attrTargetName}`);
  333. if (!$attrTarget.length) $attrTarget = $modal.find(`${attrTargetName}`);
  334. if (!$attrTarget.length) continue; // TODO: show errors in dev mode to remind developers that there is a bug
  335. if (attrTargetAttr) {
  336. $attrTarget[0][attrTargetAttr] = attrib.value;
  337. } else if ($attrTarget[0].matches('input, textarea')) {
  338. $attrTarget.val(attrib.value); // FIXME: add more supports like checkbox
  339. } else {
  340. $attrTarget.text(attrib.value); // FIXME: it should be more strict here, only handle div/span/p
  341. }
  342. }
  343. $modal.modal('setting', {
  344. onApprove: () => {
  345. // "form-fetch-action" can handle network errors gracefully,
  346. // so keep the modal dialog to make users can re-submit the form if anything wrong happens.
  347. if ($modal.find('.form-fetch-action').length) return false;
  348. },
  349. }).modal('show');
  350. });
  351. }
  352. export function initGlobalButtons() {
  353. // There are many "cancel button" elements in modal dialogs, Fomantic UI expects they are button-like elements but never submit a form.
  354. // However, Gitea misuses the modal dialog and put the cancel buttons inside forms, so we must prevent the form submission.
  355. // There are a few cancel buttons in non-modal forms, and there are some dynamically created forms (eg: the "Edit Issue Content")
  356. $(document).on('click', 'form button.ui.cancel.button', (e) => {
  357. e.preventDefault();
  358. });
  359. $('.show-panel').on('click', function (e) {
  360. // a '.show-panel' element can show a panel, by `data-panel="selector"`
  361. // if it has "toggle" class, it toggles the panel
  362. e.preventDefault();
  363. const sel = this.getAttribute('data-panel');
  364. if (this.classList.contains('toggle')) {
  365. toggleElem(sel);
  366. } else {
  367. showElem(sel);
  368. }
  369. });
  370. $('.hide-panel').on('click', function (e) {
  371. // a `.hide-panel` element can hide a panel, by `data-panel="selector"` or `data-panel-closest="selector"`
  372. e.preventDefault();
  373. let sel = this.getAttribute('data-panel');
  374. if (sel) {
  375. hideElem($(sel));
  376. return;
  377. }
  378. sel = this.getAttribute('data-panel-closest');
  379. if (sel) {
  380. hideElem($(this).closest(sel));
  381. return;
  382. }
  383. // should never happen, otherwise there is a bug in code
  384. showErrorToast('Nothing to hide');
  385. });
  386. initGlobalShowModal();
  387. }
  388. /**
  389. * Too many users set their ROOT_URL to wrong value, and it causes a lot of problems:
  390. * * Cross-origin API request without correct cookie
  391. * * Incorrect href in <a>
  392. * * ...
  393. * So we check whether current URL starts with AppUrl(ROOT_URL).
  394. * If they don't match, show a warning to users.
  395. */
  396. export function checkAppUrl() {
  397. const curUrl = window.location.href;
  398. // some users visit "https://domain/gitea" while appUrl is "https://domain/gitea/", there should be no warning
  399. if (curUrl.startsWith(appUrl) || `${curUrl}/` === appUrl) {
  400. return;
  401. }
  402. showGlobalErrorMessage(`Your ROOT_URL in app.ini is "${appUrl}", it's unlikely matching the site you are visiting.
  403. Mismatched ROOT_URL config causes wrong URL links for web UI/mail content/webhook notification/OAuth2 sign-in.`);
  404. }