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

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