Frontend refactor, PascalCase to camelCase, remove unused code (#17365)

* Frontend refactor, PascalCase to camelCase, remove unused code

* fix
tokarchuk/v1.17
wxiaoguang 3 years ago committed by GitHub
parent 5879ab83b5
commit 2add8fe9be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 9
      integrations/branches_test.go
  2. 2
      integrations/html_helper.go
  3. 4
      integrations/pull_create_test.go
  4. 2
      modules/context/context.go
  5. 4
      routers/web/repo/projects.go
  6. 35
      templates/base/head.tmpl
  7. 2
      templates/repo/projects/list.tmpl
  8. 2
      templates/repo/projects/new.tmpl
  9. 10
      templates/repo/projects/view.tmpl
  10. 4
      web_src/js/components/ContextPopup.vue
  11. 6
      web_src/js/components/DashboardRepoList.js
  12. 2
      web_src/js/components/VueComponentLoader.js
  13. 4
      web_src/js/features/admin-common.js
  14. 16
      web_src/js/features/common-global.js
  15. 8
      web_src/js/features/comp/ImagePaste.js
  16. 4
      web_src/js/features/comp/MarkupContentPreview.js
  17. 4
      web_src/js/features/comp/ReactionSelector.js
  18. 4
      web_src/js/features/comp/SearchUserBox.js
  19. 4
      web_src/js/features/comp/WebHookEditor.js
  20. 10
      web_src/js/features/emoji.js
  21. 10
      web_src/js/features/issue-content-history.js
  22. 6
      web_src/js/features/lastcommitloader.js
  23. 28
      web_src/js/features/notification.js
  24. 4
      web_src/js/features/org-team.js
  25. 16
      web_src/js/features/projects.js
  26. 4
      web_src/js/features/repo-common.js
  27. 4
      web_src/js/features/repo-diff.js
  28. 6
      web_src/js/features/repo-editor.js
  29. 8
      web_src/js/features/repo-home.js
  30. 24
      web_src/js/features/repo-issue.js
  31. 10
      web_src/js/features/repo-legacy.js
  32. 6
      web_src/js/features/repo-migrate.js
  33. 8
      web_src/js/features/repo-settings.js
  34. 4
      web_src/js/features/repo-template.js
  35. 4
      web_src/js/features/repo-wiki.js
  36. 8
      web_src/js/features/serviceworker.js
  37. 26
      web_src/js/features/stopwatch.js
  38. 2
      web_src/js/features/tribute.js
  39. 18
      web_src/js/features/user-auth-u2f.js
  40. 6
      web_src/js/markup/mermaid.js
  41. 2
      web_src/js/markup/tasklist.js
  42. 4
      web_src/js/publicpath.js

@ -9,7 +9,6 @@ import (
"net/url" "net/url"
"testing" "testing"
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/unknwon/i18n" "github.com/unknwon/i18n"
) )
@ -62,7 +61,7 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
} }
req = NewRequestWithValues(t, "POST", link, map[string]string{ req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": getCsrf(t, htmlDoc.doc), "_csrf": htmlDoc.GetCSRF(),
}) })
session.MakeRequest(t, req, http.StatusOK) session.MakeRequest(t, req, http.StatusOK)
@ -73,9 +72,3 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
return NewHTMLParser(t, resp.Body), url.Query().Get("name") return NewHTMLParser(t, resp.Body), url.Query().Get("name")
} }
func getCsrf(t *testing.T, doc *goquery.Document) string {
csrf, exists := doc.Find("meta[name=\"_csrf\"]").Attr("content")
assert.True(t, exists)
return csrf
}

@ -44,7 +44,7 @@ func (doc *HTMLDoc) Find(selector string) *goquery.Selection {
return doc.doc.Find(selector) return doc.doc.Find(selector)
} }
// GetCSRF for get CSRC token value from input // GetCSRF for getting CSRF token value from input
func (doc *HTMLDoc) GetCSRF() string { func (doc *HTMLDoc) GetCSRF() string {
return doc.GetInputValueByName("_csrf") return doc.GetInputValueByName("_csrf")
} }

@ -114,7 +114,7 @@ func testUIDeleteBranch(t *testing.T, session *TestSession, ownerName, repoName,
htmlDoc := NewHTMLParser(t, resp.Body) htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", relURL+"/delete", map[string]string{ req = NewRequestWithValues(t, "POST", relURL+"/delete", map[string]string{
"_csrf": getCsrf(t, htmlDoc.doc), "_csrf": htmlDoc.GetCSRF(),
"name": branchName, "name": branchName,
}) })
session.MakeRequest(t, req, http.StatusOK) session.MakeRequest(t, req, http.StatusOK)
@ -127,7 +127,7 @@ func testDeleteRepository(t *testing.T, session *TestSession, ownerName, repoNam
htmlDoc := NewHTMLParser(t, resp.Body) htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", relURL+"?action=delete", map[string]string{ req = NewRequestWithValues(t, "POST", relURL+"?action=delete", map[string]string{
"_csrf": getCsrf(t, htmlDoc.doc), "_csrf": htmlDoc.GetCSRF(),
"repo_name": repoName, "repo_name": repoName,
}) })
session.MakeRequest(t, req, http.StatusFound) session.MakeRequest(t, req, http.StatusFound)

@ -645,7 +645,7 @@ func Contexter() func(next http.Handler) http.Handler {
"CurrentURL": setting.AppSubURL + req.URL.RequestURI(), "CurrentURL": setting.AppSubURL + req.URL.RequestURI(),
"PageStartTime": startTime, "PageStartTime": startTime,
"Link": link, "Link": link,
"IsProd": setting.IsProd, "RunModeIsProd": setting.IsProd,
}, },
} }
// PageData is passed by reference, and it will be rendered to `window.config.pageData` in `head.tmpl` for JavaScript modules // PageData is passed by reference, and it will be rendered to `window.config.pageData` in `head.tmpl` for JavaScript modules

@ -205,7 +205,6 @@ func DeleteProject(ctx *context.Context) {
// EditProject allows a project to be edited // EditProject allows a project to be edited
func EditProject(ctx *context.Context) { func EditProject(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("repo.projects.edit") ctx.Data["Title"] = ctx.Tr("repo.projects.edit")
ctx.Data["PageIsProjects"] = true
ctx.Data["PageIsEditProjects"] = true ctx.Data["PageIsEditProjects"] = true
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)
@ -233,7 +232,6 @@ func EditProject(ctx *context.Context) {
func EditProjectPost(ctx *context.Context) { func EditProjectPost(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.CreateProjectForm) form := web.GetForm(ctx).(*forms.CreateProjectForm)
ctx.Data["Title"] = ctx.Tr("repo.projects.edit") ctx.Data["Title"] = ctx.Tr("repo.projects.edit")
ctx.Data["PageIsProjects"] = true
ctx.Data["PageIsEditProjects"] = true ctx.Data["PageIsEditProjects"] = true
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)
@ -335,8 +333,6 @@ func ViewProject(ctx *context.Context) {
ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects) ctx.Data["CanWriteProjects"] = ctx.Repo.Permission.CanWrite(models.UnitTypeProjects)
ctx.Data["Project"] = project ctx.Data["Project"] = project
ctx.Data["Boards"] = boards ctx.Data["Boards"] = boards
ctx.Data["PageIsProjects"] = true
ctx.Data["RequiresDraggable"] = true
ctx.HTML(http.StatusOK, tplProjectsView) ctx.HTML(http.StatusOK, tplProjectsView)
} }

@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{if .Title}}{{.Title | RenderEmojiPlain}} - {{end}} {{if .Repository.Name}}{{.Repository.Name}} - {{end}}{{AppName}} </title> <title>{{if .Title}}{{.Title | RenderEmojiPlain}} - {{end}} {{if .Repository.Name}}{{.Repository.Name}} - {{end}}{{AppName}}</title>
<link rel="manifest" href="data:{{.ManifestData}}"/> <link rel="manifest" href="data:{{.ManifestData}}"/>
<meta name="theme-color" content="{{ThemeColorMetaTag}}"> <meta name="theme-color" content="{{ThemeColorMetaTag}}">
<meta name="default-theme" content="{{DefaultTheme}}" /> <meta name="default-theme" content="{{DefaultTheme}}" />
@ -11,7 +11,6 @@
<meta name="description" content="{{if .Repository}}{{.Repository.Name}}{{if .Repository.Description}} - {{.Repository.Description}}{{end}}{{else}}{{MetaDescription}}{{end}}" /> <meta name="description" content="{{if .Repository}}{{.Repository.Name}}{{if .Repository.Description}} - {{.Repository.Description}}{{end}}{{else}}{{MetaDescription}}{{end}}" />
<meta name="keywords" content="{{MetaKeywords}}"> <meta name="keywords" content="{{MetaKeywords}}">
<meta name="referrer" content="no-referrer" /> <meta name="referrer" content="no-referrer" />
<meta name="_csrf" content="{{.CsrfToken}}" />
{{if .GoGetImport}} {{if .GoGetImport}}
<meta name="go-import" content="{{.GoGetImport}} git {{.CloneLink.HTTPS}}"> <meta name="go-import" content="{{.GoGetImport}} git {{.CloneLink.HTTPS}}">
<meta name="go-source" content="{{.GoGetImport}} _ {{.GoDocDirectory}} {{.GoDocFile}}"> <meta name="go-source" content="{{.GoGetImport}} _ {{.GoDocDirectory}} {{.GoDocFile}}">
@ -19,25 +18,17 @@
<script> <script>
<!-- /* eslint-disable */ --> <!-- /* eslint-disable */ -->
window.config = { window.config = {
AppVer: '{{AppVer}}', appVer: '{{AppVer}}',
AppSubUrl: '{{AppSubUrl}}', appSubUrl: '{{AppSubUrl}}',
AssetUrlPrefix: '{{AssetUrlPrefix}}', assetUrlPrefix: '{{AssetUrlPrefix}}',
IsProd: {{.IsProd}}, runModeIsProd: {{.RunModeIsProd}},
CustomEmojis: {{CustomEmojis}}, customEmojis: {{CustomEmojis}},
UseServiceWorker: {{UseServiceWorker}}, useServiceWorker: {{UseServiceWorker}},
csrf: '{{.CsrfToken}}', csrfToken: '{{.CsrfToken}}',
pageData: {{ .PageData }}, pageData: {{.PageData}},
HighlightJS: {{if .RequireHighlightJS}}true{{else}}false{{end}}, requireTribute: {{.RequireTribute}},
SimpleMDE: {{if .RequireSimpleMDE}}true{{else}}false{{end}}, notificationSettings: {{NotificationSettings}}, {{/*a map provided by NewFuncMap in helper.go*/}}
Tribute: {{if .RequireTribute}}true{{else}}false{{end}}, enableTimeTracking: {{EnableTimetracking}},
NotificationSettings: {
MinTimeout: {{NotificationSettings.MinTimeout}},
TimeoutStep: {{NotificationSettings.TimeoutStep}},
MaxTimeout: {{NotificationSettings.MaxTimeout}},
EventSourceUpdateTime: {{NotificationSettings.EventSourceUpdateTime}},
},
EnableTimetracking: {{if EnableTimetracking}}true{{else}}false{{end}},
PageIsProjects: {{if .PageIsProjects }}true{{else}}false{{end}},
{{if .RequireTribute}} {{if .RequireTribute}}
tributeValues: Array.from(new Map([ tributeValues: Array.from(new Map([
{{ range .Participants }} {{ range .Participants }}
@ -54,7 +45,7 @@
{{ end }} {{ end }}
]).values()), ]).values()),
{{end}} {{end}}
MermaidMaxSourceCharacters: {{MermaidMaxSourceCharacters}}, mermaidMaxSourceCharacters: {{MermaidMaxSourceCharacters}},
}; };
</script> </script>
<link rel="icon" href="{{AssetUrlPrefix}}/img/logo.svg" type="image/svg+xml"> <link rel="icon" href="{{AssetUrlPrefix}}/img/logo.svg" type="image/svg+xml">

@ -1,5 +1,5 @@
{{template "base/head" .}} {{template "base/head" .}}
<div class="page-content repository milestones"> <div class="page-content repository projects milestones">
{{template "repo/header" .}} {{template "repo/header" .}}
<div class="ui container"> <div class="ui container">
<div class="navbar"> <div class="navbar">

@ -1,5 +1,5 @@
{{template "base/head" .}} {{template "base/head" .}}
<div class="page-content repository new milestone"> <div class="page-content repository projects edit-project new milestone">
{{template "repo/header" .}} {{template "repo/header" .}}
<div class="ui container"> <div class="ui container">
<div class="navbar"> <div class="navbar">

@ -1,5 +1,5 @@
{{template "base/head" .}} {{template "base/head" .}}
<div class="page-content repository"> <div class="page-content repository projects view-project">
{{template "repo/header" .}} {{template "repo/header" .}}
<div class="ui container"> <div class="ui container">
<div class="ui two column stackable grid"> <div class="ui two column stackable grid">
@ -7,7 +7,7 @@
{{template "repo/issue/navbar" .}} {{template "repo/issue/navbar" .}}
</div> </div>
<div class="column right aligned"> <div class="column right aligned">
{{if and .CanWriteProjects (not .Repository.IsArchived) .PageIsProjects}} {{if and .CanWriteProjects (not .Repository.IsArchived)}}
<a class="ui green button show-modal item" href="{{$.RepoLink}}/issues/new?project={{$.Project.ID}}">{{.i18n.Tr "repo.issues.new"}}</a> <a class="ui green button show-modal item" href="{{$.RepoLink}}/issues/new?project={{$.Project.ID}}">{{.i18n.Tr "repo.issues.new"}}</a>
<a class="ui green button show-modal item" data-modal="#new-board-item">{{.i18n.Tr "new_project_board"}}</a> <a class="ui green button show-modal item" data-modal="#new-board-item">{{.i18n.Tr "new_project_board"}}</a>
{{end}} {{end}}
@ -80,10 +80,10 @@
<div class="board"> <div class="board">
{{ range $board := .Boards }} {{ range $board := .Boards }}
<div class="ui segment board-column" style="background: {{.Color}}!important;" data-id="{{.ID}}" data-sorting="{{.Sorting}}" data-url="{{$.RepoLink}}/projects/{{$.Project.ID}}/{{.ID}}"> <div class="ui segment board-column" style="background: {{.Color}} !important;" data-id="{{.ID}}" data-sorting="{{.Sorting}}" data-url="{{$.RepoLink}}/projects/{{$.Project.ID}}/{{.ID}}">
<div class="board-column-header df ac sb"> <div class="board-column-header df ac sb">
<div class="ui large label board-label py-2">{{.Title}}</div> <div class="ui large label board-label py-2">{{.Title}}</div>
{{if and $.CanWriteProjects (not $.Repository.IsArchived) $.PageIsProjects (ne .ID 0)}} {{if and $.CanWriteProjects (not $.Repository.IsArchived) (ne .ID 0)}}
<div class="ui dropdown jump item poping up" data-variation="tiny inverted"> <div class="ui dropdown jump item poping up" data-variation="tiny inverted">
<div class="not-mobile px-3" tabindex="-1"> <div class="not-mobile px-3" tabindex="-1">
{{svg "octicon-kebab-horizontal"}} {{svg "octicon-kebab-horizontal"}}
@ -232,7 +232,7 @@
{{if .Labels}} {{if .Labels}}
<div class="extra content labels-list p-0 pt-2"> <div class="extra content labels-list p-0 pt-2">
{{ range .Labels }} {{ range .Labels }}
<a class="ui label" href="{{$.RepoLink}}/issues?labels={{.ID}}" style="color: {{.ForegroundColor}}; background-color: {{.Color}}" title="{{.Description | RenderEmojiPlain}}">{{.Name | RenderEmoji}}</a> <a class="ui label" href="{{$.RepoLink}}/issues?labels={{.ID}}" style="color: {{.ForegroundColor}}; background-color: {{.Color}};" title="{{.Description | RenderEmojiPlain}}">{{.Name | RenderEmoji}}</a>
{{ end }} {{ end }}
</div> </div>
{{end}} {{end}}

@ -22,7 +22,7 @@
<script> <script>
import {SvgIcon} from '../svg.js'; import {SvgIcon} from '../svg.js';
const {AppSubUrl} = window.config; const {appSubUrl} = window.config;
// NOTE: see models/issue_label.go for similar implementation // NOTE: see models/issue_label.go for similar implementation
const srgbToLinear = (color) => { const srgbToLinear = (color) => {
@ -112,7 +112,7 @@ export default {
methods: { methods: {
load(data, callback) { load(data, callback) {
this.loading = true; this.loading = true;
$.get(`${AppSubUrl}/api/v1/repos/${data.owner}/${data.repo}/issues/${data.index}`, (issue) => { $.get(`${appSubUrl}/api/v1/repos/${data.owner}/${data.repo}/issues/${data.index}`, (issue) => {
this.issue = issue; this.issue = issue;
this.loading = false; this.loading = false;
this.$nextTick(() => { this.$nextTick(() => {

@ -1,7 +1,7 @@
import Vue from 'vue'; import Vue from 'vue';
import {initVueSvg, vueDelimiters} from './VueComponentLoader.js'; import {initVueSvg, vueDelimiters} from './VueComponentLoader.js';
const {AppSubUrl, AssetUrlPrefix, pageData} = window.config; const {appSubUrl, assetUrlPrefix, pageData} = window.config;
function initVueComponents() { function initVueComponents() {
Vue.component('repo-search', { Vue.component('repo-search', {
@ -95,7 +95,7 @@ function initVueComponents() {
finalPage: 1, finalPage: 1,
searchQuery, searchQuery,
isLoading: false, isLoading: false,
staticPrefix: AssetUrlPrefix, staticPrefix: assetUrlPrefix,
counts: {}, counts: {},
repoTypes: { repoTypes: {
all: { all: {
@ -361,7 +361,7 @@ export function initDashboardRepoList() {
data: () => { data: () => {
return { return {
searchLimit: dashboardRepoListData.searchLimit || 0, searchLimit: dashboardRepoListData.searchLimit || 0,
subUrl: AppSubUrl, subUrl: appSubUrl,
uid: dashboardRepoListData.uid || 0, uid: dashboardRepoListData.uid || 0,
}; };
}, },

@ -8,7 +8,7 @@ export function initVueEnv() {
if (vueEnvInited) return; if (vueEnvInited) return;
vueEnvInited = true; vueEnvInited = true;
const isProd = window.config.IsProd; const isProd = window.config.runModeIsProd;
Vue.config.productionTip = false; Vue.config.productionTip = false;
Vue.config.devtools = !isProd; Vue.config.devtools = !isProd;
} }

@ -1,4 +1,4 @@
const {csrf} = window.config; const {csrfToken} = window.config;
export function initAdminCommon() { export function initAdminCommon() {
if ($('.admin').length === 0) { if ($('.admin').length === 0) {
@ -204,7 +204,7 @@ export function initAdminCommon() {
} }
}); });
$.post($this.data('link'), { $.post($this.data('link'), {
_csrf: csrf, _csrf: csrfToken,
ids ids
}).done(() => { }).done(() => {
window.location.href = $this.data('redirect'); window.location.href = $this.data('redirect');

@ -4,7 +4,7 @@ import {initCompColorPicker} from './comp/ColorPicker.js';
import 'jquery.are-you-sure'; import 'jquery.are-you-sure';
const {csrf} = window.config; const {csrfToken} = window.config;
export function initGlobalFormDirtyLeaveConfirm() { export function initGlobalFormDirtyLeaveConfirm() {
// Warn users that try to leave a page after entering data into a form. // Warn users that try to leave a page after entering data into a form.
@ -136,7 +136,7 @@ export async function initGlobalDropzone() {
const $dropzone = $(el); const $dropzone = $(el);
await createDropzone(el, { await createDropzone(el, {
url: $dropzone.data('upload-url'), url: $dropzone.data('upload-url'),
headers: {'X-Csrf-Token': csrf}, headers: {'X-Csrf-Token': csrfToken},
maxFiles: $dropzone.data('max-file'), maxFiles: $dropzone.data('max-file'),
maxFilesize: $dropzone.data('max-size'), maxFilesize: $dropzone.data('max-size'),
acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'), acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'),
@ -159,7 +159,7 @@ export async function initGlobalDropzone() {
if ($dropzone.data('remove-url')) { if ($dropzone.data('remove-url')) {
$.post($dropzone.data('remove-url'), { $.post($dropzone.data('remove-url'), {
file: file.uuid, file: file.uuid,
_csrf: csrf, _csrf: csrfToken,
}); });
} }
}); });
@ -194,7 +194,7 @@ export function initGlobalLinkActions() {
} }
const postData = { const postData = {
_csrf: csrf, _csrf: csrfToken,
}; };
for (const [key, value] of Object.entries(dataArray)) { for (const [key, value] of Object.entries(dataArray)) {
if (key && key.startsWith('data')) { if (key && key.startsWith('data')) {
@ -232,7 +232,7 @@ export function initGlobalLinkActions() {
} }
$.post($this.data('url'), { $.post($this.data('url'), {
_csrf: csrf, _csrf: csrfToken,
id: $this.data('id') id: $this.data('id')
}).done((data) => { }).done((data) => {
window.location.href = data.redirect; window.location.href = data.redirect;
@ -247,7 +247,7 @@ export function initGlobalLinkActions() {
const $this = $(this); const $this = $(this);
const redirect = $this.data('redirect'); const redirect = $this.data('redirect');
$.post($this.data('url'), { $.post($this.data('url'), {
_csrf: csrf _csrf: csrfToken
}).done((data) => { }).done((data) => {
if (data.redirect) { if (data.redirect) {
window.location.href = data.redirect; window.location.href = data.redirect;
@ -270,7 +270,7 @@ export function initGlobalLinkActions() {
$('.undo-button').on('click', function () { $('.undo-button').on('click', function () {
const $this = $(this); const $this = $(this);
$.post($this.data('url'), { $.post($this.data('url'), {
_csrf: csrf, _csrf: csrfToken,
id: $this.data('id') id: $this.data('id')
}).done((data) => { }).done((data) => {
window.location.href = data.redirect; window.location.href = data.redirect;
@ -298,7 +298,7 @@ export function initGlobalButtons() {
$('.delete-post.button').on('click', function () { $('.delete-post.button').on('click', function () {
const $this = $(this); const $this = $(this);
$.post($this.data('request-url'), { $.post($this.data('request-url'), {
_csrf: csrf _csrf: csrfToken
}).done(() => { }).done(() => {
window.location.href = $this.data('done-url'); window.location.href = $this.data('done-url');
}); });

@ -1,4 +1,4 @@
const {AppSubUrl, csrf} = window.config; const {appSubUrl, csrfToken} = window.config;
async function uploadFile(file, uploadUrl) { async function uploadFile(file, uploadUrl) {
const formData = new FormData(); const formData = new FormData();
@ -6,7 +6,7 @@ async function uploadFile(file, uploadUrl) {
const res = await fetch(uploadUrl, { const res = await fetch(uploadUrl, {
method: 'POST', method: 'POST',
headers: {'X-Csrf-Token': csrf}, headers: {'X-Csrf-Token': csrfToken},
body: formData, body: formData,
}); });
return await res.json(); return await res.json();
@ -67,7 +67,7 @@ export function initCompImagePaste($target) {
const name = img.name.substr(0, img.name.lastIndexOf('.')); const name = img.name.substr(0, img.name.lastIndexOf('.'));
insertAtCursor(textarea, `![${name}]()`); insertAtCursor(textarea, `![${name}]()`);
const data = await uploadFile(img, uploadUrl); const data = await uploadFile(img, uploadUrl);
replaceAndKeepCursor(textarea, `![${name}]()`, `![${name}](${AppSubUrl}/attachments/${data.uuid})`); replaceAndKeepCursor(textarea, `![${name}]()`, `![${name}](${appSubUrl}/attachments/${data.uuid})`);
const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid); const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
dropzoneFiles.appendChild(input[0]); dropzoneFiles.appendChild(input[0]);
} }
@ -83,7 +83,7 @@ export function initSimpleMDEImagePaste(simplemde, dropzone, files) {
const name = img.name.substr(0, img.name.lastIndexOf('.')); const name = img.name.substr(0, img.name.lastIndexOf('.'));
const data = await uploadFile(img, uploadUrl); const data = await uploadFile(img, uploadUrl);
const pos = simplemde.codemirror.getCursor(); const pos = simplemde.codemirror.getCursor();
simplemde.codemirror.replaceRange(`![${name}](${AppSubUrl}/attachments/${data.uuid})`, pos); simplemde.codemirror.replaceRange(`![${name}](${appSubUrl}/attachments/${data.uuid})`, pos);
const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid); const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
files.append(input); files.append(input);
} }

@ -1,6 +1,6 @@
import {initMarkupContent} from '../../markup/content.js'; import {initMarkupContent} from '../../markup/content.js';
const {csrf} = window.config; const {csrfToken} = window.config;
export function initCompMarkupContentPreviewTab($form) { export function initCompMarkupContentPreviewTab($form) {
const $tabMenu = $form.find('.tabular.menu'); const $tabMenu = $form.find('.tabular.menu');
@ -8,7 +8,7 @@ export function initCompMarkupContentPreviewTab($form) {
$tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`).on('click', function () { $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`).on('click', function () {
const $this = $(this); const $this = $(this);
$.post($this.data('url'), { $.post($this.data('url'), {
_csrf: csrf, _csrf: csrfToken,
mode: 'comment', mode: 'comment',
context: $this.data('context'), context: $this.data('context'),
text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val() text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()

@ -1,4 +1,4 @@
const {csrf} = window.config; const {csrfToken} = window.config;
export function initCompReactionSelector(parent) { export function initCompReactionSelector(parent) {
let reactions = ''; let reactions = '';
@ -20,7 +20,7 @@ export function initCompReactionSelector(parent) {
type: 'POST', type: 'POST',
url, url,
data: { data: {
_csrf: csrf, _csrf: csrfToken,
content: $(this).data('content') content: $(this).data('content')
} }
}).done((resp) => { }).done((resp) => {

@ -1,13 +1,13 @@
import {htmlEscape} from 'escape-goat'; import {htmlEscape} from 'escape-goat';
const {AppSubUrl} = window.config; const {appSubUrl} = window.config;
export function initSearchUserBox() { export function initSearchUserBox() {
const $searchUserBox = $('#search-user-box'); const $searchUserBox = $('#search-user-box');
$searchUserBox.search({ $searchUserBox.search({
minCharacters: 2, minCharacters: 2,
apiSettings: { apiSettings: {
url: `${AppSubUrl}/api/v1/users/search?q={query}`, url: `${appSubUrl}/api/v1/users/search?q={query}`,
onResponse(response) { onResponse(response) {
const items = []; const items = [];
const searchQueryUppercase = $searchUserBox.find('input').val().toUpperCase(); const searchQueryUppercase = $searchUserBox.find('input').val().toUpperCase();

@ -1,4 +1,4 @@
const {csrf} = window.config; const {csrfToken} = window.config;
export function initWebHookEditor() { export function initWebHookEditor() {
if ($('.new.webhook').length === 0) { if ($('.new.webhook').length === 0) {
@ -30,7 +30,7 @@ export function initWebHookEditor() {
const $this = $(this); const $this = $(this);
$this.addClass('loading disabled'); $this.addClass('loading disabled');
$.post($this.data('link'), { $.post($this.data('link'), {
_csrf: csrf _csrf: csrfToken
}).done( }).done(
setTimeout(() => { setTimeout(() => {
window.location.href = $this.data('redirect'); window.location.href = $this.data('redirect');

@ -1,9 +1,9 @@
import emojis from '../../../assets/emoji.json'; import emojis from '../../../assets/emoji.json';
const {AssetUrlPrefix} = window.config; const {assetUrlPrefix} = window.config;
const {CustomEmojis} = window.config; const {customEmojis} = window.config;
const tempMap = {...CustomEmojis}; const tempMap = {...customEmojis};
for (const {emoji, aliases} of emojis) { for (const {emoji, aliases} of emojis) {
for (const alias of aliases || []) { for (const alias of aliases || []) {
tempMap[alias] = emoji; tempMap[alias] = emoji;
@ -24,8 +24,8 @@ for (const key of emojiKeys) {
// retrieve HTML for given emoji name // retrieve HTML for given emoji name
export function emojiHTML(name) { export function emojiHTML(name) {
let inner; let inner;
if (Object.prototype.hasOwnProperty.call(CustomEmojis, name)) { if (Object.prototype.hasOwnProperty.call(customEmojis, name)) {
inner = `<img alt=":${name}:" src="${AssetUrlPrefix}/img/emoji/${name}.png">`; inner = `<img alt=":${name}:" src="${assetUrlPrefix}/img/emoji/${name}.png">`;
} else { } else {
inner = emojiString(name); inner = emojiString(name);
} }

@ -1,6 +1,6 @@
import {svg} from '../svg.js'; import {svg} from '../svg.js';
const {AppSubUrl, csrf} = window.config; const {appSubUrl, csrfToken} = window.config;
let i18nTextEdited; let i18nTextEdited;
let i18nTextOptions; let i18nTextOptions;
@ -37,7 +37,7 @@ function showContentHistoryDetail(issueBaseUrl, commentId, historyId, itemTitleH
if (optionItem === 'delete') { if (optionItem === 'delete') {
if (window.confirm(i18nTextDeleteFromHistoryConfirm)) { if (window.confirm(i18nTextDeleteFromHistoryConfirm)) {
$.post(`${issueBaseUrl}/content-history/soft-delete?comment_id=${commentId}&history_id=${historyId}`, { $.post(`${issueBaseUrl}/content-history/soft-delete?comment_id=${commentId}&history_id=${historyId}`, {
_csrf: csrf, _csrf: csrfToken,
}).done((resp) => { }).done((resp) => {
if (resp.ok) { if (resp.ok) {
$dialog.modal('hide'); $dialog.modal('hide');
@ -59,7 +59,7 @@ function showContentHistoryDetail(issueBaseUrl, commentId, historyId, itemTitleH
$.ajax({ $.ajax({
url: `${issueBaseUrl}/content-history/detail?comment_id=${commentId}&history_id=${historyId}`, url: `${issueBaseUrl}/content-history/detail?comment_id=${commentId}&history_id=${historyId}`,
data: { data: {
_csrf: csrf, _csrf: csrfToken,
}, },
}).done((resp) => { }).done((resp) => {
$dialog.find('.content').html(resp.diffHtml); $dialog.find('.content').html(resp.diffHtml);
@ -110,12 +110,12 @@ export function initIssueContentHistory() {
if (!issueIndex || !$itemIssue.length) return; if (!issueIndex || !$itemIssue.length) return;
const repoLink = $('#repolink').val(); const repoLink = $('#repolink').val();
const issueBaseUrl = `${AppSubUrl}/${repoLink}/issues/${issueIndex}`; const issueBaseUrl = `${appSubUrl}/${repoLink}/issues/${issueIndex}`;
$.ajax({ $.ajax({
url: `${issueBaseUrl}/content-history/overview`, url: `${issueBaseUrl}/content-history/overview`,
data: { data: {
_csrf: csrf, _csrf: csrfToken,
}, },
}).done((resp) => { }).done((resp) => {
i18nTextEdited = resp.i18n.textEdited; i18nTextEdited = resp.i18n.textEdited;

@ -1,4 +1,4 @@
const {csrf} = window.config; const {csrfToken} = window.config;
export async function initLastCommitLoader() { export async function initLastCommitLoader() {
const entryMap = {}; const entryMap = {};
@ -18,7 +18,7 @@ export async function initLastCommitLoader() {
if (entries.length > 200) { if (entries.length > 200) {
$.post(lastCommitLoaderURL, { $.post(lastCommitLoaderURL, {
_csrf: csrf, _csrf: csrfToken,
}, (data) => { }, (data) => {
$('table#repo-files-table').replaceWith(data); $('table#repo-files-table').replaceWith(data);
}); });
@ -26,7 +26,7 @@ export async function initLastCommitLoader() {
} }
$.post(lastCommitLoaderURL, { $.post(lastCommitLoaderURL, {
_csrf: csrf, _csrf: csrfToken,
'f': entries, 'f': entries,
}, (data) => { }, (data) => {
$(data).find('tr').each((_, row) => { $(data).find('tr').each((_, row) => {

@ -1,4 +1,4 @@
const {AppSubUrl, csrf, NotificationSettings} = window.config; const {appSubUrl, csrfToken, notificationSettings} = window.config;
let notificationSequenceNumber = 0; let notificationSequenceNumber = 0;
@ -47,7 +47,7 @@ export async function initNotificationCount() {
return; return;
} }
if (NotificationSettings.EventSourceUpdateTime > 0 && !!window.EventSource && window.SharedWorker) { if (notificationSettings.EventSourceUpdateTime > 0 && !!window.EventSource && window.SharedWorker) {
// Try to connect to the event source via the shared worker first // Try to connect to the event source via the shared worker first
const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js`, 'notification-worker'); const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js`, 'notification-worker');
worker.addEventListener('error', (event) => { worker.addEventListener('error', (event) => {
@ -58,7 +58,7 @@ export async function initNotificationCount() {
}); });
worker.port.postMessage({ worker.port.postMessage({
type: 'start', type: 'start',
url: `${window.location.origin}${AppSubUrl}/user/events`, url: `${window.location.origin}${appSubUrl}/user/events`,
}); });
worker.port.addEventListener('message', (event) => { worker.port.addEventListener('message', (event) => {
if (!event.data || !event.data.type) { if (!event.data || !event.data.type) {
@ -77,7 +77,7 @@ export async function initNotificationCount() {
type: 'close', type: 'close',
}); });
worker.port.close(); worker.port.close();
window.location.href = AppSubUrl; window.location.href = appSubUrl;
} else if (event.data.type === 'close') { } else if (event.data.type === 'close') {
worker.port.postMessage({ worker.port.postMessage({
type: 'close', type: 'close',
@ -99,7 +99,7 @@ export async function initNotificationCount() {
return; return;
} }
if (NotificationSettings.MinTimeout <= 0) { if (notificationSettings.MinTimeout <= 0) {
return; return;
} }
@ -109,13 +109,13 @@ export async function initNotificationCount() {
}, timeout); }, timeout);
}; };
fn(NotificationSettings.MinTimeout, notificationCount.text()); fn(notificationSettings.MinTimeout, notificationCount.text());
} }
async function updateNotificationCountWithCallback(callback, timeout, lastCount) { async function updateNotificationCountWithCallback(callback, timeout, lastCount) {
const currentCount = $('.notification_count').text(); const currentCount = $('.notification_count').text();
if (lastCount !== currentCount) { if (lastCount !== currentCount) {
callback(NotificationSettings.MinTimeout, currentCount); callback(notificationSettings.MinTimeout, currentCount);
return; return;
} }
@ -124,9 +124,9 @@ async function updateNotificationCountWithCallback(callback, timeout, lastCount)
if (lastCount !== newCount) { if (lastCount !== newCount) {
needsUpdate = true; needsUpdate = true;
timeout = NotificationSettings.MinTimeout; timeout = notificationSettings.MinTimeout;
} else if (timeout < NotificationSettings.MaxTimeout) { } else if (timeout < notificationSettings.MaxTimeout) {
timeout += NotificationSettings.TimeoutStep; timeout += notificationSettings.TimeoutStep;
} }
callback(timeout, newCount); callback(timeout, newCount);
@ -140,7 +140,7 @@ async function updateNotificationTable() {
if (notificationDiv.length > 0) { if (notificationDiv.length > 0) {
const data = await $.ajax({ const data = await $.ajax({
type: 'GET', type: 'GET',
url: `${AppSubUrl}/notifications?${notificationDiv.data('params')}`, url: `${appSubUrl}/notifications?${notificationDiv.data('params')}`,
data: { data: {
'div-only': true, 'div-only': true,
'sequence-number': ++notificationSequenceNumber, 'sequence-number': ++notificationSequenceNumber,
@ -156,9 +156,9 @@ async function updateNotificationTable() {
async function updateNotificationCount() { async function updateNotificationCount() {
const data = await $.ajax({ const data = await $.ajax({
type: 'GET', type: 'GET',
url: `${AppSubUrl}/api/v1/notifications/new`, url: `${appSubUrl}/api/v1/notifications/new`,
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
}, },
}); });
@ -183,7 +183,7 @@ async function updateNotification(url, status, page, q, notificationID) {
type: 'POST', type: 'POST',
url, url,
data: { data: {
_csrf: csrf, _csrf: csrfToken,
notification_id: notificationID, notification_id: notificationID,
status, status,
page, page,

@ -1,4 +1,4 @@
const {AppSubUrl} = window.config; const {appSubUrl} = window.config;
export function initOrgTeamSettings() { export function initOrgTeamSettings() {
// Change team access mode // Change team access mode
@ -18,7 +18,7 @@ export function initOrgTeamSearchRepoBox() {
$searchRepoBox.search({ $searchRepoBox.search({
minCharacters: 2, minCharacters: 2,
apiSettings: { apiSettings: {
url: `${AppSubUrl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data('uid')}`, url: `${appSubUrl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data('uid')}`,
onResponse(response) { onResponse(response) {
const items = []; const items = [];
$.each(response.data, (_i, item) => { $.each(response.data, (_i, item) => {

@ -1,7 +1,7 @@
const {csrf, PageIsProjects} = window.config; const {csrfToken} = window.config;
export default async function initProject() { export default async function initProject() {
if (!PageIsProjects) { if (!$('.repository.projects').length) {
return; return;
} }
@ -25,7 +25,7 @@ export default async function initProject() {
url: $(column).data('url'), url: $(column).data('url'),
data: JSON.stringify({sorting: i, color: rgbToHex($(column).css('backgroundColor'))}), data: JSON.stringify({sorting: i, color: rgbToHex($(column).css('backgroundColor'))}),
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
'X-Remote': true, 'X-Remote': true,
}, },
contentType: 'application/json', contentType: 'application/json',
@ -47,7 +47,7 @@ export default async function initProject() {
onAdd: (e) => { onAdd: (e) => {
$.ajax(`${e.to.dataset.url}/${e.item.dataset.issue}`, { $.ajax(`${e.to.dataset.url}/${e.item.dataset.issue}`, {
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
'X-Remote': true, 'X-Remote': true,
}, },
contentType: 'application/json', contentType: 'application/json',
@ -83,7 +83,7 @@ export default async function initProject() {
url: $(this).data('url'), url: $(this).data('url'),
data: JSON.stringify({title: projectTitleInput.val(), color: projectColorInput.val()}), data: JSON.stringify({title: projectTitleInput.val(), color: projectColorInput.val()}),
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
'X-Remote': true, 'X-Remote': true,
}, },
contentType: 'application/json', contentType: 'application/json',
@ -107,7 +107,7 @@ export default async function initProject() {
method: 'POST', method: 'POST',
url: $(this).data('url'), url: $(this).data('url'),
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
'X-Remote': true, 'X-Remote': true,
}, },
contentType: 'application/json', contentType: 'application/json',
@ -123,7 +123,7 @@ export default async function initProject() {
$.ajax({ $.ajax({
url: $(this).data('url'), url: $(this).data('url'),
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
'X-Remote': true, 'X-Remote': true,
}, },
contentType: 'application/json', contentType: 'application/json',
@ -144,7 +144,7 @@ export default async function initProject() {
url: $(this).data('url'), url: $(this).data('url'),
data: JSON.stringify({title: boardTitle.val(), color: projectColorInput.val()}), data: JSON.stringify({title: boardTitle.val(), color: projectColorInput.val()}),
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
'X-Remote': true, 'X-Remote': true,
}, },
contentType: 'application/json', contentType: 'application/json',

@ -1,11 +1,11 @@
const {csrf} = window.config; const {csrfToken} = window.config;
function getArchive($target, url, first) { function getArchive($target, url, first) {
$.ajax({ $.ajax({
url, url,
type: 'POST', type: 'POST',
data: { data: {
_csrf: csrf, _csrf: csrfToken,
}, },
complete(xhr) { complete(xhr) {
if (xhr.status === 200) { if (xhr.status === 200) {

@ -1,6 +1,6 @@
import {initCompReactionSelector} from './comp/ReactionSelector.js'; import {initCompReactionSelector} from './comp/ReactionSelector.js';
const {csrf} = window.config; const {csrfToken} = window.config;
export function initRepoDiffReviewButton() { export function initRepoDiffReviewButton() {
$(document).on('click', 'button[name="is_review"]', (e) => { $(document).on('click', 'button[name="is_review"]', (e) => {
@ -45,7 +45,7 @@ export function initRepoDiffConversationForm() {
const action = $(this).data('action'); const action = $(this).data('action');
const url = $(this).data('update-url'); const url = $(this).data('update-url');
const data = await $.post(url, {_csrf: csrf, origin, action, comment_id}); const data = await $.post(url, {_csrf: csrfToken, origin, action, comment_id});
if ($(this).closest('.conversation-holder').length) { if ($(this).closest('.conversation-holder').length) {
const conversation = $(data); const conversation = $(data);

@ -1,7 +1,7 @@
import {initMarkupContent} from '../markup/content.js'; import {initMarkupContent} from '../markup/content.js';
import {createCodeEditor} from './codeeditor.js'; import {createCodeEditor} from './codeeditor.js';
const {csrf} = window.config; const {csrfToken} = window.config;
let previewFileModes; let previewFileModes;
@ -21,7 +21,7 @@ function initEditPreviewTab($form) {
} }
context = context.substring(0, context.lastIndexOf('/')); context = context.substring(0, context.lastIndexOf('/'));
$.post($this.data('url'), { $.post($this.data('url'), {
_csrf: csrf, _csrf: csrfToken,
mode, mode,
context, context,
text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val() text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
@ -40,7 +40,7 @@ function initEditDiffTab($form) {
$tabMenu.find(`.item[data-tab="${$tabMenu.data('diff')}"]`).on('click', function () { $tabMenu.find(`.item[data-tab="${$tabMenu.data('diff')}"]`).on('click', function () {
const $this = $(this); const $this = $(this);
$.post($this.data('url'), { $.post($this.data('url'), {
_csrf: csrf, _csrf: csrfToken,
context: $this.data('context'), context: $this.data('context'),
content: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val() content: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
}, (data) => { }, (data) => {

@ -1,6 +1,6 @@
import {stripTags} from '../utils.js'; import {stripTags} from '../utils.js';
const {AppSubUrl, csrf} = window.config; const {appSubUrl, csrfToken} = window.config;
export function initRepoTopicBar() { export function initRepoTopicBar() {
const mgrBtn = $('#manage_topic'); const mgrBtn = $('#manage_topic');
@ -30,7 +30,7 @@ export function initRepoTopicBar() {
const topics = $('input[name=topics]').val(); const topics = $('input[name=topics]').val();
$.post(saveBtn.data('link'), { $.post(saveBtn.data('link'), {
_csrf: csrf, _csrf: csrfToken,
topics topics
}, (_data, _textStatus, xhr) => { }, (_data, _textStatus, xhr) => {
if (xhr.responseJSON.status === 'ok') { if (xhr.responseJSON.status === 'ok') {
@ -41,7 +41,7 @@ export function initRepoTopicBar() {
const last = viewDiv.children('a').last(); const last = viewDiv.children('a').last();
for (let i = 0; i < topicArray.length; i++) { for (let i = 0; i < topicArray.length; i++) {
const link = $('<a class="ui repo-topic large label topic"></a>'); const link = $('<a class="ui repo-topic large label topic"></a>');
link.attr('href', `${AppSubUrl}/explore/repos?q=${encodeURIComponent(topicArray[i])}&topic=1`); link.attr('href', `${appSubUrl}/explore/repos?q=${encodeURIComponent(topicArray[i])}&topic=1`);
link.text(topicArray[i]); link.text(topicArray[i]);
link.insertBefore(last); link.insertBefore(last);
} }
@ -90,7 +90,7 @@ export function initRepoTopicBar() {
label: 'ui small label' label: 'ui small label'
}, },
apiSettings: { apiSettings: {
url: `${AppSubUrl}/api/v1/topics/search?q={query}`, url: `${appSubUrl}/api/v1/topics/search?q={query}`,
throttle: 500, throttle: 500,
cache: false, cache: false,
onResponse(res) { onResponse(res) {

@ -4,7 +4,7 @@ import {createCommentSimpleMDE} from './comp/CommentSimpleMDE.js';
import {initCompImagePaste} from './comp/ImagePaste.js'; import {initCompImagePaste} from './comp/ImagePaste.js';
import {initCompMarkupContentPreviewTab} from './comp/MarkupContentPreview.js'; import {initCompMarkupContentPreviewTab} from './comp/MarkupContentPreview.js';
const {AppSubUrl, csrf} = window.config; const {appSubUrl, csrfToken} = window.config;
export function initRepoIssueTimeTracking() { export function initRepoIssueTimeTracking() {
$(document).on('click', '.issue-add-time', () => { $(document).on('click', '.issue-add-time', () => {
@ -58,7 +58,7 @@ function updateDeadline(deadlineString) {
due_date: realDeadline, due_date: realDeadline,
}), }),
headers: { headers: {
'X-Csrf-Token': csrf, 'X-Csrf-Token': csrfToken,
'X-Remote': true, 'X-Remote': true,
}, },
contentType: 'application/json', contentType: 'application/json',
@ -91,9 +91,9 @@ export function initRepoIssueList() {
const repoId = $('#repoId').val(); const repoId = $('#repoId').val();
const crossRepoSearch = $('#crossRepoSearch').val(); const crossRepoSearch = $('#crossRepoSearch').val();
const tp = $('#type').val(); const tp = $('#type').val();
let issueSearchUrl = `${AppSubUrl}/api/v1/repos/${repolink}/issues?q={query}&type=${tp}`; let issueSearchUrl = `${appSubUrl}/api/v1/repos/${repolink}/issues?q={query}&type=${tp}`;
if (crossRepoSearch === 'true') { if (crossRepoSearch === 'true') {
issueSearchUrl = `${AppSubUrl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`; issueSearchUrl = `${appSubUrl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`;
} }
$('#new-dependency-drop-list') $('#new-dependency-drop-list')
.dropdown({ .dropdown({
@ -157,7 +157,7 @@ export function initRepoIssueCommentDelete() {
const $this = $(this); const $this = $(this);
if (window.confirm($this.data('locale'))) { if (window.confirm($this.data('locale'))) {
$.post($this.data('url'), { $.post($this.data('url'), {
_csrf: csrf, _csrf: csrfToken,
}).done(() => { }).done(() => {
const $conversationHolder = $this.closest('.conversation-holder'); const $conversationHolder = $this.closest('.conversation-holder');
$(`#${$this.data('comment-id')}`).remove(); $(`#${$this.data('comment-id')}`).remove();
@ -258,7 +258,7 @@ export function initRepoPullRequestUpdate() {
const redirect = $this.data('redirect'); const redirect = $this.data('redirect');
$this.addClass('loading'); $this.addClass('loading');
$.post($this.data('do'), { $.post($this.data('do'), {
_csrf: csrf _csrf: csrfToken
}).done((data) => { }).done((data) => {
if (data.redirect) { if (data.redirect) {
window.location.href = data.redirect; window.location.href = data.redirect;
@ -291,7 +291,7 @@ export function initRepoIssueReferenceRepositorySearch() {
$('.issue_reference_repository_search') $('.issue_reference_repository_search')
.dropdown({ .dropdown({
apiSettings: { apiSettings: {
url: `${AppSubUrl}/api/v1/repos/search?q={query}&limit=20`, url: `${appSubUrl}/api/v1/repos/search?q={query}&limit=20`,
onResponse(response) { onResponse(response) {
const filteredResponse = {success: true, results: []}; const filteredResponse = {success: true, results: []};
$.each(response.data, (_r, repo) => { $.each(response.data, (_r, repo) => {
@ -306,7 +306,7 @@ export function initRepoIssueReferenceRepositorySearch() {
}, },
onChange(_value, _text, $choice) { onChange(_value, _text, $choice) {
const $form = $choice.closest('form'); const $form = $choice.closest('form');
$form.attr('action', `${AppSubUrl}/${_text}/issues/new`); $form.attr('action', `${appSubUrl}/${_text}/issues/new`);
}, },
fullTextSearch: true fullTextSearch: true
}); });
@ -338,7 +338,7 @@ export function updateIssuesMeta(url, action, issueIds, elementId) {
type: 'POST', type: 'POST',
url, url,
data: { data: {
_csrf: csrf, _csrf: csrfToken,
action, action,
issue_ids: issueIds, issue_ids: issueIds,
id: elementId, id: elementId,
@ -556,7 +556,7 @@ export function initRepoIssueWipToggle() {
e.preventDefault(); e.preventDefault();
const {title, wipPrefix, updateUrl} = e.currentTarget.closest('.toggle-wip').dataset; const {title, wipPrefix, updateUrl} = e.currentTarget.closest('.toggle-wip').dataset;
await $.post(updateUrl, { await $.post(updateUrl, {
_csrf: csrf, _csrf: csrfToken,
title: title?.startsWith(wipPrefix) ? title.substr(wipPrefix.length).trim() : `${wipPrefix.trim()} ${title}`, title: title?.startsWith(wipPrefix) ? title.substr(wipPrefix.length).trim() : `${wipPrefix.trim()} ${title}`,
}); });
window.location.reload(); window.location.reload();
@ -591,7 +591,7 @@ export function initRepoIssueTitleEdit() {
return false; return false;
} }
$.post(update_url, { $.post(update_url, {
_csrf: csrf, _csrf: csrfToken,
target_branch: targetBranch target_branch: targetBranch
}).done((data) => { }).done((data) => {
$branchTarget.text(data.base_branch); $branchTarget.text(data.base_branch);
@ -606,7 +606,7 @@ export function initRepoIssueTitleEdit() {
pullrequest_targetbranch_change(pullrequest_target_update_url); pullrequest_targetbranch_change(pullrequest_target_update_url);
} else { } else {
$.post($(this).data('update-url'), { $.post($(this).data('update-url'), {
_csrf: csrf, _csrf: csrfToken,
title: $editInput.val() title: $editInput.val()
}, (data) => { }, (data) => {
$editInput.val(data.title); $editInput.val(data.title);

@ -27,7 +27,7 @@ import {initCommentContent, initMarkupContent} from '../markup/content.js';
import {initCompReactionSelector} from './comp/ReactionSelector.js'; import {initCompReactionSelector} from './comp/ReactionSelector.js';
import {initRepoSettingBranches} from './repo-settings.js'; import {initRepoSettingBranches} from './repo-settings.js';
const {csrf} = window.config; const {csrfToken} = window.config;
const commentMDEditors = {}; const commentMDEditors = {};
@ -54,7 +54,7 @@ export function initRepoCommentForm() {
if (editMode === 'true') { if (editMode === 'true') {
const form = $('#update_issueref_form'); const form = $('#update_issueref_form');
$.post(form.attr('action'), {_csrf: csrf, ref: selectedValue}, () => window.location.reload()); $.post(form.attr('action'), {_csrf: csrfToken, ref: selectedValue}, () => window.location.reload());
} else if (editMode === '') { } else if (editMode === '') {
$selectBranch.find('.ui .branch-name').text(selectedValue); $selectBranch.find('.ui .branch-name').text(selectedValue);
} }
@ -370,7 +370,7 @@ export async function initRepository() {
const fileUuidDict = {}; const fileUuidDict = {};
dz = await createDropzone($dropzone[0], { dz = await createDropzone($dropzone[0], {
url: $dropzone.data('upload-url'), url: $dropzone.data('upload-url'),
headers: {'X-Csrf-Token': csrf}, headers: {'X-Csrf-Token': csrfToken},
maxFiles: $dropzone.data('max-file'), maxFiles: $dropzone.data('max-file'),
maxFilesize: $dropzone.data('max-size'), maxFilesize: $dropzone.data('max-size'),
acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'), acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'),
@ -396,7 +396,7 @@ export async function initRepository() {
if ($dropzone.data('remove-url') && !fileUuidDict[file.uuid].submitted) { if ($dropzone.data('remove-url') && !fileUuidDict[file.uuid].submitted) {
$.post($dropzone.data('remove-url'), { $.post($dropzone.data('remove-url'), {
file: file.uuid, file: file.uuid,
_csrf: csrf, _csrf: csrfToken,
}); });
} }
}); });
@ -458,7 +458,7 @@ export async function initRepository() {
return $(this).val(); return $(this).val();
}).get(); }).get();
$.post($editContentZone.data('update-url'), { $.post($editContentZone.data('update-url'), {
_csrf: csrf, _csrf: csrfToken,
content: $textarea.val(), content: $textarea.val(),
context: $editContentZone.data('context'), context: $editContentZone.data('context'),
files: $attachments, files: $attachments,

@ -1,4 +1,4 @@
const {AppSubUrl, csrf} = window.config; const {appSubUrl, csrfToken} = window.config;
export function initRepoMigrationStatusChecker() { export function initRepoMigrationStatusChecker() {
const migrating = $('#repo_migrating'); const migrating = $('#repo_migrating');
@ -12,9 +12,9 @@ export function initRepoMigrationStatusChecker() {
} }
$.ajax({ $.ajax({
type: 'GET', type: 'GET',
url: `${AppSubUrl}/user/task/${task}`, url: `${appSubUrl}/user/task/${task}`,
data: { data: {
_csrf: csrf, _csrf: csrfToken,
}, },
complete(xhr) { complete(xhr) {
if (xhr.status === 200 && xhr.responseJSON) { if (xhr.status === 200 && xhr.responseJSON) {

@ -1,14 +1,14 @@
import {createMonaco} from './codeeditor.js'; import {createMonaco} from './codeeditor.js';
import {initRepoCommonFilterSearchDropdown} from './repo-common.js'; import {initRepoCommonFilterSearchDropdown} from './repo-common.js';
const {AppSubUrl, csrf} = window.config; const {appSubUrl, csrfToken} = window.config;
export function initRepoSettingsCollaboration() { export function initRepoSettingsCollaboration() {
// Change collaborator access mode // Change collaborator access mode
$('.access-mode.menu .item').on('click', function () { $('.access-mode.menu .item').on('click', function () {
const $menu = $(this).parent(); const $menu = $(this).parent();
$.post($menu.data('url'), { $.post($menu.data('url'), {
_csrf: csrf, _csrf: csrfToken,
uid: $menu.data('uid'), uid: $menu.data('uid'),
mode: $(this).data('value') mode: $(this).data('value')
}); });
@ -20,8 +20,8 @@ export function initRepoSettingSearchTeamBox() {
$searchTeamBox.search({ $searchTeamBox.search({
minCharacters: 2, minCharacters: 2,
apiSettings: { apiSettings: {
url: `${AppSubUrl}/api/v1/orgs/${$searchTeamBox.data('org')}/teams/search?q={query}`, url: `${appSubUrl}/api/v1/orgs/${$searchTeamBox.data('org')}/teams/search?q={query}`,
headers: {'X-Csrf-Token': csrf}, headers: {'X-Csrf-Token': csrfToken},
onResponse(response) { onResponse(response) {
const items = []; const items = [];
$.each(response.data, (_i, item) => { $.each(response.data, (_i, item) => {

@ -1,6 +1,6 @@
import {htmlEscape} from 'escape-goat'; import {htmlEscape} from 'escape-goat';
const {AppSubUrl} = window.config; const {appSubUrl} = window.config;
export function initRepoTemplateSearch() { export function initRepoTemplateSearch() {
const $repoTemplate = $('#repo_template'); const $repoTemplate = $('#repo_template');
@ -22,7 +22,7 @@ export function initRepoTemplateSearch() {
$('#repo_template_search') $('#repo_template_search')
.dropdown({ .dropdown({
apiSettings: { apiSettings: {
url: `${AppSubUrl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$('#uid').val()}`, url: `${appSubUrl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$('#uid').val()}`,
onResponse(response) { onResponse(response) {
const filteredResponse = {success: true, results: []}; const filteredResponse = {success: true, results: []};
filteredResponse.results.push({ filteredResponse.results.push({

@ -1,7 +1,7 @@
import {initMarkupContent} from '../markup/content.js'; import {initMarkupContent} from '../markup/content.js';
import {initCompMarkupContentPreviewTab} from './comp/MarkupContentPreview.js'; import {initCompMarkupContentPreviewTab} from './comp/MarkupContentPreview.js';
const {csrf} = window.config; const {csrfToken} = window.config;
export function initRepoWikiForm() { export function initRepoWikiForm() {
const $editArea = $('.repository.wiki textarea#edit_area'); const $editArea = $('.repository.wiki textarea#edit_area');
@ -22,7 +22,7 @@ export function initRepoWikiForm() {
sideBySideTimeout = null; sideBySideTimeout = null;
} }
$.post($editArea.data('url'), { $.post($editArea.data('url'), {
_csrf: csrf, _csrf: csrfToken,
mode: 'gfm', mode: 'gfm',
context: $editArea.data('context'), context: $editArea.data('context'),
text: plainText, text: plainText,

@ -1,8 +1,8 @@
import {joinPaths} from '../utils.js'; import {joinPaths} from '../utils.js';
const {UseServiceWorker, AssetUrlPrefix, AppVer} = window.config; const {useServiceWorker, assetUrlPrefix, appVer} = window.config;
const cachePrefix = 'static-cache-v'; // actual version is set in the service worker script const cachePrefix = 'static-cache-v'; // actual version is set in the service worker script
const workerAssetPath = joinPaths(AssetUrlPrefix, 'serviceworker.js'); const workerAssetPath = joinPaths(assetUrlPrefix, 'serviceworker.js');
async function unregisterAll() { async function unregisterAll() {
for (const registration of await navigator.serviceWorker.getRegistrations()) { for (const registration of await navigator.serviceWorker.getRegistrations()) {
@ -24,7 +24,7 @@ async function invalidateCache() {
} }
async function checkCacheValidity() { async function checkCacheValidity() {
const cacheKey = AppVer; const cacheKey = appVer;
const storedCacheKey = localStorage.getItem('staticCacheKey'); const storedCacheKey = localStorage.getItem('staticCacheKey');
// invalidate cache if it belongs to a different gitea version // invalidate cache if it belongs to a different gitea version
@ -37,7 +37,7 @@ async function checkCacheValidity() {
export default async function initServiceWorker() { export default async function initServiceWorker() {
if (!('serviceWorker' in navigator)) return; if (!('serviceWorker' in navigator)) return;
if (UseServiceWorker) { if (useServiceWorker) {
// unregister all service workers where scriptURL does not match the current one // unregister all service workers where scriptURL does not match the current one
await unregisterOtherWorkers(); await unregisterOtherWorkers();
try { try {

@ -1,10 +1,10 @@
import prettyMilliseconds from 'pretty-ms'; import prettyMilliseconds from 'pretty-ms';
const {AppSubUrl, csrf, NotificationSettings, EnableTimetracking} = window.config; const {appSubUrl, csrfToken, notificationSettings, enableTimeTracking} = window.config;
let updateTimeInterval = null; // holds setInterval id when active let updateTimeInterval = null; // holds setInterval id when active
export async function initStopwatch() { export async function initStopwatch() {
if (!EnableTimetracking) { if (!enableTimeTracking) {
return; return;
} }
@ -25,7 +25,7 @@ export async function initStopwatch() {
$(this).parent().trigger('submit'); $(this).parent().trigger('submit');
}); });
if (NotificationSettings.EventSourceUpdateTime > 0 && !!window.EventSource && window.SharedWorker) { if (notificationSettings.EventSourceUpdateTime > 0 && !!window.EventSource && window.SharedWorker) {
// Try to connect to the event source via the shared worker first // Try to connect to the event source via the shared worker first
const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js`, 'notification-worker'); const worker = new SharedWorker(`${__webpack_public_path__}js/eventsource.sharedworker.js`, 'notification-worker');
worker.addEventListener('error', (event) => { worker.addEventListener('error', (event) => {
@ -36,7 +36,7 @@ export async function initStopwatch() {
}); });
worker.port.postMessage({ worker.port.postMessage({
type: 'start', type: 'start',
url: `${window.location.origin}${AppSubUrl}/user/events`, url: `${window.location.origin}${appSubUrl}/user/events`,
}); });
worker.port.addEventListener('message', (event) => { worker.port.addEventListener('message', (event) => {
if (!event.data || !event.data.type) { if (!event.data || !event.data.type) {
@ -55,7 +55,7 @@ export async function initStopwatch() {
type: 'close', type: 'close',
}); });
worker.port.close(); worker.port.close();
window.location.href = AppSubUrl; window.location.href = appSubUrl;
} else if (event.data.type === 'close') { } else if (event.data.type === 'close') {
worker.port.postMessage({ worker.port.postMessage({
type: 'close', type: 'close',
@ -77,7 +77,7 @@ export async function initStopwatch() {
return; return;
} }
if (NotificationSettings.MinTimeout <= 0) { if (notificationSettings.MinTimeout <= 0) {
return; return;
} }
@ -87,7 +87,7 @@ export async function initStopwatch() {
}, timeout); }, timeout);
}; };
fn(NotificationSettings.MinTimeout); fn(notificationSettings.MinTimeout);
const currSeconds = $('.stopwatch-time').data('seconds'); const currSeconds = $('.stopwatch-time').data('seconds');
if (currSeconds) { if (currSeconds) {
@ -99,9 +99,9 @@ async function updateStopwatchWithCallback(callback, timeout) {
const isSet = await updateStopwatch(); const isSet = await updateStopwatch();
if (!isSet) { if (!isSet) {
timeout = NotificationSettings.MinTimeout; timeout = notificationSettings.MinTimeout;
} else if (timeout < NotificationSettings.MaxTimeout) { } else if (timeout < notificationSettings.MaxTimeout) {
timeout += NotificationSettings.TimeoutStep; timeout += notificationSettings.TimeoutStep;
} }
callback(timeout); callback(timeout);
@ -110,8 +110,8 @@ async function updateStopwatchWithCallback(callback, timeout) {
async function updateStopwatch() { async function updateStopwatch() {
const data = await $.ajax({ const data = await $.ajax({
type: 'GET', type: 'GET',
url: `${AppSubUrl}/api/v1/user/stopwatches`, url: `${appSubUrl}/api/v1/user/stopwatches`,
headers: {'X-Csrf-Token': csrf}, headers: {'X-Csrf-Token': csrfToken},
}); });
if (updateTimeInterval) { if (updateTimeInterval) {
@ -129,7 +129,7 @@ async function updateStopwatchData(data) {
btnEl.addClass('hidden'); btnEl.addClass('hidden');
} else { } else {
const {repo_owner_name, repo_name, issue_index, seconds} = watch; const {repo_owner_name, repo_name, issue_index, seconds} = watch;
const issueUrl = `${AppSubUrl}/${repo_owner_name}/${repo_name}/issues/${issue_index}`; const issueUrl = `${appSubUrl}/${repo_owner_name}/${repo_name}/issues/${issue_index}`;
$('.stopwatch-link').attr('href', issueUrl); $('.stopwatch-link').attr('href', issueUrl);
$('.stopwatch-commit').attr('action', `${issueUrl}/times/stopwatch/toggle`); $('.stopwatch-commit').attr('action', `${issueUrl}/times/stopwatch/toggle`);
$('.stopwatch-cancel').attr('action', `${issueUrl}/times/stopwatch/cancel`); $('.stopwatch-cancel').attr('action', `${issueUrl}/times/stopwatch/cancel`);

@ -49,7 +49,7 @@ function makeCollections({mentions, emoji}) {
} }
export default async function attachTribute(elementOrNodeList, {mentions, emoji} = {}) { export default async function attachTribute(elementOrNodeList, {mentions, emoji} = {}) {
if (!window.config.Tribute || !elementOrNodeList) return; if (!window.config.requireTribute || !elementOrNodeList) return;
const nodes = Array.from('length' in elementOrNodeList ? elementOrNodeList : [elementOrNodeList]); const nodes = Array.from('length' in elementOrNodeList ? elementOrNodeList : [elementOrNodeList]);
if (!nodes.length) return; if (!nodes.length) return;

@ -1,11 +1,11 @@
const {AppSubUrl, csrf} = window.config; const {appSubUrl, csrfToken} = window.config;
export function initUserAuthU2fAuth() { export function initUserAuthU2fAuth() {
if ($('#wait-for-key').length === 0) { if ($('#wait-for-key').length === 0) {
return; return;
} }
u2fApi.ensureSupport().then(() => { u2fApi.ensureSupport().then(() => {
$.getJSON(`${AppSubUrl}/user/u2f/challenge`).done((req) => { $.getJSON(`${appSubUrl}/user/u2f/challenge`).done((req) => {
u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30) u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
.then(u2fSigned) .then(u2fSigned)
.catch((err) => { .catch((err) => {
@ -18,15 +18,15 @@ export function initUserAuthU2fAuth() {
}); });
}).catch(() => { }).catch(() => {
// Fallback in case browser do not support U2F // Fallback in case browser do not support U2F
window.location.href = `${AppSubUrl}/user/two_factor`; window.location.href = `${appSubUrl}/user/two_factor`;
}); });
} }
function u2fSigned(resp) { function u2fSigned(resp) {
$.ajax({ $.ajax({
url: `${AppSubUrl}/user/u2f/sign`, url: `${appSubUrl}/user/u2f/sign`,
type: 'POST', type: 'POST',
headers: {'X-Csrf-Token': csrf}, headers: {'X-Csrf-Token': csrfToken},
data: JSON.stringify(resp), data: JSON.stringify(resp),
contentType: 'application/json; charset=utf-8', contentType: 'application/json; charset=utf-8',
}).done((res) => { }).done((res) => {
@ -41,9 +41,9 @@ function u2fRegistered(resp) {
return; return;
} }
$.ajax({ $.ajax({
url: `${AppSubUrl}/user/settings/security/u2f/register`, url: `${appSubUrl}/user/settings/security/u2f/register`,
type: 'POST', type: 'POST',
headers: {'X-Csrf-Token': csrf}, headers: {'X-Csrf-Token': csrfToken},
data: JSON.stringify(resp), data: JSON.stringify(resp),
contentType: 'application/json; charset=utf-8', contentType: 'application/json; charset=utf-8',
success() { success() {
@ -99,8 +99,8 @@ export function initUserAuthU2fRegister() {
} }
function u2fRegisterRequest() { function u2fRegisterRequest() {
$.post(`${AppSubUrl}/user/settings/security/u2f/request_register`, { $.post(`${appSubUrl}/user/settings/security/u2f/request_register`, {
_csrf: csrf, _csrf: csrfToken,
name: $('#nickname').val() name: $('#nickname').val()
}).done((req) => { }).done((req) => {
$('#nickname').closest('div.field').removeClass('error'); $('#nickname').closest('div.field').removeClass('error');

@ -1,4 +1,4 @@
const {MermaidMaxSourceCharacters} = window.config; const {mermaidMaxSourceCharacters} = window.config;
function displayError(el, err) { function displayError(el, err) {
el.closest('pre').classList.remove('is-loading'); el.closest('pre').classList.remove('is-loading');
@ -26,8 +26,8 @@ export async function renderMermaid(els) {
}); });
for (const el of els) { for (const el of els) {
if (MermaidMaxSourceCharacters >= 0 && el.textContent.length > MermaidMaxSourceCharacters) { if (mermaidMaxSourceCharacters >= 0 && el.textContent.length > mermaidMaxSourceCharacters) {
displayError(el, new Error(`Mermaid source of ${el.textContent.length} characters exceeds the maximum allowed length of ${MermaidMaxSourceCharacters}.`)); displayError(el, new Error(`Mermaid source of ${el.textContent.length} characters exceeds the maximum allowed length of ${mermaidMaxSourceCharacters}.`));
continue; continue;
} }

@ -47,7 +47,7 @@ export function initMarkupTasklist() {
await $.post(updateUrl, { await $.post(updateUrl, {
ignore_attachments: true, ignore_attachments: true,
_csrf: window.config.csrf, _csrf: window.config.csrfToken,
content: newContent, content: newContent,
context context
}); });

@ -1,6 +1,6 @@
// This sets up the URL prefix used in webpack's chunk loading. // This sets up the URL prefix used in webpack's chunk loading.
// This file must be imported before any lazy-loading is being attempted. // This file must be imported before any lazy-loading is being attempted.
import {joinPaths} from './utils.js'; import {joinPaths} from './utils.js';
const {AssetUrlPrefix} = window.config; const {assetUrlPrefix} = window.config;
__webpack_public_path__ = joinPaths(AssetUrlPrefix, '/'); __webpack_public_path__ = joinPaths(assetUrlPrefix, '/');

Loading…
Cancel
Save