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 122 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
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
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
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
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
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
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
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
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
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
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
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
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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
Add Octicon SVG spritemap (#10107) * Add octicon SVG sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Static prefix Signed-off-by: jolheiser <john.olheiser@gmail.com> * SVG for all repo icons Signed-off-by: jolheiser <john.olheiser@gmail.com> * make vendor Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap out octicons Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move octicons to top of less imports Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix JS Signed-off-by: jolheiser <john.olheiser@gmail.com> * Definitely not a search/replace Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed regex Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move to more generic calls and webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * make svg -> make webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg-sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed a test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg from makefile Signed-off-by: jolheiser <john.olheiser@gmail.com> * Suggestions Signed-off-by: jolheiser <john.olheiser@gmail.com> * Attempt to fix test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert timetracking test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap .octicon for .svg in less Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add aria-hidden Signed-off-by: jolheiser <john.olheiser@gmail.com> * Replace mega-octicon Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix webpack globbing on Windows Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert Co-Authored-By: silverwind <me@silverwind.io> * Fix octions from upstream Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix Vue and missed JS function Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add JS helper and PWA Signed-off-by: jolheiser <john.olheiser@gmail.com> * Preload SVG Signed-off-by: jolheiser <john.olheiser@gmail.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: techknowlogick <matti@mdranta.net>
5 years ago
4 years ago
Add Octicon SVG spritemap (#10107) * Add octicon SVG sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Static prefix Signed-off-by: jolheiser <john.olheiser@gmail.com> * SVG for all repo icons Signed-off-by: jolheiser <john.olheiser@gmail.com> * make vendor Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap out octicons Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move octicons to top of less imports Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix JS Signed-off-by: jolheiser <john.olheiser@gmail.com> * Definitely not a search/replace Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed regex Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move to more generic calls and webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * make svg -> make webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg-sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed a test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg from makefile Signed-off-by: jolheiser <john.olheiser@gmail.com> * Suggestions Signed-off-by: jolheiser <john.olheiser@gmail.com> * Attempt to fix test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert timetracking test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap .octicon for .svg in less Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add aria-hidden Signed-off-by: jolheiser <john.olheiser@gmail.com> * Replace mega-octicon Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix webpack globbing on Windows Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert Co-Authored-By: silverwind <me@silverwind.io> * Fix octions from upstream Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix Vue and missed JS function Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add JS helper and PWA Signed-off-by: jolheiser <john.olheiser@gmail.com> * Preload SVG Signed-off-by: jolheiser <john.olheiser@gmail.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: techknowlogick <matti@mdranta.net>
5 years ago
4 years ago
4 years ago
Add Octicon SVG spritemap (#10107) * Add octicon SVG sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Static prefix Signed-off-by: jolheiser <john.olheiser@gmail.com> * SVG for all repo icons Signed-off-by: jolheiser <john.olheiser@gmail.com> * make vendor Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap out octicons Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move octicons to top of less imports Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix JS Signed-off-by: jolheiser <john.olheiser@gmail.com> * Definitely not a search/replace Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed regex Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move to more generic calls and webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * make svg -> make webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg-sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed a test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg from makefile Signed-off-by: jolheiser <john.olheiser@gmail.com> * Suggestions Signed-off-by: jolheiser <john.olheiser@gmail.com> * Attempt to fix test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert timetracking test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap .octicon for .svg in less Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add aria-hidden Signed-off-by: jolheiser <john.olheiser@gmail.com> * Replace mega-octicon Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix webpack globbing on Windows Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert Co-Authored-By: silverwind <me@silverwind.io> * Fix octions from upstream Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix Vue and missed JS function Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add JS helper and PWA Signed-off-by: jolheiser <john.olheiser@gmail.com> * Preload SVG Signed-off-by: jolheiser <john.olheiser@gmail.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: techknowlogick <matti@mdranta.net>
5 years ago
Add Octicon SVG spritemap (#10107) * Add octicon SVG sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Static prefix Signed-off-by: jolheiser <john.olheiser@gmail.com> * SVG for all repo icons Signed-off-by: jolheiser <john.olheiser@gmail.com> * make vendor Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap out octicons Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move octicons to top of less imports Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix JS Signed-off-by: jolheiser <john.olheiser@gmail.com> * Definitely not a search/replace Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed regex Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move to more generic calls and webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * make svg -> make webpack Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg-sprite Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Missed a test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove svg from makefile Signed-off-by: jolheiser <john.olheiser@gmail.com> * Suggestions Signed-off-by: jolheiser <john.olheiser@gmail.com> * Attempt to fix test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert timetracking test Signed-off-by: jolheiser <john.olheiser@gmail.com> * Swap .octicon for .svg in less Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add aria-hidden Signed-off-by: jolheiser <john.olheiser@gmail.com> * Replace mega-octicon Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix webpack globbing on Windows Signed-off-by: jolheiser <john.olheiser@gmail.com> * Revert Co-Authored-By: silverwind <me@silverwind.io> * Fix octions from upstream Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix Vue and missed JS function Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add JS helper and PWA Signed-off-by: jolheiser <john.olheiser@gmail.com> * Preload SVG Signed-off-by: jolheiser <john.olheiser@gmail.com> Co-authored-by: silverwind <me@silverwind.io> Co-authored-by: techknowlogick <matti@mdranta.net>
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272
  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 Vue from 'vue';
  7. import 'jquery.are-you-sure';
  8. import './vendor/semanticdropdown.js';
  9. import {svg} from './utils.js';
  10. import initContextPopups from './features/contextpopup.js';
  11. import initGitGraph from './features/gitgraph.js';
  12. import initClipboard from './features/clipboard.js';
  13. import initUserHeatmap from './features/userheatmap.js';
  14. import initDateTimePicker from './features/datetimepicker.js';
  15. import {
  16. initTribute,
  17. issuesTribute,
  18. emojiTribute
  19. } from './features/tribute.js';
  20. import createDropzone from './features/dropzone.js';
  21. import highlight from './features/highlight.js';
  22. import ActivityTopAuthors from './components/ActivityTopAuthors.vue';
  23. import {
  24. initNotificationsTable,
  25. initNotificationCount
  26. } from './features/notification.js';
  27. import {createCodeEditor} from './features/codeeditor.js';
  28. import MinioUploader from './components/MinioUploader.vue';
  29. const {AppSubUrl, StaticUrlPrefix, csrf} = window.config;
  30. function htmlEncode(text) {
  31. return jQuery('<div />')
  32. .text(text)
  33. .html();
  34. }
  35. let previewFileModes;
  36. const commentMDEditors = {};
  37. // Silence fomantic's error logging when tabs are used without a target content element
  38. $.fn.tab.settings.silent = true;
  39. function initCommentPreviewTab($form) {
  40. const $tabMenu = $form.find('.tabular.menu');
  41. $tabMenu.find('.item').tab();
  42. $tabMenu
  43. .find(`.item[data-tab="${$tabMenu.data('preview')}"]`)
  44. .on('click', function () {
  45. const $this = $(this);
  46. $.post(
  47. $this.data('url'),
  48. {
  49. _csrf: csrf,
  50. mode: 'gfm',
  51. context: $this.data('context'),
  52. text: $form
  53. .find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`)
  54. .val()
  55. },
  56. (data) => {
  57. const $previewPanel = $form.find(
  58. `.tab[data-tab="${$tabMenu.data('preview')}"]`
  59. );
  60. $previewPanel.html(data);
  61. $('pre code', $previewPanel[0]).each(function () {
  62. highlight(this);
  63. });
  64. }
  65. );
  66. });
  67. buttonsClickOnEnter();
  68. }
  69. function initEditPreviewTab($form) {
  70. const $tabMenu = $form.find('.tabular.menu');
  71. $tabMenu.find('.item').tab();
  72. const $previewTab = $tabMenu.find(
  73. `.item[data-tab="${$tabMenu.data('preview')}"]`
  74. );
  75. if ($previewTab.length) {
  76. previewFileModes = $previewTab.data('preview-file-modes').split(',');
  77. $previewTab.on('click', function () {
  78. const $this = $(this);
  79. let context = `${$this.data('context')}/`;
  80. const treePathEl = $form.find('input#tree_path');
  81. if (treePathEl.length > 0) {
  82. context += treePathEl.val();
  83. }
  84. context = context.substring(0, context.lastIndexOf('/'));
  85. $.post(
  86. $this.data('url'),
  87. {
  88. _csrf: csrf,
  89. mode: 'gfm',
  90. context,
  91. text: $form
  92. .find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`)
  93. .val()
  94. },
  95. (data) => {
  96. const $previewPanel = $form.find(
  97. `.tab[data-tab="${$tabMenu.data('preview')}"]`
  98. );
  99. $previewPanel.html(data);
  100. $('pre code', $previewPanel[0]).each(function () {
  101. highlight(this);
  102. });
  103. }
  104. );
  105. });
  106. }
  107. }
  108. function initEditDiffTab($form) {
  109. const $tabMenu = $form.find('.tabular.menu');
  110. $tabMenu.find('.item').tab();
  111. $tabMenu
  112. .find(`.item[data-tab="${$tabMenu.data('diff')}"]`)
  113. .on('click', function () {
  114. const $this = $(this);
  115. $.post(
  116. $this.data('url'),
  117. {
  118. _csrf: csrf,
  119. context: $this.data('context'),
  120. content: $form
  121. .find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`)
  122. .val()
  123. },
  124. (data) => {
  125. const $diffPreviewPanel = $form.find(
  126. `.tab[data-tab="${$tabMenu.data('diff')}"]`
  127. );
  128. $diffPreviewPanel.html(data);
  129. }
  130. );
  131. });
  132. }
  133. function initEditForm() {
  134. if ($('.edit.form').length === 0) {
  135. return;
  136. }
  137. initEditPreviewTab($('.edit.form'));
  138. initEditDiffTab($('.edit.form'));
  139. }
  140. function initBranchSelector() {
  141. const $selectBranch = $('.ui.select-branch');
  142. const $branchMenu = $selectBranch.find('.reference-list-menu');
  143. $branchMenu.find('.item:not(.no-select)').click(function () {
  144. $($(this).data('id-selector')).val($(this).data('id'));
  145. $selectBranch.find('.ui .branch-name').text($(this).data('name'));
  146. });
  147. $selectBranch.find('.reference.column').on('click', function () {
  148. $selectBranch.find('.scrolling.reference-list-menu').css('display', 'none');
  149. $selectBranch.find('.reference .text').removeClass('black');
  150. $($(this).data('target')).css('display', 'block');
  151. $(this)
  152. .find('.text')
  153. .addClass('black');
  154. return false;
  155. });
  156. }
  157. function initLabelEdit() {
  158. // Create label
  159. const $newLabelPanel = $('.new-label.segment');
  160. $('.new-label.button').on('click', () => {
  161. $newLabelPanel.show();
  162. });
  163. $('.new-label.segment .cancel').on('click', () => {
  164. $newLabelPanel.hide();
  165. });
  166. $('.color-picker').each(function () {
  167. $(this).minicolors();
  168. });
  169. $('.precolors .color').on('click', function () {
  170. const color_hex = $(this).data('color-hex');
  171. $('.color-picker').val(color_hex);
  172. $('.minicolors-swatch-color').css('background-color', color_hex);
  173. });
  174. $('.edit-label-button').on('click', function () {
  175. $('#label-modal-id').val($(this).data('id'));
  176. $('.edit-label .new-label-input').val($(this).data('title'));
  177. $('.edit-label .new-label-desc-input').val($(this).data('description'));
  178. $('.edit-label .color-picker').val($(this).data('color'));
  179. $('.minicolors-swatch-color').css(
  180. 'background-color',
  181. $(this).data('color')
  182. );
  183. $('.edit-label.modal')
  184. .modal({
  185. onApprove() {
  186. $('.edit-label.form').trigger('submit');
  187. }
  188. })
  189. .modal('show');
  190. return false;
  191. });
  192. }
  193. function updateIssuesMeta(url, action, issueIds, elementId, isAdd) {
  194. return new Promise((resolve) => {
  195. $.ajax({
  196. type: 'POST',
  197. url,
  198. data: {
  199. _csrf: csrf,
  200. action,
  201. issue_ids: issueIds,
  202. id: elementId,
  203. is_add: isAdd
  204. },
  205. success: resolve
  206. });
  207. });
  208. }
  209. function initRepoStatusChecker() {
  210. const migrating = $('#repo_migrating');
  211. $('#repo_migrating_failed').hide();
  212. if (migrating) {
  213. const repo_name = migrating.attr('repo');
  214. if (typeof repo_name === 'undefined') {
  215. return;
  216. }
  217. $.ajax({
  218. type: 'GET',
  219. url: `${AppSubUrl}/${repo_name}/status`,
  220. data: {
  221. _csrf: csrf
  222. },
  223. complete(xhr) {
  224. if (xhr.status === 200) {
  225. if (xhr.responseJSON) {
  226. if (xhr.responseJSON.status === 0) {
  227. window.location.reload();
  228. return;
  229. }
  230. setTimeout(() => {
  231. initRepoStatusChecker();
  232. }, 2000);
  233. return;
  234. }
  235. }
  236. $('#repo_migrating_progress').hide();
  237. $('#repo_migrating_failed').show();
  238. }
  239. });
  240. }
  241. }
  242. function initReactionSelector(parent) {
  243. let reactions = '';
  244. if (!parent) {
  245. parent = $(document);
  246. reactions = '.reactions > ';
  247. }
  248. parent.find(`${reactions}a.label`).popup({
  249. position: 'bottom left',
  250. metadata: {content: 'title', title: 'none'}
  251. });
  252. parent
  253. .find(`.select-reaction > .menu > .item, ${reactions}a.label`)
  254. .on('click', function (e) {
  255. const vm = this;
  256. e.preventDefault();
  257. if ($(this).hasClass('disabled')) return;
  258. const actionURL = $(this).hasClass('item') ?
  259. $(this)
  260. .closest('.select-reaction')
  261. .data('action-url') :
  262. $(this).data('action-url');
  263. const url = `${actionURL}/${
  264. $(this).hasClass('blue') ? 'unreact' : 'react'
  265. }`;
  266. $.ajax({
  267. type: 'POST',
  268. url,
  269. data: {
  270. _csrf: csrf,
  271. content: $(this).data('content')
  272. }
  273. }).done((resp) => {
  274. if (resp && (resp.html || resp.empty)) {
  275. const content = $(vm).closest('.content');
  276. let react = content.find('.segment.reactions');
  277. if (!resp.empty && react.length > 0) {
  278. react.remove();
  279. }
  280. if (!resp.empty) {
  281. react = $('<div class="ui attached segment reactions"></div>');
  282. const attachments = content.find('.segment.bottom:first');
  283. if (attachments.length > 0) {
  284. react.insertBefore(attachments);
  285. } else {
  286. react.appendTo(content);
  287. }
  288. react.html(resp.html);
  289. react.find('.dropdown').dropdown();
  290. initReactionSelector(react);
  291. }
  292. }
  293. });
  294. });
  295. }
  296. function insertAtCursor(field, value) {
  297. if (field.selectionStart || field.selectionStart === 0) {
  298. const startPos = field.selectionStart;
  299. const endPos = field.selectionEnd;
  300. field.value =
  301. field.value.substring(0, startPos) +
  302. value +
  303. field.value.substring(endPos, field.value.length);
  304. field.selectionStart = startPos + value.length;
  305. field.selectionEnd = startPos + value.length;
  306. } else {
  307. field.value += value;
  308. }
  309. }
  310. function replaceAndKeepCursor(field, oldval, newval) {
  311. if (field.selectionStart || field.selectionStart === 0) {
  312. const startPos = field.selectionStart;
  313. const endPos = field.selectionEnd;
  314. field.value = field.value.replace(oldval, newval);
  315. field.selectionStart = startPos + newval.length - oldval.length;
  316. field.selectionEnd = endPos + newval.length - oldval.length;
  317. } else {
  318. field.value = field.value.replace(oldval, newval);
  319. }
  320. }
  321. function retrieveImageFromClipboardAsBlob(pasteEvent, callback) {
  322. if (!pasteEvent.clipboardData) {
  323. return;
  324. }
  325. const {items} = pasteEvent.clipboardData;
  326. if (typeof items === 'undefined') {
  327. return;
  328. }
  329. for (let i = 0; i < items.length; i++) {
  330. if (!items[i].type.includes('image')) continue;
  331. const blob = items[i].getAsFile();
  332. if (typeof callback === 'function') {
  333. pasteEvent.preventDefault();
  334. pasteEvent.stopPropagation();
  335. callback(blob);
  336. }
  337. }
  338. }
  339. function uploadFile(file, callback) {
  340. const xhr = new XMLHttpRequest();
  341. xhr.addEventListener('load', () => {
  342. if (xhr.status === 200) {
  343. callback(xhr.responseText);
  344. }
  345. });
  346. xhr.open('post', `${AppSubUrl}/attachments`, true);
  347. xhr.setRequestHeader('X-Csrf-Token', csrf);
  348. const formData = new FormData();
  349. formData.append('file', file, file.name);
  350. xhr.send(formData);
  351. }
  352. function reload() {
  353. window.location.reload();
  354. }
  355. function initImagePaste(target) {
  356. target.each(function () {
  357. const field = this;
  358. field.addEventListener(
  359. 'paste',
  360. (event) => {
  361. retrieveImageFromClipboardAsBlob(event, (img) => {
  362. const name = img.name.substr(0, img.name.lastIndexOf('.'));
  363. insertAtCursor(field, `![${name}]()`);
  364. uploadFile(img, (res) => {
  365. const data = JSON.parse(res);
  366. replaceAndKeepCursor(
  367. field,
  368. `![${name}]()`,
  369. `![${name}](${AppSubUrl}/attachments/${data.uuid})`
  370. );
  371. const input = $(
  372. `<input id="${data.uuid}" name="files" type="hidden">`
  373. ).val(data.uuid);
  374. $('.files').append(input);
  375. });
  376. });
  377. },
  378. false
  379. );
  380. });
  381. }
  382. function initSimpleMDEImagePaste(simplemde, files) {
  383. simplemde.codemirror.on('paste', (_, event) => {
  384. retrieveImageFromClipboardAsBlob(event, (img) => {
  385. const name = img.name.substr(0, img.name.lastIndexOf('.'));
  386. uploadFile(img, (res) => {
  387. const data = JSON.parse(res);
  388. const pos = simplemde.codemirror.getCursor();
  389. simplemde.codemirror.replaceRange(
  390. `![${name}](${AppSubUrl}/attachments/${data.uuid})`,
  391. pos
  392. );
  393. const input = $(
  394. `<input id="${data.uuid}" name="files" type="hidden">`
  395. ).val(data.uuid);
  396. files.append(input);
  397. });
  398. });
  399. });
  400. }
  401. let autoSimpleMDE;
  402. function initCommentForm() {
  403. if ($('.comment.form').length === 0) {
  404. return;
  405. }
  406. autoSimpleMDE = setCommentSimpleMDE(
  407. $('.comment.form textarea:not(.review-textarea)')
  408. );
  409. initBranchSelector();
  410. initCommentPreviewTab($('.comment.form'));
  411. initImagePaste($('.comment.form textarea'));
  412. // Listsubmit
  413. function initListSubmits(selector, outerSelector) {
  414. const $list = $(`.ui.${outerSelector}.list`);
  415. const $noSelect = $list.find('.no-select');
  416. const $listMenu = $(`.${selector} .menu`);
  417. let hasLabelUpdateAction = $listMenu.data('action') === 'update';
  418. const labels = {};
  419. $(`.${selector}`).dropdown('setting', 'onHide', () => {
  420. hasLabelUpdateAction = $listMenu.data('action') === 'update'; // Update the var
  421. if (hasLabelUpdateAction) {
  422. const promises = [];
  423. Object.keys(labels).forEach((elementId) => {
  424. const label = labels[elementId];
  425. const promise = updateIssuesMeta(
  426. label['update-url'],
  427. label.action,
  428. label['issue-id'],
  429. elementId,
  430. label['is-checked']
  431. );
  432. promises.push(promise);
  433. });
  434. Promise.all(promises).then(reload);
  435. }
  436. });
  437. $listMenu.find('.item:not(.no-select)').on('click', function () {
  438. // we don't need the action attribute when updating assignees
  439. if (
  440. selector === 'select-assignees-modify' ||
  441. selector === 'select-reviewers-modify'
  442. ) {
  443. // UI magic. We need to do this here, otherwise it would destroy the functionality of
  444. // adding/removing labels
  445. if ($(this).data('can-change') === 'block') {
  446. return false;
  447. }
  448. if ($(this).hasClass('checked')) {
  449. $(this).removeClass('checked');
  450. $(this)
  451. .find('.octicon-check')
  452. .addClass('invisible');
  453. $(this).data('is-checked', 'remove');
  454. } else {
  455. $(this).addClass('checked');
  456. $(this)
  457. .find('.octicon-check')
  458. .removeClass('invisible');
  459. $(this).data('is-checked', 'add');
  460. }
  461. updateIssuesMeta(
  462. $listMenu.data('update-url'),
  463. '',
  464. $listMenu.data('issue-id'),
  465. $(this).data('id'),
  466. $(this).data('is-checked')
  467. );
  468. $listMenu.data('action', 'update'); // Update to reload the page when we updated items
  469. return false;
  470. }
  471. if ($(this).hasClass('checked')) {
  472. $(this).removeClass('checked');
  473. $(this)
  474. .find('.octicon-check')
  475. .addClass('invisible');
  476. if (hasLabelUpdateAction) {
  477. if (!($(this).data('id') in labels)) {
  478. labels[$(this).data('id')] = {
  479. 'update-url': $listMenu.data('update-url'),
  480. action: 'detach',
  481. 'issue-id': $listMenu.data('issue-id')
  482. };
  483. } else {
  484. delete labels[$(this).data('id')];
  485. }
  486. }
  487. } else {
  488. $(this).addClass('checked');
  489. $(this)
  490. .find('.octicon-check')
  491. .removeClass('invisible');
  492. if (hasLabelUpdateAction) {
  493. if (!($(this).data('id') in labels)) {
  494. labels[$(this).data('id')] = {
  495. 'update-url': $listMenu.data('update-url'),
  496. action: 'attach',
  497. 'issue-id': $listMenu.data('issue-id')
  498. };
  499. } else {
  500. delete labels[$(this).data('id')];
  501. }
  502. }
  503. }
  504. const listIds = [];
  505. $(this)
  506. .parent()
  507. .find('.item')
  508. .each(function () {
  509. if ($(this).hasClass('checked')) {
  510. listIds.push($(this).data('id'));
  511. $($(this).data('id-selector')).removeClass('hide');
  512. } else {
  513. $($(this).data('id-selector')).addClass('hide');
  514. }
  515. });
  516. if (listIds.length === 0) {
  517. $noSelect.removeClass('hide');
  518. } else {
  519. $noSelect.addClass('hide');
  520. }
  521. $(
  522. $(this)
  523. .parent()
  524. .data('id')
  525. ).val(listIds.join(','));
  526. return false;
  527. });
  528. $listMenu.find('.no-select.item').on('click', function () {
  529. if (hasLabelUpdateAction || selector === 'select-assignees-modify') {
  530. updateIssuesMeta(
  531. $listMenu.data('update-url'),
  532. 'clear',
  533. $listMenu.data('issue-id'),
  534. '',
  535. ''
  536. ).then(reload);
  537. }
  538. $(this)
  539. .parent()
  540. .find('.item')
  541. .each(function () {
  542. $(this).removeClass('checked');
  543. $(this)
  544. .find('.octicon')
  545. .addClass('invisible');
  546. $(this).data('is-checked', 'remove');
  547. });
  548. $list.find('.item').each(function () {
  549. $(this).addClass('hide');
  550. });
  551. $noSelect.removeClass('hide');
  552. $(
  553. $(this)
  554. .parent()
  555. .data('id')
  556. ).val('');
  557. });
  558. }
  559. // Init labels and assignees
  560. initListSubmits('select-label', 'labels');
  561. initListSubmits('select-assignees', 'assignees');
  562. initListSubmits('select-assignees-modify', 'assignees');
  563. initListSubmits('select-reviewers-modify', 'assignees');
  564. function selectItem(select_id, input_id) {
  565. const $menu = $(`${select_id} .menu`);
  566. const $list = $(`.ui${select_id}.list`);
  567. const hasUpdateAction = $menu.data('action') === 'update';
  568. $menu.find('.item:not(.no-select)').on('click', function () {
  569. $(this)
  570. .parent()
  571. .find('.item')
  572. .each(function () {
  573. $(this).removeClass('selected active');
  574. });
  575. $(this).addClass('selected active');
  576. if (hasUpdateAction) {
  577. updateIssuesMeta(
  578. $menu.data('update-url'),
  579. '',
  580. $menu.data('issue-id'),
  581. $(this).data('id'),
  582. $(this).data('is-checked')
  583. ).then(reload);
  584. }
  585. switch (input_id) {
  586. case '#milestone_id':
  587. $list
  588. .find('.selected')
  589. .html(
  590. `<a class="item" href=${$(this).data('href')}>${htmlEncode(
  591. $(this).text()
  592. )}</a>`
  593. );
  594. break;
  595. case '#assignee_id':
  596. $list
  597. .find('.selected')
  598. .html(
  599. `<a class="item" href=${$(this).data('href')}>` +
  600. `<img class="ui avatar image" src=${$(this).data(
  601. 'avatar'
  602. )}>${htmlEncode($(this).text())}</a>`
  603. );
  604. }
  605. $(`.ui${select_id}.list .no-select`).addClass('hide');
  606. $(input_id).val($(this).data('id'));
  607. });
  608. $menu.find('.no-select.item').on('click', function () {
  609. $(this)
  610. .parent()
  611. .find('.item:not(.no-select)')
  612. .each(function () {
  613. $(this).removeClass('selected active');
  614. });
  615. if (hasUpdateAction) {
  616. updateIssuesMeta(
  617. $menu.data('update-url'),
  618. '',
  619. $menu.data('issue-id'),
  620. $(this).data('id'),
  621. $(this).data('is-checked')
  622. ).then(reload);
  623. }
  624. $list.find('.selected').html('');
  625. $list.find('.no-select').removeClass('hide');
  626. $(input_id).val('');
  627. });
  628. }
  629. // Milestone and assignee
  630. selectItem('.select-milestone', '#milestone_id');
  631. selectItem('.select-assignee', '#assignee_id');
  632. }
  633. function initInstall() {
  634. if ($('.install').length === 0) {
  635. return;
  636. }
  637. if ($('#db_host').val() === '') {
  638. $('#db_host').val('127.0.0.1:3306');
  639. $('#db_user').val('gitea');
  640. $('#db_name').val('gitea');
  641. }
  642. // Database type change detection.
  643. $('#db_type').on('change', function () {
  644. const sqliteDefault = 'data/gitea.db';
  645. const tidbDefault = 'data/gitea_tidb';
  646. const dbType = $(this).val();
  647. if (dbType === 'SQLite3') {
  648. $('#sql_settings').hide();
  649. $('#pgsql_settings').hide();
  650. $('#mysql_settings').hide();
  651. $('#sqlite_settings').show();
  652. if (dbType === 'SQLite3' && $('#db_path').val() === tidbDefault) {
  653. $('#db_path').val(sqliteDefault);
  654. }
  655. return;
  656. }
  657. const dbDefaults = {
  658. MySQL: '127.0.0.1:3306',
  659. PostgreSQL: '127.0.0.1:5432',
  660. MSSQL: '127.0.0.1:1433'
  661. };
  662. $('#sqlite_settings').hide();
  663. $('#sql_settings').show();
  664. $('#pgsql_settings').toggle(dbType === 'PostgreSQL');
  665. $('#mysql_settings').toggle(dbType === 'MySQL');
  666. $.each(dbDefaults, (_type, defaultHost) => {
  667. if ($('#db_host').val() === defaultHost) {
  668. $('#db_host').val(dbDefaults[dbType]);
  669. return false;
  670. }
  671. });
  672. });
  673. // TODO: better handling of exclusive relations.
  674. $('#offline-mode input').on('change', function () {
  675. if ($(this).is(':checked')) {
  676. $('#disable-gravatar').checkbox('check');
  677. $('#federated-avatar-lookup').checkbox('uncheck');
  678. }
  679. });
  680. $('#disable-gravatar input').on('change', function () {
  681. if ($(this).is(':checked')) {
  682. $('#federated-avatar-lookup').checkbox('uncheck');
  683. } else {
  684. $('#offline-mode').checkbox('uncheck');
  685. }
  686. });
  687. $('#federated-avatar-lookup input').on('change', function () {
  688. if ($(this).is(':checked')) {
  689. $('#disable-gravatar').checkbox('uncheck');
  690. $('#offline-mode').checkbox('uncheck');
  691. }
  692. });
  693. $('#enable-openid-signin input').on('change', function () {
  694. if ($(this).is(':checked')) {
  695. if (!$('#disable-registration input').is(':checked')) {
  696. $('#enable-openid-signup').checkbox('check');
  697. }
  698. } else {
  699. $('#enable-openid-signup').checkbox('uncheck');
  700. }
  701. });
  702. $('#disable-registration input').on('change', function () {
  703. if ($(this).is(':checked')) {
  704. $('#enable-captcha').checkbox('uncheck');
  705. $('#enable-openid-signup').checkbox('uncheck');
  706. } else {
  707. $('#enable-openid-signup').checkbox('check');
  708. }
  709. });
  710. $('#enable-captcha input').on('change', function () {
  711. if ($(this).is(':checked')) {
  712. $('#disable-registration').checkbox('uncheck');
  713. }
  714. });
  715. }
  716. function initIssueComments() {
  717. if ($('.repository.view.issue .timeline').length === 0) return;
  718. $('.re-request-review').on('click', function (event) {
  719. const url = $(this).data('update-url');
  720. const issueId = $(this).data('issue-id');
  721. const id = $(this).data('id');
  722. const isChecked = $(this).data('is-checked');
  723. event.preventDefault();
  724. updateIssuesMeta(url, '', issueId, id, isChecked).then(reload);
  725. });
  726. $(document).on('click', (event) => {
  727. const urlTarget = $(':target');
  728. if (urlTarget.length === 0) return;
  729. const urlTargetId = urlTarget.attr('id');
  730. if (!urlTargetId) return;
  731. if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return;
  732. const $target = $(event.target);
  733. if ($target.closest(`#${urlTargetId}`).length === 0) {
  734. const scrollPosition = $(window).scrollTop();
  735. window.location.hash = '';
  736. $(window).scrollTop(scrollPosition);
  737. window.history.pushState(null, null, ' ');
  738. }
  739. });
  740. }
  741. async function initRepository() {
  742. if ($('.repository').length === 0) {
  743. return;
  744. }
  745. function initFilterSearchDropdown(selector) {
  746. const $dropdown = $(selector);
  747. $dropdown.dropdown({
  748. fullTextSearch: true,
  749. selectOnKeydown: false,
  750. onChange(_text, _value, $choice) {
  751. if ($choice.data('url')) {
  752. window.location.href = $choice.data('url');
  753. }
  754. },
  755. message: {noResults: $dropdown.data('no-results')}
  756. });
  757. }
  758. // File list and commits
  759. if (
  760. $('.repository.file.list').length > 0 ||
  761. '.repository.commits'.length > 0
  762. ) {
  763. initFilterBranchTagDropdown('.choose.reference .dropdown');
  764. }
  765. // Wiki
  766. if ($('.repository.wiki.view').length > 0) {
  767. initFilterSearchDropdown('.choose.page .dropdown');
  768. }
  769. // Options
  770. if ($('.repository.settings.options').length > 0) {
  771. // Enable or select internal/external wiki system and issue tracker.
  772. $('.enable-system').on('change', function () {
  773. if (this.checked) {
  774. $($(this).data('target')).removeClass('disabled');
  775. if (!$(this).data('context')) {
  776. $($(this).data('context')).addClass('disabled');
  777. }
  778. } else {
  779. $($(this).data('target')).addClass('disabled');
  780. if (!$(this).data('context')) {
  781. $($(this).data('context')).removeClass('disabled');
  782. }
  783. }
  784. });
  785. $('.enable-system-radio').on('change', function () {
  786. if (this.value === 'false') {
  787. $($(this).data('target')).addClass('disabled');
  788. if (typeof $(this).data('context') !== 'undefined') {
  789. $($(this).data('context')).removeClass('disabled');
  790. }
  791. } else if (this.value === 'true') {
  792. $($(this).data('target')).removeClass('disabled');
  793. if (typeof $(this).data('context') !== 'undefined') {
  794. $($(this).data('context')).addClass('disabled');
  795. }
  796. }
  797. });
  798. }
  799. // Labels
  800. if ($('.repository.labels').length > 0) {
  801. initLabelEdit();
  802. }
  803. // Milestones
  804. if ($('.repository.new.milestone').length > 0) {
  805. const $datepicker = $('.milestone.datepicker');
  806. await initDateTimePicker($datepicker.data('lang'));
  807. $datepicker.datetimepicker({
  808. inline: true,
  809. timepicker: false,
  810. startDate: $datepicker.data('start-date'),
  811. onSelectDate(date) {
  812. $('#deadline').val(date.toISOString().substring(0, 10));
  813. }
  814. });
  815. $('#clear-date').on('click', () => {
  816. $('#deadline').val('');
  817. return false;
  818. });
  819. }
  820. // Issues
  821. if ($('.repository.view.issue').length > 0) {
  822. // Edit issue title
  823. const $issueTitle = $('#issue-title');
  824. const $editInput = $('#edit-title-input input');
  825. const editTitleToggle = function () {
  826. $issueTitle.toggle();
  827. $('.not-in-edit').toggle();
  828. $('#edit-title-input').toggle();
  829. $('#pull-desc').toggle();
  830. $('#pull-desc-edit').toggle();
  831. $('.in-edit').toggle();
  832. $editInput.focus();
  833. return false;
  834. };
  835. const changeBranchSelect = function () {
  836. const selectionTextField = $('#pull-target-branch');
  837. const baseName = selectionTextField.data('basename');
  838. const branchNameNew = $(this).data('branch');
  839. const branchNameOld = selectionTextField.data('branch');
  840. // Replace branch name to keep translation from HTML template
  841. selectionTextField.html(
  842. selectionTextField
  843. .html()
  844. .replace(
  845. `${baseName}:${branchNameOld}`,
  846. `${baseName}:${branchNameNew}`
  847. )
  848. );
  849. selectionTextField.data('branch', branchNameNew); // update branch name in setting
  850. };
  851. $('#branch-select > .item').on('click', changeBranchSelect);
  852. $('#edit-title').on('click', editTitleToggle);
  853. $('#cancel-edit-title').on('click', editTitleToggle);
  854. $('#save-edit-title')
  855. .on('click', editTitleToggle)
  856. .on('click', function () {
  857. const pullrequest_targetbranch_change = function (update_url) {
  858. const targetBranch = $('#pull-target-branch').data('branch');
  859. const $branchTarget = $('#branch_target');
  860. if (targetBranch === $branchTarget.text()) {
  861. return false;
  862. }
  863. $.post(update_url, {
  864. _csrf: csrf,
  865. target_branch: targetBranch
  866. })
  867. .done((data) => {
  868. $branchTarget.text(data.base_branch);
  869. })
  870. .always(() => {
  871. reload();
  872. });
  873. };
  874. const pullrequest_target_update_url = $(this).data('target-update-url');
  875. if (
  876. $editInput.val().length === 0 ||
  877. $editInput.val() === $issueTitle.text()
  878. ) {
  879. $editInput.val($issueTitle.text());
  880. pullrequest_targetbranch_change(pullrequest_target_update_url);
  881. } else {
  882. $.post(
  883. $(this).data('update-url'),
  884. {
  885. _csrf: csrf,
  886. title: $editInput.val()
  887. },
  888. (data) => {
  889. $editInput.val(data.title);
  890. $issueTitle.text(data.title);
  891. pullrequest_targetbranch_change(pullrequest_target_update_url);
  892. reload();
  893. }
  894. );
  895. }
  896. return false;
  897. });
  898. // Issue Comments
  899. initIssueComments();
  900. // Issue/PR Context Menus
  901. $('.context-dropdown').dropdown({
  902. action: 'hide'
  903. });
  904. // Quote reply
  905. $('.quote-reply').on('click', function (event) {
  906. $(this)
  907. .closest('.dropdown')
  908. .find('.menu')
  909. .toggle('visible');
  910. const target = $(this).data('target');
  911. const quote = $(`#comment-${target}`)
  912. .text()
  913. .replace(/\n/g, '\n> ');
  914. const content = `> ${quote}\n\n`;
  915. let $content;
  916. if ($(this).hasClass('quote-reply-diff')) {
  917. const $parent = $(this).closest('.comment-code-cloud');
  918. $parent.find('button.comment-form-reply').trigger('click');
  919. $content = $parent.find('[name="content"]');
  920. if ($content.val() !== '') {
  921. $content.val(`${$content.val()}\n\n${content}`);
  922. } else {
  923. $content.val(`${content}`);
  924. }
  925. $content.focus();
  926. } else if (autoSimpleMDE !== null) {
  927. if (autoSimpleMDE.value() !== '') {
  928. autoSimpleMDE.value(`${autoSimpleMDE.value()}\n\n${content}`);
  929. } else {
  930. autoSimpleMDE.value(`${content}`);
  931. }
  932. }
  933. event.preventDefault();
  934. });
  935. // Edit issue or comment content
  936. $('.edit-content').on('click', async function (event) {
  937. $(this)
  938. .closest('.dropdown')
  939. .find('.menu')
  940. .toggle('visible');
  941. const $segment = $(this)
  942. .closest('.header')
  943. .next();
  944. const $editContentZone = $segment.find('.edit-content-zone');
  945. const $renderContent = $segment.find('.render-content');
  946. const $rawContent = $segment.find('.raw-content');
  947. let $textarea;
  948. let $simplemde;
  949. // Setup new form
  950. if ($editContentZone.html().length === 0) {
  951. $editContentZone.html($('#edit-content-form').html());
  952. $textarea = $editContentZone.find('textarea');
  953. issuesTribute.attach($textarea.get());
  954. emojiTribute.attach($textarea.get());
  955. let dz;
  956. const $dropzone = $editContentZone.find('.dropzone');
  957. const $files = $editContentZone.find('.comment-files');
  958. if ($dropzone.length > 0) {
  959. $dropzone.data('saved', false);
  960. const filenameDict = {};
  961. dz = await createDropzone($dropzone[0], {
  962. url: $dropzone.data('upload-url'),
  963. headers: {'X-Csrf-Token': csrf},
  964. maxFiles: $dropzone.data('max-file'),
  965. maxFilesize: $dropzone.data('max-size'),
  966. acceptedFiles:
  967. $dropzone.data('accepts') === '*/*' ?
  968. null :
  969. $dropzone.data('accepts'),
  970. addRemoveLinks: true,
  971. dictDefaultMessage: $dropzone.data('default-message'),
  972. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  973. dictFileTooBig: $dropzone.data('file-too-big'),
  974. dictRemoveFile: $dropzone.data('remove-file'),
  975. init() {
  976. this.on('success', (file, data) => {
  977. filenameDict[file.name] = {
  978. uuid: data.uuid,
  979. submitted: false
  980. };
  981. const input = $(
  982. `<input id="${data.uuid}" name="files" type="hidden">`
  983. ).val(data.uuid);
  984. $files.append(input);
  985. });
  986. this.on('removedfile', (file) => {
  987. if (!(file.name in filenameDict)) {
  988. return;
  989. }
  990. $(`#${filenameDict[file.name].uuid}`).remove();
  991. if (
  992. $dropzone.data('remove-url') &&
  993. $dropzone.data('csrf') &&
  994. !filenameDict[file.name].submitted
  995. ) {
  996. $.post($dropzone.data('remove-url'), {
  997. file: filenameDict[file.name].uuid,
  998. _csrf: $dropzone.data('csrf')
  999. });
  1000. }
  1001. });
  1002. this.on('submit', () => {
  1003. $.each(filenameDict, (name) => {
  1004. filenameDict[name].submitted = true;
  1005. });
  1006. });
  1007. this.on('reload', () => {
  1008. $.getJSON($editContentZone.data('attachment-url'), (data) => {
  1009. dz.removeAllFiles(true);
  1010. $files.empty();
  1011. $.each(data, function () {
  1012. const imgSrc = `${$dropzone.data('upload-url')}/${
  1013. this.uuid
  1014. }`;
  1015. dz.emit('addedfile', this);
  1016. dz.emit('thumbnail', this, imgSrc);
  1017. dz.emit('complete', this);
  1018. dz.files.push(this);
  1019. filenameDict[this.name] = {
  1020. submitted: true,
  1021. uuid: this.uuid
  1022. };
  1023. $dropzone
  1024. .find(`img[src='${imgSrc}']`)
  1025. .css('max-width', '100%');
  1026. const input = $(
  1027. `<input id="${this.uuid}" name="files" type="hidden">`
  1028. ).val(this.uuid);
  1029. $files.append(input);
  1030. });
  1031. });
  1032. });
  1033. }
  1034. });
  1035. dz.emit('reload');
  1036. }
  1037. // Give new write/preview data-tab name to distinguish from others
  1038. const $editContentForm = $editContentZone.find('.ui.comment.form');
  1039. const $tabMenu = $editContentForm.find('.tabular.menu');
  1040. $tabMenu.attr('data-write', $editContentZone.data('write'));
  1041. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  1042. $tabMenu
  1043. .find('.write.item')
  1044. .attr('data-tab', $editContentZone.data('write'));
  1045. $tabMenu
  1046. .find('.preview.item')
  1047. .attr('data-tab', $editContentZone.data('preview'));
  1048. $editContentForm
  1049. .find('.write')
  1050. .attr('data-tab', $editContentZone.data('write'));
  1051. $editContentForm
  1052. .find('.preview')
  1053. .attr('data-tab', $editContentZone.data('preview'));
  1054. $simplemde = setCommentSimpleMDE($textarea);
  1055. commentMDEditors[$editContentZone.data('write')] = $simplemde;
  1056. initCommentPreviewTab($editContentForm);
  1057. initSimpleMDEImagePaste($simplemde, $files);
  1058. $editContentZone.find('.cancel.button').on('click', () => {
  1059. $renderContent.show();
  1060. $editContentZone.hide();
  1061. dz.emit('reload');
  1062. });
  1063. $editContentZone.find('.save.button').on('click', () => {
  1064. $renderContent.show();
  1065. $editContentZone.hide();
  1066. const $attachments = $files
  1067. .find('[name=files]')
  1068. .map(function () {
  1069. return $(this).val();
  1070. })
  1071. .get();
  1072. $.post(
  1073. $editContentZone.data('update-url'),
  1074. {
  1075. _csrf: csrf,
  1076. content: $textarea.val(),
  1077. context: $editContentZone.data('context'),
  1078. files: $attachments
  1079. },
  1080. (data) => {
  1081. if (data.length === 0) {
  1082. $renderContent.html($('#no-content').html());
  1083. } else {
  1084. $renderContent.html(data.content);
  1085. $('pre code', $renderContent[0]).each(function () {
  1086. highlight(this);
  1087. });
  1088. }
  1089. const $content = $segment.parent();
  1090. if (!$content.find('.ui.small.images').length) {
  1091. if (data.attachments !== '') {
  1092. $content.append(
  1093. '<div class="ui bottom attached segment"><div class="ui small images"></div></div>'
  1094. );
  1095. $content.find('.ui.small.images').html(data.attachments);
  1096. }
  1097. } else if (data.attachments === '') {
  1098. $content
  1099. .find('.ui.small.images')
  1100. .parent()
  1101. .remove();
  1102. } else {
  1103. $content.find('.ui.small.images').html(data.attachments);
  1104. }
  1105. dz.emit('submit');
  1106. dz.emit('reload');
  1107. }
  1108. );
  1109. });
  1110. } else {
  1111. $textarea = $segment.find('textarea');
  1112. $simplemde = commentMDEditors[$editContentZone.data('write')];
  1113. }
  1114. // Show write/preview tab and copy raw content as needed
  1115. $editContentZone.show();
  1116. $renderContent.hide();
  1117. if ($textarea.val().length === 0) {
  1118. $textarea.val($rawContent.text());
  1119. $simplemde.value($rawContent.text());
  1120. }
  1121. $textarea.focus();
  1122. $simplemde.codemirror.focus();
  1123. event.preventDefault();
  1124. });
  1125. // Delete comment
  1126. $('.delete-comment').on('click', function () {
  1127. const $this = $(this);
  1128. if (window.confirm($this.data('locale'))) {
  1129. $.post($this.data('url'), {
  1130. _csrf: csrf
  1131. }).done(() => {
  1132. $(`#${$this.data('comment-id')}`).remove();
  1133. });
  1134. }
  1135. return false;
  1136. });
  1137. // Change status
  1138. const $statusButton = $('#status-button');
  1139. $('#comment-form .edit_area').on('keyup', function () {
  1140. if ($(this).val().length === 0) {
  1141. $statusButton.text($statusButton.data('status'));
  1142. } else {
  1143. $statusButton.text($statusButton.data('status-and-comment'));
  1144. }
  1145. });
  1146. $statusButton.on('click', () => {
  1147. $('#status').val($statusButton.data('status-val'));
  1148. $('#comment-form').trigger('submit');
  1149. });
  1150. // Pull Request merge button
  1151. const $mergeButton = $('.merge-button > button');
  1152. $mergeButton.on('click', function (e) {
  1153. e.preventDefault();
  1154. $(`.${$(this).data('do')}-fields`).show();
  1155. $(this)
  1156. .parent()
  1157. .hide();
  1158. });
  1159. $('.merge-button > .dropdown').dropdown({
  1160. onChange(_text, _value, $choice) {
  1161. if ($choice.data('do')) {
  1162. $mergeButton.find('.button-text').text($choice.text());
  1163. $mergeButton.data('do', $choice.data('do'));
  1164. }
  1165. }
  1166. });
  1167. $('.merge-cancel').on('click', function (e) {
  1168. e.preventDefault();
  1169. $(this)
  1170. .closest('.form')
  1171. .hide();
  1172. $mergeButton.parent().show();
  1173. });
  1174. initReactionSelector();
  1175. }
  1176. // Datasets
  1177. if ($('.repository.dataset-list.view').length > 0) {
  1178. const editContentToggle = function () {
  1179. $('#dataset-content').toggle();
  1180. $('#dataset-content-edit').toggle();
  1181. $('#dataset-content input').focus();
  1182. return false;
  1183. };
  1184. $('[data-dataset-status]').on('click', function () {
  1185. const $this = $(this);
  1186. const $private = $this.data('private');
  1187. const $is_private = $this.data('is-private');
  1188. if ($is_private === $private) {
  1189. return;
  1190. }
  1191. const $uuid = $this.data('uuid');
  1192. $.post($this.data('url'), {
  1193. _csrf: $this.data('csrf'),
  1194. file: $uuid,
  1195. is_private: $private
  1196. })
  1197. .done((_data) => {
  1198. $(`[data-uuid='${$uuid}']`).removeClass('positive active');
  1199. $(`[data-uuid='${$uuid}']`).data('is-private', $private);
  1200. $this.addClass('positive active');
  1201. })
  1202. .fail(() => {
  1203. window.location.reload();
  1204. });
  1205. });
  1206. $('[data-dataset-delete]').on('click', function () {
  1207. const $this = $(this);
  1208. $('#data-dataset-delete-modal')
  1209. .modal({
  1210. closable: false,
  1211. onApprove() {
  1212. $.post($this.data('remove-url'), {
  1213. _csrf: $this.data('csrf'),
  1214. file: $this.data('uuid')
  1215. })
  1216. .done((_data) => {
  1217. $(`#${$this.data('uuid')}`).hide();
  1218. })
  1219. .fail(() => {
  1220. window.location.reload();
  1221. });
  1222. }
  1223. })
  1224. .modal('show');
  1225. });
  1226. $('[data-category-id]').on('click', function () {
  1227. const category = $(this).data('category-id');
  1228. $('#category').val(category);
  1229. $('#submit').click();
  1230. });
  1231. $('[data-task-id]').on('click', function () {
  1232. const task = $(this).data('task-id');
  1233. $('#task').val(task);
  1234. $('#submit').click();
  1235. });
  1236. $('[data-license-id]').on('click', function () {
  1237. const license = $(this).data('license-id');
  1238. $('#license').val(license);
  1239. $('#submit').click();
  1240. });
  1241. $('#dataset-edit').on('click', editContentToggle);
  1242. $('#cancel').on('click', editContentToggle);
  1243. }
  1244. // Diff
  1245. if ($('.repository.diff').length > 0) {
  1246. $('.diff-counter').each(function () {
  1247. const $item = $(this);
  1248. const addLine = $item.find('span[data-line].add').data('line');
  1249. const delLine = $item.find('span[data-line].del').data('line');
  1250. const addPercent =
  1251. (parseFloat(addLine) / (parseFloat(addLine) + parseFloat(delLine))) *
  1252. 100;
  1253. $item.find('.bar .add').css('width', `${addPercent}%`);
  1254. });
  1255. }
  1256. // Quick start and repository home
  1257. $('#repo-clone-ssh').on('click', function () {
  1258. $('.clone-url').text($(this).data('link'));
  1259. $('#repo-clone-url').val($(this).data('link'));
  1260. $(this).addClass('blue');
  1261. $('#repo-clone-https').removeClass('blue');
  1262. localStorage.setItem('repo-clone-protocol', 'ssh');
  1263. });
  1264. $('#repo-clone-https').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-ssh').removeClass('blue');
  1269. localStorage.setItem('repo-clone-protocol', 'https');
  1270. });
  1271. $('#repo-clone-url').on('click', function () {
  1272. $(this).select();
  1273. });
  1274. // Pull request
  1275. const $repoComparePull = $('.repository.compare.pull');
  1276. if ($repoComparePull.length > 0) {
  1277. initFilterSearchDropdown('.choose.branch .dropdown');
  1278. // show pull request form
  1279. $repoComparePull.find('button.show-form').on('click', function (e) {
  1280. e.preventDefault();
  1281. $repoComparePull.find('.pullrequest-form').show();
  1282. autoSimpleMDE.codemirror.refresh();
  1283. $(this)
  1284. .parent()
  1285. .hide();
  1286. });
  1287. }
  1288. // Branches
  1289. if ($('.repository.settings.branches').length > 0) {
  1290. initFilterSearchDropdown('.protected-branches .dropdown');
  1291. $('.enable-protection, .enable-whitelist, .enable-statuscheck').on(
  1292. 'change',
  1293. function () {
  1294. if (this.checked) {
  1295. $($(this).data('target')).removeClass('disabled');
  1296. } else {
  1297. $($(this).data('target')).addClass('disabled');
  1298. }
  1299. }
  1300. );
  1301. $('.disable-whitelist').on('change', function () {
  1302. if (this.checked) {
  1303. $($(this).data('target')).addClass('disabled');
  1304. }
  1305. });
  1306. }
  1307. // Language stats
  1308. if ($('.language-stats').length > 0) {
  1309. $('.language-stats').on('click', (e) => {
  1310. e.preventDefault();
  1311. $('.language-stats-details, .repository-menu').slideToggle();
  1312. });
  1313. }
  1314. }
  1315. function initMigration() {
  1316. const toggleMigrations = function () {
  1317. const authUserName = $('#auth_username').val();
  1318. const cloneAddr = $('#clone_addr').val();
  1319. if (
  1320. !$('#mirror').is(':checked') &&
  1321. authUserName &&
  1322. authUserName.length > 0 &&
  1323. cloneAddr !== undefined &&
  1324. (cloneAddr.startsWith('https://github.com') ||
  1325. cloneAddr.startsWith('http://github.com') ||
  1326. cloneAddr.startsWith('http://gitlab.com') ||
  1327. cloneAddr.startsWith('https://gitlab.com'))
  1328. ) {
  1329. $('#migrate_items').show();
  1330. } else {
  1331. $('#migrate_items').hide();
  1332. }
  1333. };
  1334. toggleMigrations();
  1335. $('#clone_addr').on('input', toggleMigrations);
  1336. $('#auth_username').on('input', toggleMigrations);
  1337. $('#mirror').on('change', toggleMigrations);
  1338. }
  1339. function initPullRequestReview() {
  1340. $('.show-outdated').on('click', function (e) {
  1341. e.preventDefault();
  1342. const id = $(this).data('comment');
  1343. $(this).addClass('hide');
  1344. $(`#code-comments-${id}`).removeClass('hide');
  1345. $(`#code-preview-${id}`).removeClass('hide');
  1346. $(`#hide-outdated-${id}`).removeClass('hide');
  1347. });
  1348. $('.hide-outdated').on('click', function (e) {
  1349. e.preventDefault();
  1350. const id = $(this).data('comment');
  1351. $(this).addClass('hide');
  1352. $(`#code-comments-${id}`).addClass('hide');
  1353. $(`#code-preview-${id}`).addClass('hide');
  1354. $(`#show-outdated-${id}`).removeClass('hide');
  1355. });
  1356. $('button.comment-form-reply').on('click', function (e) {
  1357. e.preventDefault();
  1358. $(this).hide();
  1359. const form = $(this)
  1360. .parent()
  1361. .find('.comment-form');
  1362. form.removeClass('hide');
  1363. assingMenuAttributes(form.find('.menu'));
  1364. });
  1365. // The following part is only for diff views
  1366. if ($('.repository.pull.diff').length === 0) {
  1367. return;
  1368. }
  1369. $('.diff-detail-box.ui.sticky').sticky();
  1370. $('.btn-review')
  1371. .on('click', function (e) {
  1372. e.preventDefault();
  1373. $(this)
  1374. .closest('.dropdown')
  1375. .find('.menu')
  1376. .toggle('visible');
  1377. })
  1378. .closest('.dropdown')
  1379. .find('.link.close')
  1380. .on('click', function (e) {
  1381. e.preventDefault();
  1382. $(this)
  1383. .closest('.menu')
  1384. .toggle('visible');
  1385. });
  1386. $('.code-view .lines-code,.code-view .lines-num')
  1387. .on('mouseenter', function () {
  1388. const parent = $(this).closest('td');
  1389. $(this)
  1390. .closest('tr')
  1391. .addClass(
  1392. parent.hasClass('lines-num-old') || parent.hasClass('lines-code-old') ?
  1393. 'focus-lines-old' :
  1394. 'focus-lines-new'
  1395. );
  1396. })
  1397. .on('mouseleave', function () {
  1398. $(this)
  1399. .closest('tr')
  1400. .removeClass('focus-lines-new focus-lines-old');
  1401. });
  1402. $('.add-code-comment').on('click', function (e) {
  1403. // https://github.com/go-gitea/gitea/issues/4745
  1404. if ($(e.target).hasClass('btn-add-single')) {
  1405. return;
  1406. }
  1407. e.preventDefault();
  1408. const isSplit = $(this)
  1409. .closest('.code-diff')
  1410. .hasClass('code-diff-split');
  1411. const side = $(this).data('side');
  1412. const idx = $(this).data('idx');
  1413. const path = $(this).data('path');
  1414. const form = $('#pull_review_add_comment').html();
  1415. const tr = $(this).closest('tr');
  1416. let ntr = tr.next();
  1417. if (!ntr.hasClass('add-comment')) {
  1418. ntr = $(
  1419. `<tr class="add-comment">${
  1420. isSplit ?
  1421. '<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>' :
  1422. '<td class="lines-num"></td><td class="lines-num"></td><td class="add-comment-left add-comment-right" colspan="2"></td>'
  1423. }</tr>`
  1424. );
  1425. tr.after(ntr);
  1426. }
  1427. const td = ntr.find(`.add-comment-${side}`);
  1428. let commentCloud = td.find('.comment-code-cloud');
  1429. if (commentCloud.length === 0) {
  1430. td.html(form);
  1431. commentCloud = td.find('.comment-code-cloud');
  1432. assingMenuAttributes(commentCloud.find('.menu'));
  1433. td.find("input[name='line']").val(idx);
  1434. td.find("input[name='side']").val(
  1435. side === 'left' ? 'previous' : 'proposed'
  1436. );
  1437. td.find("input[name='path']").val(path);
  1438. }
  1439. commentCloud.find('textarea').focus();
  1440. });
  1441. }
  1442. function assingMenuAttributes(menu) {
  1443. const id = Math.floor(Math.random() * Math.floor(1000000));
  1444. menu.attr('data-write', menu.attr('data-write') + id);
  1445. menu.attr('data-preview', menu.attr('data-preview') + id);
  1446. menu.find('.item').each(function () {
  1447. const tab = $(this).attr('data-tab') + id;
  1448. $(this).attr('data-tab', tab);
  1449. });
  1450. menu
  1451. .parent()
  1452. .find("*[data-tab='write']")
  1453. .attr('data-tab', `write${id}`);
  1454. menu
  1455. .parent()
  1456. .find("*[data-tab='preview']")
  1457. .attr('data-tab', `preview${id}`);
  1458. initCommentPreviewTab(menu.parent('.form'));
  1459. return id;
  1460. }
  1461. function initRepositoryCollaboration() {
  1462. // Change collaborator access mode
  1463. $('.access-mode.menu .item').on('click', function () {
  1464. const $menu = $(this).parent();
  1465. $.post($menu.data('url'), {
  1466. _csrf: csrf,
  1467. uid: $menu.data('uid'),
  1468. mode: $(this).data('value')
  1469. });
  1470. });
  1471. }
  1472. function initTeamSettings() {
  1473. // Change team access mode
  1474. $('.organization.new.team input[name=permission]').on('change', () => {
  1475. const val = $(
  1476. 'input[name=permission]:checked',
  1477. '.organization.new.team'
  1478. ).val();
  1479. if (val === 'admin') {
  1480. $('.organization.new.team .team-units').hide();
  1481. } else {
  1482. $('.organization.new.team .team-units').show();
  1483. }
  1484. });
  1485. }
  1486. function initWikiForm() {
  1487. const $editArea = $('.repository.wiki textarea#edit_area');
  1488. let sideBySideChanges = 0;
  1489. let sideBySideTimeout = null;
  1490. if ($editArea.length > 0) {
  1491. const simplemde = new SimpleMDE({
  1492. autoDownloadFontAwesome: false,
  1493. element: $editArea[0],
  1494. forceSync: true,
  1495. previewRender(plainText, preview) {
  1496. // Async method
  1497. setTimeout(() => {
  1498. // FIXME: still send render request when return back to edit mode
  1499. const render = function () {
  1500. sideBySideChanges = 0;
  1501. if (sideBySideTimeout !== null) {
  1502. clearTimeout(sideBySideTimeout);
  1503. sideBySideTimeout = null;
  1504. }
  1505. $.post(
  1506. $editArea.data('url'),
  1507. {
  1508. _csrf: csrf,
  1509. mode: 'gfm',
  1510. context: $editArea.data('context'),
  1511. text: plainText
  1512. },
  1513. (data) => {
  1514. preview.innerHTML = `<div class="markdown ui segment">${data}</div>`;
  1515. $(preview)
  1516. .find('pre code')
  1517. .each((_, e) => {
  1518. highlight(e);
  1519. });
  1520. }
  1521. );
  1522. };
  1523. if (!simplemde.isSideBySideActive()) {
  1524. render();
  1525. } else {
  1526. // delay preview by keystroke counting
  1527. sideBySideChanges++;
  1528. if (sideBySideChanges > 10) {
  1529. render();
  1530. }
  1531. // or delay preview by timeout
  1532. if (sideBySideTimeout !== null) {
  1533. clearTimeout(sideBySideTimeout);
  1534. sideBySideTimeout = null;
  1535. }
  1536. sideBySideTimeout = setTimeout(render, 600);
  1537. }
  1538. }, 0);
  1539. if (!simplemde.isSideBySideActive()) {
  1540. return 'Loading...';
  1541. }
  1542. return preview.innerHTML;
  1543. },
  1544. renderingConfig: {
  1545. singleLineBreaks: false
  1546. },
  1547. indentWithTabs: false,
  1548. tabSize: 4,
  1549. spellChecker: false,
  1550. toolbar: [
  1551. 'bold',
  1552. 'italic',
  1553. 'strikethrough',
  1554. '|',
  1555. 'heading-1',
  1556. 'heading-2',
  1557. 'heading-3',
  1558. 'heading-bigger',
  1559. 'heading-smaller',
  1560. '|',
  1561. {
  1562. name: 'code-inline',
  1563. action(e) {
  1564. const cm = e.codemirror;
  1565. const selection = cm.getSelection();
  1566. cm.replaceSelection(`\`${selection}\``);
  1567. if (!selection) {
  1568. const cursorPos = cm.getCursor();
  1569. cm.setCursor(cursorPos.line, cursorPos.ch - 1);
  1570. }
  1571. cm.focus();
  1572. },
  1573. className: 'fa fa-angle-right',
  1574. title: 'Add Inline Code'
  1575. },
  1576. 'code',
  1577. 'quote',
  1578. '|',
  1579. {
  1580. name: 'checkbox-empty',
  1581. action(e) {
  1582. const cm = e.codemirror;
  1583. cm.replaceSelection(`\n- [ ] ${cm.getSelection()}`);
  1584. cm.focus();
  1585. },
  1586. className: 'fa fa-square-o',
  1587. title: 'Add Checkbox (empty)'
  1588. },
  1589. {
  1590. name: 'checkbox-checked',
  1591. action(e) {
  1592. const cm = e.codemirror;
  1593. cm.replaceSelection(`\n- [x] ${cm.getSelection()}`);
  1594. cm.focus();
  1595. },
  1596. className: 'fa fa-check-square-o',
  1597. title: 'Add Checkbox (checked)'
  1598. },
  1599. '|',
  1600. 'unordered-list',
  1601. 'ordered-list',
  1602. '|',
  1603. 'link',
  1604. 'image',
  1605. 'table',
  1606. 'horizontal-rule',
  1607. '|',
  1608. 'clean-block',
  1609. 'preview',
  1610. 'fullscreen',
  1611. 'side-by-side',
  1612. '|',
  1613. {
  1614. name: 'revert-to-textarea',
  1615. action(e) {
  1616. e.toTextArea();
  1617. },
  1618. className: 'fa fa-file',
  1619. title: 'Revert to simple textarea'
  1620. }
  1621. ]
  1622. });
  1623. $(simplemde.codemirror.getInputField()).addClass('js-quick-submit');
  1624. setTimeout(() => {
  1625. const $bEdit = $('.repository.wiki.new .previewtabs a[data-tab="write"]');
  1626. const $bPrev = $(
  1627. '.repository.wiki.new .previewtabs a[data-tab="preview"]'
  1628. );
  1629. const $toolbar = $('.editor-toolbar');
  1630. const $bPreview = $('.editor-toolbar a.fa-eye');
  1631. const $bSideBySide = $('.editor-toolbar a.fa-columns');
  1632. $bEdit.on('click', () => {
  1633. if ($toolbar.hasClass('disabled-for-preview')) {
  1634. $bPreview.trigger('click');
  1635. }
  1636. });
  1637. $bPrev.on('click', () => {
  1638. if (!$toolbar.hasClass('disabled-for-preview')) {
  1639. $bPreview.trigger('click');
  1640. }
  1641. });
  1642. $bPreview.on('click', () => {
  1643. setTimeout(() => {
  1644. if ($toolbar.hasClass('disabled-for-preview')) {
  1645. if ($bEdit.hasClass('active')) {
  1646. $bEdit.removeClass('active');
  1647. }
  1648. if (!$bPrev.hasClass('active')) {
  1649. $bPrev.addClass('active');
  1650. }
  1651. } else {
  1652. if (!$bEdit.hasClass('active')) {
  1653. $bEdit.addClass('active');
  1654. }
  1655. if ($bPrev.hasClass('active')) {
  1656. $bPrev.removeClass('active');
  1657. }
  1658. }
  1659. }, 0);
  1660. });
  1661. $bSideBySide.on('click', () => {
  1662. sideBySideChanges = 10;
  1663. });
  1664. }, 0);
  1665. }
  1666. }
  1667. // Adding function to get the cursor position in a text field to jQuery object.
  1668. $.fn.getCursorPosition = function () {
  1669. const el = $(this).get(0);
  1670. let pos = 0;
  1671. if ('selectionStart' in el) {
  1672. pos = el.selectionStart;
  1673. } else if ('selection' in document) {
  1674. el.focus();
  1675. const Sel = document.selection.createRange();
  1676. const SelLength = document.selection.createRange().text.length;
  1677. Sel.moveStart('character', -el.value.length);
  1678. pos = Sel.text.length - SelLength;
  1679. }
  1680. return pos;
  1681. };
  1682. function setCommentSimpleMDE($editArea) {
  1683. const simplemde = new SimpleMDE({
  1684. autoDownloadFontAwesome: false,
  1685. element: $editArea[0],
  1686. forceSync: true,
  1687. renderingConfig: {
  1688. singleLineBreaks: false
  1689. },
  1690. indentWithTabs: false,
  1691. tabSize: 4,
  1692. spellChecker: false,
  1693. toolbar: [
  1694. 'bold',
  1695. 'italic',
  1696. 'strikethrough',
  1697. '|',
  1698. 'heading-1',
  1699. 'heading-2',
  1700. 'heading-3',
  1701. 'heading-bigger',
  1702. 'heading-smaller',
  1703. '|',
  1704. 'code',
  1705. 'quote',
  1706. '|',
  1707. 'unordered-list',
  1708. 'ordered-list',
  1709. '|',
  1710. 'link',
  1711. 'image',
  1712. 'table',
  1713. 'horizontal-rule',
  1714. '|',
  1715. 'clean-block',
  1716. '|',
  1717. {
  1718. name: 'revert-to-textarea',
  1719. action(e) {
  1720. e.toTextArea();
  1721. },
  1722. className: 'fa fa-file',
  1723. title: 'Revert to simple textarea'
  1724. }
  1725. ]
  1726. });
  1727. $(simplemde.codemirror.getInputField()).addClass('js-quick-submit');
  1728. simplemde.codemirror.setOption('extraKeys', {
  1729. Enter: () => {
  1730. if (!(issuesTribute.isActive || emojiTribute.isActive)) {
  1731. return CodeMirror.Pass;
  1732. }
  1733. },
  1734. Backspace: (cm) => {
  1735. if (cm.getInputField().trigger) {
  1736. cm.getInputField().trigger('input');
  1737. }
  1738. cm.execCommand('delCharBefore');
  1739. }
  1740. });
  1741. issuesTribute.attach(simplemde.codemirror.getInputField());
  1742. emojiTribute.attach(simplemde.codemirror.getInputField());
  1743. return simplemde;
  1744. }
  1745. async function initEditor() {
  1746. $('.js-quick-pull-choice-option').on('change', function () {
  1747. if ($(this).val() === 'commit-to-new-branch') {
  1748. $('.quick-pull-branch-name').show();
  1749. $('.quick-pull-branch-name input').prop('required', true);
  1750. } else {
  1751. $('.quick-pull-branch-name').hide();
  1752. $('.quick-pull-branch-name input').prop('required', false);
  1753. }
  1754. $('#commit-button').text($(this).attr('button_text'));
  1755. });
  1756. const $editFilename = $('#file-name');
  1757. $editFilename
  1758. .on('keyup', function (e) {
  1759. const $section = $('.breadcrumb span.section');
  1760. const $divider = $('.breadcrumb div.divider');
  1761. let value;
  1762. let parts;
  1763. if (e.keyCode === 8) {
  1764. if ($(this).getCursorPosition() === 0) {
  1765. if ($section.length > 0) {
  1766. value = $section
  1767. .last()
  1768. .find('a')
  1769. .text();
  1770. $(this).val(value + $(this).val());
  1771. $(this)[0].setSelectionRange(value.length, value.length);
  1772. $section.last().remove();
  1773. $divider.last().remove();
  1774. }
  1775. }
  1776. }
  1777. if (e.keyCode === 191) {
  1778. parts = $(this)
  1779. .val()
  1780. .split('/');
  1781. for (let i = 0; i < parts.length; ++i) {
  1782. value = parts[i];
  1783. if (i < parts.length - 1) {
  1784. if (value.length) {
  1785. $(
  1786. `<span class="section"><a href="#">${value}</a></span>`
  1787. ).insertBefore($(this));
  1788. $('<div class="divider"> / </div>').insertBefore($(this));
  1789. }
  1790. } else {
  1791. $(this).val(value);
  1792. }
  1793. $(this)[0].setSelectionRange(0, 0);
  1794. }
  1795. }
  1796. parts = [];
  1797. $('.breadcrumb span.section').each(function () {
  1798. const element = $(this);
  1799. if (element.find('a').length) {
  1800. parts.push(element.find('a').text());
  1801. } else {
  1802. parts.push(element.text());
  1803. }
  1804. });
  1805. if ($(this).val()) parts.push($(this).val());
  1806. $('#tree_path').val(parts.join('/'));
  1807. })
  1808. .trigger('keyup');
  1809. const $editArea = $('.repository.editor textarea#edit_area');
  1810. if (!$editArea.length) return;
  1811. await createCodeEditor($editArea[0], $editFilename[0], previewFileModes);
  1812. // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
  1813. // to enable or disable the commit button
  1814. const $commitButton = $('#commit-button');
  1815. const $editForm = $('.ui.edit.form');
  1816. const dirtyFileClass = 'dirty-file';
  1817. // Disabling the button at the start
  1818. $commitButton.prop('disabled', true);
  1819. // Registering a custom listener for the file path and the file content
  1820. $editForm.areYouSure({
  1821. silent: true,
  1822. dirtyClass: dirtyFileClass,
  1823. fieldSelector: ':input:not(.commit-form-wrapper :input)',
  1824. change() {
  1825. const dirty = $(this).hasClass(dirtyFileClass);
  1826. $commitButton.prop('disabled', !dirty);
  1827. }
  1828. });
  1829. $commitButton.on('click', (event) => {
  1830. // A modal which asks if an empty file should be committed
  1831. if ($editArea.val().length === 0) {
  1832. $('#edit-empty-content-modal')
  1833. .modal({
  1834. onApprove() {
  1835. $('.edit.form').trigger('submit');
  1836. }
  1837. })
  1838. .modal('show');
  1839. event.preventDefault();
  1840. }
  1841. });
  1842. }
  1843. function initOrganization() {
  1844. if ($('.organization').length === 0) {
  1845. return;
  1846. }
  1847. // Options
  1848. if ($('.organization.settings.options').length > 0) {
  1849. $('#org_name').on('keyup', function () {
  1850. const $prompt = $('#org-name-change-prompt');
  1851. if (
  1852. $(this)
  1853. .val()
  1854. .toString()
  1855. .toLowerCase() !==
  1856. $(this)
  1857. .data('org-name')
  1858. .toString()
  1859. .toLowerCase()
  1860. ) {
  1861. $prompt.show();
  1862. } else {
  1863. $prompt.hide();
  1864. }
  1865. });
  1866. }
  1867. // Labels
  1868. if ($('.organization.settings.labels').length > 0) {
  1869. initLabelEdit();
  1870. }
  1871. }
  1872. function initUserSettings() {
  1873. // Options
  1874. if ($('.user.settings.profile').length > 0) {
  1875. $('#username').on('keyup', function () {
  1876. const $prompt = $('#name-change-prompt');
  1877. if (
  1878. $(this)
  1879. .val()
  1880. .toString()
  1881. .toLowerCase() !==
  1882. $(this)
  1883. .data('name')
  1884. .toString()
  1885. .toLowerCase()
  1886. ) {
  1887. $prompt.show();
  1888. } else {
  1889. $prompt.hide();
  1890. }
  1891. });
  1892. }
  1893. }
  1894. function initGithook() {
  1895. if ($('.edit.githook').length === 0) {
  1896. return;
  1897. }
  1898. CodeMirror.autoLoadMode(
  1899. CodeMirror.fromTextArea($('#content')[0], {
  1900. lineNumbers: true,
  1901. mode: 'shell'
  1902. }),
  1903. 'shell'
  1904. );
  1905. }
  1906. function initWebhook() {
  1907. if ($('.new.webhook').length === 0) {
  1908. return;
  1909. }
  1910. $('.events.checkbox input').on('change', function () {
  1911. if ($(this).is(':checked')) {
  1912. $('.events.fields').show();
  1913. }
  1914. });
  1915. $('.non-events.checkbox input').on('change', function () {
  1916. if ($(this).is(':checked')) {
  1917. $('.events.fields').hide();
  1918. }
  1919. });
  1920. const updateContentType = function () {
  1921. const visible = $('#http_method').val() === 'POST';
  1922. $('#content_type')
  1923. .parent()
  1924. .parent()
  1925. [visible ? 'show' : 'hide']();
  1926. };
  1927. updateContentType();
  1928. $('#http_method').on('change', () => {
  1929. updateContentType();
  1930. });
  1931. // Test delivery
  1932. $('#test-delivery').on('click', function () {
  1933. const $this = $(this);
  1934. $this.addClass('loading disabled');
  1935. $.post($this.data('link'), {
  1936. _csrf: csrf
  1937. }).done(
  1938. setTimeout(() => {
  1939. window.location.href = $this.data('redirect');
  1940. }, 5000)
  1941. );
  1942. });
  1943. }
  1944. function initAdmin() {
  1945. if ($('.admin').length === 0) {
  1946. return;
  1947. }
  1948. // New user
  1949. if ($('.admin.new.user').length > 0 || $('.admin.edit.user').length > 0) {
  1950. $('#login_type').on('change', function () {
  1951. if (
  1952. $(this)
  1953. .val()
  1954. .substring(0, 1) === '0'
  1955. ) {
  1956. $('#login_name').removeAttr('required');
  1957. $('.non-local').hide();
  1958. $('.local').show();
  1959. $('#user_name').focus();
  1960. if ($(this).data('password') === 'required') {
  1961. $('#password').attr('required', 'required');
  1962. }
  1963. } else {
  1964. $('#login_name').attr('required', 'required');
  1965. $('.non-local').show();
  1966. $('.local').hide();
  1967. $('#login_name').focus();
  1968. $('#password').removeAttr('required');
  1969. }
  1970. });
  1971. }
  1972. function onSecurityProtocolChange() {
  1973. if ($('#security_protocol').val() > 0) {
  1974. $('.has-tls').show();
  1975. } else {
  1976. $('.has-tls').hide();
  1977. }
  1978. }
  1979. function onUsePagedSearchChange() {
  1980. if ($('#use_paged_search').prop('checked')) {
  1981. $('.search-page-size')
  1982. .show()
  1983. .find('input')
  1984. .attr('required', 'required');
  1985. } else {
  1986. $('.search-page-size')
  1987. .hide()
  1988. .find('input')
  1989. .removeAttr('required');
  1990. }
  1991. }
  1992. function onOAuth2Change() {
  1993. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1994. $('.open_id_connect_auto_discovery_url input[required]').removeAttr(
  1995. 'required'
  1996. );
  1997. const provider = $('#oauth2_provider').val();
  1998. switch (provider) {
  1999. case 'github':
  2000. case 'gitlab':
  2001. case 'gitea':
  2002. case 'nextcloud':
  2003. $('.oauth2_use_custom_url').show();
  2004. break;
  2005. case 'openidConnect':
  2006. $('.open_id_connect_auto_discovery_url input').attr(
  2007. 'required',
  2008. 'required'
  2009. );
  2010. $('.open_id_connect_auto_discovery_url').show();
  2011. break;
  2012. }
  2013. onOAuth2UseCustomURLChange();
  2014. }
  2015. function onOAuth2UseCustomURLChange() {
  2016. const provider = $('#oauth2_provider').val();
  2017. $('.oauth2_use_custom_url_field').hide();
  2018. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  2019. if ($('#oauth2_use_custom_url').is(':checked')) {
  2020. $('#oauth2_token_url').val($(`#${provider}_token_url`).val());
  2021. $('#oauth2_auth_url').val($(`#${provider}_auth_url`).val());
  2022. $('#oauth2_profile_url').val($(`#${provider}_profile_url`).val());
  2023. $('#oauth2_email_url').val($(`#${provider}_email_url`).val());
  2024. switch (provider) {
  2025. case 'github':
  2026. $(
  2027. '.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input'
  2028. ).attr('required', 'required');
  2029. $(
  2030. '.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url'
  2031. ).show();
  2032. break;
  2033. case 'nextcloud':
  2034. case 'gitea':
  2035. case 'gitlab':
  2036. $(
  2037. '.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input'
  2038. ).attr('required', 'required');
  2039. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  2040. $('#oauth2_email_url').val('');
  2041. break;
  2042. }
  2043. }
  2044. }
  2045. // New authentication
  2046. if ($('.admin.new.authentication').length > 0) {
  2047. $('#auth_type').on('change', function () {
  2048. $(
  2049. '.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls, .search-page-size, .sspi'
  2050. ).hide();
  2051. $(
  2052. '.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]'
  2053. ).removeAttr('required');
  2054. $('.binddnrequired').removeClass('required');
  2055. const authType = $(this).val();
  2056. switch (authType) {
  2057. case '2': // LDAP
  2058. $('.ldap').show();
  2059. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr(
  2060. 'required',
  2061. 'required'
  2062. );
  2063. $('.binddnrequired').addClass('required');
  2064. break;
  2065. case '3': // SMTP
  2066. $('.smtp').show();
  2067. $('.has-tls').show();
  2068. $('.smtp div.required input, .has-tls').attr('required', 'required');
  2069. break;
  2070. case '4': // PAM
  2071. $('.pam').show();
  2072. $('.pam input').attr('required', 'required');
  2073. break;
  2074. case '5': // LDAP
  2075. $('.dldap').show();
  2076. $('.dldap div.required:not(.ldap) input').attr(
  2077. 'required',
  2078. 'required'
  2079. );
  2080. break;
  2081. case '6': // OAuth2
  2082. $('.oauth2').show();
  2083. $(
  2084. '.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input'
  2085. ).attr('required', 'required');
  2086. onOAuth2Change();
  2087. break;
  2088. case '7': // SSPI
  2089. $('.sspi').show();
  2090. $('.sspi div.required input').attr('required', 'required');
  2091. break;
  2092. }
  2093. if (authType === '2' || authType === '5') {
  2094. onSecurityProtocolChange();
  2095. }
  2096. if (authType === '2') {
  2097. onUsePagedSearchChange();
  2098. }
  2099. });
  2100. $('#auth_type').trigger('change');
  2101. $('#security_protocol').on('change', onSecurityProtocolChange);
  2102. $('#use_paged_search').on('change', onUsePagedSearchChange);
  2103. $('#oauth2_provider').on('change', onOAuth2Change);
  2104. $('#oauth2_use_custom_url').on('change', onOAuth2UseCustomURLChange);
  2105. }
  2106. // Edit authentication
  2107. if ($('.admin.edit.authentication').length > 0) {
  2108. const authType = $('#auth_type').val();
  2109. if (authType === '2' || authType === '5') {
  2110. $('#security_protocol').on('change', onSecurityProtocolChange);
  2111. if (authType === '2') {
  2112. $('#use_paged_search').on('change', onUsePagedSearchChange);
  2113. }
  2114. } else if (authType === '6') {
  2115. $('#oauth2_provider').on('change', onOAuth2Change);
  2116. $('#oauth2_use_custom_url').on('change', onOAuth2UseCustomURLChange);
  2117. onOAuth2Change();
  2118. }
  2119. }
  2120. // Notice
  2121. if ($('.admin.notice')) {
  2122. const $detailModal = $('#detail-modal');
  2123. // Attach view detail modals
  2124. $('.view-detail').on('click', function () {
  2125. $detailModal.find('.content pre').text($(this).data('content'));
  2126. $detailModal.modal('show');
  2127. return false;
  2128. });
  2129. // Select actions
  2130. const $checkboxes = $('.select.table .ui.checkbox');
  2131. $('.select.action').on('click', function () {
  2132. switch ($(this).data('action')) {
  2133. case 'select-all':
  2134. $checkboxes.checkbox('check');
  2135. break;
  2136. case 'deselect-all':
  2137. $checkboxes.checkbox('uncheck');
  2138. break;
  2139. case 'inverse':
  2140. $checkboxes.checkbox('toggle');
  2141. break;
  2142. }
  2143. });
  2144. $('#delete-selection').on('click', function () {
  2145. const $this = $(this);
  2146. $this.addClass('loading disabled');
  2147. const ids = [];
  2148. $checkboxes.each(function () {
  2149. if ($(this).checkbox('is checked')) {
  2150. ids.push($(this).data('id'));
  2151. }
  2152. });
  2153. $.post($this.data('link'), {
  2154. _csrf: csrf,
  2155. ids
  2156. }).done(() => {
  2157. window.location.href = $this.data('redirect');
  2158. });
  2159. });
  2160. }
  2161. }
  2162. function buttonsClickOnEnter() {
  2163. $('.ui.button').on('keypress', function (e) {
  2164. if (e.keyCode === 13 || e.keyCode === 32) {
  2165. // enter key or space bar
  2166. $(this).trigger('click');
  2167. }
  2168. });
  2169. }
  2170. function searchUsers() {
  2171. const $searchUserBox = $('#search-user-box');
  2172. $searchUserBox.search({
  2173. minCharacters: 2,
  2174. apiSettings: {
  2175. url: `${AppSubUrl}/api/v1/users/search?q={query}`,
  2176. onResponse(response) {
  2177. const items = [];
  2178. $.each(response.data, (_i, item) => {
  2179. let title = item.login;
  2180. if (item.full_name && item.full_name.length > 0) {
  2181. title += ` (${htmlEncode(item.full_name)})`;
  2182. }
  2183. items.push({
  2184. title,
  2185. image: item.avatar_url
  2186. });
  2187. });
  2188. return {results: items};
  2189. }
  2190. },
  2191. searchFields: ['login', 'full_name'],
  2192. showNoResults: false
  2193. });
  2194. }
  2195. function searchTeams() {
  2196. const $searchTeamBox = $('#search-team-box');
  2197. $searchTeamBox.search({
  2198. minCharacters: 2,
  2199. apiSettings: {
  2200. url: `${AppSubUrl}/api/v1/orgs/${$searchTeamBox.data(
  2201. 'org'
  2202. )}/teams/search?q={query}`,
  2203. headers: {'X-Csrf-Token': csrf},
  2204. onResponse(response) {
  2205. const items = [];
  2206. $.each(response.data, (_i, item) => {
  2207. const title = `${item.name} (${item.permission} access)`;
  2208. items.push({
  2209. title
  2210. });
  2211. });
  2212. return {results: items};
  2213. }
  2214. },
  2215. searchFields: ['name', 'description'],
  2216. showNoResults: false
  2217. });
  2218. }
  2219. function searchRepositories() {
  2220. const $searchRepoBox = $('#search-repo-box');
  2221. $searchRepoBox.search({
  2222. minCharacters: 2,
  2223. apiSettings: {
  2224. url: `${AppSubUrl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data(
  2225. 'uid'
  2226. )}`,
  2227. onResponse(response) {
  2228. const items = [];
  2229. $.each(response.data, (_i, item) => {
  2230. items.push({
  2231. title: item.full_name.split('/')[1],
  2232. description: item.full_name
  2233. });
  2234. });
  2235. return {results: items};
  2236. }
  2237. },
  2238. searchFields: ['full_name'],
  2239. showNoResults: false
  2240. });
  2241. }
  2242. function initCodeView() {
  2243. if ($('.code-view .linenums').length > 0) {
  2244. $(document).on('click', '.lines-num span', function (e) {
  2245. const $select = $(this);
  2246. const $list = $select
  2247. .parent()
  2248. .siblings('.lines-code')
  2249. .find('ol.linenums > li');
  2250. selectRange(
  2251. $list,
  2252. $list.filter(`[rel=${$select.attr('id')}]`),
  2253. e.shiftKey ? $list.filter('.active').eq(0) : null
  2254. );
  2255. deSelect();
  2256. });
  2257. $(window)
  2258. .on('hashchange', () => {
  2259. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  2260. const $list = $('.code-view ol.linenums > li');
  2261. let $first;
  2262. if (m) {
  2263. $first = $list.filter(`.${m[1]}`);
  2264. selectRange($list, $first, $list.filter(`.${m[2]}`));
  2265. $('html, body').scrollTop($first.offset().top - 200);
  2266. return;
  2267. }
  2268. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  2269. if (m) {
  2270. $first = $list.filter(`.L${m[2]}`);
  2271. selectRange($list, $first);
  2272. $('html, body').scrollTop($first.offset().top - 200);
  2273. }
  2274. })
  2275. .trigger('hashchange');
  2276. }
  2277. $('.fold-code').on('click', ({target}) => {
  2278. const box = target.closest('.file-content');
  2279. const folded = box.dataset.folded !== 'true';
  2280. target.classList.add(`fa-chevron-${folded ? 'right' : 'down'}`);
  2281. target.classList.remove(`fa-chevron-${folded ? 'down' : 'right'}`);
  2282. box.dataset.folded = String(folded);
  2283. });
  2284. function insertBlobExcerpt(e) {
  2285. const $blob = $(e.target);
  2286. const $row = $blob.parent().parent();
  2287. $.get(
  2288. `${$blob.data('url')}?${$blob.data('query')}&anchor=${$blob.data(
  2289. 'anchor'
  2290. )}`,
  2291. (blob) => {
  2292. $row.replaceWith(blob);
  2293. $(`[data-anchor="${$blob.data('anchor')}"]`).on('click', (e) => {
  2294. insertBlobExcerpt(e);
  2295. });
  2296. $('.diff-detail-box.ui.sticky').sticky();
  2297. }
  2298. );
  2299. }
  2300. $('.ui.blob-excerpt').on('click', (e) => {
  2301. insertBlobExcerpt(e);
  2302. });
  2303. }
  2304. function initU2FAuth() {
  2305. if ($('#wait-for-key').length === 0) {
  2306. return;
  2307. }
  2308. u2fApi
  2309. .ensureSupport()
  2310. .then(() => {
  2311. $.getJSON(`${AppSubUrl}/user/u2f/challenge`).done((req) => {
  2312. u2fApi
  2313. .sign(req.appId, req.challenge, req.registeredKeys, 30)
  2314. .then(u2fSigned)
  2315. .catch((err) => {
  2316. if (err === undefined) {
  2317. u2fError(1);
  2318. return;
  2319. }
  2320. u2fError(err.metaData.code);
  2321. });
  2322. });
  2323. })
  2324. .catch(() => {
  2325. // Fallback in case browser do not support U2F
  2326. window.location.href = `${AppSubUrl}/user/two_factor`;
  2327. });
  2328. }
  2329. function u2fSigned(resp) {
  2330. $.ajax({
  2331. url: `${AppSubUrl}/user/u2f/sign`,
  2332. type: 'POST',
  2333. headers: {'X-Csrf-Token': csrf},
  2334. data: JSON.stringify(resp),
  2335. contentType: 'application/json; charset=utf-8'
  2336. })
  2337. .done((res) => {
  2338. window.location.replace(res);
  2339. })
  2340. .fail(() => {
  2341. u2fError(1);
  2342. });
  2343. }
  2344. function u2fRegistered(resp) {
  2345. if (checkError(resp)) {
  2346. return;
  2347. }
  2348. $.ajax({
  2349. url: `${AppSubUrl}/user/settings/security/u2f/register`,
  2350. type: 'POST',
  2351. headers: {'X-Csrf-Token': csrf},
  2352. data: JSON.stringify(resp),
  2353. contentType: 'application/json; charset=utf-8',
  2354. success() {
  2355. reload();
  2356. },
  2357. fail() {
  2358. u2fError(1);
  2359. }
  2360. });
  2361. }
  2362. function checkError(resp) {
  2363. if (!('errorCode' in resp)) {
  2364. return false;
  2365. }
  2366. if (resp.errorCode === 0) {
  2367. return false;
  2368. }
  2369. u2fError(resp.errorCode);
  2370. return true;
  2371. }
  2372. function u2fError(errorType) {
  2373. const u2fErrors = {
  2374. browser: $('#unsupported-browser'),
  2375. 1: $('#u2f-error-1'),
  2376. 2: $('#u2f-error-2'),
  2377. 3: $('#u2f-error-3'),
  2378. 4: $('#u2f-error-4'),
  2379. 5: $('.u2f-error-5')
  2380. };
  2381. u2fErrors[errorType].removeClass('hide');
  2382. Object.keys(u2fErrors).forEach((type) => {
  2383. if (type !== errorType) {
  2384. u2fErrors[type].addClass('hide');
  2385. }
  2386. });
  2387. $('#u2f-error').modal('show');
  2388. }
  2389. function initU2FRegister() {
  2390. $('#register-device').modal({allowMultiple: false});
  2391. $('#u2f-error').modal({allowMultiple: false});
  2392. $('#register-security-key').on('click', (e) => {
  2393. e.preventDefault();
  2394. u2fApi
  2395. .ensureSupport()
  2396. .then(u2fRegisterRequest)
  2397. .catch(() => {
  2398. u2fError('browser');
  2399. });
  2400. });
  2401. }
  2402. function u2fRegisterRequest() {
  2403. $.post(`${AppSubUrl}/user/settings/security/u2f/request_register`, {
  2404. _csrf: csrf,
  2405. name: $('#nickname').val()
  2406. })
  2407. .done((req) => {
  2408. $('#nickname')
  2409. .closest('div.field')
  2410. .removeClass('error');
  2411. $('#register-device').modal('show');
  2412. if (req.registeredKeys === null) {
  2413. req.registeredKeys = [];
  2414. }
  2415. u2fApi
  2416. .register(req.appId, req.registerRequests, req.registeredKeys, 30)
  2417. .then(u2fRegistered)
  2418. .catch((reason) => {
  2419. if (reason === undefined) {
  2420. u2fError(1);
  2421. return;
  2422. }
  2423. u2fError(reason.metaData.code);
  2424. });
  2425. })
  2426. .fail((xhr) => {
  2427. if (xhr.status === 409) {
  2428. $('#nickname')
  2429. .closest('div.field')
  2430. .addClass('error');
  2431. }
  2432. });
  2433. }
  2434. function initWipTitle() {
  2435. $('.title_wip_desc > a').on('click', (e) => {
  2436. e.preventDefault();
  2437. const $issueTitle = $('#issue_title');
  2438. $issueTitle.focus();
  2439. const value = $issueTitle
  2440. .val()
  2441. .trim()
  2442. .toUpperCase();
  2443. for (const i in wipPrefixes) {
  2444. if (value.startsWith(wipPrefixes[i].toUpperCase())) {
  2445. return;
  2446. }
  2447. }
  2448. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  2449. });
  2450. }
  2451. function initTemplateSearch() {
  2452. const $repoTemplate = $('#repo_template');
  2453. const checkTemplate = function () {
  2454. const $templateUnits = $('#template_units');
  2455. const $nonTemplate = $('#non_template');
  2456. if ($repoTemplate.val() !== '' && $repoTemplate.val() !== '0') {
  2457. $templateUnits.show();
  2458. $nonTemplate.hide();
  2459. } else {
  2460. $templateUnits.hide();
  2461. $nonTemplate.show();
  2462. }
  2463. };
  2464. $repoTemplate.on('change', checkTemplate);
  2465. checkTemplate();
  2466. const changeOwner = function () {
  2467. $('#repo_template_search').dropdown({
  2468. apiSettings: {
  2469. url: `${AppSubUrl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$(
  2470. '#uid'
  2471. ).val()}`,
  2472. onResponse(response) {
  2473. const filteredResponse = {success: true, results: []};
  2474. filteredResponse.results.push({
  2475. name: '',
  2476. value: ''
  2477. });
  2478. // Parse the response from the api to work with our dropdown
  2479. $.each(response.data, (_r, repo) => {
  2480. filteredResponse.results.push({
  2481. name: htmlEncode(repo.full_name),
  2482. value: repo.id
  2483. });
  2484. });
  2485. return filteredResponse;
  2486. },
  2487. cache: false
  2488. },
  2489. fullTextSearch: true
  2490. });
  2491. };
  2492. $('#uid').on('change', changeOwner);
  2493. changeOwner();
  2494. }
  2495. $(document).ready(async () => {
  2496. // Show exact time
  2497. $('.time-since').each(function () {
  2498. $(this)
  2499. .addClass('poping up')
  2500. .attr('data-content', $(this).attr('title'))
  2501. .attr('data-variation', 'inverted tiny')
  2502. .attr('title', '');
  2503. });
  2504. // Semantic UI modules.
  2505. $('.dropdown:not(.custom)').dropdown();
  2506. $('.jump.dropdown').dropdown({
  2507. action: 'hide',
  2508. onShow() {
  2509. $('.poping.up').popup('hide');
  2510. }
  2511. });
  2512. $('.slide.up.dropdown').dropdown({
  2513. transition: 'slide up'
  2514. });
  2515. $('.upward.dropdown').dropdown({
  2516. direction: 'upward'
  2517. });
  2518. $('.ui.accordion').accordion();
  2519. $('.ui.checkbox').checkbox();
  2520. $('.ui.progress').progress({
  2521. showActivity: false
  2522. });
  2523. $('.poping.up').popup();
  2524. $('.top.menu .poping.up').popup({
  2525. onShow() {
  2526. if ($('.top.menu .menu.transition').hasClass('visible')) {
  2527. return false;
  2528. }
  2529. }
  2530. });
  2531. $('.tabular.menu .item').tab();
  2532. $('.tabable.menu .item').tab();
  2533. $('.toggle.button').on('click', function () {
  2534. $($(this).data('target')).slideToggle(100);
  2535. });
  2536. // make table <tr> element clickable like a link
  2537. $('tr[data-href]').on('click', function () {
  2538. window.location = $(this).data('href');
  2539. });
  2540. // make table <td> element clickable like a link
  2541. $('td[data-href]').click(function () {
  2542. window.location = $(this).data('href');
  2543. });
  2544. // Dropzone
  2545. const $dropzone = $('#dropzone');
  2546. if ($dropzone.length > 0) {
  2547. const filenameDict = {};
  2548. await createDropzone('#dropzone', {
  2549. url: $dropzone.data('upload-url'),
  2550. headers: {'X-Csrf-Token': csrf},
  2551. maxFiles: $dropzone.data('max-file'),
  2552. maxFilesize: $dropzone.data('max-size'),
  2553. acceptedFiles:
  2554. $dropzone.data('accepts') === '*/*' ? null : $dropzone.data('accepts'),
  2555. addRemoveLinks: true,
  2556. dictDefaultMessage: $dropzone.data('default-message'),
  2557. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  2558. dictFileTooBig: $dropzone.data('file-too-big'),
  2559. dictRemoveFile: $dropzone.data('remove-file'),
  2560. init() {
  2561. this.on('success', (file, data) => {
  2562. filenameDict[file.name] = data.uuid;
  2563. const input = $(
  2564. `<input id="${data.uuid}" name="files" type="hidden">`
  2565. ).val(data.uuid);
  2566. $('.files').append(input);
  2567. });
  2568. this.on('removedfile', (file) => {
  2569. if (file.name in filenameDict) {
  2570. $(`#${filenameDict[file.name]}`).remove();
  2571. }
  2572. if ($dropzone.data('remove-url') && $dropzone.data('csrf')) {
  2573. $.post($dropzone.data('remove-url'), {
  2574. file: filenameDict[file.name],
  2575. _csrf: $dropzone.data('csrf')
  2576. });
  2577. }
  2578. });
  2579. }
  2580. });
  2581. }
  2582. // dataset Dropzone
  2583. // const $dataset = $('#dataset');
  2584. // if ($dataset.length > 0) {
  2585. // const filenameDict = {};
  2586. // let previewTemplate = '';
  2587. // previewTemplate += '<div class="dz-preview dz-file-preview">\n ';
  2588. // previewTemplate += ' <div class="dz-details">\n ';
  2589. // previewTemplate += ' <div class="dz-filename">';
  2590. // previewTemplate += ' <span data-dz-name data-dz-thumbnail></span>';
  2591. // previewTemplate += ' </div>\n ';
  2592. // previewTemplate += ' <div class="dz-size" data-dz-size></div>\n ';
  2593. // previewTemplate += ' </div>\n ';
  2594. // previewTemplate += ' <div class="dz-progress ui active progress">';
  2595. // previewTemplate += ' <div class="dz-upload bar" data-dz-uploadprogress><div class="progress"></div></div>\n ';
  2596. // previewTemplate += ' </div>\n ';
  2597. // previewTemplate += ' <div class="dz-success-mark">';
  2598. // previewTemplate += ' <span>上传成功</span>';
  2599. // previewTemplate += ' </div>\n ';
  2600. // previewTemplate += ' <div class="dz-error-mark">';
  2601. // previewTemplate += ' <span>上传失败</span>';
  2602. // previewTemplate += ' </div>\n ';
  2603. // previewTemplate += ' <div class="dz-error-message">';
  2604. // previewTemplate += ' <span data-dz-errormessage></span>';
  2605. // previewTemplate += ' </div>\n';
  2606. // previewTemplate += '</div>';
  2607. // await createDropzone('#dataset', {
  2608. // url: $dataset.data('upload-url'),
  2609. // headers: {'X-Csrf-Token': csrf},
  2610. // maxFiles: $dataset.data('max-file'),
  2611. // maxFilesize: $dataset.data('max-size'),
  2612. // acceptedFiles: ($dataset.data('accepts') === '*/*') ? null : $dataset.data('accepts'),
  2613. // addRemoveLinks: true,
  2614. // timeout: 0,
  2615. // dictDefaultMessage: $dataset.data('default-message'),
  2616. // dictInvalidFileType: $dataset.data('invalid-input-type'),
  2617. // dictFileTooBig: $dataset.data('file-too-big'),
  2618. // dictRemoveFile: $dataset.data('remove-file'),
  2619. // previewTemplate,
  2620. // init() {
  2621. // this.on('success', (file, data) => {
  2622. // filenameDict[file.name] = data.uuid;
  2623. // const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  2624. // $('.files').append(input);
  2625. // });
  2626. // this.on('removedfile', (file) => {
  2627. // if (file.name in filenameDict) {
  2628. // $(`#${filenameDict[file.name]}`).remove();
  2629. // }
  2630. // if ($dataset.data('remove-url') && $dataset.data('csrf')) {
  2631. // $.post($dataset.data('remove-url'), {
  2632. // file: filenameDict[file.name],
  2633. // _csrf: $dataset.data('csrf')
  2634. // });
  2635. // }
  2636. // });
  2637. // },
  2638. // });
  2639. // }
  2640. // Helpers.
  2641. $('.delete-button').on('click', showDeletePopup);
  2642. $('.add-all-button').on('click', showAddAllPopup);
  2643. $('.link-action').on('click', linkAction);
  2644. $('.link-email-action').on('click', linkEmailAction);
  2645. $('.delete-branch-button').on('click', showDeletePopup);
  2646. $('.undo-button').on('click', function () {
  2647. const $this = $(this);
  2648. $.post($this.data('url'), {
  2649. _csrf: csrf,
  2650. id: $this.data('id')
  2651. }).done((data) => {
  2652. window.location.href = data.redirect;
  2653. });
  2654. });
  2655. $('.show-panel.button').on('click', function () {
  2656. $($(this).data('panel')).show();
  2657. });
  2658. $('.show-modal.button').on('click', function () {
  2659. $($(this).data('modal')).modal('show');
  2660. });
  2661. $('.delete-post.button').on('click', function () {
  2662. const $this = $(this);
  2663. $.post($this.data('request-url'), {
  2664. _csrf: csrf
  2665. }).done(() => {
  2666. window.location.href = $this.data('done-url');
  2667. });
  2668. });
  2669. // Set anchor.
  2670. $('.markdown').each(function () {
  2671. $(this)
  2672. .find('h1, h2, h3, h4, h5, h6')
  2673. .each(function () {
  2674. let node = $(this);
  2675. node = node.wrap('<div class="anchor-wrap"></div>');
  2676. node.append(
  2677. `<a class="anchor" href="#${encodeURIComponent(
  2678. node.attr('id')
  2679. )}">${svg('octicon-link', 16)}</a>`
  2680. );
  2681. });
  2682. });
  2683. $('.issue-checkbox').on('click', () => {
  2684. const numChecked = $('.issue-checkbox').children('input:checked').length;
  2685. if (numChecked > 0) {
  2686. $('#issue-filters').addClass('hide');
  2687. $('#issue-actions').removeClass('hide');
  2688. } else {
  2689. $('#issue-filters').removeClass('hide');
  2690. $('#issue-actions').addClass('hide');
  2691. }
  2692. });
  2693. $('.issue-action').on('click', function () {
  2694. let {action} = this.dataset;
  2695. let {elementId} = this.dataset;
  2696. const issueIDs = $('.issue-checkbox')
  2697. .children('input:checked')
  2698. .map(function () {
  2699. return this.dataset.issueId;
  2700. })
  2701. .get()
  2702. .join();
  2703. const {url} = this.dataset;
  2704. if (elementId === '0' && url.substr(-9) === '/assignee') {
  2705. elementId = '';
  2706. action = 'clear';
  2707. }
  2708. updateIssuesMeta(url, action, issueIDs, elementId, '').then(() => {
  2709. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2710. if (action === 'close' || action === 'open') {
  2711. // uncheck all checkboxes
  2712. $('.issue-checkbox input[type="checkbox"]').each((_, e) => {
  2713. e.checked = false;
  2714. });
  2715. }
  2716. reload();
  2717. });
  2718. });
  2719. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2720. // trigger ckecked event, if checkboxes are checked on load
  2721. $('.issue-checkbox input[type="checkbox"]:checked')
  2722. .first()
  2723. .each((_, e) => {
  2724. e.checked = false;
  2725. $(e).trigger('click');
  2726. });
  2727. $('.resolve-conversation').on('click', function (e) {
  2728. e.preventDefault();
  2729. const id = $(this).data('comment-id');
  2730. const action = $(this).data('action');
  2731. const url = $(this).data('update-url');
  2732. $.post(url, {
  2733. _csrf: csrf,
  2734. action,
  2735. comment_id: id
  2736. }).then(reload);
  2737. });
  2738. buttonsClickOnEnter();
  2739. searchUsers();
  2740. searchTeams();
  2741. searchRepositories();
  2742. initCommentForm();
  2743. initInstall();
  2744. initRepository();
  2745. initMigration();
  2746. initWikiForm();
  2747. initEditForm();
  2748. initEditor();
  2749. initOrganization();
  2750. initGithook();
  2751. initWebhook();
  2752. initAdmin();
  2753. initCodeView();
  2754. initVueApp();
  2755. initVueUploader();
  2756. initTeamSettings();
  2757. initCtrlEnterSubmit();
  2758. initNavbarContentToggle();
  2759. initTopicbar();
  2760. initU2FAuth();
  2761. initU2FRegister();
  2762. initIssueList();
  2763. initWipTitle();
  2764. initPullRequestReview();
  2765. initRepoStatusChecker();
  2766. initTemplateSearch();
  2767. initContextPopups();
  2768. initNotificationsTable();
  2769. initNotificationCount();
  2770. initTribute();
  2771. // Repo clone url.
  2772. if ($('#repo-clone-url').length > 0) {
  2773. switch (localStorage.getItem('repo-clone-protocol')) {
  2774. case 'ssh':
  2775. if ($('#repo-clone-ssh').length === 0) {
  2776. $('#repo-clone-https').trigger('click');
  2777. }
  2778. break;
  2779. default:
  2780. $('#repo-clone-https').trigger('click');
  2781. break;
  2782. }
  2783. }
  2784. const routes = {
  2785. 'div.user.settings': initUserSettings,
  2786. 'div.repository.settings.collaboration': initRepositoryCollaboration
  2787. };
  2788. let selector;
  2789. for (selector in routes) {
  2790. if ($(selector).length > 0) {
  2791. routes[selector]();
  2792. break;
  2793. }
  2794. }
  2795. const $cloneAddr = $('#clone_addr');
  2796. $cloneAddr.on('change', () => {
  2797. const $repoName = $('#repo_name');
  2798. if ($cloneAddr.val().length > 0 && $repoName.val().length === 0) {
  2799. // Only modify if repo_name input is blank
  2800. $repoName.val($cloneAddr.val().match(/^(.*\/)?((.+?)(\.git)?)$/)[3]);
  2801. }
  2802. });
  2803. // parallel init of lazy-loaded features
  2804. await Promise.all([
  2805. highlight(document.querySelectorAll('pre code')),
  2806. initGitGraph(),
  2807. initClipboard(),
  2808. initUserHeatmap()
  2809. ]);
  2810. });
  2811. function changeHash(hash) {
  2812. if (window.history.pushState) {
  2813. window.history.pushState(null, null, hash);
  2814. } else {
  2815. window.location.hash = hash;
  2816. }
  2817. }
  2818. function deSelect() {
  2819. if (window.getSelection) {
  2820. window.getSelection().removeAllRanges();
  2821. } else {
  2822. document.selection.empty();
  2823. }
  2824. }
  2825. function selectRange($list, $select, $from) {
  2826. $list.removeClass('active');
  2827. if ($from) {
  2828. let a = parseInt($select.attr('rel').substr(1));
  2829. let b = parseInt($from.attr('rel').substr(1));
  2830. let c;
  2831. if (a !== b) {
  2832. if (a > b) {
  2833. c = a;
  2834. a = b;
  2835. b = c;
  2836. }
  2837. const classes = [];
  2838. for (let i = a; i <= b; i++) {
  2839. classes.push(`.L${i}`);
  2840. }
  2841. $list.filter(classes.join(',')).addClass('active');
  2842. changeHash(`#L${a}-L${b}`);
  2843. return;
  2844. }
  2845. }
  2846. $select.addClass('active');
  2847. changeHash(`#${$select.attr('rel')}`);
  2848. }
  2849. $(() => {
  2850. // Warn users that try to leave a page after entering data into a form.
  2851. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2852. if ($('.user.signin').length === 0) {
  2853. $('form:not(.ignore-dirty)').areYouSure();
  2854. }
  2855. // Parse SSH Key
  2856. $('#ssh-key-content').on('change paste keyup', function () {
  2857. const arrays = $(this)
  2858. .val()
  2859. .split(' ');
  2860. const $title = $('#ssh-key-title');
  2861. if ($title.val() === '' && arrays.length === 3 && arrays[2] !== '') {
  2862. $title.val(arrays[2]);
  2863. }
  2864. });
  2865. });
  2866. function showDeletePopup() {
  2867. const $this = $(this);
  2868. let filter = '';
  2869. if ($this.attr('id')) {
  2870. filter += `#${$this.attr('id')}`;
  2871. }
  2872. const dialog = $(`.delete.modal${filter}`);
  2873. dialog.find('.name').text($this.data('name'));
  2874. dialog
  2875. .modal({
  2876. closable: false,
  2877. onApprove() {
  2878. if ($this.data('type') === 'form') {
  2879. $($this.data('form')).trigger('submit');
  2880. return;
  2881. }
  2882. $.post($this.data('url'), {
  2883. _csrf: csrf,
  2884. id: $this.data('id')
  2885. }).done((data) => {
  2886. window.location.href = data.redirect;
  2887. });
  2888. }
  2889. })
  2890. .modal('show');
  2891. return false;
  2892. }
  2893. function showAddAllPopup() {
  2894. const $this = $(this);
  2895. let filter = '';
  2896. if ($this.attr('id')) {
  2897. filter += `#${$this.attr('id')}`;
  2898. }
  2899. const dialog = $(`.addall.modal${filter}`);
  2900. dialog.find('.name').text($this.data('name'));
  2901. dialog
  2902. .modal({
  2903. closable: false,
  2904. onApprove() {
  2905. if ($this.data('type') === 'form') {
  2906. $($this.data('form')).trigger('submit');
  2907. return;
  2908. }
  2909. $.post($this.data('url'), {
  2910. _csrf: csrf,
  2911. id: $this.data('id')
  2912. }).done((data) => {
  2913. window.location.href = data.redirect;
  2914. });
  2915. }
  2916. })
  2917. .modal('show');
  2918. return false;
  2919. }
  2920. function linkAction(e) {
  2921. e.preventDefault();
  2922. const $this = $(this);
  2923. const redirect = $this.data('redirect');
  2924. $.post($this.data('url'), {
  2925. _csrf: csrf
  2926. }).done((data) => {
  2927. if (data.redirect) {
  2928. window.location.href = data.redirect;
  2929. } else if (redirect) {
  2930. window.location.href = redirect;
  2931. } else {
  2932. window.location.reload();
  2933. }
  2934. });
  2935. }
  2936. function linkEmailAction(e) {
  2937. const $this = $(this);
  2938. $('#form-uid').val($this.data('uid'));
  2939. $('#form-email').val($this.data('email'));
  2940. $('#form-primary').val($this.data('primary'));
  2941. $('#form-activate').val($this.data('activate'));
  2942. $('#form-uid').val($this.data('uid'));
  2943. $('#change-email-modal').modal('show');
  2944. e.preventDefault();
  2945. }
  2946. function initVueComponents() {
  2947. const vueDelimeters = ['${', '}'];
  2948. Vue.component('repo-search', {
  2949. delimiters: vueDelimeters,
  2950. props: {
  2951. searchLimit: {
  2952. type: Number,
  2953. default: 10
  2954. },
  2955. suburl: {
  2956. type: String,
  2957. required: true
  2958. },
  2959. uid: {
  2960. type: Number,
  2961. required: true
  2962. },
  2963. organizations: {
  2964. type: Array,
  2965. default: []
  2966. },
  2967. isOrganization: {
  2968. type: Boolean,
  2969. default: true
  2970. },
  2971. canCreateOrganization: {
  2972. type: Boolean,
  2973. default: false
  2974. },
  2975. organizationsTotalCount: {
  2976. type: Number,
  2977. default: 0
  2978. },
  2979. moreReposLink: {
  2980. type: String,
  2981. default: ''
  2982. }
  2983. },
  2984. data() {
  2985. const params = new URLSearchParams(window.location.search);
  2986. let tab = params.get('repo-search-tab');
  2987. if (!tab) {
  2988. tab = 'repos';
  2989. }
  2990. let reposFilter = params.get('repo-search-filter');
  2991. if (!reposFilter) {
  2992. reposFilter = 'all';
  2993. }
  2994. let privateFilter = params.get('repo-search-private');
  2995. if (!privateFilter) {
  2996. privateFilter = 'both';
  2997. }
  2998. let archivedFilter = params.get('repo-search-archived');
  2999. if (!archivedFilter) {
  3000. archivedFilter = 'unarchived';
  3001. }
  3002. let searchQuery = params.get('repo-search-query');
  3003. if (!searchQuery) {
  3004. searchQuery = '';
  3005. }
  3006. let page = 1;
  3007. try {
  3008. page = parseInt(params.get('repo-search-page'));
  3009. } catch {
  3010. // noop
  3011. }
  3012. if (!page) {
  3013. page = 1;
  3014. }
  3015. return {
  3016. tab,
  3017. repos: [],
  3018. reposTotalCount: 0,
  3019. reposFilter,
  3020. archivedFilter,
  3021. privateFilter,
  3022. page,
  3023. finalPage: 1,
  3024. searchQuery,
  3025. isLoading: false,
  3026. staticPrefix: StaticUrlPrefix,
  3027. counts: {},
  3028. repoTypes: {
  3029. all: {
  3030. searchMode: ''
  3031. },
  3032. forks: {
  3033. searchMode: 'fork'
  3034. },
  3035. mirrors: {
  3036. searchMode: 'mirror'
  3037. },
  3038. sources: {
  3039. searchMode: 'source'
  3040. },
  3041. collaborative: {
  3042. searchMode: 'collaborative'
  3043. }
  3044. }
  3045. };
  3046. },
  3047. computed: {
  3048. showMoreReposLink() {
  3049. return (
  3050. this.repos.length > 0 &&
  3051. this.repos.length <
  3052. this.counts[
  3053. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`
  3054. ]
  3055. );
  3056. },
  3057. searchURL() {
  3058. return `${
  3059. this.suburl
  3060. }/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&q=${
  3061. this.searchQuery
  3062. }&page=${this.page}&limit=${this.searchLimit}&mode=${
  3063. this.repoTypes[this.reposFilter].searchMode
  3064. }${this.reposFilter !== 'all' ? '&exclusive=1' : ''}${
  3065. this.archivedFilter === 'archived' ? '&archived=true' : ''
  3066. }${this.archivedFilter === 'unarchived' ? '&archived=false' : ''}${
  3067. this.privateFilter === 'private' ? '&onlyPrivate=true' : ''
  3068. }${this.privateFilter === 'public' ? '&private=false' : ''}`;
  3069. },
  3070. repoTypeCount() {
  3071. return this.counts[
  3072. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`
  3073. ];
  3074. }
  3075. },
  3076. mounted() {
  3077. this.searchRepos(this.reposFilter);
  3078. $(this.$el)
  3079. .find('.poping.up')
  3080. .popup();
  3081. $(this.$el)
  3082. .find('.dropdown')
  3083. .dropdown();
  3084. this.setCheckboxes();
  3085. const self = this;
  3086. Vue.nextTick(() => {
  3087. self.$refs.search.focus();
  3088. });
  3089. },
  3090. methods: {
  3091. changeTab(t) {
  3092. this.tab = t;
  3093. this.updateHistory();
  3094. },
  3095. setCheckboxes() {
  3096. switch (this.archivedFilter) {
  3097. case 'unarchived':
  3098. $('#archivedFilterCheckbox').checkbox('set unchecked');
  3099. break;
  3100. case 'archived':
  3101. $('#archivedFilterCheckbox').checkbox('set checked');
  3102. break;
  3103. case 'both':
  3104. $('#archivedFilterCheckbox').checkbox('set indeterminate');
  3105. break;
  3106. default:
  3107. this.archivedFilter = 'unarchived';
  3108. $('#archivedFilterCheckbox').checkbox('set unchecked');
  3109. break;
  3110. }
  3111. switch (this.privateFilter) {
  3112. case 'public':
  3113. $('#privateFilterCheckbox').checkbox('set unchecked');
  3114. break;
  3115. case 'private':
  3116. $('#privateFilterCheckbox').checkbox('set checked');
  3117. break;
  3118. case 'both':
  3119. $('#privateFilterCheckbox').checkbox('set indeterminate');
  3120. break;
  3121. default:
  3122. this.privateFilter = 'both';
  3123. $('#privateFilterCheckbox').checkbox('set indeterminate');
  3124. break;
  3125. }
  3126. },
  3127. changeReposFilter(filter) {
  3128. this.reposFilter = filter;
  3129. this.repos = [];
  3130. this.page = 1;
  3131. Vue.set(
  3132. this.counts,
  3133. `${filter}:${this.archivedFilter}:${this.privateFilter}`,
  3134. 0
  3135. );
  3136. this.searchRepos();
  3137. },
  3138. updateHistory() {
  3139. const params = new URLSearchParams(window.location.search);
  3140. if (this.tab === 'repos') {
  3141. params.delete('repo-search-tab');
  3142. } else {
  3143. params.set('repo-search-tab', this.tab);
  3144. }
  3145. if (this.reposFilter === 'all') {
  3146. params.delete('repo-search-filter');
  3147. } else {
  3148. params.set('repo-search-filter', this.reposFilter);
  3149. }
  3150. if (this.privateFilter === 'both') {
  3151. params.delete('repo-search-private');
  3152. } else {
  3153. params.set('repo-search-private', this.privateFilter);
  3154. }
  3155. if (this.archivedFilter === 'unarchived') {
  3156. params.delete('repo-search-archived');
  3157. } else {
  3158. params.set('repo-search-archived', this.archivedFilter);
  3159. }
  3160. if (this.searchQuery === '') {
  3161. params.delete('repo-search-query');
  3162. } else {
  3163. params.set('repo-search-query', this.searchQuery);
  3164. }
  3165. if (this.page === 1) {
  3166. params.delete('repo-search-page');
  3167. } else {
  3168. params.set('repo-search-page', `${this.page}`);
  3169. }
  3170. window.history.replaceState({}, '', `?${params.toString()}`);
  3171. },
  3172. toggleArchivedFilter() {
  3173. switch (this.archivedFilter) {
  3174. case 'both':
  3175. this.archivedFilter = 'unarchived';
  3176. break;
  3177. case 'unarchived':
  3178. this.archivedFilter = 'archived';
  3179. break;
  3180. case 'archived':
  3181. this.archivedFilter = 'both';
  3182. break;
  3183. default:
  3184. this.archivedFilter = 'unarchived';
  3185. break;
  3186. }
  3187. this.page = 1;
  3188. this.repos = [];
  3189. this.setCheckboxes();
  3190. Vue.set(
  3191. this.counts,
  3192. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`,
  3193. 0
  3194. );
  3195. this.searchRepos();
  3196. },
  3197. togglePrivateFilter() {
  3198. switch (this.privateFilter) {
  3199. case 'both':
  3200. this.privateFilter = 'public';
  3201. break;
  3202. case 'public':
  3203. this.privateFilter = 'private';
  3204. break;
  3205. case 'private':
  3206. this.privateFilter = 'both';
  3207. break;
  3208. default:
  3209. this.privateFilter = 'both';
  3210. break;
  3211. }
  3212. this.page = 1;
  3213. this.repos = [];
  3214. this.setCheckboxes();
  3215. Vue.set(
  3216. this.counts,
  3217. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`,
  3218. 0
  3219. );
  3220. this.searchRepos();
  3221. },
  3222. changePage(page) {
  3223. this.page = page;
  3224. if (this.page > this.finalPage) {
  3225. this.page = this.finalPage;
  3226. }
  3227. if (this.page < 1) {
  3228. this.page = 1;
  3229. }
  3230. this.repos = [];
  3231. Vue.set(
  3232. this.counts,
  3233. `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`,
  3234. 0
  3235. );
  3236. this.searchRepos();
  3237. },
  3238. showArchivedRepo(repo) {
  3239. switch (this.archivedFilter) {
  3240. case 'both':
  3241. return true;
  3242. case 'unarchived':
  3243. return !repo.archived;
  3244. case 'archived':
  3245. return repo.archived;
  3246. default:
  3247. return !repo.archived;
  3248. }
  3249. },
  3250. showPrivateRepo(repo) {
  3251. switch (this.privateFilter) {
  3252. case 'both':
  3253. return true;
  3254. case 'public':
  3255. return !repo.private;
  3256. case 'private':
  3257. return repo.private;
  3258. default:
  3259. return true;
  3260. }
  3261. },
  3262. showFilteredRepo(repo) {
  3263. switch (this.reposFilter) {
  3264. case 'sources':
  3265. return repo.owner.id === this.uid && !repo.mirror && !repo.fork;
  3266. case 'forks':
  3267. return repo.owner.id === this.uid && !repo.mirror && repo.fork;
  3268. case 'mirrors':
  3269. return repo.mirror;
  3270. case 'collaborative':
  3271. return repo.owner.id !== this.uid && !repo.mirror;
  3272. default:
  3273. return true;
  3274. }
  3275. },
  3276. showRepo(repo) {
  3277. return (
  3278. this.showArchivedRepo(repo) &&
  3279. this.showPrivateRepo(repo) &&
  3280. this.showFilteredRepo(repo)
  3281. );
  3282. },
  3283. searchRepos() {
  3284. const self = this;
  3285. this.isLoading = true;
  3286. const searchedMode = this.repoTypes[this.reposFilter].searchMode;
  3287. const searchedURL = this.searchURL;
  3288. const searchedQuery = this.searchQuery;
  3289. $.getJSON(searchedURL, (result, _textStatus, request) => {
  3290. if (searchedURL === self.searchURL) {
  3291. self.repos = result.data;
  3292. const count = request.getResponseHeader('X-Total-Count');
  3293. if (
  3294. searchedQuery === '' &&
  3295. searchedMode === '' &&
  3296. self.archivedFilter === 'both'
  3297. ) {
  3298. self.reposTotalCount = count;
  3299. }
  3300. Vue.set(
  3301. self.counts,
  3302. `${self.reposFilter}:${self.archivedFilter}:${self.privateFilter}`,
  3303. count
  3304. );
  3305. self.finalPage = Math.floor(count / self.searchLimit) + 1;
  3306. self.updateHistory();
  3307. }
  3308. }).always(() => {
  3309. if (searchedURL === self.searchURL) {
  3310. self.isLoading = false;
  3311. }
  3312. });
  3313. },
  3314. repoClass(repo) {
  3315. if (repo.fork) {
  3316. return 'octicon-repo-forked';
  3317. }
  3318. if (repo.mirror) {
  3319. return 'octicon-repo-clone';
  3320. }
  3321. if (repo.template) {
  3322. return `octicon-repo-template${repo.private ? '-private' : ''}`;
  3323. }
  3324. if (repo.private) {
  3325. return 'octicon-lock';
  3326. }
  3327. return 'octicon-repo';
  3328. }
  3329. }
  3330. });
  3331. }
  3332. function initCtrlEnterSubmit() {
  3333. $('.js-quick-submit').on('keydown', function (e) {
  3334. if (
  3335. ((e.ctrlKey && !e.altKey) || e.metaKey) &&
  3336. (e.keyCode === 13 || e.keyCode === 10)
  3337. ) {
  3338. $(this)
  3339. .closest('form')
  3340. .trigger('submit');
  3341. }
  3342. });
  3343. }
  3344. function initVueApp() {
  3345. const el = document.getElementById('app');
  3346. if (!el) {
  3347. return;
  3348. }
  3349. initVueComponents();
  3350. new Vue({
  3351. delimiters: ['${', '}'],
  3352. el,
  3353. data: {
  3354. searchLimit: Number(
  3355. (document.querySelector('meta[name=_search_limit]') || {}).content
  3356. ),
  3357. suburl: AppSubUrl,
  3358. uid: Number(
  3359. (document.querySelector('meta[name=_context_uid]') || {}).content
  3360. ),
  3361. activityTopAuthors: window.ActivityTopAuthors || []
  3362. },
  3363. components: {
  3364. ActivityTopAuthors
  3365. }
  3366. });
  3367. }
  3368. function initVueUploader() {
  3369. const el = document.getElementById('minioUploader');
  3370. if (!el) {
  3371. return;
  3372. }
  3373. new Vue({
  3374. el: '#minioUploader',
  3375. components: {MinioUploader},
  3376. template: '<MinioUploader />'
  3377. });
  3378. }
  3379. window.timeAddManual = function () {
  3380. $('.mini.modal')
  3381. .modal({
  3382. duration: 200,
  3383. onApprove() {
  3384. $('#add_time_manual_form').trigger('submit');
  3385. }
  3386. })
  3387. .modal('show');
  3388. };
  3389. window.toggleStopwatch = function () {
  3390. $('#toggle_stopwatch_form').trigger('submit');
  3391. };
  3392. window.cancelStopwatch = function () {
  3393. $('#cancel_stopwatch_form').trigger('submit');
  3394. };
  3395. function initFilterBranchTagDropdown(selector) {
  3396. $(selector).each(function () {
  3397. const $dropdown = $(this);
  3398. const $data = $dropdown.find('.data');
  3399. const data = {
  3400. items: [],
  3401. mode: $data.data('mode'),
  3402. searchTerm: '',
  3403. noResults: '',
  3404. canCreateBranch: false,
  3405. menuVisible: false,
  3406. active: 0
  3407. };
  3408. $data.find('.item').each(function () {
  3409. data.items.push({
  3410. name: $(this).text(),
  3411. url: $(this).data('url'),
  3412. branch: $(this).hasClass('branch'),
  3413. tag: $(this).hasClass('tag'),
  3414. selected: $(this).hasClass('selected')
  3415. });
  3416. });
  3417. $data.remove();
  3418. new Vue({
  3419. delimiters: ['${', '}'],
  3420. el: this,
  3421. data,
  3422. beforeMount() {
  3423. const vm = this;
  3424. this.noResults = vm.$el.getAttribute('data-no-results');
  3425. this.canCreateBranch =
  3426. vm.$el.getAttribute('data-can-create-branch') === 'true';
  3427. document.body.addEventListener('click', (event) => {
  3428. if (vm.$el.contains(event.target)) {
  3429. return;
  3430. }
  3431. if (vm.menuVisible) {
  3432. Vue.set(vm, 'menuVisible', false);
  3433. }
  3434. });
  3435. },
  3436. watch: {
  3437. menuVisible(visible) {
  3438. if (visible) {
  3439. this.focusSearchField();
  3440. }
  3441. }
  3442. },
  3443. computed: {
  3444. filteredItems() {
  3445. const vm = this;
  3446. const items = vm.items.filter((item) => {
  3447. return (
  3448. ((vm.mode === 'branches' && item.branch) ||
  3449. (vm.mode === 'tags' && item.tag)) &&
  3450. (!vm.searchTerm ||
  3451. item.name.toLowerCase().includes(vm.searchTerm.toLowerCase()))
  3452. );
  3453. });
  3454. vm.active = items.length === 0 && vm.showCreateNewBranch ? 0 : -1;
  3455. return items;
  3456. },
  3457. showNoResults() {
  3458. return this.filteredItems.length === 0 && !this.showCreateNewBranch;
  3459. },
  3460. showCreateNewBranch() {
  3461. const vm = this;
  3462. if (!this.canCreateBranch || !vm.searchTerm || vm.mode === 'tags') {
  3463. return false;
  3464. }
  3465. return (
  3466. vm.items.filter(
  3467. (item) => item.name.toLowerCase() === vm.searchTerm.toLowerCase()
  3468. ).length === 0
  3469. );
  3470. }
  3471. },
  3472. methods: {
  3473. selectItem(item) {
  3474. const prev = this.getSelected();
  3475. if (prev !== null) {
  3476. prev.selected = false;
  3477. }
  3478. item.selected = true;
  3479. window.location.href = item.url;
  3480. },
  3481. createNewBranch() {
  3482. if (!this.showCreateNewBranch) {
  3483. return;
  3484. }
  3485. $(this.$refs.newBranchForm).trigger('submit');
  3486. },
  3487. focusSearchField() {
  3488. const vm = this;
  3489. Vue.nextTick(() => {
  3490. vm.$refs.searchField.focus();
  3491. });
  3492. },
  3493. getSelected() {
  3494. for (let i = 0, j = this.items.length; i < j; ++i) {
  3495. if (this.items[i].selected) return this.items[i];
  3496. }
  3497. return null;
  3498. },
  3499. getSelectedIndexInFiltered() {
  3500. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  3501. if (this.filteredItems[i].selected) return i;
  3502. }
  3503. return -1;
  3504. },
  3505. scrollToActive() {
  3506. let el = this.$refs[`listItem${this.active}`];
  3507. if (!el || el.length === 0) {
  3508. return;
  3509. }
  3510. if (Array.isArray(el)) {
  3511. el = el[0];
  3512. }
  3513. const cont = this.$refs.scrollContainer;
  3514. if (el.offsetTop < cont.scrollTop) {
  3515. cont.scrollTop = el.offsetTop;
  3516. } else if (
  3517. el.offsetTop + el.clientHeight >
  3518. cont.scrollTop + cont.clientHeight
  3519. ) {
  3520. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  3521. }
  3522. },
  3523. keydown(event) {
  3524. const vm = this;
  3525. if (event.keyCode === 40) {
  3526. // arrow down
  3527. event.preventDefault();
  3528. if (vm.active === -1) {
  3529. vm.active = vm.getSelectedIndexInFiltered();
  3530. }
  3531. if (
  3532. vm.active + (vm.showCreateNewBranch ? 0 : 1) >=
  3533. vm.filteredItems.length
  3534. ) {
  3535. return;
  3536. }
  3537. vm.active++;
  3538. vm.scrollToActive();
  3539. }
  3540. if (event.keyCode === 38) {
  3541. // arrow up
  3542. event.preventDefault();
  3543. if (vm.active === -1) {
  3544. vm.active = vm.getSelectedIndexInFiltered();
  3545. }
  3546. if (vm.active <= 0) {
  3547. return;
  3548. }
  3549. vm.active--;
  3550. vm.scrollToActive();
  3551. }
  3552. if (event.keyCode === 13) {
  3553. // enter
  3554. event.preventDefault();
  3555. if (vm.active >= vm.filteredItems.length) {
  3556. vm.createNewBranch();
  3557. } else if (vm.active >= 0) {
  3558. vm.selectItem(vm.filteredItems[vm.active]);
  3559. }
  3560. }
  3561. if (event.keyCode === 27) {
  3562. // escape
  3563. event.preventDefault();
  3564. vm.menuVisible = false;
  3565. }
  3566. }
  3567. }
  3568. });
  3569. });
  3570. }
  3571. $('.commit-button').on('click', function (e) {
  3572. e.preventDefault();
  3573. $(this)
  3574. .parent()
  3575. .find('.commit-body')
  3576. .toggle();
  3577. });
  3578. function initNavbarContentToggle() {
  3579. const content = $('#navbar');
  3580. const toggle = $('#navbar-expand-toggle');
  3581. let isExpanded = false;
  3582. toggle.on('click', () => {
  3583. isExpanded = !isExpanded;
  3584. if (isExpanded) {
  3585. content.addClass('shown');
  3586. toggle.addClass('active');
  3587. } else {
  3588. content.removeClass('shown');
  3589. toggle.removeClass('active');
  3590. }
  3591. });
  3592. }
  3593. function initTopicbar() {
  3594. const mgrBtn = $('#manage_topic');
  3595. const editDiv = $('#topic_edit');
  3596. const viewDiv = $('#repo-topics');
  3597. const saveBtn = $('#save_topic');
  3598. const topicDropdown = $('#topic_edit .dropdown');
  3599. const topicForm = $('#topic_edit.ui.form');
  3600. const topicPrompts = getPrompts();
  3601. mgrBtn.on('click', () => {
  3602. viewDiv.hide();
  3603. editDiv.css('display', ''); // show Semantic UI Grid
  3604. });
  3605. function getPrompts() {
  3606. const hidePrompt = $('div.hide#validate_prompt');
  3607. const prompts = {
  3608. countPrompt: hidePrompt.children('#count_prompt').text(),
  3609. formatPrompt: hidePrompt.children('#format_prompt').text()
  3610. };
  3611. hidePrompt.remove();
  3612. return prompts;
  3613. }
  3614. saveBtn.on('click', () => {
  3615. const topics = $('input[name=topics]').val();
  3616. $.post(
  3617. saveBtn.data('link'),
  3618. {
  3619. _csrf: csrf,
  3620. topics
  3621. },
  3622. (_data, _textStatus, xhr) => {
  3623. if (xhr.responseJSON.status === 'ok') {
  3624. viewDiv.children('.topic').remove();
  3625. if (topics.length) {
  3626. const topicArray = topics.split(',');
  3627. const last = viewDiv.children('a').last();
  3628. for (let i = 0; i < topicArray.length; i++) {
  3629. const link = $('<a class="ui repo-topic small label topic"></a>');
  3630. link.attr(
  3631. 'href',
  3632. `${AppSubUrl}/explore/repos?q=${encodeURIComponent(
  3633. topicArray[i]
  3634. )}&topic=1`
  3635. );
  3636. link.text(topicArray[i]);
  3637. link.insertBefore(last);
  3638. }
  3639. }
  3640. editDiv.css('display', 'none');
  3641. viewDiv.show();
  3642. }
  3643. }
  3644. )
  3645. .fail((xhr) => {
  3646. if (xhr.status === 422) {
  3647. if (xhr.responseJSON.invalidTopics.length > 0) {
  3648. topicPrompts.formatPrompt = xhr.responseJSON.message;
  3649. const {invalidTopics} = xhr.responseJSON;
  3650. const topicLables = topicDropdown.children('a.ui.label');
  3651. topics.split(',').forEach((value, index) => {
  3652. for (let i = 0; i < invalidTopics.length; i++) {
  3653. if (invalidTopics[i] === value) {
  3654. topicLables
  3655. .eq(index)
  3656. .removeClass('green')
  3657. .addClass('red');
  3658. }
  3659. }
  3660. });
  3661. } else {
  3662. topicPrompts.countPrompt = xhr.responseJSON.message;
  3663. }
  3664. }
  3665. })
  3666. .always(() => {
  3667. topicForm.form('validate form');
  3668. });
  3669. });
  3670. topicDropdown.dropdown({
  3671. allowAdditions: true,
  3672. forceSelection: false,
  3673. fields: {name: 'description', value: 'data-value'},
  3674. saveRemoteData: false,
  3675. label: {
  3676. transition: 'horizontal flip',
  3677. duration: 200,
  3678. variation: false,
  3679. blue: true,
  3680. basic: true
  3681. },
  3682. className: {
  3683. label: 'ui small label'
  3684. },
  3685. apiSettings: {
  3686. url: `${AppSubUrl}/api/v1/topics/search?q={query}`,
  3687. throttle: 500,
  3688. cache: false,
  3689. onResponse(res) {
  3690. const formattedResponse = {
  3691. success: false,
  3692. results: []
  3693. };
  3694. const stripTags = function (text) {
  3695. return text.replace(/<[^>]*>?/gm, '');
  3696. };
  3697. const query = stripTags(this.urlData.query.trim());
  3698. let found_query = false;
  3699. const current_topics = [];
  3700. topicDropdown
  3701. .find('div.label.visible.topic,a.label.visible')
  3702. .each((_, e) => {
  3703. current_topics.push(e.dataset.value);
  3704. });
  3705. if (res.topics) {
  3706. let found = false;
  3707. for (let i = 0; i < res.topics.length; i++) {
  3708. // skip currently added tags
  3709. if (current_topics.includes(res.topics[i].topic_name)) {
  3710. continue;
  3711. }
  3712. if (
  3713. res.topics[i].topic_name.toLowerCase() === query.toLowerCase()
  3714. ) {
  3715. found_query = true;
  3716. }
  3717. formattedResponse.results.push({
  3718. description: res.topics[i].topic_name,
  3719. 'data-value': res.topics[i].topic_name
  3720. });
  3721. found = true;
  3722. }
  3723. formattedResponse.success = found;
  3724. }
  3725. if (query.length > 0 && !found_query) {
  3726. formattedResponse.success = true;
  3727. formattedResponse.results.unshift({
  3728. description: query,
  3729. 'data-value': query
  3730. });
  3731. } else if (query.length > 0 && found_query) {
  3732. formattedResponse.results.sort((a, b) => {
  3733. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  3734. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  3735. if (a.description > b.description) return -1;
  3736. if (a.description < b.description) return 1;
  3737. return 0;
  3738. });
  3739. }
  3740. return formattedResponse;
  3741. }
  3742. },
  3743. onLabelCreate(value) {
  3744. value = value.toLowerCase().trim();
  3745. this.attr('data-value', value)
  3746. .contents()
  3747. .first()
  3748. .replaceWith(value);
  3749. return $(this);
  3750. },
  3751. onAdd(addedValue, _addedText, $addedChoice) {
  3752. addedValue = addedValue.toLowerCase().trim();
  3753. $($addedChoice).attr('data-value', addedValue);
  3754. $($addedChoice).attr('data-text', addedValue);
  3755. }
  3756. });
  3757. $.fn.form.settings.rules.validateTopic = function (_values, regExp) {
  3758. const topics = topicDropdown.children('a.ui.label');
  3759. const status =
  3760. topics.length === 0 ||
  3761. topics
  3762. .last()
  3763. .attr('data-value')
  3764. .match(regExp);
  3765. if (!status) {
  3766. topics
  3767. .last()
  3768. .removeClass('green')
  3769. .addClass('red');
  3770. }
  3771. return status && topicDropdown.children('a.ui.label.red').length === 0;
  3772. };
  3773. topicForm.form({
  3774. on: 'change',
  3775. inline: true,
  3776. fields: {
  3777. topics: {
  3778. identifier: 'topics',
  3779. rules: [
  3780. {
  3781. type: 'validateTopic',
  3782. value: /^[a-z0-9][a-z0-9-]{0,35}$/,
  3783. prompt: topicPrompts.formatPrompt
  3784. },
  3785. {
  3786. type: 'maxCount[25]',
  3787. prompt: topicPrompts.countPrompt
  3788. }
  3789. ]
  3790. }
  3791. }
  3792. });
  3793. }
  3794. window.toggleDeadlineForm = function () {
  3795. $('#deadlineForm').fadeToggle(150);
  3796. };
  3797. window.setDeadline = function () {
  3798. const deadline = $('#deadlineDate').val();
  3799. window.updateDeadline(deadline);
  3800. };
  3801. window.updateDeadline = function (deadlineString) {
  3802. $('#deadline-err-invalid-date').hide();
  3803. $('#deadline-loader').addClass('loading');
  3804. let realDeadline = null;
  3805. if (deadlineString !== '') {
  3806. const newDate = Date.parse(deadlineString);
  3807. if (Number.isNaN(newDate)) {
  3808. $('#deadline-loader').removeClass('loading');
  3809. $('#deadline-err-invalid-date').show();
  3810. return false;
  3811. }
  3812. realDeadline = new Date(newDate);
  3813. }
  3814. $.ajax(`${$('#update-issue-deadline-form').attr('action')}/deadline`, {
  3815. data: JSON.stringify({
  3816. due_date: realDeadline
  3817. }),
  3818. headers: {
  3819. 'X-Csrf-Token': csrf,
  3820. 'X-Remote': true
  3821. },
  3822. contentType: 'application/json',
  3823. type: 'POST',
  3824. success() {
  3825. reload();
  3826. },
  3827. error() {
  3828. $('#deadline-loader').removeClass('loading');
  3829. $('#deadline-err-invalid-date').show();
  3830. }
  3831. });
  3832. };
  3833. window.deleteDependencyModal = function (id, type) {
  3834. $('.remove-dependency')
  3835. .modal({
  3836. closable: false,
  3837. duration: 200,
  3838. onApprove() {
  3839. $('#removeDependencyID').val(id);
  3840. $('#dependencyType').val(type);
  3841. $('#removeDependencyForm').trigger('submit');
  3842. }
  3843. })
  3844. .modal('show');
  3845. };
  3846. function initIssueList() {
  3847. const repolink = $('#repolink').val();
  3848. const repoId = $('#repoId').val();
  3849. const crossRepoSearch = $('#crossRepoSearch').val();
  3850. const tp = $('#type').val();
  3851. let issueSearchUrl = `${AppSubUrl}/api/v1/repos/${repolink}/issues?q={query}&type=${tp}`;
  3852. if (crossRepoSearch === 'true') {
  3853. issueSearchUrl = `${AppSubUrl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`;
  3854. }
  3855. $('#new-dependency-drop-list').dropdown({
  3856. apiSettings: {
  3857. url: issueSearchUrl,
  3858. onResponse(response) {
  3859. const filteredResponse = {success: true, results: []};
  3860. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  3861. // Parse the response from the api to work with our dropdown
  3862. $.each(response, (_i, issue) => {
  3863. // Don't list current issue in the dependency list.
  3864. if (issue.id === currIssueId) {
  3865. return;
  3866. }
  3867. filteredResponse.results.push({
  3868. name: `#${issue.number} ${htmlEncode(
  3869. issue.title
  3870. )}<div class="text small dont-break-out">${htmlEncode(
  3871. issue.repository.full_name
  3872. )}</div>`,
  3873. value: issue.id
  3874. });
  3875. });
  3876. return filteredResponse;
  3877. },
  3878. cache: false
  3879. },
  3880. fullTextSearch: true
  3881. });
  3882. $('.menu a.label-filter-item').each(function () {
  3883. $(this).on('click', function (e) {
  3884. if (e.altKey) {
  3885. e.preventDefault();
  3886. const href = $(this).attr('href');
  3887. const id = $(this).data('label-id');
  3888. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3889. const newStr = 'labels=$1-$2$3&';
  3890. window.location = href.replace(new RegExp(regStr), newStr);
  3891. }
  3892. });
  3893. });
  3894. $('.menu .ui.dropdown.label-filter').on('keydown', (e) => {
  3895. if (e.altKey && e.keyCode === 13) {
  3896. const selectedItems = $(
  3897. '.menu .ui.dropdown.label-filter .menu .item.selected'
  3898. );
  3899. if (selectedItems.length > 0) {
  3900. const item = $(selectedItems[0]);
  3901. const href = item.attr('href');
  3902. const id = item.data('label-id');
  3903. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3904. const newStr = 'labels=$1-$2$3&';
  3905. window.location = href.replace(new RegExp(regStr), newStr);
  3906. }
  3907. }
  3908. });
  3909. }
  3910. window.cancelCodeComment = function (btn) {
  3911. const form = $(btn).closest('form');
  3912. if (form.length > 0 && form.hasClass('comment-form')) {
  3913. form.addClass('hide');
  3914. form
  3915. .parent()
  3916. .find('button.comment-form-reply')
  3917. .show();
  3918. } else {
  3919. form.closest('.comment-code-cloud').remove();
  3920. }
  3921. };
  3922. window.submitReply = function (btn) {
  3923. const form = $(btn).closest('form');
  3924. if (form.length > 0 && form.hasClass('comment-form')) {
  3925. form.trigger('submit');
  3926. }
  3927. };
  3928. window.onOAuthLoginClick = function () {
  3929. const oauthLoader = $('#oauth2-login-loader');
  3930. const oauthNav = $('#oauth2-login-navigator');
  3931. oauthNav.hide();
  3932. oauthLoader.removeClass('disabled');
  3933. setTimeout(() => {
  3934. // recover previous content to let user try again
  3935. // usually redirection will be performed before this action
  3936. oauthLoader.addClass('disabled');
  3937. oauthNav.show();
  3938. }, 5000);
  3939. };
  3940. // Pull SVGs via AJAX to workaround CORS issues with <use> tags
  3941. // https://css-tricks.com/ajaxing-svg-sprite/
  3942. $.get(`${window.config.StaticUrlPrefix}/img/svg/icons.svg`, (data) => {
  3943. const div = document.createElement('div');
  3944. div.style.display = 'none';
  3945. div.innerHTML = new XMLSerializer().serializeToString(data.documentElement);
  3946. document.body.insertBefore(div, document.body.childNodes[0]);
  3947. });