You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 152 kB

Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
4 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
3 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
3 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
4 years ago
3 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
3 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
3 years ago
4 years ago
Change target branch for pull request (#6488) * Adds functionality to change target branch of created pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use const instead of var in JavaScript additions Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Check if branches are equal and if PR already exists before changing target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Make sure to check all commits Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Print error messages for user as error flash message Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Disallow changing target branch of closed or merged pull requests Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Resolve conflicts after merge of upstream/master Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Change order of branch select fields Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes duplicate check Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use ctx.Tr for translations Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Recompile JS Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Use correct translation namespace Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove redundant if condition Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves most change branch logic into pull service Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Completes comment Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Add Ref to ChangesPayload for logging changed target branches instead of creating a new struct Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Revert changes to go.mod Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Directly use createComment method Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return 404 if pull request is not found. Move written check up Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Remove variable declaration Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return client errors on change pull request target errors Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Return error in commit.HasPreviousCommit Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds blank line Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Test patch before persisting new target branch Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update patch before testing (not working) Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes patch calls when changeing pull request target Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Removes unneeded check for base name Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Moves ChangeTargetBranch completely to pull service. Update patch status. Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Set webhook mode after errors were validated Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Update PR in one transaction Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Move logic for check if head is equal with branch to pull model Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adds missing comment and simplify return Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com> * Adjust CreateComment method call Signed-off-by: Mario Lubenka <mario.lubenka@googlemail.com>
5 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
Add Organization Wide Labels (#10814) * Add organization wide labels Implement organization wide labels similar to organization wide webhooks. This lets you create individual labels for organizations that can be used for all repos under that organization (so being able to reuse the same label across multiple repos). This makes it possible for small organizations with many repos to use labels effectively. Fixes #7406 * Add migration * remove comments * fix tests * Update options/locale/locale_en-US.ini Removed unused translation string * show org labels in issue search label filter * Use more clear var name * rename migration after merge from master * comment typo * update migration again after rebase with master * check for orgID <=0 per guillep2k review * fmt * Apply suggestions from code review Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * remove unused code * Make sure RepoID is 0 when searching orgID per code review * more changes/code review requests * More descriptive translation var per code review * func description/delete comment when issue label deleted instead of hiding it * remove comment * only use issues in that repo when calculating number of open issues for org label on repo label page * Add integration test for IssuesSearch API with labels * remove unused function * Update models/issue_label.go Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Use subquery in GetLabelIDsInReposByNames * Fix tests to use correct orgID * fix more tests * IssuesSearch api now uses new BuildLabelNamesIssueIDsCondition. Add a few more tests as well * update comment for clarity * Revert previous code change now that we can use the new BuildLabelNamesIssueIDsCondition * Don't sort repos by date in IssuesSearch API After much debugging I've found a strange issue where in some cases MySQL will return a different result than other enigines if a query is sorted by a null collumn. For example with our integration test data where we don't set updated_unix in repository fixtures: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 45 Returns different results for MySQL than other engines. However, the similar query: SELECT `id`, `owner_id`, `owner_name`, `lower_name`, `name`, `description`, `website`, `original_service_type`, `original_url`, `default_branch`, `num_watches`, `num_stars`, `num_forks`, `num_issues`, `num_closed_issues`, `num_pulls`, `num_closed_pulls`, `num_milestones`, `num_closed_milestones`, `is_private`, `is_empty`, `is_archived`, `is_mirror`, `status`, `is_fork`, `fork_id`, `is_template`, `template_id`, `size`, `is_fsck_enabled`, `close_issues_via_commit_in_any_branch`, `topics`, `avatar`, `created_unix`, `updated_unix` FROM `repository` ORDER BY updated_unix DESC LIMIT 15 OFFSET 30 Returns the same results. This causes integration tests to fail on MySQL in certain cases but would never show up in a real installation. Since this API call always returns issues based on the optionally provided repo_priority_id or the issueID itself, there is no change to results by changing the repo sorting method used to get ids earlier in the function. * linter is back! * code review * remove now unused option * Fix newline at end of files * more unused code * update to master * check for matching ids before query * Update models/issue_label.go Co-Authored-By: 6543 <6543@obermui.de> * Update models/issue_label.go * update comments * Update routers/org/setting.go Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com> Co-authored-by: 6543 <6543@obermui.de>
5 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
Add single sign-on support via SSPI on Windows (#8463) * Add single sign-on support via SSPI on Windows * Ensure plugins implement interface * Ensure plugins implement interface * Move functions used only by the SSPI auth method to sspi_windows.go * Field SSPISeparatorReplacement of AuthenticationForm should not be required via binding, as binding will insist the field is non-empty even if another login type is selected * Fix breaking of oauth authentication on download links. Do not create new session with SSPI authentication on download links. * Update documentation for the new 'SPNEGO with SSPI' login source * Mention in documentation that ROOT_URL should contain the FQDN of the server * Make sure that Contexter is not checking for active login sources when the ORM engine is not initialized (eg. when installing) * Always initialize and free SSO methods, even if they are not enabled, as a method can be activated while the app is running (from Authentication sources) * Add option in SSPIConfig for removing of domains from logon names * Update helper text for StripDomainNames option * Make sure handleSignIn() is called after a new user object is created by SSPI auth method * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Remove default value from text of form field helper Co-Authored-By: Lauris BH <lauris@nix.lv> * Only make a query to the DB to check if SSPI is enabled on handlers that need that information for templates * Remove code duplication * Log errors in ActiveLoginSources Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert suffix of randomly generated E-mails for Reverse proxy authentication Co-Authored-By: Lauris BH <lauris@nix.lv> * Revert unneeded white-space change in template Co-Authored-By: Lauris BH <lauris@nix.lv> * Add copyright comments at the top of new files * Use loopback name for randomly generated emails * Add locale tag for the SSPISeparatorReplacement field with proper casing * Revert casing of SSPISeparatorReplacement field in locale file, moving it up, next to other form fields * Update docs/content/doc/features/authentication.en-us.md Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Remove Priority() method and define the order in which SSO auth methods should be executed in one place * Log authenticated username only if it's not empty * Rephrase helper text for automatic creation of users * Return error if more than one active SSPI auth source is found * Change newUser() function to return error, letting caller log/handle the error * Move isPublicResource, isPublicPage and handleSignIn functions outside SSPI auth method to allow other SSO methods to reuse them if needed * Refactor initialization of the list containing SSO auth methods * Validate SSPI settings on POST * Change SSPI to only perform authentication on its own login page, API paths and download links. Leave Toggle middleware to redirect non authenticated users to login page * Make 'Default language' in SSPI config empty, unless changed by admin * Show error if admin tries to add a second authentication source of type SSPI * Simplify declaration of global variable * Rebuild gitgraph.js on Linux * Make sure config values containing only whitespace are not accepted
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
Use AJAX for notifications table (#10961) * Use AJAX for notifications table Signed-off-by: Andrew Thornton <art27@cantab.net> * move to separate js Signed-off-by: Andrew Thornton <art27@cantab.net> * placate golangci-lint Signed-off-by: Andrew Thornton <art27@cantab.net> * Add autoupdating notification count Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix wipeall Signed-off-by: Andrew Thornton <art27@cantab.net> * placate tests Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hide and hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * More auto-update improvements Only run checker on pages that have a count Change starting checker to 10s with a back-off to 60s if there is no change Signed-off-by: Andrew Thornton <art27@cantab.net> * string comparison! Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @silverwind Signed-off-by: Andrew Thornton <art27@cantab.net> * add configurability as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Add documentation as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Use CSRF header not query Signed-off-by: Andrew Thornton <art27@cantab.net> * Further JS improvements Fix @etzelia update notification table request Fix @silverwind comments Co-Authored-By: silverwind <me@silverwind.io> Signed-off-by: Andrew Thornton <art27@cantab.net> * Simplify the notification count fns Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: silverwind <me@silverwind.io>
5 years ago
3 years ago
Use AJAX for notifications table (#10961) * Use AJAX for notifications table Signed-off-by: Andrew Thornton <art27@cantab.net> * move to separate js Signed-off-by: Andrew Thornton <art27@cantab.net> * placate golangci-lint Signed-off-by: Andrew Thornton <art27@cantab.net> * Add autoupdating notification count Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix wipeall Signed-off-by: Andrew Thornton <art27@cantab.net> * placate tests Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hide and hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * More auto-update improvements Only run checker on pages that have a count Change starting checker to 10s with a back-off to 60s if there is no change Signed-off-by: Andrew Thornton <art27@cantab.net> * string comparison! Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @silverwind Signed-off-by: Andrew Thornton <art27@cantab.net> * add configurability as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Add documentation as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Use CSRF header not query Signed-off-by: Andrew Thornton <art27@cantab.net> * Further JS improvements Fix @etzelia update notification table request Fix @silverwind comments Co-Authored-By: silverwind <me@silverwind.io> Signed-off-by: Andrew Thornton <art27@cantab.net> * Simplify the notification count fns Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: silverwind <me@silverwind.io>
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
Use AJAX for notifications table (#10961) * Use AJAX for notifications table Signed-off-by: Andrew Thornton <art27@cantab.net> * move to separate js Signed-off-by: Andrew Thornton <art27@cantab.net> * placate golangci-lint Signed-off-by: Andrew Thornton <art27@cantab.net> * Add autoupdating notification count Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix wipeall Signed-off-by: Andrew Thornton <art27@cantab.net> * placate tests Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hide and hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * More auto-update improvements Only run checker on pages that have a count Change starting checker to 10s with a back-off to 60s if there is no change Signed-off-by: Andrew Thornton <art27@cantab.net> * string comparison! Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @silverwind Signed-off-by: Andrew Thornton <art27@cantab.net> * add configurability as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Add documentation as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Use CSRF header not query Signed-off-by: Andrew Thornton <art27@cantab.net> * Further JS improvements Fix @etzelia update notification table request Fix @silverwind comments Co-Authored-By: silverwind <me@silverwind.io> Signed-off-by: Andrew Thornton <art27@cantab.net> * Simplify the notification count fns Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: silverwind <me@silverwind.io>
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
Use AJAX for notifications table (#10961) * Use AJAX for notifications table Signed-off-by: Andrew Thornton <art27@cantab.net> * move to separate js Signed-off-by: Andrew Thornton <art27@cantab.net> * placate golangci-lint Signed-off-by: Andrew Thornton <art27@cantab.net> * Add autoupdating notification count Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix wipeall Signed-off-by: Andrew Thornton <art27@cantab.net> * placate tests Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * Try hide and hidden Signed-off-by: Andrew Thornton <art27@cantab.net> * More auto-update improvements Only run checker on pages that have a count Change starting checker to 10s with a back-off to 60s if there is no change Signed-off-by: Andrew Thornton <art27@cantab.net> * string comparison! Signed-off-by: Andrew Thornton <art27@cantab.net> * as per @silverwind Signed-off-by: Andrew Thornton <art27@cantab.net> * add configurability as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Add documentation as per @6543 Signed-off-by: Andrew Thornton <art27@cantab.net> * Use CSRF header not query Signed-off-by: Andrew Thornton <art27@cantab.net> * Further JS improvements Fix @etzelia update notification table request Fix @silverwind comments Co-Authored-By: silverwind <me@silverwind.io> Signed-off-by: Andrew Thornton <art27@cantab.net> * Simplify the notification count fns Signed-off-by: Andrew Thornton <art27@cantab.net> Co-authored-by: silverwind <me@silverwind.io>
5 years ago
Support unicode emojis and remove emojify.js (#11032) * Support unicode emojis and remove emojify.js This PR replaces all use of emojify.js and adds unicode emoji support to various areas of gitea. This works in a few ways: First it adds emoji parsing support into gitea itself. This allows us to * Render emojis from valid alias (:smile:) * Detect unicode emojis and let us put them in their own class with proper aria-labels and styling * Easily allow for custom "emoji" * Support all emoji rendering and features without javascript * Uses plain unicode and lets the system render in appropriate emoji font * Doesn't leave us relying on external sources for updates/fixes/features That same list of emoji is also used to create a json file which replaces the part of emojify.js that populates the emoji search tribute. This file is about 35KB with GZIP turned on and I've set it to load after the page renders to not hinder page load time (and this removes loading emojify.js also) For custom "emoji" it uses a pretty simple scheme of just looking for /emojis/img/name.png where name is something a user has put in the "allowed reactions" setting we already have. The gitea reaction that was previously hard coded into a forked copy of emojify.js is included and works as a custom reaction under this method. The emoji data sourced here is from https://github.com/github/gemoji which is the gem library Github uses for their emoji rendering (and a data source for other sites). So we should be able to easily render any emoji and :alias: that Github can, removing any errors from migrated content. They also update it as well, so we can sync when there are new unicode emoji lists released. I've included a slimmed down and slightly modified forked copy of https://github.com/knq/emoji to make up our own emoji module. The code is pretty straight forward and again allows us to have a lot of flexibility in what happens. I had seen a few comments about performance in some of the other threads if we render this ourselves, but there doesn't seem to be any issue here. In a test it can parse, convert, and render 1,000 emojis inside of a large markdown table in about 100ms on my laptop (which is many more emojis than will ever be in any normal issue). This also prevents any flickering and other weirdness from using javascript to render some things while using go for others. Not included here are image fall back URLS. I don't really think they are necessary for anything new being written in 2020. However, managing the emoji ourselves would allow us to add these as a feature later on if it seems necessary. Fixes: https://github.com/go-gitea/gitea/issues/9182 Fixes: https://github.com/go-gitea/gitea/issues/8974 Fixes: https://github.com/go-gitea/gitea/issues/8953 Fixes: https://github.com/go-gitea/gitea/issues/6628 Fixes: https://github.com/go-gitea/gitea/issues/5130 * add new shared function emojiHTML * don't increase emoji size in issue title * Update templates/repo/issue/view_content/add_reaction.tmpl Co-Authored-By: 6543 <6543@obermui.de> * Support for emoji rendering in various templates * Render code and review comments as they should be * Better way to handle mail subjects * insert unicode from tribute selection * Add template helper for plain text when needed * Use existing replace function I forgot about * Don't include emoji greater than Unicode Version 12 Only include emoji and aliases in JSON * Update build/generate-emoji.go * Tweak regex slightly to really match everything including random invisible characters. Run tests for every emoji we have * final updates * code review * code review * hard code gitea custom emoji to match previous behavior * Update .eslintrc Co-Authored-By: silverwind <me@silverwind.io> * disable preempt Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: Lauris BH <lauris@nix.lv> Co-authored-by: guillep2k <18600385+guillep2k@users.noreply.github.com>
5 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
2 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
2 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159
  1. /* globals wipPrefixes */
  2. /* exported timeAddManual, toggleStopwatch, cancelStopwatch */
  3. /* exported toggleDeadlineForm, setDeadline, updateDeadline, deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */
  4. import "./publicpath.js";
  5. import "./polyfills.js";
  6. import "./features/letteravatar.js";
  7. import Vue from "vue";
  8. import ElementUI from "element-ui";
  9. import "element-ui/lib/theme-chalk/index.css";
  10. import axios from "axios";
  11. import qs from "qs";
  12. import Cookies from "js-cookie";
  13. import "jquery.are-you-sure";
  14. import "./vendor/semanticdropdown.js";
  15. import { svg } from "./utils.js";
  16. import echarts from "echarts";
  17. import initContextPopups from "./features/contextpopup.js";
  18. import initGitGraph from "./features/gitgraph.js";
  19. import initClipboard from "./features/clipboard.js";
  20. import initUserHeatmap from "./features/userheatmap.js";
  21. import initDateTimePicker from "./features/datetimepicker.js";
  22. import initContextMenu from "./features/contexmenu.js";
  23. import {
  24. initTribute,
  25. issuesTribute,
  26. emojiTribute,
  27. } from "./features/tribute.js";
  28. import createDropzone from "./features/dropzone.js";
  29. import highlight from "./features/highlight.js";
  30. import ActivityTopAuthors from "./components/ActivityTopAuthors.vue";
  31. import {
  32. initNotificationsTable,
  33. initNotificationCount,
  34. } from "./features/notification.js";
  35. import { createCodeEditor } from "./features/codeeditor.js";
  36. import MinioUploader from "./components/MinioUploader.vue";
  37. import EditAboutInfo from "./components/EditAboutInfo.vue";
  38. // import Images from './components/Images.vue';
  39. import EditTopics from "./components/EditTopics.vue";
  40. import DataAnalysis from "./components/DataAnalysis.vue";
  41. import Contributors from "./components/Contributors.vue";
  42. import Model from "./components/Model.vue";
  43. import WxAutorize from "./components/WxAutorize.vue";
  44. import initCloudrain from "./features/cloudrbanin.js";
  45. import initCloudrainSow from "./features/cloudbrainShow.js";
  46. import initImage from "./features/images.js";
  47. import selectDataset from "./components/dataset/selectDataset.vue";
  48. // import $ from 'jquery.js'
  49. import router from "./router/index.js";
  50. import { Message } from "element-ui";
  51. Vue.use(ElementUI);
  52. Vue.prototype.$axios = axios;
  53. Vue.prototype.$Cookies = Cookies;
  54. Vue.prototype.qs = qs;
  55. Vue.prototype.$message = Message;
  56. const { AppSubUrl, StaticUrlPrefix, csrf } = window.config;
  57. Object.defineProperty(Vue.prototype, "$echarts", {
  58. value: echarts,
  59. });
  60. function htmlEncode(text) {
  61. return jQuery("<div />").text(text).html();
  62. }
  63. let previewFileModes;
  64. const commentMDEditors = {};
  65. // Silence fomantic's error logging when tabs are used without a target content element
  66. $.fn.tab.settings.silent = true;
  67. function initCommentPreviewTab($form) {
  68. const $tabMenu = $form.find(".tabular.menu");
  69. $tabMenu.find(".item").tab();
  70. $tabMenu
  71. .find(`.item[data-tab="${$tabMenu.data("preview")}"]`)
  72. .on("click", function () {
  73. const $this = $(this);
  74. $.post(
  75. $this.data("url"),
  76. {
  77. _csrf: csrf,
  78. mode: "gfm",
  79. context: $this.data("context"),
  80. text: $form
  81. .find(`.tab[data-tab="${$tabMenu.data("write")}"] textarea`)
  82. .val(),
  83. },
  84. (data) => {
  85. const $previewPanel = $form.find(
  86. `.tab[data-tab="${$tabMenu.data("preview")}"]`
  87. );
  88. $previewPanel.html(data);
  89. $("pre code", $previewPanel[0]).each(function () {
  90. highlight(this);
  91. });
  92. }
  93. );
  94. });
  95. buttonsClickOnEnter();
  96. }
  97. function initEditPreviewTab($form) {
  98. const $tabMenu = $form.find(".tabular.menu");
  99. $tabMenu.find(".item").tab();
  100. const $previewTab = $tabMenu.find(
  101. `.item[data-tab="${$tabMenu.data("preview")}"]`
  102. );
  103. if ($previewTab.length) {
  104. previewFileModes = $previewTab.data("preview-file-modes").split(",");
  105. $previewTab.on("click", function () {
  106. const $this = $(this);
  107. let context = `${$this.data("context")}/`;
  108. const treePathEl = $form.find("input#tree_path");
  109. if (treePathEl.length > 0) {
  110. context += treePathEl.val();
  111. }
  112. context = context.substring(0, context.lastIndexOf("/"));
  113. $.post(
  114. $this.data("url"),
  115. {
  116. _csrf: csrf,
  117. mode: "gfm",
  118. context,
  119. text: $form
  120. .find(`.tab[data-tab="${$tabMenu.data("write")}"] textarea`)
  121. .val(),
  122. },
  123. (data) => {
  124. const $previewPanel = $form.find(
  125. `.tab[data-tab="${$tabMenu.data("preview")}"]`
  126. );
  127. $previewPanel.html(data);
  128. $("pre code", $previewPanel[0]).each(function () {
  129. highlight(this);
  130. });
  131. }
  132. );
  133. });
  134. }
  135. }
  136. function initEditDiffTab($form) {
  137. const $tabMenu = $form.find(".tabular.menu");
  138. $tabMenu.find(".item").tab();
  139. $tabMenu
  140. .find(`.item[data-tab="${$tabMenu.data("diff")}"]`)
  141. .on("click", function () {
  142. const $this = $(this);
  143. $.post(
  144. $this.data("url"),
  145. {
  146. _csrf: csrf,
  147. context: $this.data("context"),
  148. content: $form
  149. .find(`.tab[data-tab="${$tabMenu.data("write")}"] textarea`)
  150. .val(),
  151. },
  152. (data) => {
  153. const $diffPreviewPanel = $form.find(
  154. `.tab[data-tab="${$tabMenu.data("diff")}"]`
  155. );
  156. $diffPreviewPanel.html(data);
  157. }
  158. );
  159. });
  160. }
  161. function initEditForm() {
  162. if ($(".edit.form").length === 0) {
  163. return;
  164. }
  165. initEditPreviewTab($(".edit.form"));
  166. initEditDiffTab($(".edit.form"));
  167. }
  168. function initBranchSelector() {
  169. const $selectBranch = $(".ui.select-branch");
  170. const $branchMenu = $selectBranch.find(".reference-list-menu");
  171. $branchMenu.find(".item:not(.no-select)").click(function () {
  172. $($(this).data("id-selector")).val($(this).data("id"));
  173. $selectBranch.find(".ui .branch-name").text($(this).data("name"));
  174. });
  175. $selectBranch.find(".reference.column").on("click", function () {
  176. $selectBranch.find(".scrolling.reference-list-menu").css("display", "none");
  177. $selectBranch.find(".reference .text").addClass("black");
  178. $($(this).data("target")).css("display", "block");
  179. $(this).find(".text.black").removeClass("black");
  180. return false;
  181. });
  182. }
  183. function initLabelEdit() {
  184. // Create label
  185. const $newLabelPanel = $(".new-label.segment");
  186. $(".new-label.button").on("click", () => {
  187. $newLabelPanel.show();
  188. });
  189. $(".new-label.segment .cancel").on("click", () => {
  190. $newLabelPanel.hide();
  191. });
  192. $(".color-picker").each(function () {
  193. $(this).minicolors();
  194. });
  195. $(".precolors .color").on("click", function () {
  196. const color_hex = $(this).data("color-hex");
  197. $(".color-picker").val(color_hex);
  198. $(".minicolors-swatch-color").css("background-color", color_hex);
  199. });
  200. $(".edit-label-button").on("click", function () {
  201. $("#label-modal-id").val($(this).data("id"));
  202. $(".edit-label .new-label-input").val($(this).data("title"));
  203. $(".edit-label .new-label-desc-input").val($(this).data("description"));
  204. $(".edit-label .color-picker").val($(this).data("color"));
  205. $(".minicolors-swatch-color").css(
  206. "background-color",
  207. $(this).data("color")
  208. );
  209. $(".edit-label.modal")
  210. .modal({
  211. onApprove() {
  212. $(".edit-label.form").trigger("submit");
  213. },
  214. })
  215. .modal("show");
  216. return false;
  217. });
  218. }
  219. function updateIssuesMeta(url, action, issueIds, elementId, isAdd) {
  220. return new Promise((resolve) => {
  221. $.ajax({
  222. type: "POST",
  223. url,
  224. data: {
  225. _csrf: csrf,
  226. action,
  227. issue_ids: issueIds,
  228. id: elementId,
  229. is_add: isAdd,
  230. },
  231. success: resolve,
  232. });
  233. });
  234. }
  235. function initRepoStatusChecker() {
  236. const migrating = $("#repo_migrating");
  237. $("#repo_migrating_failed").hide();
  238. if (migrating) {
  239. const repo_name = migrating.attr("repo");
  240. if (typeof repo_name === "undefined") {
  241. return;
  242. }
  243. $.ajax({
  244. type: "GET",
  245. url: `${AppSubUrl}/${repo_name}/status`,
  246. data: {
  247. _csrf: csrf,
  248. },
  249. complete(xhr) {
  250. if (xhr.status === 200) {
  251. if (xhr.responseJSON) {
  252. if (xhr.responseJSON.status === 0) {
  253. window.location.reload();
  254. return;
  255. }
  256. setTimeout(() => {
  257. initRepoStatusChecker();
  258. }, 2000);
  259. return;
  260. }
  261. }
  262. $("#repo_migrating_progress").hide();
  263. $("#repo_migrating_failed").show();
  264. },
  265. });
  266. }
  267. }
  268. function initReactionSelector(parent) {
  269. let reactions = "";
  270. if (!parent) {
  271. parent = $(document);
  272. reactions = ".reactions > ";
  273. }
  274. parent.find(`${reactions}a.label`).popup({
  275. position: "bottom left",
  276. metadata: { content: "title", title: "none" },
  277. });
  278. parent
  279. .find(`.select-reaction > .menu > .item, ${reactions}a.label`)
  280. .on("click", function (e) {
  281. const vm = this;
  282. e.preventDefault();
  283. if ($(this).hasClass("disabled")) return;
  284. const actionURL = $(this).hasClass("item")
  285. ? $(this).closest(".select-reaction").data("action-url")
  286. : $(this).data("action-url");
  287. const url = `${actionURL}/${
  288. $(this).hasClass("blue") ? "unreact" : "react"
  289. }`;
  290. $.ajax({
  291. type: "POST",
  292. url,
  293. data: {
  294. _csrf: csrf,
  295. content: $(this).data("content"),
  296. },
  297. }).done((resp) => {
  298. if (resp && (resp.html || resp.empty)) {
  299. const content = $(vm).closest(".content");
  300. let react = content.find(".segment.reactions");
  301. if (!resp.empty && react.length > 0) {
  302. react.remove();
  303. }
  304. if (!resp.empty) {
  305. react = $('<div class="ui attached segment reactions"></div>');
  306. const attachments = content.find(".segment.bottom:first");
  307. if (attachments.length > 0) {
  308. react.insertBefore(attachments);
  309. } else {
  310. react.appendTo(content);
  311. }
  312. react.html(resp.html);
  313. react.find(".dropdown").dropdown();
  314. initReactionSelector(react);
  315. }
  316. }
  317. });
  318. });
  319. }
  320. function insertAtCursor(field, value) {
  321. if (field.selectionStart || field.selectionStart === 0) {
  322. const startPos = field.selectionStart;
  323. const endPos = field.selectionEnd;
  324. field.value =
  325. field.value.substring(0, startPos) +
  326. value +
  327. field.value.substring(endPos, field.value.length);
  328. field.selectionStart = startPos + value.length;
  329. field.selectionEnd = startPos + value.length;
  330. } else {
  331. field.value += value;
  332. }
  333. }
  334. function replaceAndKeepCursor(field, oldval, newval) {
  335. if (field.selectionStart || field.selectionStart === 0) {
  336. const startPos = field.selectionStart;
  337. const endPos = field.selectionEnd;
  338. field.value = field.value.replace(oldval, newval);
  339. field.selectionStart = startPos + newval.length - oldval.length;
  340. field.selectionEnd = endPos + newval.length - oldval.length;
  341. } else {
  342. field.value = field.value.replace(oldval, newval);
  343. }
  344. }
  345. function retrieveImageFromClipboardAsBlob(pasteEvent, callback) {
  346. if (!pasteEvent.clipboardData) {
  347. return;
  348. }
  349. const { items } = pasteEvent.clipboardData;
  350. if (typeof items === "undefined") {
  351. return;
  352. }
  353. for (let i = 0; i < items.length; i++) {
  354. if (!items[i].type.includes("image")) continue;
  355. const blob = items[i].getAsFile();
  356. if (typeof callback === "function") {
  357. pasteEvent.preventDefault();
  358. pasteEvent.stopPropagation();
  359. callback(blob);
  360. }
  361. }
  362. }
  363. function uploadFile(file, callback) {
  364. const xhr = new XMLHttpRequest();
  365. xhr.addEventListener("load", () => {
  366. if (xhr.status === 200) {
  367. callback(xhr.responseText);
  368. }
  369. });
  370. xhr.open("post", `${AppSubUrl}/attachments`, true);
  371. xhr.setRequestHeader("X-Csrf-Token", csrf);
  372. const formData = new FormData();
  373. formData.append("file", file, file.name);
  374. xhr.send(formData);
  375. }
  376. function reload() {
  377. window.location.reload();
  378. }
  379. function initImagePaste(target) {
  380. target.each(function () {
  381. const field = this;
  382. field.addEventListener(
  383. "paste",
  384. (event) => {
  385. retrieveImageFromClipboardAsBlob(event, (img) => {
  386. const name = img.name.substr(0, img.name.lastIndexOf("."));
  387. insertAtCursor(field, `![${name}]()`);
  388. uploadFile(img, (res) => {
  389. const data = JSON.parse(res);
  390. replaceAndKeepCursor(
  391. field,
  392. `![${name}]()`,
  393. `![${name}](${AppSubUrl}/attachments/${data.uuid})`
  394. );
  395. const input = $(
  396. `<input id="${data.uuid}" name="files" type="hidden">`
  397. ).val(data.uuid);
  398. $(".files").append(input);
  399. });
  400. });
  401. },
  402. false
  403. );
  404. });
  405. }
  406. function initSimpleMDEImagePaste(simplemde, files) {
  407. simplemde.codemirror.on("paste", (_, event) => {
  408. retrieveImageFromClipboardAsBlob(event, (img) => {
  409. const name = img.name.substr(0, img.name.lastIndexOf("."));
  410. uploadFile(img, (res) => {
  411. const data = JSON.parse(res);
  412. const pos = simplemde.codemirror.getCursor();
  413. simplemde.codemirror.replaceRange(
  414. `![${name}](${AppSubUrl}/attachments/${data.uuid})`,
  415. pos
  416. );
  417. const input = $(
  418. `<input id="${data.uuid}" name="files" type="hidden">`
  419. ).val(data.uuid);
  420. files.append(input);
  421. });
  422. });
  423. });
  424. }
  425. let autoSimpleMDE;
  426. function initCommentForm() {
  427. if ($(".comment.form").length === 0) {
  428. return;
  429. }
  430. autoSimpleMDE = setCommentSimpleMDE(
  431. $(".comment.form textarea:not(.review-textarea)")
  432. );
  433. initBranchSelector();
  434. initCommentPreviewTab($(".comment.form"));
  435. initImagePaste($(".comment.form textarea"));
  436. // Listsubmit
  437. function initListSubmits(selector, outerSelector) {
  438. const $list = $(`.ui.${outerSelector}.list`);
  439. const $noSelect = $list.find(".no-select");
  440. const $listMenu = $(`.${selector} .menu`);
  441. let hasLabelUpdateAction = $listMenu.data("action") === "update";
  442. const labels = {};
  443. $(`.${selector}`).dropdown("setting", "onHide", () => {
  444. hasLabelUpdateAction = $listMenu.data("action") === "update"; // Update the var
  445. if (hasLabelUpdateAction) {
  446. const promises = [];
  447. Object.keys(labels).forEach((elementId) => {
  448. const label = labels[elementId];
  449. console.log("label:", label);
  450. const promise = updateIssuesMeta(
  451. label["update-url"],
  452. label.action,
  453. label["issue-id"],
  454. elementId,
  455. label["is-checked"]
  456. );
  457. promises.push(promise);
  458. });
  459. Promise.all(promises).then(reload);
  460. }
  461. });
  462. $listMenu.find(".item:not(.no-select)").on("click", function () {
  463. // we don't need the action attribute when updating assignees
  464. if (
  465. selector === "select-assignees-modify" ||
  466. selector === "select-reviewers-modify"
  467. ) {
  468. // UI magic. We need to do this here, otherwise it would destroy the functionality of
  469. // adding/removing labels
  470. if ($(this).data("can-change") === "block") {
  471. return false;
  472. }
  473. if ($(this).hasClass("checked")) {
  474. $(this).removeClass("checked");
  475. $(this).find(".octicon-check").addClass("invisible");
  476. $(this).data("is-checked", "remove");
  477. } else {
  478. $(this).addClass("checked");
  479. $(this).find(".octicon-check").removeClass("invisible");
  480. $(this).data("is-checked", "add");
  481. }
  482. updateIssuesMeta(
  483. $listMenu.data("update-url"),
  484. "",
  485. $listMenu.data("issue-id"),
  486. $(this).data("id"),
  487. $(this).data("is-checked")
  488. );
  489. $listMenu.data("action", "update"); // Update to reload the page when we updated items
  490. return false;
  491. }
  492. if ($(this).hasClass("checked")) {
  493. $(this).removeClass("checked");
  494. $(this).find(".octicon-check").addClass("invisible");
  495. if (hasLabelUpdateAction) {
  496. if (!($(this).data("id") in labels)) {
  497. labels[$(this).data("id")] = {
  498. "update-url": $listMenu.data("update-url"),
  499. action: "detach",
  500. "issue-id": $listMenu.data("issue-id"),
  501. };
  502. } else {
  503. delete labels[$(this).data("id")];
  504. }
  505. }
  506. } else {
  507. $(this).addClass("checked");
  508. $(this).find(".octicon-check").removeClass("invisible");
  509. if (hasLabelUpdateAction) {
  510. if (!($(this).data("id") in labels)) {
  511. labels[$(this).data("id")] = {
  512. "update-url": $listMenu.data("update-url"),
  513. action: "attach",
  514. "issue-id": $listMenu.data("issue-id"),
  515. };
  516. } else {
  517. delete labels[$(this).data("id")];
  518. }
  519. }
  520. }
  521. const listIds = [];
  522. $(this)
  523. .parent()
  524. .find(".item")
  525. .each(function () {
  526. if ($(this).hasClass("checked")) {
  527. listIds.push($(this).data("id"));
  528. $($(this).data("id-selector")).removeClass("hide");
  529. } else {
  530. $($(this).data("id-selector")).addClass("hide");
  531. }
  532. });
  533. if (listIds.length === 0) {
  534. $noSelect.removeClass("hide");
  535. } else {
  536. $noSelect.addClass("hide");
  537. }
  538. $($(this).parent().data("id")).val(listIds.join(","));
  539. return false;
  540. });
  541. $listMenu.find(".no-select.item").on("click", function () {
  542. if (hasLabelUpdateAction || selector === "select-assignees-modify") {
  543. updateIssuesMeta(
  544. $listMenu.data("update-url"),
  545. "clear",
  546. $listMenu.data("issue-id"),
  547. "",
  548. ""
  549. ).then(reload);
  550. }
  551. $(this)
  552. .parent()
  553. .find(".item")
  554. .each(function () {
  555. $(this).removeClass("checked");
  556. $(this).find(".octicon").addClass("invisible");
  557. $(this).data("is-checked", "remove");
  558. });
  559. $list.find(".item").each(function () {
  560. $(this).addClass("hide");
  561. });
  562. $noSelect.removeClass("hide");
  563. $($(this).parent().data("id")).val("");
  564. });
  565. }
  566. // Init labels and assignees
  567. initListSubmits("select-label", "labels");
  568. initListSubmits("select-assignees", "assignees");
  569. initListSubmits("select-assignees-modify", "assignees");
  570. initListSubmits("select-reviewers-modify", "assignees");
  571. function selectItem(select_id, input_id) {
  572. let $menu;
  573. if (select_id == ".select-branch") {
  574. $menu = $(`${select_id} .menu`).eq(1);
  575. } else {
  576. $menu = $(`${select_id} .menu`);
  577. }
  578. const $list = $(`.ui${select_id}.list`);
  579. const hasUpdateAction = $menu.data("action") === "update";
  580. $menu.find(".item:not(.no-select)").on("click", function () {
  581. $(this)
  582. .parent()
  583. .find(".item")
  584. .each(function () {
  585. $(this).removeClass("selected active");
  586. });
  587. $(this).addClass("selected active");
  588. if (hasUpdateAction) {
  589. //let ref = ''
  590. //if (select_id=='.select-branch'){
  591. // ref = $(this).data('name');
  592. // }
  593. updateIssuesMeta(
  594. $menu.data("update-url"),
  595. "",
  596. $menu.data("issue-id"),
  597. $(this).data("id"),
  598. $(this).data("is-checked")
  599. ).then(reload);
  600. }
  601. switch (input_id) {
  602. case "#milestone_id":
  603. $list
  604. .find(".selected")
  605. .html(
  606. `<a class="item" href=${$(this).data("href")}>${htmlEncode(
  607. $(this).text()
  608. )}</a>`
  609. );
  610. break;
  611. case "#assignee_id":
  612. $list
  613. .find(".selected")
  614. .html(
  615. `<a class="item" href=${$(this).data("href")}>` +
  616. `<img class="ui avatar image" src=${$(this).data(
  617. "avatar"
  618. )}>${htmlEncode($(this).text())}</a>`
  619. );
  620. }
  621. $(`.ui${select_id}.list .no-select`).addClass("hide");
  622. $(input_id).val($(this).data("id"));
  623. });
  624. $menu.find(".no-select.item").on("click", function () {
  625. $(this)
  626. .parent()
  627. .find(".item:not(.no-select)")
  628. .each(function () {
  629. $(this).removeClass("selected active");
  630. });
  631. if (hasUpdateAction) {
  632. updateIssuesMeta(
  633. $menu.data("update-url"),
  634. "",
  635. $menu.data("issue-id"),
  636. $(this).data("id"),
  637. $(this).data("is-checked")
  638. ).then(reload);
  639. }
  640. $list.find(".selected").html("");
  641. $list.find(".no-select").removeClass("hide");
  642. $(input_id).val("");
  643. });
  644. }
  645. // Milestone and assignee
  646. selectItem(".select-milestone", "#milestone_id");
  647. selectItem(".select-assignee", "#assignee_id");
  648. selectItem(".select-branch", "");
  649. }
  650. function initInstall() {
  651. if ($(".install").length === 0) {
  652. return;
  653. }
  654. if ($("#db_host").val() === "") {
  655. $("#db_host").val("127.0.0.1:3306");
  656. $("#db_user").val("gitea");
  657. $("#db_name").val("gitea");
  658. }
  659. // Database type change detection.
  660. $("#db_type").on("change", function () {
  661. const sqliteDefault = "data/gitea.db";
  662. const tidbDefault = "data/gitea_tidb";
  663. const dbType = $(this).val();
  664. if (dbType === "SQLite3") {
  665. $("#sql_settings").hide();
  666. $("#pgsql_settings").hide();
  667. $("#mysql_settings").hide();
  668. $("#sqlite_settings").show();
  669. if (dbType === "SQLite3" && $("#db_path").val() === tidbDefault) {
  670. $("#db_path").val(sqliteDefault);
  671. }
  672. return;
  673. }
  674. const dbDefaults = {
  675. MySQL: "127.0.0.1:3306",
  676. PostgreSQL: "127.0.0.1:5432",
  677. MSSQL: "127.0.0.1:1433",
  678. };
  679. $("#sqlite_settings").hide();
  680. $("#sql_settings").show();
  681. $("#pgsql_settings").toggle(dbType === "PostgreSQL");
  682. $("#mysql_settings").toggle(dbType === "MySQL");
  683. $.each(dbDefaults, (_type, defaultHost) => {
  684. if ($("#db_host").val() === defaultHost) {
  685. $("#db_host").val(dbDefaults[dbType]);
  686. return false;
  687. }
  688. });
  689. });
  690. // TODO: better handling of exclusive relations.
  691. $("#offline-mode input").on("change", function () {
  692. if ($(this).is(":checked")) {
  693. $("#disable-gravatar").checkbox("check");
  694. $("#federated-avatar-lookup").checkbox("uncheck");
  695. }
  696. });
  697. $("#disable-gravatar input").on("change", function () {
  698. if ($(this).is(":checked")) {
  699. $("#federated-avatar-lookup").checkbox("uncheck");
  700. } else {
  701. $("#offline-mode").checkbox("uncheck");
  702. }
  703. });
  704. $("#federated-avatar-lookup input").on("change", function () {
  705. if ($(this).is(":checked")) {
  706. $("#disable-gravatar").checkbox("uncheck");
  707. $("#offline-mode").checkbox("uncheck");
  708. }
  709. });
  710. $("#enable-openid-signin input").on("change", function () {
  711. if ($(this).is(":checked")) {
  712. if (!$("#disable-registration input").is(":checked")) {
  713. $("#enable-openid-signup").checkbox("check");
  714. }
  715. } else {
  716. $("#enable-openid-signup").checkbox("uncheck");
  717. }
  718. });
  719. $("#disable-registration input").on("change", function () {
  720. if ($(this).is(":checked")) {
  721. $("#enable-captcha").checkbox("uncheck");
  722. $("#enable-openid-signup").checkbox("uncheck");
  723. } else {
  724. $("#enable-openid-signup").checkbox("check");
  725. }
  726. });
  727. $("#enable-captcha input").on("change", function () {
  728. if ($(this).is(":checked")) {
  729. $("#disable-registration").checkbox("uncheck");
  730. }
  731. });
  732. }
  733. function initIssueComments() {
  734. if ($(".repository.view.issue .timeline").length === 0) return;
  735. $(".re-request-review").on("click", function (event) {
  736. const url = $(this).data("update-url");
  737. const issueId = $(this).data("issue-id");
  738. const id = $(this).data("id");
  739. const isChecked = $(this).data("is-checked");
  740. //const ref = $(this).data('name');
  741. event.preventDefault();
  742. updateIssuesMeta(url, "", issueId, id, isChecked).then(reload);
  743. });
  744. $(document).on("click", (event) => {
  745. const urlTarget = $(":target");
  746. if (urlTarget.length === 0) return;
  747. const urlTargetId = urlTarget.attr("id");
  748. if (!urlTargetId) return;
  749. if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return;
  750. const $target = $(event.target);
  751. if ($target.closest(`#${urlTargetId}`).length === 0) {
  752. const scrollPosition = $(window).scrollTop();
  753. window.location.hash = "";
  754. $(window).scrollTop(scrollPosition);
  755. window.history.pushState(null, null, " ");
  756. }
  757. });
  758. }
  759. async function initRepository() {
  760. if ($(".repository").length === 0) {
  761. return;
  762. }
  763. function initFilterSearchDropdown(selector) {
  764. const $dropdown = $(selector);
  765. $dropdown.dropdown({
  766. fullTextSearch: true,
  767. selectOnKeydown: false,
  768. onChange(_text, _value, $choice) {
  769. if ($choice.data("url")) {
  770. window.location.href = $choice.data("url");
  771. }
  772. },
  773. message: { noResults: $dropdown.data("no-results") },
  774. });
  775. }
  776. // File list and commits
  777. if (
  778. $(".repository.file.list").length > 0 ||
  779. ".repository.commits".length > 0
  780. ) {
  781. initFilterBranchTagDropdown(".choose.reference .dropdown");
  782. }
  783. // Wiki
  784. if ($(".repository.wiki.view").length > 0) {
  785. initFilterSearchDropdown(".choose.page .dropdown");
  786. }
  787. // Options
  788. if ($(".repository.settings.options").length > 0) {
  789. // Enable or select internal/external wiki system and issue tracker.
  790. $(".enable-system").on("change", function () {
  791. if (this.checked) {
  792. $($(this).data("target")).removeClass("disabled");
  793. if (!$(this).data("context")) {
  794. $($(this).data("context")).addClass("disabled");
  795. }
  796. } else {
  797. $($(this).data("target")).addClass("disabled");
  798. if (!$(this).data("context")) {
  799. $($(this).data("context")).removeClass("disabled");
  800. }
  801. }
  802. });
  803. $(".enable-system-radio").on("change", function () {
  804. if (this.value === "false") {
  805. $($(this).data("target")).addClass("disabled");
  806. if (typeof $(this).data("context") !== "undefined") {
  807. $($(this).data("context")).removeClass("disabled");
  808. }
  809. } else if (this.value === "true") {
  810. $($(this).data("target")).removeClass("disabled");
  811. if (typeof $(this).data("context") !== "undefined") {
  812. $($(this).data("context")).addClass("disabled");
  813. }
  814. }
  815. });
  816. }
  817. // Labels
  818. if ($(".repository.labels").length > 0) {
  819. initLabelEdit();
  820. }
  821. // Milestones
  822. if ($(".repository.new.milestone").length > 0) {
  823. const $datepicker = $(".milestone.datepicker");
  824. await initDateTimePicker($datepicker.data("lang"));
  825. $datepicker.datetimepicker({
  826. inline: true,
  827. timepicker: false,
  828. startDate: $datepicker.data("start-date"),
  829. onSelectDate(date) {
  830. $("#deadline").val(date.toISOString().substring(0, 10));
  831. },
  832. });
  833. $("#clear-date").on("click", () => {
  834. $("#deadline").val("");
  835. return false;
  836. });
  837. }
  838. // Issues
  839. if ($(".repository.view.issue").length > 0) {
  840. // Edit issue title
  841. const $issueTitle = $("#issue-title");
  842. const $editInput = $("#edit-title-input input");
  843. const editTitleToggle = function () {
  844. $issueTitle.toggle();
  845. $(".not-in-edit").toggle();
  846. $("#edit-title-input").toggle();
  847. $("#pull-desc").toggle();
  848. $("#pull-desc-edit").toggle();
  849. $(".in-edit").toggle();
  850. $editInput.focus();
  851. return false;
  852. };
  853. const changeBranchSelect = function () {
  854. const selectionTextField = $("#pull-target-branch");
  855. const baseName = selectionTextField.data("basename");
  856. const branchNameNew = $(this).data("branch");
  857. const branchNameOld = selectionTextField.data("branch");
  858. // Replace branch name to keep translation from HTML template
  859. selectionTextField.html(
  860. selectionTextField
  861. .html()
  862. .replace(
  863. `${baseName}:${branchNameOld}`,
  864. `${baseName}:${branchNameNew}`
  865. )
  866. );
  867. selectionTextField.data("branch", branchNameNew); // update branch name in setting
  868. };
  869. $("#branch-select > .item").on("click", changeBranchSelect);
  870. $("#edit-title").on("click", editTitleToggle);
  871. $("#cancel-edit-title").on("click", editTitleToggle);
  872. $("#save-edit-title")
  873. .on("click", editTitleToggle)
  874. .on("click", function () {
  875. const pullrequest_targetbranch_change = function (update_url) {
  876. const targetBranch = $("#pull-target-branch").data("branch");
  877. const $branchTarget = $("#branch_target");
  878. if (targetBranch === $branchTarget.text()) {
  879. return false;
  880. }
  881. $.post(update_url, {
  882. _csrf: csrf,
  883. target_branch: targetBranch,
  884. })
  885. .done((data) => {
  886. $branchTarget.text(data.base_branch);
  887. })
  888. .always(() => {
  889. reload();
  890. });
  891. };
  892. const pullrequest_target_update_url = $(this).data("target-update-url");
  893. if (
  894. $editInput.val().length === 0 ||
  895. $editInput.val() === $issueTitle.text()
  896. ) {
  897. $editInput.val($issueTitle.text());
  898. pullrequest_targetbranch_change(pullrequest_target_update_url);
  899. } else {
  900. $.post(
  901. $(this).data("update-url"),
  902. {
  903. _csrf: csrf,
  904. title: $editInput.val(),
  905. },
  906. (data) => {
  907. $editInput.val(data.title);
  908. $issueTitle.text(data.title);
  909. pullrequest_targetbranch_change(pullrequest_target_update_url);
  910. reload();
  911. }
  912. );
  913. }
  914. return false;
  915. });
  916. // Issue Comments
  917. initIssueComments();
  918. // Issue/PR Context Menus
  919. $(".context-dropdown").dropdown({
  920. action: "hide",
  921. });
  922. // Quote reply
  923. $(".quote-reply").on("click", function (event) {
  924. $(this).closest(".dropdown").find(".menu").toggle("visible");
  925. const target = $(this).data("target");
  926. const quote = $(`#comment-${target}`).text().replace(/\n/g, "\n> ");
  927. const content = `> ${quote}\n\n`;
  928. let $content;
  929. if ($(this).hasClass("quote-reply-diff")) {
  930. const $parent = $(this).closest(".comment-code-cloud");
  931. $parent.find("button.comment-form-reply").trigger("click");
  932. $content = $parent.find('[name="content"]');
  933. if ($content.val() !== "") {
  934. $content.val(`${$content.val()}\n\n${content}`);
  935. } else {
  936. $content.val(`${content}`);
  937. }
  938. $content.focus();
  939. } else if (autoSimpleMDE !== null) {
  940. if (autoSimpleMDE.value() !== "") {
  941. autoSimpleMDE.value(`${autoSimpleMDE.value()}\n\n${content}`);
  942. } else {
  943. autoSimpleMDE.value(`${content}`);
  944. }
  945. }
  946. event.preventDefault();
  947. });
  948. // Edit issue or comment content
  949. $(".edit-content").on("click", async function (event) {
  950. $(this).closest(".dropdown").find(".menu").toggle("visible");
  951. const $segment = $(this).closest(".header").next();
  952. const $editContentZone = $segment.find(".edit-content-zone");
  953. const $renderContent = $segment.find(".render-content");
  954. const $rawContent = $segment.find(".raw-content");
  955. let $textarea;
  956. let $simplemde;
  957. // Setup new form
  958. if ($editContentZone.html().length === 0) {
  959. $editContentZone.html($("#edit-content-form").html());
  960. $textarea = $editContentZone.find("textarea");
  961. issuesTribute.attach($textarea.get());
  962. emojiTribute.attach($textarea.get());
  963. let dz;
  964. const $dropzone = $editContentZone.find(".dropzone");
  965. const $files = $editContentZone.find(".comment-files");
  966. if ($dropzone.length > 0) {
  967. $dropzone.data("saved", false);
  968. const filenameDict = {};
  969. dz = await createDropzone($dropzone[0], {
  970. url: $dropzone.data("upload-url"),
  971. headers: { "X-Csrf-Token": csrf },
  972. maxFiles: $dropzone.data("max-file"),
  973. maxFilesize: $dropzone.data("max-size"),
  974. acceptedFiles:
  975. $dropzone.data("accepts") === "*/*"
  976. ? null
  977. : $dropzone.data("accepts"),
  978. addRemoveLinks: true,
  979. dictDefaultMessage: $dropzone.data("default-message"),
  980. dictInvalidFileType: $dropzone.data("invalid-input-type"),
  981. dictFileTooBig: $dropzone.data("file-too-big"),
  982. dictRemoveFile: $dropzone.data("remove-file"),
  983. init() {
  984. this.on("success", (file, data) => {
  985. filenameDict[file.name] = {
  986. uuid: data.uuid,
  987. submitted: false,
  988. };
  989. const input = $(
  990. `<input id="${data.uuid}" name="files" type="hidden">`
  991. ).val(data.uuid);
  992. $files.append(input);
  993. });
  994. this.on("removedfile", (file) => {
  995. if (!(file.name in filenameDict)) {
  996. return;
  997. }
  998. $(`#${filenameDict[file.name].uuid}`).remove();
  999. if (
  1000. $dropzone.data("remove-url") &&
  1001. $dropzone.data("csrf") &&
  1002. !filenameDict[file.name].submitted
  1003. ) {
  1004. $.post($dropzone.data("remove-url"), {
  1005. file: filenameDict[file.name].uuid,
  1006. _csrf: $dropzone.data("csrf"),
  1007. });
  1008. }
  1009. });
  1010. this.on("submit", () => {
  1011. $.each(filenameDict, (name) => {
  1012. filenameDict[name].submitted = true;
  1013. });
  1014. });
  1015. this.on("reload", () => {
  1016. $.getJSON($editContentZone.data("attachment-url"), (data) => {
  1017. dz.removeAllFiles(true);
  1018. $files.empty();
  1019. $.each(data, function () {
  1020. const imgSrc = `${$dropzone.data("upload-url")}/${
  1021. this.uuid
  1022. }`;
  1023. dz.emit("addedfile", this);
  1024. dz.emit("thumbnail", this, imgSrc);
  1025. dz.emit("complete", this);
  1026. dz.files.push(this);
  1027. filenameDict[this.name] = {
  1028. submitted: true,
  1029. uuid: this.uuid,
  1030. };
  1031. $dropzone
  1032. .find(`img[src='${imgSrc}']`)
  1033. .css("max-width", "100%");
  1034. const input = $(
  1035. `<input id="${this.uuid}" name="files" type="hidden">`
  1036. ).val(this.uuid);
  1037. $files.append(input);
  1038. });
  1039. });
  1040. });
  1041. },
  1042. });
  1043. dz.emit("reload");
  1044. }
  1045. // Give new write/preview data-tab name to distinguish from others
  1046. const $editContentForm = $editContentZone.find(".ui.comment.form");
  1047. const $tabMenu = $editContentForm.find(".tabular.menu");
  1048. $tabMenu.attr("data-write", $editContentZone.data("write"));
  1049. $tabMenu.attr("data-preview", $editContentZone.data("preview"));
  1050. $tabMenu
  1051. .find(".write.item")
  1052. .attr("data-tab", $editContentZone.data("write"));
  1053. $tabMenu
  1054. .find(".preview.item")
  1055. .attr("data-tab", $editContentZone.data("preview"));
  1056. $editContentForm
  1057. .find(".write")
  1058. .attr("data-tab", $editContentZone.data("write"));
  1059. $editContentForm
  1060. .find(".preview")
  1061. .attr("data-tab", $editContentZone.data("preview"));
  1062. $simplemde = setCommentSimpleMDE($textarea);
  1063. commentMDEditors[$editContentZone.data("write")] = $simplemde;
  1064. initCommentPreviewTab($editContentForm);
  1065. initSimpleMDEImagePaste($simplemde, $files);
  1066. $editContentZone.find(".cancel.button").on("click", () => {
  1067. $renderContent.show();
  1068. $editContentZone.hide();
  1069. dz.emit("reload");
  1070. });
  1071. $editContentZone.find(".save.button").on("click", () => {
  1072. $renderContent.show();
  1073. $editContentZone.hide();
  1074. const $attachments = $files
  1075. .find("[name=files]")
  1076. .map(function () {
  1077. return $(this).val();
  1078. })
  1079. .get();
  1080. $.post(
  1081. $editContentZone.data("update-url"),
  1082. {
  1083. _csrf: csrf,
  1084. content: $textarea.val(),
  1085. context: $editContentZone.data("context"),
  1086. files: $attachments,
  1087. },
  1088. (data) => {
  1089. if (data.length === 0 || data.content === "") {
  1090. $renderContent.html($("#no-content").html());
  1091. } else {
  1092. $renderContent.html(data.content);
  1093. $("pre code", $renderContent[0]).each(function () {
  1094. highlight(this);
  1095. });
  1096. }
  1097. let imageShow = "";
  1098. const $content = $segment.parent();
  1099. if (!$content.find(".ui.small.images").length) {
  1100. if (data.attachments !== "" && data.attachments) {
  1101. if ($content.find(".ui.middle.aligned").length === 0) {
  1102. imageShow += '<div class="ui clearing divider"></div>';
  1103. imageShow += '<div class="ui middle aligned padded grid">';
  1104. imageShow += data.attachments;
  1105. imageShow += "</div>";
  1106. $content.find(".ui.attached.segment").append(imageShow);
  1107. } else {
  1108. $content.find(".ui.middle.aligned").html(data.attachments);
  1109. }
  1110. }
  1111. } else if (data.attachments === "") {
  1112. $content.find(".ui.small.images").parent().remove();
  1113. } else {
  1114. $content.find(".ui.small.images").html(data.attachments);
  1115. }
  1116. dz.emit("submit");
  1117. dz.emit("reload");
  1118. }
  1119. );
  1120. });
  1121. } else {
  1122. $textarea = $segment.find("textarea");
  1123. $simplemde = commentMDEditors[$editContentZone.data("write")];
  1124. }
  1125. // Show write/preview tab and copy raw content as needed
  1126. $editContentZone.show();
  1127. $renderContent.hide();
  1128. if ($textarea.val().length === 0) {
  1129. $textarea.val($rawContent.text());
  1130. $simplemde.value($rawContent.text());
  1131. }
  1132. $textarea.focus();
  1133. $simplemde.codemirror.focus();
  1134. event.preventDefault();
  1135. });
  1136. // Delete comment
  1137. $(".delete-comment").on("click", function () {
  1138. const $this = $(this);
  1139. if (window.confirm($this.data("locale"))) {
  1140. $.post($this.data("url"), {
  1141. _csrf: csrf,
  1142. }).done(() => {
  1143. $(`#${$this.data("comment-id")}`).remove();
  1144. });
  1145. }
  1146. return false;
  1147. });
  1148. // Change status
  1149. const $statusButton = $("#status-button");
  1150. $("#comment-form .edit_area").on("keyup", function () {
  1151. if ($(this).val().length === 0) {
  1152. $statusButton.text($statusButton.data("status"));
  1153. } else {
  1154. $statusButton.text($statusButton.data("status-and-comment"));
  1155. }
  1156. });
  1157. $statusButton.on("click", () => {
  1158. $("#status").val($statusButton.data("status-val"));
  1159. $("#comment-form").trigger("submit");
  1160. });
  1161. // Pull Request merge button
  1162. const $mergeButton = $(".merge-button > button");
  1163. $mergeButton.on("click", function (e) {
  1164. e.preventDefault();
  1165. $(`.${$(this).data("do")}-fields`).show();
  1166. $(this).parent().hide();
  1167. });
  1168. $(".merge-button > .dropdown").dropdown({
  1169. onChange(_text, _value, $choice) {
  1170. if ($choice.data("do")) {
  1171. $mergeButton.find(".button-text").text($choice.text());
  1172. $mergeButton.data("do", $choice.data("do"));
  1173. }
  1174. },
  1175. });
  1176. $(".merge-cancel").on("click", function (e) {
  1177. e.preventDefault();
  1178. $(this).closest(".form").hide();
  1179. $mergeButton.parent().show();
  1180. });
  1181. initReactionSelector();
  1182. }
  1183. // Datasets
  1184. if ($(".repository.dataset-list.view").length > 0) {
  1185. const editContentToggle = function () {
  1186. $("#dataset-content").toggle();
  1187. $("#dataset-content-edit").toggle();
  1188. $("#dataset-content input").focus();
  1189. return false;
  1190. };
  1191. $("[data-dataset-status]").on("click", function () {
  1192. const $this = $(this);
  1193. const $private = $this.data("private");
  1194. const $is_private = $this.data("is-private");
  1195. if ($is_private === $private) {
  1196. return;
  1197. }
  1198. const $uuid = $this.data("uuid");
  1199. $.post($this.data("url"), {
  1200. _csrf: $this.data("csrf"),
  1201. file: $uuid,
  1202. is_private: $private,
  1203. })
  1204. .done((_data) => {
  1205. $(`[data-uuid='${$uuid}']`).removeClass("positive active");
  1206. $(`[data-uuid='${$uuid}']`).data("is-private", $private);
  1207. $this.addClass("positive active");
  1208. })
  1209. .fail(() => {
  1210. window.location.reload();
  1211. });
  1212. });
  1213. $("[data-dataset-delete]").on("click", function () {
  1214. const $this = $(this);
  1215. $("#data-dataset-delete-modal")
  1216. .modal({
  1217. closable: false,
  1218. onApprove() {
  1219. $.post($this.data("remove-url"), {
  1220. _csrf: $this.data("csrf"),
  1221. file: $this.data("uuid"),
  1222. })
  1223. .done((_data) => {
  1224. $(`#${$this.data("uuid")}`).hide();
  1225. })
  1226. .fail(() => {
  1227. window.location.reload();
  1228. });
  1229. },
  1230. })
  1231. .modal("show");
  1232. });
  1233. $("[data-category-id]").on("click", function () {
  1234. const category = $(this).data("category-id");
  1235. $("#category").val(category);
  1236. $("#submit").click();
  1237. });
  1238. $("[data-task-id]").on("click", function () {
  1239. const task = $(this).data("task-id");
  1240. $("#task").val(task);
  1241. $("#submit").click();
  1242. });
  1243. $("[data-license-id]").on("click", function () {
  1244. const license = $(this).data("license-id");
  1245. $("#license").val(license);
  1246. $("#submit").click();
  1247. });
  1248. $("#dataset-edit").on("click", editContentToggle);
  1249. $("#cancel").on("click", editContentToggle);
  1250. }
  1251. // Diff
  1252. if ($(".repository.diff").length > 0) {
  1253. $(".diff-counter").each(function () {
  1254. const $item = $(this);
  1255. const addLine = $item.find("span[data-line].add").data("line");
  1256. const delLine = $item.find("span[data-line].del").data("line");
  1257. const addPercent =
  1258. (parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine))) *
  1259. 100;
  1260. $item.find(".bar .add").css("width", `${addPercent}%`);
  1261. });
  1262. }
  1263. // Quick start and repository home
  1264. $("#repo-clone-ssh").on("click", function () {
  1265. $(".clone-url").text($(this).data("link"));
  1266. $("#repo-clone-url").val($(this).data("link"));
  1267. $(this).addClass("blue");
  1268. $("#repo-clone-https").removeClass("blue");
  1269. localStorage.setItem("repo-clone-protocol", "ssh");
  1270. });
  1271. $("#repo-clone-https").on("click", function () {
  1272. $(".clone-url").text($(this).data("link"));
  1273. $("#repo-clone-url").val($(this).data("link"));
  1274. $(this).addClass("blue");
  1275. $("#repo-clone-ssh").removeClass("blue");
  1276. localStorage.setItem("repo-clone-protocol", "https");
  1277. });
  1278. $("#repo-clone-url").on("click", function () {
  1279. $(this).select();
  1280. });
  1281. // Pull request
  1282. const $repoComparePull = $(".repository.compare.pull");
  1283. if ($repoComparePull.length > 0) {
  1284. initFilterSearchDropdown(".choose.branch .dropdown");
  1285. // show pull request form
  1286. $repoComparePull.find("button.show-form").on("click", function (e) {
  1287. e.preventDefault();
  1288. $repoComparePull.find(".pullrequest-form").show();
  1289. autoSimpleMDE.codemirror.refresh();
  1290. $(this).parent().hide();
  1291. });
  1292. }
  1293. // Branches
  1294. if ($(".repository.settings.branches").length > 0) {
  1295. initFilterSearchDropdown(".protected-branches .dropdown");
  1296. $(".enable-protection, .enable-whitelist, .enable-statuscheck").on(
  1297. "change",
  1298. function () {
  1299. if (this.checked) {
  1300. $($(this).data("target")).removeClass("disabled");
  1301. } else {
  1302. $($(this).data("target")).addClass("disabled");
  1303. }
  1304. }
  1305. );
  1306. $(".disable-whitelist").on("change", function () {
  1307. if (this.checked) {
  1308. $($(this).data("target")).addClass("disabled");
  1309. }
  1310. });
  1311. }
  1312. // Language stats
  1313. if ($(".language-stats").length > 0) {
  1314. $(".language-stats").on("click", (e) => {
  1315. e.preventDefault();
  1316. $(".language-stats-details, .repository-menu").slideToggle();
  1317. });
  1318. }
  1319. }
  1320. function initMigration() {
  1321. const toggleMigrations = function () {
  1322. const authUserName = $("#auth_username").val();
  1323. const cloneAddr = $("#clone_addr").val();
  1324. if (
  1325. !$("#mirror").is(":checked") &&
  1326. authUserName &&
  1327. authUserName.length > 0 &&
  1328. cloneAddr !== undefined &&
  1329. (cloneAddr.startsWith("https://github.com") ||
  1330. cloneAddr.startsWith("http://github.com") ||
  1331. cloneAddr.startsWith("http://gitlab.com") ||
  1332. cloneAddr.startsWith("https://gitlab.com"))
  1333. ) {
  1334. $("#migrate_items").show();
  1335. } else {
  1336. $("#migrate_items").hide();
  1337. }
  1338. };
  1339. toggleMigrations();
  1340. $("#clone_addr").on("input", toggleMigrations);
  1341. $("#auth_username").on("input", toggleMigrations);
  1342. $("#mirror").on("change", toggleMigrations);
  1343. }
  1344. function initPullRequestReview() {
  1345. $(".show-outdated").on("click", function (e) {
  1346. e.preventDefault();
  1347. const id = $(this).data("comment");
  1348. $(this).addClass("hide");
  1349. $(`#code-comments-${id}`).removeClass("hide");
  1350. $(`#code-preview-${id}`).removeClass("hide");
  1351. $(`#hide-outdated-${id}`).removeClass("hide");
  1352. });
  1353. $(".hide-outdated").on("click", function (e) {
  1354. e.preventDefault();
  1355. const id = $(this).data("comment");
  1356. $(this).addClass("hide");
  1357. $(`#code-comments-${id}`).addClass("hide");
  1358. $(`#code-preview-${id}`).addClass("hide");
  1359. $(`#show-outdated-${id}`).removeClass("hide");
  1360. });
  1361. $("button.comment-form-reply").on("click", function (e) {
  1362. e.preventDefault();
  1363. $(this).hide();
  1364. const form = $(this).parent().find(".comment-form");
  1365. form.removeClass("hide");
  1366. assingMenuAttributes(form.find(".menu"));
  1367. });
  1368. // The following part is only for diff views
  1369. if ($(".repository.pull.diff").length === 0) {
  1370. return;
  1371. }
  1372. $(".diff-detail-box.ui.sticky").sticky();
  1373. $(".btn-review")
  1374. .on("click", function (e) {
  1375. e.preventDefault();
  1376. $(this).closest(".dropdown").find(".menu").toggle("visible");
  1377. })
  1378. .closest(".dropdown")
  1379. .find(".link.close")
  1380. .on("click", function (e) {
  1381. e.preventDefault();
  1382. $(this).closest(".menu").toggle("visible");
  1383. });
  1384. $(".code-view .lines-code,.code-view .lines-num")
  1385. .on("mouseenter", function () {
  1386. const parent = $(this).closest("td");
  1387. $(this)
  1388. .closest("tr")
  1389. .addClass(
  1390. parent.hasClass("lines-num-old") || parent.hasClass("lines-code-old")
  1391. ? "focus-lines-old"
  1392. : "focus-lines-new"
  1393. );
  1394. })
  1395. .on("mouseleave", function () {
  1396. $(this).closest("tr").removeClass("focus-lines-new focus-lines-old");
  1397. });
  1398. $(".add-code-comment").on("click", function (e) {
  1399. // https://github.com/go-gitea/gitea/issues/4745
  1400. if ($(e.target).hasClass("btn-add-single")) {
  1401. return;
  1402. }
  1403. e.preventDefault();
  1404. const isSplit = $(this).closest(".code-diff").hasClass("code-diff-split");
  1405. const side = $(this).data("side");
  1406. const idx = $(this).data("idx");
  1407. const path = $(this).data("path");
  1408. const form = $("#pull_review_add_comment").html();
  1409. const tr = $(this).closest("tr");
  1410. let ntr = tr.next();
  1411. if (!ntr.hasClass("add-comment")) {
  1412. ntr = $(
  1413. `<tr class="add-comment">${
  1414. isSplit
  1415. ? '<td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-left"></td><td class="lines-num"></td><td class="lines-type-marker"></td><td class="add-comment-right"></td>'
  1416. : '<td class="lines-num"></td><td class="lines-num"></td><td class="add-comment-left add-comment-right" colspan="2"></td>'
  1417. }</tr>`
  1418. );
  1419. tr.after(ntr);
  1420. }
  1421. const td = ntr.find(`.add-comment-${side}`);
  1422. let commentCloud = td.find(".comment-code-cloud");
  1423. if (commentCloud.length === 0) {
  1424. td.html(form);
  1425. commentCloud = td.find(".comment-code-cloud");
  1426. assingMenuAttributes(commentCloud.find(".menu"));
  1427. td.find("input[name='line']").val(idx);
  1428. td.find("input[name='side']").val(
  1429. side === "left" ? "previous" : "proposed"
  1430. );
  1431. td.find("input[name='path']").val(path);
  1432. }
  1433. commentCloud.find("textarea").focus();
  1434. });
  1435. }
  1436. function assingMenuAttributes(menu) {
  1437. const id = Math.floor(Math.random() * Math.floor(1000000));
  1438. menu.attr("data-write", menu.attr("data-write") + id);
  1439. menu.attr("data-preview", menu.attr("data-preview") + id);
  1440. menu.find(".item").each(function () {
  1441. const tab = $(this).attr("data-tab") + id;
  1442. $(this).attr("data-tab", tab);
  1443. });
  1444. menu.parent().find("*[data-tab='write']").attr("data-tab", `write${id}`);
  1445. menu.parent().find("*[data-tab='preview']").attr("data-tab", `preview${id}`);
  1446. initCommentPreviewTab(menu.parent(".form"));
  1447. return id;
  1448. }
  1449. function initRepositoryCollaboration() {
  1450. // Change collaborator access mode
  1451. $(".access-mode.menu .item").on("click", function () {
  1452. const $menu = $(this).parent();
  1453. $.post($menu.data("url"), {
  1454. _csrf: csrf,
  1455. uid: $menu.data("uid"),
  1456. mode: $(this).data("value"),
  1457. });
  1458. });
  1459. }
  1460. function initTeamSettings() {
  1461. // Change team access mode
  1462. $(".organization.new.team input[name=permission]").on("change", () => {
  1463. const val = $(
  1464. "input[name=permission]:checked",
  1465. ".organization.new.team"
  1466. ).val();
  1467. if (val === "admin") {
  1468. $(".organization.new.team .team-units").hide();
  1469. } else {
  1470. $(".organization.new.team .team-units").show();
  1471. }
  1472. });
  1473. }
  1474. function initWikiForm() {
  1475. const $editArea = $(".repository.wiki textarea#edit_area");
  1476. let sideBySideChanges = 0;
  1477. let sideBySideTimeout = null;
  1478. if ($editArea.length > 0) {
  1479. const simplemde = new SimpleMDE({
  1480. autoDownloadFontAwesome: false,
  1481. element: $editArea[0],
  1482. forceSync: true,
  1483. previewRender(plainText, preview) {
  1484. // Async method
  1485. setTimeout(() => {
  1486. // FIXME: still send render request when return back to edit mode
  1487. const render = function () {
  1488. sideBySideChanges = 0;
  1489. if (sideBySideTimeout !== null) {
  1490. clearTimeout(sideBySideTimeout);
  1491. sideBySideTimeout = null;
  1492. }
  1493. $.post(
  1494. $editArea.data("url"),
  1495. {
  1496. _csrf: csrf,
  1497. mode: "gfm",
  1498. context: $editArea.data("context"),
  1499. text: plainText,
  1500. },
  1501. (data) => {
  1502. preview.innerHTML = `<div class="markdown ui segment">${data}</div>`;
  1503. $(preview)
  1504. .find("pre code")
  1505. .each((_, e) => {
  1506. highlight(e);
  1507. });
  1508. }
  1509. );
  1510. };
  1511. if (!simplemde.isSideBySideActive()) {
  1512. render();
  1513. } else {
  1514. // delay preview by keystroke counting
  1515. sideBySideChanges++;
  1516. if (sideBySideChanges > 10) {
  1517. render();
  1518. }
  1519. // or delay preview by timeout
  1520. if (sideBySideTimeout !== null) {
  1521. clearTimeout(sideBySideTimeout);
  1522. sideBySideTimeout = null;
  1523. }
  1524. sideBySideTimeout = setTimeout(render, 600);
  1525. }
  1526. }, 0);
  1527. if (!simplemde.isSideBySideActive()) {
  1528. return "Loading...";
  1529. }
  1530. return preview.innerHTML;
  1531. },
  1532. renderingConfig: {
  1533. singleLineBreaks: false,
  1534. },
  1535. indentWithTabs: false,
  1536. tabSize: 4,
  1537. spellChecker: false,
  1538. toolbar: [
  1539. "bold",
  1540. "italic",
  1541. "strikethrough",
  1542. "|",
  1543. "heading-1",
  1544. "heading-2",
  1545. "heading-3",
  1546. "heading-bigger",
  1547. "heading-smaller",
  1548. "|",
  1549. {
  1550. name: "code-inline",
  1551. action(e) {
  1552. const cm = e.codemirror;
  1553. const selection = cm.getSelection();
  1554. cm.replaceSelection(`\`${selection}\``);
  1555. if (!selection) {
  1556. const cursorPos = cm.getCursor();
  1557. cm.setCursor(cursorPos.line, cursorPos.ch - 1);
  1558. }
  1559. cm.focus();
  1560. },
  1561. className: "fa fa-angle-right",
  1562. title: "Add Inline Code",
  1563. },
  1564. "code",
  1565. "quote",
  1566. "|",
  1567. {
  1568. name: "checkbox-empty",
  1569. action(e) {
  1570. const cm = e.codemirror;
  1571. cm.replaceSelection(`\n- [ ] ${cm.getSelection()}`);
  1572. cm.focus();
  1573. },
  1574. className: "fa fa-square-o",
  1575. title: "Add Checkbox (empty)",
  1576. },
  1577. {
  1578. name: "checkbox-checked",
  1579. action(e) {
  1580. const cm = e.codemirror;
  1581. cm.replaceSelection(`\n- [x] ${cm.getSelection()}`);
  1582. cm.focus();
  1583. },
  1584. className: "fa fa-check-square-o",
  1585. title: "Add Checkbox (checked)",
  1586. },
  1587. "|",
  1588. "unordered-list",
  1589. "ordered-list",
  1590. "|",
  1591. "link",
  1592. "image",
  1593. "table",
  1594. "horizontal-rule",
  1595. "|",
  1596. "clean-block",
  1597. "preview",
  1598. "fullscreen",
  1599. "side-by-side",
  1600. "|",
  1601. {
  1602. name: "revert-to-textarea",
  1603. action(e) {
  1604. e.toTextArea();
  1605. },
  1606. className: "fa fa-file",
  1607. title: "Revert to simple textarea",
  1608. },
  1609. ],
  1610. });
  1611. $(simplemde.codemirror.getInputField()).addClass("js-quick-submit");
  1612. setTimeout(() => {
  1613. const $bEdit = $('.repository.wiki.new .previewtabs a[data-tab="write"]');
  1614. const $bPrev = $(
  1615. '.repository.wiki.new .previewtabs a[data-tab="preview"]'
  1616. );
  1617. const $toolbar = $(".editor-toolbar");
  1618. const $bPreview = $(".editor-toolbar a.fa-eye");
  1619. const $bSideBySide = $(".editor-toolbar a.fa-columns");
  1620. $bEdit.on("click", () => {
  1621. if ($toolbar.hasClass("disabled-for-preview")) {
  1622. $bPreview.trigger("click");
  1623. }
  1624. });
  1625. $bPrev.on("click", () => {
  1626. if (!$toolbar.hasClass("disabled-for-preview")) {
  1627. $bPreview.trigger("click");
  1628. }
  1629. });
  1630. $bPreview.on("click", () => {
  1631. setTimeout(() => {
  1632. if ($toolbar.hasClass("disabled-for-preview")) {
  1633. if ($bEdit.hasClass("active")) {
  1634. $bEdit.removeClass("active");
  1635. }
  1636. if (!$bPrev.hasClass("active")) {
  1637. $bPrev.addClass("active");
  1638. }
  1639. } else {
  1640. if (!$bEdit.hasClass("active")) {
  1641. $bEdit.addClass("active");
  1642. }
  1643. if ($bPrev.hasClass("active")) {
  1644. $bPrev.removeClass("active");
  1645. }
  1646. }
  1647. }, 0);
  1648. });
  1649. $bSideBySide.on("click", () => {
  1650. sideBySideChanges = 10;
  1651. });
  1652. }, 0);
  1653. }
  1654. }
  1655. // Adding function to get the cursor position in a text field to jQuery object.
  1656. $.fn.getCursorPosition = function () {
  1657. const el = $(this).get(0);
  1658. let pos = 0;
  1659. if ("selectionStart" in el) {
  1660. pos = el.selectionStart;
  1661. } else if ("selection" in document) {
  1662. el.focus();
  1663. const Sel = document.selection.createRange();
  1664. const SelLength = document.selection.createRange().text.length;
  1665. Sel.moveStart("character", -el.value.length);
  1666. pos = Sel.text.length - SelLength;
  1667. }
  1668. return pos;
  1669. };
  1670. function setCommentSimpleMDE($editArea) {
  1671. const simplemde = new SimpleMDE({
  1672. autoDownloadFontAwesome: false,
  1673. element: $editArea[0],
  1674. forceSync: true,
  1675. renderingConfig: {
  1676. singleLineBreaks: false,
  1677. },
  1678. indentWithTabs: false,
  1679. tabSize: 4,
  1680. spellChecker: false,
  1681. toolbar: [
  1682. "bold",
  1683. "italic",
  1684. "strikethrough",
  1685. "|",
  1686. "heading-1",
  1687. "heading-2",
  1688. "heading-3",
  1689. "heading-bigger",
  1690. "heading-smaller",
  1691. "|",
  1692. "code",
  1693. "quote",
  1694. "|",
  1695. "unordered-list",
  1696. "ordered-list",
  1697. "|",
  1698. "link",
  1699. "image",
  1700. "table",
  1701. "horizontal-rule",
  1702. "|",
  1703. "clean-block",
  1704. "|",
  1705. {
  1706. name: "revert-to-textarea",
  1707. action(e) {
  1708. e.toTextArea();
  1709. },
  1710. className: "fa fa-file",
  1711. title: "Revert to simple textarea",
  1712. },
  1713. ],
  1714. });
  1715. $(simplemde.codemirror.getInputField()).addClass("js-quick-submit");
  1716. simplemde.codemirror.setOption("extraKeys", {
  1717. Enter: () => {
  1718. if (!(issuesTribute.isActive || emojiTribute.isActive)) {
  1719. return CodeMirror.Pass;
  1720. }
  1721. },
  1722. Backspace: (cm) => {
  1723. if (cm.getInputField().trigger) {
  1724. cm.getInputField().trigger("input");
  1725. }
  1726. cm.execCommand("delCharBefore");
  1727. },
  1728. });
  1729. issuesTribute.attach(simplemde.codemirror.getInputField());
  1730. emojiTribute.attach(simplemde.codemirror.getInputField());
  1731. return simplemde;
  1732. }
  1733. async function initEditor() {
  1734. $(".js-quick-pull-choice-option").on("change", function () {
  1735. if ($(this).val() === "commit-to-new-branch") {
  1736. $(".quick-pull-branch-name").show();
  1737. $(".quick-pull-branch-name input").prop("required", true);
  1738. } else {
  1739. $(".quick-pull-branch-name").hide();
  1740. $(".quick-pull-branch-name input").prop("required", false);
  1741. }
  1742. $("#commit-button").text($(this).attr("button_text"));
  1743. });
  1744. const $editFilename = $("#file-name");
  1745. $editFilename
  1746. .on("keyup", function (e) {
  1747. const $section = $(".breadcrumb span.section");
  1748. const $divider = $(".breadcrumb div.divider");
  1749. let value;
  1750. let parts;
  1751. if (e.keyCode === 8) {
  1752. if ($(this).getCursorPosition() === 0) {
  1753. if ($section.length > 0) {
  1754. value = $section.last().find("a").text();
  1755. $(this).val(value + $(this).val());
  1756. $(this)[0].setSelectionRange(value.length, value.length);
  1757. $section.last().remove();
  1758. $divider.last().remove();
  1759. }
  1760. }
  1761. }
  1762. if (e.keyCode === 191) {
  1763. parts = $(this).val().split("/");
  1764. for (let i = 0; i < parts.length; ++i) {
  1765. value = parts[i];
  1766. if (i < parts.length - 1) {
  1767. if (value.length) {
  1768. $(
  1769. `<span class="section"><a href="#">${value}</a></span>`
  1770. ).insertBefore($(this));
  1771. $('<div class="divider"> / </div>').insertBefore($(this));
  1772. }
  1773. } else {
  1774. $(this).val(value);
  1775. }
  1776. $(this)[0].setSelectionRange(0, 0);
  1777. }
  1778. }
  1779. parts = [];
  1780. $(".breadcrumb span.section").each(function () {
  1781. const element = $(this);
  1782. if (element.find("a").length) {
  1783. parts.push(element.find("a").text());
  1784. } else {
  1785. parts.push(element.text());
  1786. }
  1787. });
  1788. if ($(this).val()) parts.push($(this).val());
  1789. $("#tree_path").val(parts.join("/"));
  1790. })
  1791. .trigger("keyup");
  1792. const $editArea = $(".repository.editor textarea#edit_area");
  1793. if (!$editArea.length) return;
  1794. await createCodeEditor($editArea[0], $editFilename[0], previewFileModes);
  1795. // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
  1796. // to enable or disable the commit button
  1797. const $commitButton = $("#commit-button");
  1798. const $editForm = $(".ui.edit.form");
  1799. const dirtyFileClass = "dirty-file";
  1800. // Disabling the button at the start
  1801. $commitButton.prop("disabled", true);
  1802. // Registering a custom listener for the file path and the file content
  1803. $editForm.areYouSure({
  1804. silent: true,
  1805. dirtyClass: dirtyFileClass,
  1806. fieldSelector: ":input:not(.commit-form-wrapper :input)",
  1807. change() {
  1808. const dirty = $(this).hasClass(dirtyFileClass);
  1809. $commitButton.prop("disabled", !dirty);
  1810. },
  1811. });
  1812. $commitButton.on("click", (event) => {
  1813. // A modal which asks if an empty file should be committed
  1814. if ($editArea.val().length === 0) {
  1815. $("#edit-empty-content-modal")
  1816. .modal({
  1817. onApprove() {
  1818. $(".edit.form").trigger("submit");
  1819. },
  1820. })
  1821. .modal("show");
  1822. event.preventDefault();
  1823. }
  1824. });
  1825. }
  1826. function initOrganization() {
  1827. if ($(".organization").length === 0) {
  1828. return;
  1829. }
  1830. // Options
  1831. if ($(".organization.settings.options").length > 0) {
  1832. $("#org_name").on("keyup", function () {
  1833. const $prompt = $("#org-name-change-prompt");
  1834. if (
  1835. $(this).val().toString().toLowerCase() !==
  1836. $(this).data("org-name").toString().toLowerCase()
  1837. ) {
  1838. $prompt.show();
  1839. } else {
  1840. $prompt.hide();
  1841. }
  1842. });
  1843. }
  1844. // Labels
  1845. if ($(".organization.settings.labels").length > 0) {
  1846. initLabelEdit();
  1847. }
  1848. }
  1849. function initUserSettings() {
  1850. // Options
  1851. if ($(".user.settings.profile").length > 0) {
  1852. $("#username").on("keyup", function () {
  1853. const $prompt = $("#name-change-prompt");
  1854. if (
  1855. $(this).val().toString().toLowerCase() !==
  1856. $(this).data("name").toString().toLowerCase()
  1857. ) {
  1858. $prompt.show();
  1859. } else {
  1860. $prompt.hide();
  1861. }
  1862. });
  1863. }
  1864. }
  1865. function initGithook() {
  1866. if ($(".edit.githook").length === 0) {
  1867. return;
  1868. }
  1869. CodeMirror.autoLoadMode(
  1870. CodeMirror.fromTextArea($("#content")[0], {
  1871. lineNumbers: true,
  1872. mode: "shell",
  1873. }),
  1874. "shell"
  1875. );
  1876. }
  1877. function initWebhook() {
  1878. if ($(".new.webhook").length === 0) {
  1879. return;
  1880. }
  1881. $(".events.checkbox input").on("change", function () {
  1882. if ($(this).is(":checked")) {
  1883. $(".events.fields").show();
  1884. }
  1885. });
  1886. $(".non-events.checkbox input").on("change", function () {
  1887. if ($(this).is(":checked")) {
  1888. $(".events.fields").hide();
  1889. }
  1890. });
  1891. const updateContentType = function () {
  1892. const visible = $("#http_method").val() === "POST";
  1893. $("#content_type").parent().parent()[visible ? "show" : "hide"]();
  1894. };
  1895. updateContentType();
  1896. $("#http_method").on("change", () => {
  1897. updateContentType();
  1898. });
  1899. // Test delivery
  1900. $("#test-delivery").on("click", function () {
  1901. const $this = $(this);
  1902. $this.addClass("loading disabled");
  1903. $.post($this.data("link"), {
  1904. _csrf: csrf,
  1905. }).done(
  1906. setTimeout(() => {
  1907. window.location.href = $this.data("redirect");
  1908. }, 5000)
  1909. );
  1910. });
  1911. }
  1912. function initAdmin() {
  1913. if ($(".admin").length === 0) {
  1914. return;
  1915. }
  1916. // New user
  1917. if ($(".admin.new.user").length > 0 || $(".admin.edit.user").length > 0) {
  1918. $("#login_type").on("change", function () {
  1919. if ($(this).val().substring(0, 1) === "0") {
  1920. $("#login_name").removeAttr("required");
  1921. $(".non-local").hide();
  1922. $(".local").show();
  1923. $("#user_name").focus();
  1924. if ($(this).data("password") === "required") {
  1925. $("#password").attr("required", "required");
  1926. }
  1927. } else {
  1928. $("#login_name").attr("required", "required");
  1929. $(".non-local").show();
  1930. $(".local").hide();
  1931. $("#login_name").focus();
  1932. $("#password").removeAttr("required");
  1933. }
  1934. });
  1935. }
  1936. function onSecurityProtocolChange() {
  1937. if ($("#security_protocol").val() > 0) {
  1938. $(".has-tls").show();
  1939. } else {
  1940. $(".has-tls").hide();
  1941. }
  1942. }
  1943. function onUsePagedSearchChange() {
  1944. if ($("#use_paged_search").prop("checked")) {
  1945. $(".search-page-size").show().find("input").attr("required", "required");
  1946. } else {
  1947. $(".search-page-size").hide().find("input").removeAttr("required");
  1948. }
  1949. }
  1950. function onOAuth2Change() {
  1951. $(".open_id_connect_auto_discovery_url, .oauth2_use_custom_url").hide();
  1952. $(".open_id_connect_auto_discovery_url input[required]").removeAttr(
  1953. "required"
  1954. );
  1955. const provider = $("#oauth2_provider").val();
  1956. switch (provider) {
  1957. case "github":
  1958. case "gitlab":
  1959. case "gitea":
  1960. case "nextcloud":
  1961. $(".oauth2_use_custom_url").show();
  1962. break;
  1963. case "openidConnect":
  1964. $(".open_id_connect_auto_discovery_url input").attr(
  1965. "required",
  1966. "required"
  1967. );
  1968. $(".open_id_connect_auto_discovery_url").show();
  1969. break;
  1970. }
  1971. onOAuth2UseCustomURLChange();
  1972. }
  1973. function onOAuth2UseCustomURLChange() {
  1974. const provider = $("#oauth2_provider").val();
  1975. $(".oauth2_use_custom_url_field").hide();
  1976. $(".oauth2_use_custom_url_field input[required]").removeAttr("required");
  1977. if ($("#oauth2_use_custom_url").is(":checked")) {
  1978. $("#oauth2_token_url").val($(`#${provider}_token_url`).val());
  1979. $("#oauth2_auth_url").val($(`#${provider}_auth_url`).val());
  1980. $("#oauth2_profile_url").val($(`#${provider}_profile_url`).val());
  1981. $("#oauth2_email_url").val($(`#${provider}_email_url`).val());
  1982. switch (provider) {
  1983. case "github":
  1984. $(
  1985. ".oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input"
  1986. ).attr("required", "required");
  1987. $(
  1988. ".oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url"
  1989. ).show();
  1990. break;
  1991. case "nextcloud":
  1992. case "gitea":
  1993. case "gitlab":
  1994. $(
  1995. ".oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input"
  1996. ).attr("required", "required");
  1997. $(".oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url").show();
  1998. $("#oauth2_email_url").val("");
  1999. break;
  2000. }
  2001. }
  2002. }
  2003. // New authentication
  2004. if ($(".admin.new.authentication").length > 0) {
  2005. $("#auth_type").on("change", function () {
  2006. $(
  2007. ".ldap, .dldap, .smtp, .pam, .oauth2, .has-tls, .search-page-size, .sspi"
  2008. ).hide();
  2009. $(
  2010. ".ldap input[required], .binddnrequired input[required], .dldap input[required], .smtp input[required], .pam input[required], .oauth2 input[required], .has-tls input[required], .sspi input[required]"
  2011. ).removeAttr("required");
  2012. $(".binddnrequired").removeClass("required");
  2013. const authType = $(this).val();
  2014. switch (authType) {
  2015. case "2": // LDAP
  2016. $(".ldap").show();
  2017. $(".binddnrequired input, .ldap div.required:not(.dldap) input").attr(
  2018. "required",
  2019. "required"
  2020. );
  2021. $(".binddnrequired").addClass("required");
  2022. break;
  2023. case "3": // SMTP
  2024. $(".smtp").show();
  2025. $(".has-tls").show();
  2026. $(".smtp div.required input, .has-tls").attr("required", "required");
  2027. break;
  2028. case "4": // PAM
  2029. $(".pam").show();
  2030. $(".pam input").attr("required", "required");
  2031. break;
  2032. case "5": // LDAP
  2033. $(".dldap").show();
  2034. $(".dldap div.required:not(.ldap) input").attr(
  2035. "required",
  2036. "required"
  2037. );
  2038. break;
  2039. case "6": // OAuth2
  2040. $(".oauth2").show();
  2041. $(
  2042. ".oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input"
  2043. ).attr("required", "required");
  2044. onOAuth2Change();
  2045. break;
  2046. case "7": // SSPI
  2047. $(".sspi").show();
  2048. $(".sspi div.required input").attr("required", "required");
  2049. break;
  2050. }
  2051. if (authType === "2" || authType === "5") {
  2052. onSecurityProtocolChange();
  2053. }
  2054. if (authType === "2") {
  2055. onUsePagedSearchChange();
  2056. }
  2057. });
  2058. $("#auth_type").trigger("change");
  2059. $("#security_protocol").on("change", onSecurityProtocolChange);
  2060. $("#use_paged_search").on("change", onUsePagedSearchChange);
  2061. $("#oauth2_provider").on("change", onOAuth2Change);
  2062. $("#oauth2_use_custom_url").on("change", onOAuth2UseCustomURLChange);
  2063. }
  2064. // Edit authentication
  2065. if ($(".admin.edit.authentication").length > 0) {
  2066. const authType = $("#auth_type").val();
  2067. if (authType === "2" || authType === "5") {
  2068. $("#security_protocol").on("change", onSecurityProtocolChange);
  2069. if (authType === "2") {
  2070. $("#use_paged_search").on("change", onUsePagedSearchChange);
  2071. }
  2072. } else if (authType === "6") {
  2073. $("#oauth2_provider").on("change", onOAuth2Change);
  2074. $("#oauth2_use_custom_url").on("change", onOAuth2UseCustomURLChange);
  2075. onOAuth2Change();
  2076. }
  2077. }
  2078. // Notice
  2079. if ($(".admin.notice")) {
  2080. const $detailModal = $("#detail-modal");
  2081. // Attach view detail modals
  2082. $(".view-detail").on("click", function () {
  2083. $detailModal.find(".content pre").text($(this).data("content"));
  2084. $detailModal.modal("show");
  2085. return false;
  2086. });
  2087. // Select actions
  2088. const $checkboxes = $(".select.table .ui.checkbox");
  2089. $(".select.action").on("click", function () {
  2090. switch ($(this).data("action")) {
  2091. case "select-all":
  2092. $checkboxes.checkbox("check");
  2093. break;
  2094. case "deselect-all":
  2095. $checkboxes.checkbox("uncheck");
  2096. break;
  2097. case "inverse":
  2098. $checkboxes.checkbox("toggle");
  2099. break;
  2100. }
  2101. });
  2102. $("#delete-selection").on("click", function () {
  2103. const $this = $(this);
  2104. $this.addClass("loading disabled");
  2105. const ids = [];
  2106. $checkboxes.each(function () {
  2107. if ($(this).checkbox("is checked")) {
  2108. ids.push($(this).data("id"));
  2109. }
  2110. });
  2111. $.post($this.data("link"), {
  2112. _csrf: csrf,
  2113. ids,
  2114. }).done(() => {
  2115. window.location.href = $this.data("redirect");
  2116. });
  2117. });
  2118. }
  2119. }
  2120. function buttonsClickOnEnter() {
  2121. $(".ui.button").on("keypress", function (e) {
  2122. if (e.keyCode === 13 || e.keyCode === 32) {
  2123. // enter key or space bar
  2124. $(this).trigger("click");
  2125. }
  2126. });
  2127. }
  2128. function searchUsers() {
  2129. const $searchUserBox = $("#search-user-box");
  2130. $searchUserBox.search({
  2131. minCharacters: 2,
  2132. apiSettings: {
  2133. url: `${AppSubUrl}/api/v1/users/search?q={query}`,
  2134. onResponse(response) {
  2135. const items = [];
  2136. $.each(response.data, (_i, item) => {
  2137. let title = item.login;
  2138. if (item.full_name && item.full_name.length > 0) {
  2139. title += ` (${htmlEncode(item.full_name)})`;
  2140. }
  2141. items.push({
  2142. title,
  2143. image: item.avatar_url,
  2144. });
  2145. });
  2146. return { results: items };
  2147. },
  2148. },
  2149. searchFields: ["login", "full_name"],
  2150. showNoResults: false,
  2151. });
  2152. }
  2153. function searchTeams() {
  2154. const $searchTeamBox = $("#search-team-box");
  2155. $searchTeamBox.search({
  2156. minCharacters: 2,
  2157. apiSettings: {
  2158. url: `${AppSubUrl}/api/v1/orgs/${$searchTeamBox.data(
  2159. "org"
  2160. )}/teams/search?q={query}`,
  2161. headers: { "X-Csrf-Token": csrf },
  2162. onResponse(response) {
  2163. const items = [];
  2164. $.each(response.data, (_i, item) => {
  2165. const title = `${item.name} (${item.permission} access)`;
  2166. items.push({
  2167. title,
  2168. });
  2169. });
  2170. return { results: items };
  2171. },
  2172. },
  2173. searchFields: ["name", "description"],
  2174. showNoResults: false,
  2175. });
  2176. }
  2177. function searchRepositories() {
  2178. const $searchRepoBox = $("#search-repo-box");
  2179. $searchRepoBox.search({
  2180. minCharacters: 2,
  2181. apiSettings: {
  2182. url: `${AppSubUrl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data(
  2183. "uid"
  2184. )}`,
  2185. onResponse(response) {
  2186. const items = [];
  2187. $.each(response.data, (_i, item) => {
  2188. items.push({
  2189. title: item.full_display_name.split("/")[1],
  2190. description: item.full_display_name,
  2191. });
  2192. });
  2193. return { results: items };
  2194. },
  2195. },
  2196. searchFields: ["full_name"],
  2197. showNoResults: false,
  2198. });
  2199. }
  2200. function initCodeView() {
  2201. if ($(".code-view .linenums").length > 0) {
  2202. $(document).on("click", ".lines-num span", function (e) {
  2203. const $select = $(this);
  2204. const $list = $select
  2205. .parent()
  2206. .siblings(".lines-code")
  2207. .find("ol.linenums > li");
  2208. selectRange(
  2209. $list,
  2210. $list.filter(`[rel=${$select.attr("id")}]`),
  2211. e.shiftKey ? $list.filter(".active").eq(0) : null
  2212. );
  2213. deSelect();
  2214. });
  2215. $(window)
  2216. .on("hashchange", () => {
  2217. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  2218. const $list = $(".code-view ol.linenums > li");
  2219. let $first;
  2220. if (m) {
  2221. $first = $list.filter(`.${m[1]}`);
  2222. selectRange($list, $first, $list.filter(`.${m[2]}`));
  2223. $("html, body").scrollTop($first.offset().top - 200);
  2224. return;
  2225. }
  2226. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  2227. if (m) {
  2228. $first = $list.filter(`.L${m[2]}`);
  2229. selectRange($list, $first);
  2230. $("html, body").scrollTop($first.offset().top - 200);
  2231. }
  2232. })
  2233. .trigger("hashchange");
  2234. }
  2235. $(".fold-code").on("click", ({ target }) => {
  2236. const box = target.closest(".file-content");
  2237. const folded = box.dataset.folded !== "true";
  2238. target.classList.add(`fa-chevron-${folded ? "right" : "down"}`);
  2239. target.classList.remove(`fa-chevron-${folded ? "down" : "right"}`);
  2240. box.dataset.folded = String(folded);
  2241. });
  2242. function insertBlobExcerpt(e) {
  2243. const $blob = $(e.target);
  2244. const $row = $blob.parent().parent();
  2245. $.get(
  2246. `${$blob.data("url")}?${$blob.data("query")}&anchor=${$blob.data(
  2247. "anchor"
  2248. )}`,
  2249. (blob) => {
  2250. $row.replaceWith(blob);
  2251. $(`[data-anchor="${$blob.data("anchor")}"]`).on("click", (e) => {
  2252. insertBlobExcerpt(e);
  2253. });
  2254. $(".diff-detail-box.ui.sticky").sticky();
  2255. }
  2256. );
  2257. }
  2258. $(".ui.blob-excerpt").on("click", (e) => {
  2259. insertBlobExcerpt(e);
  2260. });
  2261. }
  2262. function initU2FAuth() {
  2263. if ($("#wait-for-key").length === 0) {
  2264. return;
  2265. }
  2266. u2fApi
  2267. .ensureSupport()
  2268. .then(() => {
  2269. $.getJSON(`${AppSubUrl}/user/u2f/challenge`).done((req) => {
  2270. u2fApi
  2271. .sign(req.appId, req.challenge, req.registeredKeys, 30)
  2272. .then(u2fSigned)
  2273. .catch((err) => {
  2274. if (err === undefined) {
  2275. u2fError(1);
  2276. return;
  2277. }
  2278. u2fError(err.metaData.code);
  2279. });
  2280. });
  2281. })
  2282. .catch(() => {
  2283. // Fallback in case browser do not support U2F
  2284. window.location.href = `${AppSubUrl}/user/two_factor`;
  2285. });
  2286. }
  2287. function u2fSigned(resp) {
  2288. $.ajax({
  2289. url: `${AppSubUrl}/user/u2f/sign`,
  2290. type: "POST",
  2291. headers: { "X-Csrf-Token": csrf },
  2292. data: JSON.stringify(resp),
  2293. contentType: "application/json; charset=utf-8",
  2294. })
  2295. .done((res) => {
  2296. window.location.replace(res);
  2297. })
  2298. .fail(() => {
  2299. u2fError(1);
  2300. });
  2301. }
  2302. function u2fRegistered(resp) {
  2303. if (checkError(resp)) {
  2304. return;
  2305. }
  2306. $.ajax({
  2307. url: `${AppSubUrl}/user/settings/security/u2f/register`,
  2308. type: "POST",
  2309. headers: { "X-Csrf-Token": csrf },
  2310. data: JSON.stringify(resp),
  2311. contentType: "application/json; charset=utf-8",
  2312. success() {
  2313. reload();
  2314. },
  2315. fail() {
  2316. u2fError(1);
  2317. },
  2318. });
  2319. }
  2320. function checkError(resp) {
  2321. if (!("errorCode" in resp)) {
  2322. return false;
  2323. }
  2324. if (resp.errorCode === 0) {
  2325. return false;
  2326. }
  2327. u2fError(resp.errorCode);
  2328. return true;
  2329. }
  2330. function u2fError(errorType) {
  2331. const u2fErrors = {
  2332. browser: $("#unsupported-browser"),
  2333. 1: $("#u2f-error-1"),
  2334. 2: $("#u2f-error-2"),
  2335. 3: $("#u2f-error-3"),
  2336. 4: $("#u2f-error-4"),
  2337. 5: $(".u2f-error-5"),
  2338. };
  2339. u2fErrors[errorType].removeClass("hide");
  2340. Object.keys(u2fErrors).forEach((type) => {
  2341. if (type !== errorType) {
  2342. u2fErrors[type].addClass("hide");
  2343. }
  2344. });
  2345. $("#u2f-error").modal("show");
  2346. }
  2347. function initU2FRegister() {
  2348. $("#register-device").modal({ allowMultiple: false });
  2349. $("#u2f-error").modal({ allowMultiple: false });
  2350. $("#register-security-key").on("click", (e) => {
  2351. e.preventDefault();
  2352. u2fApi
  2353. .ensureSupport()
  2354. .then(u2fRegisterRequest)
  2355. .catch(() => {
  2356. u2fError("browser");
  2357. });
  2358. });
  2359. }
  2360. function u2fRegisterRequest() {
  2361. $.post(`${AppSubUrl}/user/settings/security/u2f/request_register`, {
  2362. _csrf: csrf,
  2363. name: $("#nickname").val(),
  2364. })
  2365. .done((req) => {
  2366. $("#nickname").closest("div.field").removeClass("error");
  2367. $("#register-device").modal("show");
  2368. if (req.registeredKeys === null) {
  2369. req.registeredKeys = [];
  2370. }
  2371. u2fApi
  2372. .register(req.appId, req.registerRequests, req.registeredKeys, 30)
  2373. .then(u2fRegistered)
  2374. .catch((reason) => {
  2375. if (reason === undefined) {
  2376. u2fError(1);
  2377. return;
  2378. }
  2379. u2fError(reason.metaData.code);
  2380. });
  2381. })
  2382. .fail((xhr) => {
  2383. if (xhr.status === 409) {
  2384. $("#nickname").closest("div.field").addClass("error");
  2385. }
  2386. });
  2387. }
  2388. function initWipTitle() {
  2389. $(".title_wip_desc > a").on("click", (e) => {
  2390. e.preventDefault();
  2391. const $issueTitle = $("#issue_title");
  2392. $issueTitle.focus();
  2393. const value = $issueTitle.val().trim().toUpperCase();
  2394. for (const i in wipPrefixes) {
  2395. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  2396. return;
  2397. }
  2398. }
  2399. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  2400. });
  2401. }
  2402. function initTemplateSearch() {
  2403. const $repoTemplate = $("#repo_template");
  2404. const checkTemplate = function () {
  2405. const $templateUnits = $("#template_units");
  2406. const $nonTemplate = $("#non_template");
  2407. if ($repoTemplate.val() !== "" && $repoTemplate.val() !== "0") {
  2408. $templateUnits.show();
  2409. $nonTemplate.hide();
  2410. } else {
  2411. $templateUnits.hide();
  2412. $nonTemplate.show();
  2413. }
  2414. };
  2415. $repoTemplate.on("change", checkTemplate);
  2416. checkTemplate();
  2417. const changeOwner = function () {
  2418. $("#repo_template_search").dropdown({
  2419. apiSettings: {
  2420. url: `${AppSubUrl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$(
  2421. "#uid"
  2422. ).val()}`,
  2423. onResponse(response) {
  2424. const filteredResponse = { success: true, results: [] };
  2425. filteredResponse.results.push({
  2426. name: "",
  2427. value: "",
  2428. });
  2429. // Parse the response from the api to work with our dropdown
  2430. $.each(response.data, (_r, repo) => {
  2431. filteredResponse.results.push({
  2432. name: htmlEncode(repo.full_display_name),
  2433. value: repo.id,
  2434. });
  2435. });
  2436. return filteredResponse;
  2437. },
  2438. cache: false,
  2439. },
  2440. fullTextSearch: true,
  2441. });
  2442. };
  2443. $("#uid").on("change", changeOwner);
  2444. changeOwner();
  2445. }
  2446. $(document).ready(async () => {
  2447. // Show exact time
  2448. $(".time-since").each(function () {
  2449. $(this)
  2450. .addClass("poping up")
  2451. .attr("data-content", $(this).attr("title"))
  2452. .attr("data-variation", "inverted tiny")
  2453. .attr("title", "");
  2454. });
  2455. // Semantic UI modules.
  2456. $(".dropdown:not(.custom)").dropdown();
  2457. $(".jump.dropdown").dropdown({
  2458. action: "hide",
  2459. onShow() {
  2460. $(".poping.up").popup("hide");
  2461. },
  2462. });
  2463. $(".slide.up.dropdown").dropdown({
  2464. transition: "slide up",
  2465. });
  2466. $(".upward.dropdown").dropdown({
  2467. direction: "upward",
  2468. });
  2469. $(".ui.accordion").accordion();
  2470. $(".ui.checkbox").checkbox();
  2471. $(".ui.progress").progress({
  2472. showActivity: false,
  2473. });
  2474. $(".poping.up").popup();
  2475. $(".top.menu .poping.up").popup({
  2476. onShow() {
  2477. if ($(".top.menu .menu.transition").hasClass("visible")) {
  2478. return false;
  2479. }
  2480. },
  2481. });
  2482. $(".tabular.menu .item").tab();
  2483. $(".tabable.menu .item").tab();
  2484. $(".toggle.button").on("click", function () {
  2485. $($(this).data("target")).slideToggle(100);
  2486. });
  2487. // make table <tr> element clickable like a link
  2488. $("tr[data-href]").on("click", function () {
  2489. window.location = $(this).data("href");
  2490. });
  2491. // make table <td> element clickable like a link
  2492. $("td[data-href]").click(function () {
  2493. window.location = $(this).data("href");
  2494. });
  2495. // 在String原型对象上添加format方法
  2496. String.prototype.format = function () {
  2497. let str = this;
  2498. if (arguments.length == 0) {
  2499. return str;
  2500. } else {
  2501. Object.keys(arguments).forEach((item, index) => {
  2502. str = str.replace(/\?/, arguments[item]);
  2503. });
  2504. return str;
  2505. }
  2506. };
  2507. // Dropzone
  2508. const $dropzone = $("#dropzone");
  2509. if ($dropzone.length > 0) {
  2510. const filenameDict = {};
  2511. let maxFileTooltips;
  2512. let maxSizeTooltips;
  2513. if (
  2514. $dropzone.data("max-file-tooltips") &&
  2515. $dropzone.data("max-size-tooltips")
  2516. ) {
  2517. maxFileTooltips = $dropzone
  2518. .data("max-file-tooltips")
  2519. .format($dropzone.data("max-file"), $dropzone.data("max-size"));
  2520. maxSizeTooltips = $dropzone
  2521. .data("max-size-tooltips")
  2522. .format($dropzone.data("max-file"));
  2523. }
  2524. await createDropzone("#dropzone", {
  2525. url: $dropzone.data("upload-url"),
  2526. headers: { "X-Csrf-Token": csrf },
  2527. maxFiles: $dropzone.data("max-file"),
  2528. maxFilesize: $dropzone.data("max-size"),
  2529. acceptedFiles:
  2530. $dropzone.data("accepts") === "*/*" ? null : $dropzone.data("accepts"),
  2531. addRemoveLinks: true,
  2532. dictDefaultMessage: $dropzone.data("default-message"),
  2533. dictInvalidFileType: $dropzone.data("invalid-input-type"),
  2534. dictFileTooBig: $dropzone.data("file-too-big"),
  2535. dictRemoveFile: $dropzone.data("remove-file"),
  2536. init() {
  2537. this.on("success", (file, data) => {
  2538. filenameDict[file.name] = data.uuid;
  2539. const input = $(
  2540. `<input id="${data.uuid}" name="files" type="hidden">`
  2541. ).val(data.uuid);
  2542. $(".files").append(input);
  2543. });
  2544. this.on("removedfile", (file) => {
  2545. if (file.name in filenameDict) {
  2546. $(`#${filenameDict[file.name]}`).remove();
  2547. }
  2548. if ($dropzone.data("remove-url") && $dropzone.data("csrf")) {
  2549. $.post($dropzone.data("remove-url"), {
  2550. file: filenameDict[file.name],
  2551. _csrf: $dropzone.data("csrf"),
  2552. });
  2553. }
  2554. });
  2555. this.on("addedfile", (file) => {
  2556. if (file.size / (1000 * 1000) > $dropzone.data("max-size")) {
  2557. this.removeFile(file);
  2558. if (maxFileTooltips) {
  2559. $(".maxfilesize.ui.red.message").text(maxFileTooltips);
  2560. $(".maxfilesize.ui.red.message").css("display", "block");
  2561. }
  2562. } else {
  2563. if (maxFileTooltips) {
  2564. $(".maxfilesize.ui.red.message").css("display", "none");
  2565. }
  2566. }
  2567. });
  2568. this.on("maxfilesexceeded", (file) => {
  2569. this.removeFile(file);
  2570. if (maxSizeTooltips) {
  2571. $(".maxfilesize.ui.red.message").text(maxSizeTooltips);
  2572. $(".maxfilesize.ui.red.message").css("display", "block");
  2573. }
  2574. });
  2575. },
  2576. });
  2577. }
  2578. // Helpers.
  2579. $(".delete-button").on("click", showDeletePopup);
  2580. $(".add-all-button").on("click", showAddAllPopup);
  2581. $(".link-action").on("click", linkAction);
  2582. $(".link-email-action").on("click", linkEmailAction);
  2583. $(".delete-branch-button").on("click", showDeletePopup);
  2584. $(".undo-button").on("click", function () {
  2585. const $this = $(this);
  2586. $.post($this.data("url"), {
  2587. _csrf: csrf,
  2588. id: $this.data("id"),
  2589. }).done((data) => {
  2590. window.location.href = data.redirect;
  2591. });
  2592. });
  2593. $(".show-panel.button").on("click", function () {
  2594. $($(this).data("panel")).show();
  2595. });
  2596. $(".show-modal.button").on("click", function () {
  2597. $($(this).data("modal")).modal("show");
  2598. });
  2599. $(".delete-post.button").on("click", function () {
  2600. const $this = $(this);
  2601. $.post($this.data("request-url"), {
  2602. _csrf: csrf,
  2603. }).done(() => {
  2604. window.location.href = $this.data("done-url");
  2605. });
  2606. });
  2607. // Set anchor.
  2608. $(".markdown").each(function () {
  2609. $(this)
  2610. .find("h1, h2, h3, h4, h5, h6")
  2611. .each(function () {
  2612. let node = $(this);
  2613. node = node.wrap('<div class="anchor-wrap"></div>');
  2614. node.append(
  2615. `<a class="anchor" href="#${encodeURIComponent(
  2616. node.attr("id")
  2617. )}">${svg("octicon-link", 16)}</a>`
  2618. );
  2619. });
  2620. });
  2621. $(".issue-checkbox").on("click", () => {
  2622. const numChecked = $(".issue-checkbox").children("input:checked").length;
  2623. if (numChecked > 0) {
  2624. $("#issue-filters").addClass("hide");
  2625. $("#issue-actions").removeClass("hide");
  2626. } else {
  2627. $("#issue-filters").removeClass("hide");
  2628. $("#issue-actions").addClass("hide");
  2629. }
  2630. });
  2631. $(".issue-action").on("click", function () {
  2632. let { action } = this.dataset;
  2633. let { elementId } = this.dataset;
  2634. const issueIDs = $(".issue-checkbox")
  2635. .children("input:checked")
  2636. .map(function () {
  2637. return this.dataset.issueId;
  2638. })
  2639. .get()
  2640. .join();
  2641. console.log("this:", this);
  2642. const { url } = this.dataset;
  2643. if (elementId === "0" && url.substr(-9) === "/assignee") {
  2644. elementId = "";
  2645. action = "clear";
  2646. }
  2647. updateIssuesMeta(url, action, issueIDs, elementId, "").then(() => {
  2648. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2649. if (action === "close" || action === "open") {
  2650. // uncheck all checkboxes
  2651. $('.issue-checkbox input[type="checkbox"]').each((_, e) => {
  2652. e.checked = false;
  2653. });
  2654. }
  2655. reload();
  2656. });
  2657. });
  2658. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2659. // trigger ckecked event, if checkboxes are checked on load
  2660. $('.issue-checkbox input[type="checkbox"]:checked')
  2661. .first()
  2662. .each((_, e) => {
  2663. e.checked = false;
  2664. $(e).trigger("click");
  2665. });
  2666. $(".resolve-conversation").on("click", function (e) {
  2667. e.preventDefault();
  2668. const id = $(this).data("comment-id");
  2669. const action = $(this).data("action");
  2670. const url = $(this).data("update-url");
  2671. $.post(url, {
  2672. _csrf: csrf,
  2673. action,
  2674. comment_id: id,
  2675. }).then(reload);
  2676. });
  2677. buttonsClickOnEnter();
  2678. searchUsers();
  2679. searchTeams();
  2680. searchRepositories();
  2681. initCommentForm();
  2682. initInstall();
  2683. initRepository();
  2684. initMigration();
  2685. initWikiForm();
  2686. initEditForm();
  2687. initEditor();
  2688. initOrganization();
  2689. initGithook();
  2690. initWebhook();
  2691. initAdmin();
  2692. initCodeView();
  2693. initVueApp();
  2694. initVueUploader();
  2695. initVueDataset();
  2696. initVueEditAbout();
  2697. initVueEditTopic();
  2698. initVueContributors();
  2699. // initVueImages();
  2700. initVueModel();
  2701. initVueDataAnalysis();
  2702. initVueWxAutorize();
  2703. initVueselectDataset();
  2704. initTeamSettings();
  2705. initCtrlEnterSubmit();
  2706. initNavbarContentToggle();
  2707. // initTopicbar();vim
  2708. // closeTopicbar();
  2709. initU2FAuth();
  2710. initU2FRegister();
  2711. initIssueList();
  2712. initWipTitle();
  2713. initPullRequestReview();
  2714. initRepoStatusChecker();
  2715. initTemplateSearch();
  2716. initContextPopups();
  2717. initNotificationsTable();
  2718. initNotificationCount();
  2719. initTribute();
  2720. initDropDown();
  2721. initCloudrain();
  2722. initCloudrainSow();
  2723. initImage();
  2724. initContextMenu();
  2725. // Repo clone url.
  2726. if ($("#repo-clone-url").length > 0) {
  2727. switch (localStorage.getItem("repo-clone-protocol")) {
  2728. case "ssh":
  2729. if ($("#repo-clone-ssh").length === 0) {
  2730. $("#repo-clone-https").trigger("click");
  2731. }
  2732. break;
  2733. default:
  2734. $("#repo-clone-https").trigger("click");
  2735. break;
  2736. }
  2737. }
  2738. const routes = {
  2739. "div.user.settings": initUserSettings,
  2740. "div.repository.settings.collaboration": initRepositoryCollaboration,
  2741. };
  2742. let selector;
  2743. for (selector in routes) {
  2744. if ($(selector).length > 0) {
  2745. routes[selector]();
  2746. break;
  2747. }
  2748. }
  2749. const $cloneAddr = $("#clone_addr");
  2750. $cloneAddr.on("input change", () => {
  2751. const $repoName = $("#alias");
  2752. const $owner = $("#ownerDropdown div.text").attr("title");
  2753. const $urlAdd =
  2754. location.href.split("/")[0] + "//" + location.href.split("/")[2];
  2755. if ($cloneAddr.val().length > 0 /* && $repoName.val().length === 0 */) {
  2756. // modify when clone address change
  2757. const repoValue = $cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3];
  2758. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  2759. $.get(
  2760. `${window.config.AppSubUrl}/repo/check_name?q=${repoValue}&owner=${$owner}`,
  2761. (data) => {
  2762. const repo_name = data.name;
  2763. $("#repo_name").val(repo_name);
  2764. repo_name && $("#repo_name").parent().removeClass("error");
  2765. $("#repoAdress").css("display", "flex");
  2766. $("#repoAdress span").text(
  2767. $urlAdd + "/" + $owner + "/" + $("#repo_name").val() + ".git"
  2768. );
  2769. $("#repo_name").attr("placeholder", "");
  2770. }
  2771. );
  2772. }
  2773. });
  2774. // parallel init of lazy-loaded features
  2775. await Promise.all([
  2776. highlight(document.querySelectorAll("pre code")),
  2777. initGitGraph(),
  2778. initClipboard(),
  2779. initUserHeatmap(),
  2780. ]);
  2781. });
  2782. function changeHash(hash) {
  2783. if (window.history.pushState) {
  2784. window.history.pushState(null, null, hash);
  2785. } else {
  2786. window.location.hash = hash;
  2787. }
  2788. }
  2789. function deSelect() {
  2790. if (window.getSelection) {
  2791. window.getSelection().removeAllRanges();
  2792. } else {
  2793. document.selection.empty();
  2794. }
  2795. }
  2796. function selectRange($list, $select, $from) {
  2797. $list.removeClass("active");
  2798. if ($from) {
  2799. let a = parseInt($select.attr("rel").substr(1));
  2800. let b = parseInt($from.attr("rel").substr(1));
  2801. let c;
  2802. if (a !== b) {
  2803. if (a > b) {
  2804. c = a;
  2805. a = b;
  2806. b = c;
  2807. }
  2808. const classes = [];
  2809. for (let i = a; i <= b; i++) {
  2810. classes.push(`.L${i}`);
  2811. }
  2812. $list.filter(classes.join(",")).addClass("active");
  2813. changeHash(`#L${a}-L${b}`);
  2814. return;
  2815. }
  2816. }
  2817. $select.addClass("active");
  2818. changeHash(`#${$select.attr("rel")}`);
  2819. }
  2820. $(() => {
  2821. // Warn users that try to leave a page after entering data into a form.
  2822. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2823. if ($(".user.signin").length === 0) {
  2824. $("form:not(.ignore-dirty)").areYouSure();
  2825. }
  2826. // Parse SSH Key
  2827. $("#ssh-key-content").on("change paste keyup", function () {
  2828. const arrays = $(this).val().split(" ");
  2829. const $title = $("#ssh-key-title");
  2830. if ($title.val() === "" && arrays.length === 3 && arrays[2] !== "") {
  2831. $title.val(arrays[2]);
  2832. }
  2833. });
  2834. });
  2835. function showDeletePopup() {
  2836. const $this = $(this);
  2837. let filter = "";
  2838. if ($this.attr("id")) {
  2839. filter += `#${$this.attr("id")}`;
  2840. }
  2841. const dialog = $(`.delete.modal${filter}`);
  2842. dialog.find(".name").text($this.data("name"));
  2843. dialog
  2844. .modal({
  2845. closable: false,
  2846. onApprove() {
  2847. if ($this.data("type") === "form") {
  2848. $($this.data("form")).trigger("submit");
  2849. return;
  2850. }
  2851. $.post($this.data("url"), {
  2852. _csrf: csrf,
  2853. id: $this.data("id"),
  2854. }).done((data) => {
  2855. window.location.href = data.redirect;
  2856. });
  2857. },
  2858. })
  2859. .modal("show");
  2860. return false;
  2861. }
  2862. function showAddAllPopup() {
  2863. const $this = $(this);
  2864. let filter = "";
  2865. if ($this.attr("id")) {
  2866. filter += `#${$this.attr("id")}`;
  2867. }
  2868. const dialog = $(`.addall.modal${filter}`);
  2869. dialog.find(".name").text($this.data("name"));
  2870. dialog
  2871. .modal({
  2872. closable: false,
  2873. onApprove() {
  2874. if ($this.data("type") === "form") {
  2875. $($this.data("form")).trigger("submit");
  2876. return;
  2877. }
  2878. $.post($this.data("url"), {
  2879. _csrf: csrf,
  2880. id: $this.data("id"),
  2881. }).done((data) => {
  2882. window.location.href = data.redirect;
  2883. });
  2884. },
  2885. })
  2886. .modal("show");
  2887. return false;
  2888. }
  2889. function linkAction(e) {
  2890. e.preventDefault();
  2891. const $this = $(this);
  2892. const redirect = $this.data("redirect");
  2893. $.post($this.data("url"), {
  2894. _csrf: csrf,
  2895. }).done((data) => {
  2896. if (data.redirect) {
  2897. window.location.href = data.redirect;
  2898. } else if (redirect) {
  2899. window.location.href = redirect;
  2900. } else {
  2901. window.location.reload();
  2902. }
  2903. });
  2904. }
  2905. function linkEmailAction(e) {
  2906. const $this = $(this);
  2907. $("#form-uid").val($this.data("uid"));
  2908. $("#form-email").val($this.data("email"));
  2909. $("#form-primary").val($this.data("primary"));
  2910. $("#form-activate").val($this.data("activate"));
  2911. $("#form-uid").val($this.data("uid"));
  2912. $("#change-email-modal").modal("show");
  2913. e.preventDefault();
  2914. }
  2915. function initVueComponents() {
  2916. const vueDelimeters = ["${", "}"];
  2917. Vue.component("repo-search", {
  2918. delimiters: vueDelimeters,
  2919. props: {
  2920. searchLimit: {
  2921. type: Number,
  2922. default: 10,
  2923. },
  2924. suburl: {
  2925. type: String,
  2926. required: true,
  2927. },
  2928. uid: {
  2929. type: Number,
  2930. required: true,
  2931. },
  2932. organizations: {
  2933. type: Array,
  2934. default: [],
  2935. },
  2936. isOrganization: {
  2937. type: Boolean,
  2938. default: true,
  2939. },
  2940. canCreateOrganization: {
  2941. type: Boolean,
  2942. default: false,
  2943. },
  2944. organizationsTotalCount: {
  2945. type: Number,
  2946. default: 0,
  2947. },
  2948. moreReposLink: {
  2949. type: String,
  2950. default: "",
  2951. },
  2952. },
  2953. data() {
  2954. const params = new URLSearchParams(window.location.search);
  2955. let tab = params.get("repo-search-tab");
  2956. if (!tab) {
  2957. tab = "repos";
  2958. }
  2959. let reposFilter = params.get("repo-search-filter");
  2960. if (!reposFilter) {
  2961. reposFilter = "all";
  2962. }
  2963. let privateFilter = params.get("repo-search-private");
  2964. if (!privateFilter) {
  2965. privateFilter = "both";
  2966. }
  2967. let archivedFilter = params.get("repo-search-archived");
  2968. if (!archivedFilter) {
  2969. archivedFilter = "unarchived";
  2970. }
  2971. let searchQuery = params.get("repo-search-query");
  2972. if (!searchQuery) {
  2973. searchQuery = "";
  2974. }
  2975. let page = 1;
  2976. try {
  2977. page = parseInt(params.get("repo-search-page"));
  2978. } catch {
  2979. // noop
  2980. }
  2981. if (!page) {
  2982. page = 1;
  2983. }
  2984. return {
  2985. tab,
  2986. repos: [],
  2987. reposTotalCount: 0,
  2988. reposFilter,
  2989. archivedFilter,
  2990. privateFilter,
  2991. page,
  2992. finalPage: 1,
  2993. searchQuery,
  2994. isLoading: false,
  2995. staticPrefix: StaticUrlPrefix,
  2996. counts: {},
  2997. repoTypes: {
  2998. all: {
  2999. searchMode: "",
  3000. },
  3001. forks: {
  3002. searchMode: "fork",
  3003. },
  3004. mirrors: {
  3005. searchMode: "mirror",
  3006. },
  3007. sources: {
  3008. searchMode: "source",
  3009. },
  3010. collaborative: {
  3011. searchMode: "collaborative",
  3012. },
  3013. },
  3014. };
  3015. },
  3016. computed: {
  3017. showMoreReposLink() {
  3018. return (
  3019. this.repos.length > 0 &&
  3020. this.repos.length <
  3021. this.counts[
  3022. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`
  3023. ]
  3024. );
  3025. },
  3026. searchURL() {
  3027. return `${
  3028. this.suburl
  3029. }/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=${
  3030. this.searchQuery
  3031. }&page=${this.page}&limit=${this.searchLimit}&mode=${
  3032. this.repoTypes[this.reposFilter].searchMode
  3033. }${this.reposFilter !== "all" ? "&exclusive=1" : ""}${
  3034. this.archivedFilter === "archived" ? "&archived=true" : ""
  3035. }${this.archivedFilter === "unarchived" ? "&archived=false" : ""}${
  3036. this.privateFilter === "private" ? "&onlyPrivate=true" : ""
  3037. }${this.privateFilter === "public" ? "&private=false" : ""}`;
  3038. },
  3039. repoTypeCount() {
  3040. return this.counts[
  3041. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`
  3042. ];
  3043. },
  3044. },
  3045. mounted() {
  3046. this.searchRepos(this.reposFilter);
  3047. $(this.$el).find(".poping.up").popup();
  3048. $(this.$el).find(".dropdown").dropdown();
  3049. this.setCheckboxes();
  3050. const self = this;
  3051. Vue.nextTick(() => {
  3052. self.$refs.search.focus();
  3053. });
  3054. },
  3055. methods: {
  3056. changeTab(t) {
  3057. this.tab = t;
  3058. this.updateHistory();
  3059. },
  3060. setCheckboxes() {
  3061. switch (this.archivedFilter) {
  3062. case "unarchived":
  3063. $("#archivedFilterCheckbox").checkbox("set unchecked");
  3064. break;
  3065. case "archived":
  3066. $("#archivedFilterCheckbox").checkbox("set checked");
  3067. break;
  3068. case "both":
  3069. $("#archivedFilterCheckbox").checkbox("set indeterminate");
  3070. break;
  3071. default:
  3072. this.archivedFilter = "unarchived";
  3073. $("#archivedFilterCheckbox").checkbox("set unchecked");
  3074. break;
  3075. }
  3076. switch (this.privateFilter) {
  3077. case "public":
  3078. $("#privateFilterCheckbox").checkbox("set unchecked");
  3079. break;
  3080. case "private":
  3081. $("#privateFilterCheckbox").checkbox("set checked");
  3082. break;
  3083. case "both":
  3084. $("#privateFilterCheckbox").checkbox("set indeterminate");
  3085. break;
  3086. default:
  3087. this.privateFilter = "both";
  3088. $("#privateFilterCheckbox").checkbox("set indeterminate");
  3089. break;
  3090. }
  3091. },
  3092. changeReposFilter(filter) {
  3093. this.reposFilter = filter;
  3094. this.repos = [];
  3095. this.page = 1;
  3096. Vue.set(
  3097. this.counts,
  3098. `${filter}:${this.archivedFilter}:${this.privateFilter}`,
  3099. 0
  3100. );
  3101. this.searchRepos();
  3102. },
  3103. updateHistory() {
  3104. const params = new URLSearchParams(window.location.search);
  3105. if (this.tab === "repos") {
  3106. params.delete("repo-search-tab");
  3107. } else {
  3108. params.set("repo-search-tab", this.tab);
  3109. }
  3110. if (this.reposFilter === "all") {
  3111. params.delete("repo-search-filter");
  3112. } else {
  3113. params.set("repo-search-filter", this.reposFilter);
  3114. }
  3115. if (this.privateFilter === "both") {
  3116. params.delete("repo-search-private");
  3117. } else {
  3118. params.set("repo-search-private", this.privateFilter);
  3119. }
  3120. if (this.archivedFilter === "unarchived") {
  3121. params.delete("repo-search-archived");
  3122. } else {
  3123. params.set("repo-search-archived", this.archivedFilter);
  3124. }
  3125. if (this.searchQuery === "") {
  3126. params.delete("repo-search-query");
  3127. } else {
  3128. params.set("repo-search-query", this.searchQuery);
  3129. }
  3130. if (this.page === 1) {
  3131. params.delete("repo-search-page");
  3132. } else {
  3133. params.set("repo-search-page", `${this.page}`);
  3134. }
  3135. window.history.replaceState({}, "", `?${params.toString()}`);
  3136. },
  3137. toggleArchivedFilter() {
  3138. switch (this.archivedFilter) {
  3139. case "both":
  3140. this.archivedFilter = "unarchived";
  3141. break;
  3142. case "unarchived":
  3143. this.archivedFilter = "archived";
  3144. break;
  3145. case "archived":
  3146. this.archivedFilter = "both";
  3147. break;
  3148. default:
  3149. this.archivedFilter = "unarchived";
  3150. break;
  3151. }
  3152. this.page = 1;
  3153. this.repos = [];
  3154. this.setCheckboxes();
  3155. Vue.set(
  3156. this.counts,
  3157. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`,
  3158. 0
  3159. );
  3160. this.searchRepos();
  3161. },
  3162. togglePrivateFilter() {
  3163. switch (this.privateFilter) {
  3164. case "both":
  3165. this.privateFilter = "public";
  3166. break;
  3167. case "public":
  3168. this.privateFilter = "private";
  3169. break;
  3170. case "private":
  3171. this.privateFilter = "both";
  3172. break;
  3173. default:
  3174. this.privateFilter = "both";
  3175. break;
  3176. }
  3177. this.page = 1;
  3178. this.repos = [];
  3179. this.setCheckboxes();
  3180. Vue.set(
  3181. this.counts,
  3182. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`,
  3183. 0
  3184. );
  3185. this.searchRepos();
  3186. },
  3187. changePage(page) {
  3188. this.page = page;
  3189. if (this.page > this.finalPage) {
  3190. this.page = this.finalPage;
  3191. }
  3192. if (this.page < 1) {
  3193. this.page = 1;
  3194. }
  3195. this.repos = [];
  3196. Vue.set(
  3197. this.counts,
  3198. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`,
  3199. 0
  3200. );
  3201. this.searchRepos();
  3202. },
  3203. showArchivedRepo(repo) {
  3204. switch (this.archivedFilter) {
  3205. case "both":
  3206. return true;
  3207. case "unarchived":
  3208. return !repo.archived;
  3209. case "archived":
  3210. return repo.archived;
  3211. default:
  3212. return !repo.archived;
  3213. }
  3214. },
  3215. showPrivateRepo(repo) {
  3216. switch (this.privateFilter) {
  3217. case "both":
  3218. return true;
  3219. case "public":
  3220. return !repo.private;
  3221. case "private":
  3222. return repo.private;
  3223. default:
  3224. return true;
  3225. }
  3226. },
  3227. showFilteredRepo(repo) {
  3228. switch (this.reposFilter) {
  3229. case "sources":
  3230. return repo.owner.id === this.uid && !repo.mirror && !repo.fork;
  3231. case "forks":
  3232. return repo.owner.id === this.uid && !repo.mirror && repo.fork;
  3233. case "mirrors":
  3234. return repo.mirror;
  3235. case "collaborative":
  3236. return repo.owner.id !== this.uid && !repo.mirror;
  3237. default:
  3238. return true;
  3239. }
  3240. },
  3241. showRepo(repo) {
  3242. return (
  3243. this.showArchivedRepo(repo) &&
  3244. this.showPrivateRepo(repo) &&
  3245. this.showFilteredRepo(repo)
  3246. );
  3247. },
  3248. searchRepos() {
  3249. const self = this;
  3250. this.isLoading = true;
  3251. const searchedMode = this.repoTypes[this.reposFilter].searchMode;
  3252. const searchedURL = this.searchURL;
  3253. const searchedQuery = this.searchQuery;
  3254. $.getJSON(searchedURL, (result, _textStatus, request) => {
  3255. if (searchedURL === self.searchURL) {
  3256. self.repos = result.data;
  3257. const count = request.getResponseHeader("X-Total-Count");
  3258. if (
  3259. searchedQuery === "" &&
  3260. searchedMode === "" &&
  3261. self.archivedFilter === "both"
  3262. ) {
  3263. self.reposTotalCount = count;
  3264. }
  3265. Vue.set(
  3266. self.counts,
  3267. `${self.reposFilter}:${self.archivedFilter}:${self.privateFilter}`,
  3268. count
  3269. );
  3270. self.finalPage = Math.floor(count / self.searchLimit) + 1;
  3271. self.updateHistory();
  3272. }
  3273. }).always(() => {
  3274. if (searchedURL === self.searchURL) {
  3275. self.isLoading = false;
  3276. }
  3277. });
  3278. },
  3279. repoClass(repo) {
  3280. if (repo.fork) {
  3281. return "octicon-repo-forked";
  3282. }
  3283. if (repo.mirror) {
  3284. return "octicon-repo-clone";
  3285. }
  3286. if (repo.template) {
  3287. return `octicon-repo-template${repo.private ? "-private" : ""}`;
  3288. }
  3289. if (repo.private) {
  3290. return "octicon-lock";
  3291. }
  3292. return "octicon-repo";
  3293. },
  3294. },
  3295. });
  3296. }
  3297. function initCtrlEnterSubmit() {
  3298. $(".js-quick-submit").on("keydown", function (e) {
  3299. if (
  3300. ((e.ctrlKey && !e.altKey) || e.metaKey) &&
  3301. (e.keyCode === 13 || e.keyCode === 10)
  3302. ) {
  3303. $(this).closest("form").trigger("submit");
  3304. }
  3305. });
  3306. }
  3307. function initVueApp() {
  3308. const el = document.getElementById("app");
  3309. if (!el) {
  3310. return;
  3311. }
  3312. initVueComponents();
  3313. new Vue({
  3314. delimiters: ["${", "}"],
  3315. el,
  3316. data: {
  3317. page: parseInt(new URLSearchParams(window.location.search).get("page")),
  3318. searchLimit: Number(
  3319. (document.querySelector("meta[name=_search_limit]") || {}).content
  3320. ),
  3321. page: 1,
  3322. suburl: AppSubUrl,
  3323. uid: Number(
  3324. (document.querySelector("meta[name=_context_uid]") || {}).content
  3325. ),
  3326. activityTopAuthors: window.ActivityTopAuthors || [],
  3327. localHref: "",
  3328. },
  3329. components: {
  3330. ActivityTopAuthors,
  3331. },
  3332. mounted() {
  3333. this.page = parseInt(
  3334. new URLSearchParams(window.location.search).get("page")
  3335. );
  3336. this.localHref = location.href;
  3337. },
  3338. methods: {
  3339. handleCurrentChange: function (val) {
  3340. const searchParams = new URLSearchParams(window.location.search);
  3341. if (!window.location.search) {
  3342. window.location.href = this.localHref + "?page=" + val;
  3343. } else if (searchParams.has("page")) {
  3344. window.location.href = this.localHref.replace(
  3345. /page=[0-9]+/g,
  3346. "page=" + val
  3347. );
  3348. } else {
  3349. window.location.href = location.href + "&page=" + val;
  3350. }
  3351. this.page = val;
  3352. },
  3353. },
  3354. });
  3355. }
  3356. function initVueUploader() {
  3357. const el = document.getElementById("minioUploader");
  3358. if (!el) {
  3359. return;
  3360. }
  3361. new Vue({
  3362. el: "#minioUploader",
  3363. components: { MinioUploader },
  3364. template: "<MinioUploader />",
  3365. });
  3366. }
  3367. function initVueEditAbout() {
  3368. const el = document.getElementById("about-desc");
  3369. if (!el) {
  3370. return;
  3371. }
  3372. new Vue({
  3373. el: "#about-desc",
  3374. render: (h) => h(EditAboutInfo),
  3375. });
  3376. }
  3377. function initVueDataset() {
  3378. if ($("#dataset_check").length) {
  3379. if (location.search.indexOf("recommend=true") !== -1) {
  3380. $("#dataset_check").checkbox("set checked");
  3381. } else {
  3382. $("#dataset_check").checkbox("set unchecked");
  3383. }
  3384. $("#dataset_check").checkbox({
  3385. onChecked: function () {
  3386. if (location.search) {
  3387. const params = new URLSearchParams(location.search);
  3388. if (params.has("recommend")) {
  3389. params.delete("recommend");
  3390. location.href =
  3391. AppSubUrl +
  3392. location.pathname +
  3393. "?" +
  3394. params.toString() +
  3395. "&recommend=true";
  3396. } else {
  3397. location.href = `${window.config.AppSubUrl}/admin/datasets${location.search}&recommend=true`;
  3398. }
  3399. } else {
  3400. location.href = `${window.config.AppSubUrl}/admin/datasets?recommend=true`;
  3401. }
  3402. },
  3403. onUnchecked: function () {
  3404. if (location.search == "?recommend=true") {
  3405. location.href = AppSubUrl + location.pathname;
  3406. } else {
  3407. const params = new URLSearchParams(location.search);
  3408. params.delete("recommend");
  3409. location.href =
  3410. AppSubUrl + location.pathname + "?" + params.toString();
  3411. }
  3412. },
  3413. });
  3414. }
  3415. $(".set_dataset").on("click", function () {
  3416. const $this = $(this);
  3417. let link = $this.data("url");
  3418. $.ajax({
  3419. url: link,
  3420. type: "PUT",
  3421. success: function (res) {
  3422. console.log(res);
  3423. if (res.Code == 0) {
  3424. window.location.href = "/admin/datasets";
  3425. } else {
  3426. $(".ui.negative.message")
  3427. .text(res.Message)
  3428. .show()
  3429. .delay(1500)
  3430. .fadeOut();
  3431. }
  3432. },
  3433. error: function (xhr) {
  3434. // 隐藏 loading
  3435. // 只有请求不正常(状态码不为200)才会执行
  3436. $(".ui.negative.message")
  3437. .html(xhr.responseText)
  3438. .show()
  3439. .delay(1500)
  3440. .fadeOut();
  3441. console.log(xhr);
  3442. },
  3443. complete: function (xhr) {
  3444. // $("#mask").css({"display":"none","z-index":"1"})
  3445. },
  3446. });
  3447. });
  3448. const el = document.getElementById("dataset-base");
  3449. if (!el) {
  3450. return;
  3451. }
  3452. let link = $("#square-link").data("link");
  3453. let repolink = $(".dataset-repolink").data("repolink");
  3454. let datasetType = $(".dataset-repolink").data("dataset-type");
  3455. const clearBtn = document.getElementsByClassName("clear_dataset_value");
  3456. const params = new URLSearchParams(location.search);
  3457. for (let i = 0; i < clearBtn.length; i++) {
  3458. clearBtn[i].addEventListener("click", function (e) {
  3459. let searchType = e.target.getAttribute("data-clear-value");
  3460. if (params.has(searchType)) {
  3461. params.delete(searchType);
  3462. let clearSearch = params.toString();
  3463. location.href = link + "?" + clearSearch;
  3464. }
  3465. });
  3466. }
  3467. const items = [];
  3468. const zipStatus = [];
  3469. $("#dataset-range-value")
  3470. .find(".item")
  3471. .each(function () {
  3472. items.push($(this).data("private"));
  3473. zipStatus.push($(this).data("decompress-state"));
  3474. });
  3475. let num_stars = $("#dataset-range-value").data("num-stars");
  3476. let star_active = $("#dataset-range-value").data("star-active");
  3477. const ruleForm = {};
  3478. if (document.getElementById("dataset-edit-value")) {
  3479. let $this = $("#dataset-edit-value");
  3480. ruleForm.title = $this.data("edit-title") || "";
  3481. ruleForm.description = $this.data("edit-description") || "";
  3482. ruleForm.category = $this.data("edit-category") || "";
  3483. ruleForm.task = $this.data("edit-task") || "";
  3484. ruleForm.license = $this.data("edit-license") || "";
  3485. ruleForm.id = $this.data("edit-id") || "";
  3486. ruleForm._csrf = csrf;
  3487. }
  3488. const starItems = [];
  3489. const starActives = [];
  3490. $("#datasets-square-range-value")
  3491. .find(".item")
  3492. .each(function () {
  3493. starItems.push($(this).data("num-stars"));
  3494. starActives.push($(this).data("star-active"));
  3495. });
  3496. const taskLists = [];
  3497. const licenseLists = [];
  3498. $("#task-square-range-value")
  3499. .find(".item")
  3500. .each(function () {
  3501. taskLists.push($(this).data("task"));
  3502. });
  3503. $("#task-square-range-value")
  3504. .find(".item")
  3505. .each(function () {
  3506. licenseLists.push($(this).data("license"));
  3507. });
  3508. let dataset_file_desc;
  3509. if (document.getElementById("dataset-file-desc")) {
  3510. dataset_file_desc = document.getElementById("dataset-file-desc").value;
  3511. }
  3512. new Vue({
  3513. delimiters: ["${", "}"],
  3514. el,
  3515. data: {
  3516. suburl: AppSubUrl,
  3517. url: "",
  3518. checked: false,
  3519. clusterFlag: false,
  3520. type: 0,
  3521. desc: "",
  3522. descfile: "",
  3523. datasetType: "",
  3524. privates: [],
  3525. zipStatus: [],
  3526. starItems: [],
  3527. starActives: [],
  3528. taskLists: [],
  3529. taskShow: [],
  3530. licenseLists: [],
  3531. licenseShow: [],
  3532. hasMoreBthHis: false,
  3533. showMoreHis: false,
  3534. star_active: false,
  3535. num_stars: 0,
  3536. dialogVisible: false,
  3537. activeName: "first",
  3538. searchDataItem: "",
  3539. currentRepoDataset: [],
  3540. myDataset: [],
  3541. publicDataset: [],
  3542. myFavoriteDataset: [],
  3543. page: 1,
  3544. totalnums: 0,
  3545. repolink: "",
  3546. datasetType: 0,
  3547. dataset_uuid: "",
  3548. dataset_name: "",
  3549. loadingDataIndex: false,
  3550. timer: null,
  3551. ruleForm: {
  3552. title: "",
  3553. description: "",
  3554. category: "",
  3555. task: "",
  3556. license: "",
  3557. _csrf: csrf,
  3558. },
  3559. ruleForm1: {
  3560. title: "",
  3561. description: "",
  3562. category: "",
  3563. task: "",
  3564. license: "",
  3565. _csrf: "",
  3566. id: "",
  3567. },
  3568. rules: {
  3569. title: [
  3570. { required: true, message: "请输入数据集名称", trigger: "blur" },
  3571. {
  3572. min: 1,
  3573. max: 100,
  3574. message: "长度在 1 到 100 个字符",
  3575. trigger: "blur",
  3576. },
  3577. // {required:true,message:'test',pattern:'/^[a-zA-Z0-9-_]{1,100}[^-]$/',trigger:'blur'},
  3578. {
  3579. validator: (rule, value, callback) => {
  3580. if (/^[a-zA-Z0-9-_.]{0,100}$/.test(value) == false) {
  3581. callback(new Error("输入不符合数据集名称规则"));
  3582. } else {
  3583. callback();
  3584. }
  3585. },
  3586. trigger: "blur",
  3587. },
  3588. ],
  3589. description: [
  3590. { required: true, message: "请输入数据集描述详情", trigger: "blur" },
  3591. ],
  3592. category: [
  3593. { required: true, message: "请选择分类", trigger: "change" },
  3594. ],
  3595. task: [
  3596. {
  3597. required: true,
  3598. message: "请选择研究方向/应用领域",
  3599. trigger: "change",
  3600. },
  3601. ],
  3602. // license: [
  3603. // { required: true, message: '请选择活动区域', trigger: 'change' }
  3604. // ]
  3605. },
  3606. },
  3607. components: {
  3608. MinioUploader,
  3609. },
  3610. mounted() {
  3611. if (document.getElementById("fail_dataset_name")) {
  3612. this.dataset_name = document.getElementById("fail_dataset_name").value;
  3613. this.dataset_uuid = document.getElementById("fail_dataset_uuid").value;
  3614. }
  3615. this.getTypeList();
  3616. if (!!document.getElementById("dataset-repolink-init")) {
  3617. // this.datasetType = location.href.indexOf('cloudbrain') !== -1 ? 0 : 1
  3618. this.datasetType = $("#dataset-repolink-init").data("dataset-type");
  3619. this.getCurrentRepoDataset(this.repolink, this.datasetType);
  3620. }
  3621. const params = new URLSearchParams(location.search);
  3622. if (params.has("recommend") && params.get("recommend") == "true") {
  3623. this.checked = true;
  3624. } else {
  3625. this.checked = false;
  3626. }
  3627. },
  3628. created() {
  3629. if (document.getElementById("postPath")) {
  3630. this.url = document.getElementById("postPath").value;
  3631. }
  3632. this.privates = items;
  3633. this.zipStatus = zipStatus;
  3634. this.num_stars = num_stars;
  3635. this.star_active = star_active;
  3636. this.ruleForm1 = ruleForm;
  3637. // this.getEditInit()
  3638. this.starItems = starItems;
  3639. this.starActives = starActives;
  3640. this.taskLists = taskLists;
  3641. this.licenseLists = licenseLists;
  3642. this.descfile = dataset_file_desc;
  3643. this.repolink = repolink;
  3644. this.datasetType = datasetType;
  3645. },
  3646. methods: {
  3647. copyUrl(url) {
  3648. const cInput = document.createElement("input");
  3649. cInput.value = url;
  3650. document.body.appendChild(cInput);
  3651. cInput.select();
  3652. document.execCommand("Copy");
  3653. cInput.remove();
  3654. $("body").toast({
  3655. message: "复制成功!",
  3656. showProgress: "bottom",
  3657. showIcon: "check circle",
  3658. class: "info",
  3659. position: "top right",
  3660. });
  3661. },
  3662. handleCurrentChange(val) {
  3663. this.page = val;
  3664. switch (this.activeName) {
  3665. case "first":
  3666. this.getCurrentRepoDataset(this.repolink, this.datasetType);
  3667. break;
  3668. case "second":
  3669. this.getMyDataset(this.repolink, this.datasetType);
  3670. break;
  3671. case "third":
  3672. this.getPublicDataset(this.repolink, this.datasetType);
  3673. break;
  3674. case "fourth":
  3675. this.getStarDataset(this.repolink, this.datasetType);
  3676. break;
  3677. }
  3678. },
  3679. handleCheckedChange(val) {
  3680. if (val) {
  3681. if (location.search) {
  3682. const params = new URLSearchParams(location.search);
  3683. if (params.has("recommend")) {
  3684. params.delete("recommend");
  3685. let search = params.toString();
  3686. location.href = `${AppSubUrl}/explore/datasets?${search}&recommend=${val}`;
  3687. } else {
  3688. location.href = `${AppSubUrl}/explore/datasets${location.search}&recommend=${val}`;
  3689. }
  3690. } else {
  3691. location.href = `${AppSubUrl}/explore/datasets?recommend=${val}`;
  3692. }
  3693. } else {
  3694. if (location.search == "?recommend=true") {
  3695. location.href = AppSubUrl + location.pathname;
  3696. } else {
  3697. const params = new URLSearchParams(location.search);
  3698. params.delete("recommend");
  3699. location.href =
  3700. AppSubUrl + location.pathname + "?" + params.toString();
  3701. }
  3702. }
  3703. },
  3704. createDataset(formName) {
  3705. let _this = this;
  3706. this.$refs[formName].validate((valid) => {
  3707. if (valid) {
  3708. document.getElementById("mask").style.display = "block";
  3709. _this.$axios
  3710. .post(_this.url, _this.qs.stringify(_this.ruleForm))
  3711. .then((res) => {
  3712. if (res.data.Code === 0) {
  3713. document.getElementById("mask").style.display = "none";
  3714. location.href = _this.url.split("/create")[0] + "?type=-1";
  3715. } else {
  3716. console.log(res.data.Message);
  3717. }
  3718. document.getElementById("mask").style.display = "none";
  3719. })
  3720. .catch((error) => {
  3721. console.log(error);
  3722. });
  3723. } else {
  3724. return false;
  3725. }
  3726. });
  3727. },
  3728. cancelDataset(getpage, attachment) {
  3729. if (getpage && !attachment) {
  3730. if (getpage === "create") {
  3731. location.href = this.url.split("/create")[0] + "?type=-1";
  3732. } else if (getpage === "edit") {
  3733. location.href = this.url.split("/edit")[0] + "?type=-1";
  3734. } else {
  3735. location.href = "/";
  3736. }
  3737. } else {
  3738. location.href = `${AppSubUrl}${attachment}/datasets`;
  3739. }
  3740. },
  3741. gotoUpload(repolink, datsetId) {
  3742. // location.href = `${AppSubUrl}${repolink}/datasets/attachments/upload?datasetId=${datsetId}`
  3743. window.open(
  3744. `${AppSubUrl}${repolink}/datasets/attachments/upload?datasetId=${datsetId}`,
  3745. "_blank"
  3746. );
  3747. },
  3748. gotoDataset(datsetUrl) {
  3749. location.href = datsetUrl;
  3750. },
  3751. gotoAnnotate(repolink, uuid, type) {
  3752. location.href = `${AppSubUrl}${repolink}/datasets/label/${uuid}?type=${type}`;
  3753. },
  3754. setcluster(val) {
  3755. this.clusterFlag = val;
  3756. },
  3757. uploadGpu() {
  3758. this.type = 0;
  3759. },
  3760. uploadNpu() {
  3761. this.type = 1;
  3762. },
  3763. sortAble(dom) {
  3764. const params = new URLSearchParams(location.search);
  3765. if (params.toString() === "") {
  3766. location.href = `${location.href}?sort=${dom}Asc`;
  3767. } else if (!params.get("sort")) {
  3768. location.href = `${location.href}&sort=${dom}Asc`;
  3769. } else if (
  3770. params.get("sort") === `${dom}Desc` ||
  3771. params.get("sort").indexOf(`${dom}`) === -1
  3772. ) {
  3773. params.set("sort", `${dom}Asc`);
  3774. let asc = params.toString();
  3775. location.search = asc;
  3776. } else {
  3777. params.set("sort", `${dom}Desc`);
  3778. let desc = params.toString();
  3779. location.search = desc;
  3780. }
  3781. },
  3782. sortIcon(dom, sort) {
  3783. const params = new URLSearchParams(location.search);
  3784. if (sort === "up") {
  3785. if (params.toString() === "") {
  3786. location.href = `${location.href}?sort=${dom}Asc`;
  3787. } else if (!params.get("sort")) {
  3788. location.href = `${location.href}&sort=${dom}Asc`;
  3789. } else if (
  3790. params.get("sort") &&
  3791. params.get("sort").indexOf(`${dom}Asc`) !== -1
  3792. ) {
  3793. params.delete("sort");
  3794. location.search = params.toString();
  3795. } else {
  3796. params.set("sort", `${dom}Asc`);
  3797. let asc = params.toString();
  3798. location.search = asc;
  3799. }
  3800. } else if (sort === "down") {
  3801. if (params.toString() === "") {
  3802. location.href = `${location.href}?sort=${dom}Desc`;
  3803. } else if (!params.get("sort")) {
  3804. location.href = `${location.href}&sort=${dom}Desc`;
  3805. } else if (
  3806. params.get("sort") &&
  3807. params.get("sort").indexOf(`${dom}Desc`) !== -1
  3808. ) {
  3809. params.delete("sort");
  3810. location.search = params.toString();
  3811. } else {
  3812. params.set("sort", `${dom}Desc`);
  3813. let asc = params.toString();
  3814. location.search = asc;
  3815. }
  3816. }
  3817. },
  3818. setPrivate(uuid, privateFlag, index) {
  3819. const params = { _csrf: csrf, file: uuid, is_private: privateFlag };
  3820. this.$axios
  3821. .post("/attachments/private", this.qs.stringify(params))
  3822. .then((res) => {
  3823. this.$set(this.privates, index, privateFlag);
  3824. })
  3825. .catch((error) => {
  3826. console.log(error);
  3827. });
  3828. },
  3829. delDataset(uuid) {
  3830. let _this = this;
  3831. const params = { _csrf: csrf, file: uuid };
  3832. $("#data-dataset-delete-modal")
  3833. .modal({
  3834. closable: false,
  3835. onApprove() {
  3836. _this.$axios
  3837. .post("/attachments/delete", _this.qs.stringify(params))
  3838. .then((res) => {
  3839. // $('#'+uuid).hide()
  3840. location.reload();
  3841. })
  3842. .catch((error) => {
  3843. console.log(error);
  3844. });
  3845. },
  3846. })
  3847. .modal("show");
  3848. },
  3849. // getEditInit(){
  3850. // if($('#dataset-edit-value')){
  3851. // $this = $('#dataset-edit-value')
  3852. // this.ruleForm.title = $this.data('edit-title') || ''
  3853. // this.ruleForm.description = $this.data('edit-description') || ''
  3854. // this.ruleForm.category = $this.data('edit-category') || ''
  3855. // this.ruleForm.task = $this.data('edit-task') || ''
  3856. // this.ruleForm.license = $this.data('edit-license') || ''
  3857. // this.ruleForm.id = $this.data('edit-id')|| ''
  3858. // }
  3859. // },
  3860. editDataset(formName, id) {
  3861. let _this = this;
  3862. this.url = this.url.split(`/${id}`)[0];
  3863. this.$refs[formName].validate((valid) => {
  3864. if (valid) {
  3865. document.getElementById("mask").style.display = "block";
  3866. _this.$axios
  3867. .post(_this.url, _this.qs.stringify(_this.ruleForm1))
  3868. .then((res) => {
  3869. if (res.data.Code === 0) {
  3870. document.getElementById("mask").style.display = "none";
  3871. location.href = _this.url.split("/edit")[0] + "?type=-1";
  3872. } else {
  3873. console.log(res.data.Message);
  3874. }
  3875. document.getElementById("mask").style.display = "none";
  3876. })
  3877. .catch((err) => {
  3878. console.log(err);
  3879. });
  3880. } else {
  3881. return false;
  3882. }
  3883. });
  3884. },
  3885. editDatasetFile(id, backurl) {
  3886. let url = "/attachments/edit";
  3887. const params = { id: id, description: this.descfile, _csrf: csrf };
  3888. // document.getElementById("mask").style.display = "block"
  3889. this.$axios
  3890. .post(url, this.qs.stringify(params))
  3891. .then((res) => {
  3892. if (res.data.Code === 0) {
  3893. location.href = `${AppSubUrl}${backurl}/datasets`;
  3894. } else {
  3895. console.log(res.data.Message);
  3896. }
  3897. })
  3898. .catch((err) => {
  3899. console.log(err);
  3900. });
  3901. },
  3902. postStar(id, link) {
  3903. if (this.star_active) {
  3904. let url = link + "/" + id + "/unstar";
  3905. this.$axios.put(url).then((res) => {
  3906. if (res.data.Code === 0) {
  3907. this.star_active = false;
  3908. this.num_stars = this.num_stars - 1;
  3909. }
  3910. });
  3911. } else {
  3912. let url = link + "/" + id + "/star";
  3913. this.$axios.put(url).then((res) => {
  3914. if (res.data.Code === 0) {
  3915. this.star_active = true;
  3916. this.num_stars = this.num_stars + 1;
  3917. }
  3918. });
  3919. }
  3920. },
  3921. postSquareStar(id, link, index) {
  3922. if (this.starActives[index]) {
  3923. let url = link + "/" + id + "/unstar";
  3924. this.$axios.put(url).then((res) => {
  3925. if (res.data.Code === 0) {
  3926. this.$set(this.starActives, index, false);
  3927. this.$set(this.starItems, index, this.starItems[index] - 1);
  3928. }
  3929. });
  3930. } else {
  3931. let url = link + "/" + id + "/star";
  3932. this.$axios.put(url).then((res) => {
  3933. if (res.data.Code === 0) {
  3934. this.$set(this.starActives, index, true);
  3935. this.$set(this.starItems, index, this.starItems[index] + 1);
  3936. }
  3937. });
  3938. }
  3939. },
  3940. getTypeList() {
  3941. const params = new URLSearchParams(window.location.search);
  3942. if (window.location.search && params.has("type")) {
  3943. if (params.get("type") == 0) {
  3944. this.datasetType = "0";
  3945. }
  3946. if (params.get("type") == 1) {
  3947. this.datasetType = "1";
  3948. }
  3949. if (params.get("type") == -1) {
  3950. this.datasetType = "-1";
  3951. }
  3952. } else {
  3953. this.datasetType = "-1";
  3954. }
  3955. },
  3956. changeDatasetType(val) {
  3957. const searchParams = new URLSearchParams(window.location.search);
  3958. if (!window.location.search) {
  3959. window.location.href = window.location.href + "?type=" + val;
  3960. } else if (searchParams.has("type")) {
  3961. window.location.href = window.location.href.replace(
  3962. /type=([0-9]|-[0-9])/g,
  3963. "type=" + val
  3964. );
  3965. } else {
  3966. window.location.href = window.location.href + "&type=" + val;
  3967. }
  3968. },
  3969. gotoDatasetEidt(repolink, id) {
  3970. location.href = `${repolink}/datasets/attachments/edit/${id}`;
  3971. },
  3972. handleClick(repoLink, tabName, type) {
  3973. if (tabName == "first") {
  3974. this.page = 1;
  3975. this.searchDataItem = "";
  3976. this.getCurrentRepoDataset(repoLink, type);
  3977. }
  3978. if (tabName == "second") {
  3979. this.page = 1;
  3980. this.searchDataItem = "";
  3981. this.getMyDataset(repoLink, type);
  3982. }
  3983. if (tabName == "third") {
  3984. this.page = 1;
  3985. this.searchDataItem = "";
  3986. this.getPublicDataset(repoLink, type);
  3987. }
  3988. if (tabName == "fourth") {
  3989. this.page = 1;
  3990. this.searchDataItem = "";
  3991. this.getStarDataset(repoLink, type);
  3992. }
  3993. },
  3994. polling(checkStatuDataset, repoLink) {
  3995. this.timer = window.setInterval(() => {
  3996. setTimeout(() => {
  3997. this.getDatasetStatus(checkStatuDataset, repoLink);
  3998. }, 0);
  3999. }, 15000);
  4000. },
  4001. getDatasetStatus(checkStatuDataset, repoLink) {
  4002. const getmap = checkStatuDataset.map((item) => {
  4003. let url = `${AppSubUrl}${repolink}/datasets/status/${item.UUID}`;
  4004. return this.$axios.get(url);
  4005. });
  4006. this.$axios.all(getmap).then((res) => {
  4007. let flag = res.some((item) => {
  4008. return item.data.AttachmentStatus == 1;
  4009. });
  4010. flag && clearInterval(this.timer);
  4011. flag && this.refreshStatusDataset();
  4012. });
  4013. },
  4014. refreshStatusDataset() {
  4015. switch (this.activeName) {
  4016. case "first":
  4017. this.getCurrentRepoDataset(this.repolink, this.datasetType);
  4018. break;
  4019. case "second":
  4020. this.getMyDataset(this.repolink, this.datasetType);
  4021. break;
  4022. case "third":
  4023. this.getPublicDataset(this.repolink, this.datasetType);
  4024. break;
  4025. case "fourth":
  4026. this.getStarDataset(this.repolink, this.datasetType);
  4027. break;
  4028. }
  4029. },
  4030. getCurrentRepoDataset(repoLink, type) {
  4031. clearInterval(this.timer);
  4032. this.loadingDataIndex = true;
  4033. let url = repoLink + "/datasets/current_repo";
  4034. this.$axios
  4035. .get(url, {
  4036. params: {
  4037. type: type,
  4038. page: this.page,
  4039. q: this.searchDataItem,
  4040. },
  4041. })
  4042. .then((res) => {
  4043. if (res.data.result_code == "0") {
  4044. this.currentRepoDataset = JSON.parse(res.data.data);
  4045. const checkStatuDataset = this.currentRepoDataset.filter(
  4046. (item) => item.DecompressState === 2
  4047. );
  4048. if (checkStatuDataset.length > 0) {
  4049. this.polling(checkStatuDataset, repoLink);
  4050. }
  4051. this.totalnums = parseInt(res.data.count);
  4052. } else {
  4053. this.totalnums = 0;
  4054. }
  4055. this.loadingDataIndex = false;
  4056. });
  4057. },
  4058. getMyDataset(repoLink, type) {
  4059. clearInterval(this.timer);
  4060. this.loadingDataIndex = true;
  4061. let url = repoLink + "/datasets/my_datasets";
  4062. this.$axios
  4063. .get(url, {
  4064. params: {
  4065. type: type,
  4066. page: this.page,
  4067. q: this.searchDataItem,
  4068. },
  4069. })
  4070. .then((res) => {
  4071. this.myDataset = JSON.parse(res.data.data);
  4072. const checkStatuDataset = this.myDataset.filter(
  4073. (item) => item.DecompressState === 2
  4074. );
  4075. if (checkStatuDataset.length > 0) {
  4076. this.polling(checkStatuDataset, repoLink);
  4077. }
  4078. this.totalnums = parseInt(res.data.count);
  4079. this.loadingDataIndex = false;
  4080. });
  4081. },
  4082. getPublicDataset(repoLink, type) {
  4083. clearInterval(this.timer);
  4084. this.loadingDataIndex = true;
  4085. let url = repoLink + "/datasets/public_datasets";
  4086. this.$axios
  4087. .get(url, {
  4088. params: {
  4089. type: type,
  4090. page: this.page,
  4091. q: this.searchDataItem,
  4092. },
  4093. })
  4094. .then((res) => {
  4095. this.publicDataset = JSON.parse(res.data.data);
  4096. const checkStatuDataset = this.publicDataset.filter(
  4097. (item) => item.DecompressState === 2
  4098. );
  4099. if (checkStatuDataset.length > 0) {
  4100. this.polling(checkStatuDataset, repoLink);
  4101. }
  4102. this.totalnums = parseInt(res.data.count);
  4103. this.loadingDataIndex = false;
  4104. });
  4105. },
  4106. getStarDataset(repoLink, type) {
  4107. clearInterval(this.timer);
  4108. this.loadingDataIndex = true;
  4109. let url = repoLink + "/datasets/my_favorite";
  4110. this.$axios
  4111. .get(url, {
  4112. params: {
  4113. type: type,
  4114. page: this.page,
  4115. q: this.searchDataItem,
  4116. },
  4117. })
  4118. .then((res) => {
  4119. this.myFavoriteDataset = JSON.parse(res.data.data);
  4120. const checkStatuDataset = this.myFavoriteDataset.filter(
  4121. (item) => item.DecompressState === 2
  4122. );
  4123. if (checkStatuDataset.length > 0) {
  4124. this.polling(checkStatuDataset, repoLink);
  4125. }
  4126. this.totalnums = parseInt(res.data.count);
  4127. this.loadingDataIndex = false;
  4128. });
  4129. },
  4130. selectDataset(uuid, name) {
  4131. this.dataset_uuid = uuid;
  4132. this.dataset_name = name;
  4133. this.dialogVisible = false;
  4134. },
  4135. searchDataset() {
  4136. switch (this.activeName) {
  4137. case "first":
  4138. this.page = 1;
  4139. this.getCurrentRepoDataset(this.repolink, this.datasetType);
  4140. break;
  4141. case "second":
  4142. this.page = 1;
  4143. this.getMyDataset(this.repolink, this.datasetType);
  4144. break;
  4145. case "third":
  4146. this.page = 1;
  4147. this.getPublicDataset(this.repolink, this.datasetType);
  4148. break;
  4149. case "fourth":
  4150. this.page = 1;
  4151. this.getStarDataset(this.repolink, this.datasetType);
  4152. break;
  4153. }
  4154. },
  4155. },
  4156. watch: {
  4157. searchDataItem() {
  4158. switch (this.activeName) {
  4159. case "first":
  4160. this.page = 1;
  4161. this.getCurrentRepoDataset(this.repolink, this.datasetType);
  4162. break;
  4163. case "second":
  4164. this.page = 1;
  4165. this.getMyDataset(this.repolink, this.datasetType);
  4166. break;
  4167. case "third":
  4168. this.page = 1;
  4169. this.getPublicDataset(this.repolink, this.datasetType);
  4170. break;
  4171. case "fourth":
  4172. this.page = 1;
  4173. this.getStarDataset(this.repolink, this.datasetType);
  4174. break;
  4175. }
  4176. },
  4177. },
  4178. });
  4179. }
  4180. function initVueEditTopic() {
  4181. const el = document.getElementById("topic_edit1");
  4182. if (!el) {
  4183. return;
  4184. }
  4185. new Vue({
  4186. el: "#topic_edit1",
  4187. render: (h) => h(EditTopics),
  4188. });
  4189. }
  4190. function initVueContributors() {
  4191. const el = document.getElementById("Contributors");
  4192. if (!el) {
  4193. return;
  4194. }
  4195. new Vue({
  4196. el: "#Contributors",
  4197. render: (h) => h(Contributors),
  4198. });
  4199. }
  4200. // function initVueImages() {
  4201. // const el = document.getElementById('images');
  4202. // if (!el) {
  4203. // return;
  4204. // }
  4205. // new Vue({
  4206. // el: '#images',
  4207. // render: h => h(Images)
  4208. // });
  4209. // }
  4210. function initVueModel() {
  4211. const el = document.getElementById("model_list");
  4212. if (!el) {
  4213. return;
  4214. }
  4215. new Vue({
  4216. el: el,
  4217. render: (h) => h(Model),
  4218. });
  4219. }
  4220. function initVueDataAnalysis() {
  4221. const el = document.getElementById("data_analysis");
  4222. if (!el) {
  4223. return;
  4224. }
  4225. new Vue({
  4226. el: "#data_analysis",
  4227. router,
  4228. render: (h) => h(DataAnalysis),
  4229. });
  4230. }
  4231. function initVueWxAutorize() {
  4232. const el = document.getElementById("WxAutorize");
  4233. if (!el) {
  4234. return;
  4235. }
  4236. new Vue({
  4237. el: el,
  4238. render: (h) => h(WxAutorize),
  4239. });
  4240. }
  4241. function initVueselectDataset() {
  4242. const el = document.getElementById("select-multi-dataset");
  4243. if (!el) {
  4244. return;
  4245. }
  4246. new Vue({
  4247. el: el,
  4248. render: (h) => h(selectDataset),
  4249. });
  4250. }
  4251. window.timeAddManual = function () {
  4252. $(".mini.modal")
  4253. .modal({
  4254. duration: 200,
  4255. onApprove() {
  4256. $("#add_time_manual_form").trigger("submit");
  4257. },
  4258. })
  4259. .modal("show");
  4260. };
  4261. window.toggleStopwatch = function () {
  4262. $("#toggle_stopwatch_form").trigger("submit");
  4263. };
  4264. window.cancelStopwatch = function () {
  4265. $("#cancel_stopwatch_form").trigger("submit");
  4266. };
  4267. function initFilterBranchTagDropdown(selector) {
  4268. $(selector).each(function () {
  4269. const $dropdown = $(this);
  4270. const $data = $dropdown.find(".data");
  4271. const data = {
  4272. items: [],
  4273. mode: $data.data("mode"),
  4274. searchTerm: "",
  4275. noResults: "",
  4276. canCreateBranch: false,
  4277. menuVisible: false,
  4278. active: 0,
  4279. };
  4280. $data.find(".item").each(function () {
  4281. data.items.push({
  4282. name: $(this).text(),
  4283. url: $(this).data("url"),
  4284. branch: $(this).hasClass("branch"),
  4285. tag: $(this).hasClass("tag"),
  4286. selected: $(this).hasClass("selected"),
  4287. });
  4288. });
  4289. $data.remove();
  4290. new Vue({
  4291. delimiters: ["${", "}"],
  4292. el: this,
  4293. data,
  4294. beforeMount() {
  4295. const vm = this;
  4296. this.noResults = vm.$el.getAttribute("data-no-results");
  4297. this.canCreateBranch =
  4298. vm.$el.getAttribute("data-can-create-branch") === "true";
  4299. document.body.addEventListener("click", (event) => {
  4300. if (vm.$el.contains(event.target)) {
  4301. return;
  4302. }
  4303. if (vm.menuVisible) {
  4304. Vue.set(vm, "menuVisible", false);
  4305. }
  4306. });
  4307. },
  4308. watch: {
  4309. menuVisible(visible) {
  4310. if (visible) {
  4311. this.focusSearchField();
  4312. }
  4313. },
  4314. },
  4315. computed: {
  4316. filteredItems() {
  4317. const vm = this;
  4318. const items = vm.items.filter((item) => {
  4319. return (
  4320. ((vm.mode === "branches" && item.branch) ||
  4321. (vm.mode === "tags" && item.tag)) &&
  4322. (!vm.searchTerm ||
  4323. item.name.toLowerCase().includes(vm.searchTerm.toLowerCase()))
  4324. );
  4325. });
  4326. vm.active = items.length === 0 && vm.showCreateNewBranch ? 0 : -1;
  4327. return items;
  4328. },
  4329. showNoResults() {
  4330. return this.filteredItems.length === 0 && !this.showCreateNewBranch;
  4331. },
  4332. showCreateNewBranch() {
  4333. const vm = this;
  4334. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === "tags") {
  4335. return false;
  4336. }
  4337. return (
  4338. vm.items.filter(
  4339. (item) => item.name.toLowerCase() === vm.searchTerm.toLowerCase()
  4340. ).length === 0
  4341. );
  4342. },
  4343. },
  4344. methods: {
  4345. selectItem(item) {
  4346. const prev = this.getSelected();
  4347. if (prev !== null) {
  4348. prev.selected = false;
  4349. }
  4350. item.selected = true;
  4351. window.location.href = item.url;
  4352. },
  4353. createNewBranch() {
  4354. if (!this.showCreateNewBranch) {
  4355. return;
  4356. }
  4357. $(this.$refs.newBranchForm).trigger("submit");
  4358. },
  4359. focusSearchField() {
  4360. const vm = this;
  4361. Vue.nextTick(() => {
  4362. vm.$refs.searchField.focus();
  4363. });
  4364. },
  4365. getSelected() {
  4366. for (let i = 0, j = this.items.length; i < j; ++i) {
  4367. if (this.items[i].selected) return this.items[i];
  4368. }
  4369. return null;
  4370. },
  4371. getSelectedIndexInFiltered() {
  4372. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  4373. if (this.filteredItems[i].selected) return i;
  4374. }
  4375. return -1;
  4376. },
  4377. scrollToActive() {
  4378. let el = this.$refs[`listItem${this.active}`];
  4379. if (!el || el.length === 0) {
  4380. return;
  4381. }
  4382. if (Array.isArray(el)) {
  4383. el = el[0];
  4384. }
  4385. const cont = this.$refs.scrollContainer;
  4386. if (el.offsetTop < cont.scrollTop) {
  4387. cont.scrollTop = el.offsetTop;
  4388. } else if (
  4389. el.offsetTop + el.clientHeight >
  4390. cont.scrollTop + cont.clientHeight
  4391. ) {
  4392. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  4393. }
  4394. },
  4395. keydown(event) {
  4396. const vm = this;
  4397. if (event.keyCode === 40) {
  4398. // arrow down
  4399. event.preventDefault();
  4400. if (vm.active === -1) {
  4401. vm.active = vm.getSelectedIndexInFiltered();
  4402. }
  4403. if (
  4404. vm.active + (vm.showCreateNewBranch ? 0 : 1) >=
  4405. vm.filteredItems.length
  4406. ) {
  4407. return;
  4408. }
  4409. vm.active++;
  4410. vm.scrollToActive();
  4411. }
  4412. if (event.keyCode === 38) {
  4413. // arrow up
  4414. event.preventDefault();
  4415. if (vm.active === -1) {
  4416. vm.active = vm.getSelectedIndexInFiltered();
  4417. }
  4418. if (vm.active <= 0) {
  4419. return;
  4420. }
  4421. vm.active--;
  4422. vm.scrollToActive();
  4423. }
  4424. if (event.keyCode === 13) {
  4425. // enter
  4426. event.preventDefault();
  4427. if (vm.active >= vm.filteredItems.length) {
  4428. vm.createNewBranch();
  4429. } else if (vm.active >= 0) {
  4430. vm.selectItem(vm.filteredItems[vm.active]);
  4431. }
  4432. }
  4433. if (event.keyCode === 27) {
  4434. // escape
  4435. event.preventDefault();
  4436. vm.menuVisible = false;
  4437. }
  4438. },
  4439. },
  4440. });
  4441. });
  4442. }
  4443. $(".commit-button").on("click", function (e) {
  4444. e.preventDefault();
  4445. $(this).parent().find(".commit-body").toggle();
  4446. });
  4447. function initNavbarContentToggle() {
  4448. const content = $("#navbar");
  4449. const toggle = $("#navbar-expand-toggle");
  4450. let isExpanded = false;
  4451. toggle.on("click", () => {
  4452. isExpanded = !isExpanded;
  4453. if (isExpanded) {
  4454. content.addClass("shown");
  4455. toggle.addClass("active");
  4456. } else {
  4457. content.removeClass("shown");
  4458. toggle.removeClass("active");
  4459. }
  4460. });
  4461. }
  4462. window.toggleDeadlineForm = function () {
  4463. $("#deadlineForm").fadeToggle(150);
  4464. };
  4465. window.setDeadline = function () {
  4466. const deadline = $("#deadlineDate").val();
  4467. window.updateDeadline(deadline);
  4468. };
  4469. window.updateDeadline = function (deadlineString) {
  4470. $("#deadline-err-invalid-date").hide();
  4471. $("#deadline-loader").addClass("loading");
  4472. let realDeadline = null;
  4473. if (deadlineString !== "") {
  4474. const newDate = Date.parse(deadlineString);
  4475. if (Number.isNaN(newDate)) {
  4476. $("#deadline-loader").removeClass("loading");
  4477. $("#deadline-err-invalid-date").show();
  4478. return false;
  4479. }
  4480. realDeadline = new Date(newDate);
  4481. }
  4482. $.ajax(`${$("#update-issue-deadline-form").attr("action")}/deadline`, {
  4483. data: JSON.stringify({
  4484. due_date: realDeadline,
  4485. }),
  4486. headers: {
  4487. "X-Csrf-Token": csrf,
  4488. "X-Remote": true,
  4489. },
  4490. contentType: "application/json",
  4491. type: "POST",
  4492. success() {
  4493. reload();
  4494. },
  4495. error() {
  4496. $("#deadline-loader").removeClass("loading");
  4497. $("#deadline-err-invalid-date").show();
  4498. },
  4499. });
  4500. };
  4501. window.deleteDependencyModal = function (id, type) {
  4502. $(".remove-dependency")
  4503. .modal({
  4504. closable: false,
  4505. duration: 200,
  4506. onApprove() {
  4507. $("#removeDependencyID").val(id);
  4508. $("#dependencyType").val(type);
  4509. $("#removeDependencyForm").trigger("submit");
  4510. },
  4511. })
  4512. .modal("show");
  4513. };
  4514. function initIssueList() {
  4515. const repolink = $("#repolink").val();
  4516. const repoId = $("#repoId").val();
  4517. const crossRepoSearch = $("#crossRepoSearch").val();
  4518. const tp = $("#type").val();
  4519. let issueSearchUrl = `${AppSubUrl}/api/v1/repos/${repolink}/issues?q={query}&type=${tp}`;
  4520. if (crossRepoSearch === "true") {
  4521. issueSearchUrl = `${AppSubUrl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`;
  4522. }
  4523. $("#new-dependency-drop-list").dropdown({
  4524. apiSettings: {
  4525. url: issueSearchUrl,
  4526. onResponse(response) {
  4527. const filteredResponse = { success: true, results: [] };
  4528. const currIssueId = $("#new-dependency-drop-list").data("issue-id");
  4529. // Parse the response from the api to work with our dropdown
  4530. $.each(response, (_i, issue) => {
  4531. // Don't list current issue in the dependency list.
  4532. if (issue.id === currIssueId) {
  4533. return;
  4534. }
  4535. filteredResponse.results.push({
  4536. name: `#${issue.number} ${htmlEncode(
  4537. issue.title
  4538. )}<div class="text small dont-break-out">${htmlEncode(
  4539. issue.repository.full_name
  4540. )}</div>`,
  4541. value: issue.id,
  4542. });
  4543. });
  4544. return filteredResponse;
  4545. },
  4546. cache: false,
  4547. },
  4548. fullTextSearch: true,
  4549. });
  4550. $(".menu a.label-filter-item").each(function () {
  4551. $(this).on("click", function (e) {
  4552. if (e.altKey) {
  4553. e.preventDefault();
  4554. const href = $(this).attr("href");
  4555. const id = $(this).data("label-id");
  4556. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  4557. const newStr = "labels=$1-$2$3&";
  4558. window.location = href.replace(new RegExp(regStr), newStr);
  4559. }
  4560. });
  4561. });
  4562. $(".menu .ui.dropdown.label-filter").on("keydown", (e) => {
  4563. if (e.altKey && e.keyCode === 13) {
  4564. const selectedItems = $(
  4565. ".menu .ui.dropdown.label-filter .menu .item.selected"
  4566. );
  4567. if (selectedItems.length > 0) {
  4568. const item = $(selectedItems[0]);
  4569. const href = item.attr("href");
  4570. const id = item.data("label-id");
  4571. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  4572. const newStr = "labels=$1-$2$3&";
  4573. window.location = href.replace(new RegExp(regStr), newStr);
  4574. }
  4575. }
  4576. });
  4577. }
  4578. window.cancelCodeComment = function (btn) {
  4579. const form = $(btn).closest("form");
  4580. if (form.length > 0 && form.hasClass("comment-form")) {
  4581. form.addClass("hide");
  4582. form.parent().find("button.comment-form-reply").show();
  4583. } else {
  4584. form.closest(".comment-code-cloud").remove();
  4585. }
  4586. };
  4587. window.submitReply = function (btn) {
  4588. const form = $(btn).closest("form");
  4589. if (form.length > 0 && form.hasClass("comment-form")) {
  4590. form.trigger("submit");
  4591. }
  4592. };
  4593. window.onOAuthLoginClick = function () {
  4594. const oauthLoader = $("#oauth2-login-loader");
  4595. const oauthNav = $("#oauth2-login-navigator");
  4596. oauthNav.hide();
  4597. oauthLoader.removeClass("disabled");
  4598. setTimeout(() => {
  4599. // recover previous content to let user try again
  4600. // usually redirection will be performed before this action
  4601. oauthLoader.addClass("disabled");
  4602. oauthNav.show();
  4603. }, 5000);
  4604. };
  4605. // Pull SVGs via AJAX to workaround CORS issues with <use> tags
  4606. // https://css-tricks.com/ajaxing-svg-sprite/
  4607. $.get(`${window.config.StaticUrlPrefix}/img/svg/icons.svg`, (data) => {
  4608. const div = document.createElement("div");
  4609. div.style.display = "none";
  4610. div.innerHTML = new XMLSerializer().serializeToString(data.documentElement);
  4611. document.body.insertBefore(div, document.body.childNodes[0]);
  4612. });
  4613. function initDropDown() {
  4614. $("#dropdown_PageHome").dropdown({
  4615. on: "hover", //鼠标悬浮显示,默认值是click
  4616. });
  4617. $("#dropdown_explore").dropdown({
  4618. on: "hover", //鼠标悬浮显示,默认值是click
  4619. });
  4620. }
  4621. //云脑提示
  4622. $(".question.circle.icon.cloudbrain-question").hover(function () {
  4623. $(this).popup("show");
  4624. $(".ui.popup.mini.top.center").css({
  4625. "border-color": "rgba(50, 145, 248, 100)",
  4626. color: "rgba(3, 102, 214, 100)",
  4627. "border-radius": "5px",
  4628. "border-shadow": "none",
  4629. });
  4630. });
  4631. //云脑详情页面跳转回上一个页面
  4632. // $(".section.backTodeBug").attr("href",localStorage.getItem('all'))
  4633. //新建调试取消跳转
  4634. // $(".ui.button.cancel").attr("href",localStorage.getItem('all'))
  4635. function initcreateRepo() {
  4636. let timeout;
  4637. let keydown_flag = false;
  4638. const urlAdd =
  4639. location.href.split("/")[0] + "//" + location.href.split("/")[2];
  4640. let owner = $("#ownerDropdown div.text").attr("title");
  4641. $(document).ready(function () {
  4642. $("#ownerDropdown").dropdown({
  4643. onChange: function (value, text, $choice) {
  4644. owner = $choice[0].getAttribute("title");
  4645. $("#repoAdress").css("display", "flex");
  4646. $("#repoAdress span").text(
  4647. urlAdd + "/" + owner + "/" + $("#repo_name").val() + ".git"
  4648. );
  4649. },
  4650. });
  4651. });
  4652. $("#repo_name").keyup(function () {
  4653. keydown_flag = $("#repo_name").val() ? true : false;
  4654. if (keydown_flag) {
  4655. $("#repoAdress").css("display", "flex");
  4656. $("#repoAdress span").text(
  4657. urlAdd + "/" + owner + "/" + $("#repo_name").val() + ".git"
  4658. );
  4659. } else {
  4660. $("#repoAdress").css("display", "none");
  4661. $("#repo_name").attr("placeholder", "");
  4662. }
  4663. });
  4664. $("#create_repo_form").form({
  4665. on: "blur",
  4666. // inline:true,
  4667. fields: {
  4668. alias: {
  4669. identifier: "alias",
  4670. rules: [
  4671. {
  4672. type: "regExp[/^[\u4E00-\u9FA5A-Za-z0-9_.-]{1,100}$/]",
  4673. },
  4674. ],
  4675. },
  4676. repo_name: {
  4677. identifier: "repo_name",
  4678. rules: [
  4679. {
  4680. type: "regExp[/^[A-Za-z0-9_.-]{1,100}$/]",
  4681. },
  4682. ],
  4683. },
  4684. },
  4685. onFailure: function (e) {
  4686. return false;
  4687. },
  4688. });
  4689. $("#alias").bind("input propertychange", function (event) {
  4690. clearTimeout(timeout);
  4691. timeout = setTimeout(() => {
  4692. //在此处写调用的方法,可以实现仅最后一次操作生效
  4693. const aliasValue = $("#alias").val();
  4694. if (keydown_flag) {
  4695. $("#repo_name").attr("placeholder", "");
  4696. } else if (aliasValue) {
  4697. $("#repo_name").attr("placeholder", "正在获取路径...");
  4698. $.get(
  4699. `${window.config.AppSubUrl}/repo/check_name?q=${aliasValue}&owner=${owner}`,
  4700. (data) => {
  4701. const repo_name = data.name;
  4702. $("#repo_name").val(repo_name);
  4703. repo_name && $("#repo_name").parent().removeClass("error");
  4704. $("#repoAdress").css("display", "flex");
  4705. $("#repoAdress span").text(
  4706. urlAdd + "/" + owner + "/" + $("#repo_name").val() + ".git"
  4707. );
  4708. $("#repo_name").attr("placeholder", "");
  4709. }
  4710. );
  4711. } else {
  4712. $("#repo_name").val("");
  4713. $("#repo_name").attr("placeholder", "");
  4714. $("#repoAdress").css("display", "none");
  4715. }
  4716. }, 500);
  4717. });
  4718. }
  4719. initcreateRepo();
  4720. function initChartsNpu() {
  4721. const url = window.location.href;
  4722. const urlArr = url.split("/");
  4723. let userName = urlArr.slice(-5)[0];
  4724. let repoPath = urlArr.slice(-4)[0];
  4725. let jobID = urlArr.slice(-1)[0];
  4726. let options = {
  4727. legend: {
  4728. data: [],
  4729. },
  4730. grid: {
  4731. top: "35%",
  4732. bottom: "2%",
  4733. x: "2%",
  4734. containLabel: true,
  4735. },
  4736. tooltip: {
  4737. trigger: "axis",
  4738. backgroundColor: "rgb(51, 56, 84)",
  4739. borderColor: "rgb(51, 51, 51)",
  4740. borderWidth: 0,
  4741. textStyle: {
  4742. color: "#fff",
  4743. },
  4744. axisPointer: {
  4745. type: "line",
  4746. },
  4747. },
  4748. xAxis: {
  4749. type: "category",
  4750. data: [],
  4751. boundaryGap: false,
  4752. axisLabel: {
  4753. interval: "auto",
  4754. },
  4755. name: "时间(min)",
  4756. },
  4757. yAxis: {
  4758. show: true,
  4759. name: "占有率(%)",
  4760. axisLine: {
  4761. show: true,
  4762. },
  4763. axisTick: { show: true },
  4764. },
  4765. series: [],
  4766. };
  4767. const sortBy = (arr, k) =>
  4768. arr.concat().sort((a, b) => (a[k] > b[k] ? 1 : a[k] < b[k] ? -1 : 0));
  4769. $(".metric_chart").click(function (e) {
  4770. let versionName = $(this).data("version");
  4771. let myCharts = echarts.init(
  4772. document.getElementById(`metric-${versionName}`)
  4773. );
  4774. $.get(
  4775. `${window.config.AppSubUrl}/api/v1/repos/${userName}/${repoPath}/modelarts/train-job/${jobID}/metric_statistics?version_name=${versionName}&statistic_type=each&metrics=`,
  4776. (res) => {
  4777. let filterDta = res.MetricsInfo.filter((item) => {
  4778. return ![
  4779. "recvBytesRate",
  4780. "diskWriteRate",
  4781. "sendBytesRate",
  4782. "diskReadRate",
  4783. ].includes(item.metric);
  4784. });
  4785. filterDta = sortBy(filterDta, "metric");
  4786. let legenData = filterDta.map((item) => {
  4787. return item.metric;
  4788. });
  4789. let seriesData = filterDta.map((item) => {
  4790. let value = item.value.map((item) => {
  4791. return item > 0 ? item : "0";
  4792. });
  4793. let seriesOption = {
  4794. name: item.metric,
  4795. type: "line",
  4796. symbol: "circle",
  4797. symbolSize: 10,
  4798. smooth: true,
  4799. showSymbol: false,
  4800. lineStyle: {
  4801. width: 2,
  4802. shadowColor: "rgba(0,0,0,0.3)",
  4803. shadowBlur: 10,
  4804. shadowOffsetY: 8,
  4805. },
  4806. data: value,
  4807. };
  4808. return seriesOption;
  4809. });
  4810. let xLength = res.MetricsInfo[0].value.length;
  4811. options.xAxis.data = Array.from(
  4812. { length: xLength },
  4813. (_, index) => index
  4814. );
  4815. options.legend.data = legenData;
  4816. options.series = seriesData;
  4817. options && myCharts.setOption(options);
  4818. }
  4819. );
  4820. options && myCharts.setOption(options);
  4821. });
  4822. }
  4823. initChartsNpu();