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 119 kB

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
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
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 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
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
[RFC] Make archival asynchronous (#11296) * Make archival asynchronous The prime benefit being sought here is for large archives to not clog up the rendering process and cause unsightly proxy timeouts. As a secondary benefit, archive-in-progress is moved out of the way into a /tmp file so that new archival requests for the same commit will not get fulfilled based on an archive that isn't yet finished. This asynchronous system is fairly primitive; request comes in, we'll spawn off a new goroutine to handle it, then we'll mark it as done. Status requests will see if the file exists in the final location, and report the archival as done when it exists. Fixes #11265 * Archive links: drop initial delay to three-quarters of a second Some, or perhaps even most, archives will not take all that long to archive. The archive process starts as soon as the download button is initially clicked, so in theory they could be done quite quickly. Drop the initial delay down to three-quarters of a second to make it more responsive in the common case of the archive being quickly created. * archiver: restructure a little bit to facilitate testing This introduces two sync.Cond pointers to the archiver package. If they're non-nil when we go to process a request, we'll wait until signalled (at all) to proceed. The tests will then create the sync.Cond so that it can signal at-will and sanity-check the state of the queue at different phases. The author believes that nil-checking these two sync.Cond pointers on every archive processing will introduce minimal overhead with no impact on maintainability. * gofmt nit: no space around binary + operator * services: archiver: appease golangci-lint, lock queueMutex Locking/unlocking the queueMutex is allowed, but not required, for Cond.Signal() and Cond.Broadcast(). The magic at play here is just a little too much for golangci-lint, as we take the address of queueMutex and this is mostly used in archiver.go; the variable still gets flagged as unused. * archiver: tests: fix several timing nits Once we've signaled a cond var, it may take some small amount of time for the goroutines released to hit the spot we're wanting them to be at. Give them an appropriate amount of time. * archiver: tests: no underscore in var name, ungh * archiver: tests: Test* is run in a separate context than TestMain We must setup the mutex/cond variables at the beginning of any test that's going to use it, or else these will be nil when the test is actually ran. * archiver: tests: hopefully final tweak Things got shuffled around such that we carefully build up and release requests from the queue, so we can validate the state of the queue at each step. Fix some assertions that no longer hold true as fallout. * repo: Download: restore some semblance of previous behavior When archival was made async, the GET endpoint was only useful if a previous POST had initiated the download. This commit restores the previous behavior, to an extent; we'll now submit the archive request there and return a "202 Accepted" to indicate that it's processing if we didn't manage to complete the request within ~2 seconds of submission. This lets a client directly GET the archive, and gives them some indication that they may attempt to GET it again at a later time. * archiver: tests: simplify a bit further We don't need to risk failure and use time.ParseDuration to get 2 * time.Second. else if isn't really necessary if the conditions are simple enough and lead to the same result. * archiver: tests: resolve potential source of flakiness Increase all timeouts to 10 seconds; these aren't hard-coded sleeps, so there's no guarantee we'll actually take that long. If we need longer to not have a false-positive, then so be it. While here, various assert.{Not,}Equal arguments are flipped around so that the wording in error output reflects reality, where the expected argument is second and actual third. * archiver: setup infrastructure for notifying consumers of completion This API will *not* allow consumers to subscribe to specific requests being completed, just *any* request being completed. The caller is responsible for determining if their request is satisfied and waiting again if needed. * repo: archive: make GET endpoint synchronous again If the request isn't complete, this endpoint will now submit the request and wait for completion using the new API. This may still be susceptible to timeouts for larger repos, but other endpoints now exist that the web interface will use to negotiate its way through larger archive processes. * archiver: tests: amend test to include WaitForCompletion() This is a trivial one, so go ahead and include it. * archiver: tests: fix test by calling NewContext() The mutex is otherwise uninitialized, so we need to ensure that we're actually initializing it if we plan to test it. * archiver: tests: integrate new WaitForCompletion a little better We can use this to wait for archives to come in, rather than spinning and hoping with a timeout. * archiver: tests: combine numQueued declaration with next-instruction assignment * routers: repo: reap unused archiving flag from DownloadStatus() This had some planned usage before, indicating whether this request initiated the archival process or not. After several rounds of refactoring, this use was deemed not necessary for much of anything and got boiled down to !complete in all cases. * services: archiver: restructure to use a channel We now offer two forms of waiting for a request: - WaitForCompletion: wait for completion with no timeout - TimedWaitForCompletion: wait for completion with timeout In both cases, we wait for the given request's cchan to close; in the latter case, we do so with the caller-provided timeout. This completely removes the need for busy-wait loops in Download/InitiateDownload, as it's fairly clean to wait on a channel with timeout. * services: archiver: use defer to unlock now that we can This previously carried the lock into the goroutine, but an intermediate step just added the request to archiveInProgress outside of the new goroutine and removed the need for the goroutine to start out with it. * Revert "archiver: tests: combine numQueued declaration with next-instruction assignment" This reverts commit bcc52140238e16680f2e05e448e9be51372afdf5. Revert "archiver: tests: integrate new WaitForCompletion a little better" This reverts commit 9fc8bedb5667d24d3a3c7843dc28a229efffb1e6. Revert "archiver: tests: fix test by calling NewContext()" This reverts commit 709c35685eaaf261ebbb7d3420e3376a4ee8e7f2. Revert "archiver: tests: amend test to include WaitForCompletion()" This reverts commit 75261f56bc05d1fa8ff7e81dcbc0ccd93fdc9d50. * archiver: tests: first attempt at WaitForCompletion() tests * archiver: tests: slight improvement, less busy-loop Just wait for the requests to complete in order, instead of busy-waiting with a timeout. This is slightly less fragile. While here, reverse the arguments of a nearby assert.Equal() so that expected/actual are correct in any test output. * archiver: address lint nits * services: archiver: only close the channel once * services: archiver: use a struct{} for the wait channel This makes it obvious that the channel is only being used as a signal, rather than anything useful being piped through it. * archiver: tests: fix expectations Move the close of the channel into doArchive() itself; notably, before these goroutines move on to waiting on the Release cond. The tests are adjusted to reflect that we can't WaitForCompletion() after they've already completed, as WaitForCompletion() doesn't indicate that they've been released from the queue yet. * archiver: tests: set cchan to nil for comparison * archiver: move ctx.Error's back into the route handlers We shouldn't be setting this in a service, we should just be validating the request that we were handed. * services: archiver: use regex to match a hash This makes sure we don't try and use refName as a hash when it's clearly not one, e.g. heads/pull/foo. * routers: repo: remove the weird /archive/status endpoint We don't need to do this anymore, we can just continue POSTing to the archive/* endpoint until we're told the download's complete. This avoids a potential naming conflict, where a ref could start with "status/" * archiver: tests: bump reasonable timeout to 15s * archiver: tests: actually release timedReq * archiver: tests: run through inFlight instead of manually checking While we're here, add a test for manually re-processing an archive that's already been complete. Re-open the channel and mark it incomplete, so that doArchive can just mark it complete again. * initArchiveLinks: prevent default behavior from clicking * archiver: alias gitea's context, golang context import pending * archiver: simplify logic, just reconstruct slices While the previous logic was perhaps slightly more efficient, the new variant's readability is much improved. * archiver: don't block shutdown on waiting for archive The technique established launches a goroutine to do the wait, which will close a wait channel upon termination. For the timeout case, we also send back a value indicating whether the timeout was hit or not. The timeouts are expected to be relatively small, but still a multi- second delay to shutdown due to this could be unfortunate. * archiver: simplify shutdown logic We can just grab the shutdown channel from the graceful manager instead of constructing a channel to halt the caller and/or pass a result back. * Style issues * Fix mis-merge Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com> Co-authored-by: Lauris BH <lauris@nix.lv>
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
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
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
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
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
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 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
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
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
[RFC] Make archival asynchronous (#11296) * Make archival asynchronous The prime benefit being sought here is for large archives to not clog up the rendering process and cause unsightly proxy timeouts. As a secondary benefit, archive-in-progress is moved out of the way into a /tmp file so that new archival requests for the same commit will not get fulfilled based on an archive that isn't yet finished. This asynchronous system is fairly primitive; request comes in, we'll spawn off a new goroutine to handle it, then we'll mark it as done. Status requests will see if the file exists in the final location, and report the archival as done when it exists. Fixes #11265 * Archive links: drop initial delay to three-quarters of a second Some, or perhaps even most, archives will not take all that long to archive. The archive process starts as soon as the download button is initially clicked, so in theory they could be done quite quickly. Drop the initial delay down to three-quarters of a second to make it more responsive in the common case of the archive being quickly created. * archiver: restructure a little bit to facilitate testing This introduces two sync.Cond pointers to the archiver package. If they're non-nil when we go to process a request, we'll wait until signalled (at all) to proceed. The tests will then create the sync.Cond so that it can signal at-will and sanity-check the state of the queue at different phases. The author believes that nil-checking these two sync.Cond pointers on every archive processing will introduce minimal overhead with no impact on maintainability. * gofmt nit: no space around binary + operator * services: archiver: appease golangci-lint, lock queueMutex Locking/unlocking the queueMutex is allowed, but not required, for Cond.Signal() and Cond.Broadcast(). The magic at play here is just a little too much for golangci-lint, as we take the address of queueMutex and this is mostly used in archiver.go; the variable still gets flagged as unused. * archiver: tests: fix several timing nits Once we've signaled a cond var, it may take some small amount of time for the goroutines released to hit the spot we're wanting them to be at. Give them an appropriate amount of time. * archiver: tests: no underscore in var name, ungh * archiver: tests: Test* is run in a separate context than TestMain We must setup the mutex/cond variables at the beginning of any test that's going to use it, or else these will be nil when the test is actually ran. * archiver: tests: hopefully final tweak Things got shuffled around such that we carefully build up and release requests from the queue, so we can validate the state of the queue at each step. Fix some assertions that no longer hold true as fallout. * repo: Download: restore some semblance of previous behavior When archival was made async, the GET endpoint was only useful if a previous POST had initiated the download. This commit restores the previous behavior, to an extent; we'll now submit the archive request there and return a "202 Accepted" to indicate that it's processing if we didn't manage to complete the request within ~2 seconds of submission. This lets a client directly GET the archive, and gives them some indication that they may attempt to GET it again at a later time. * archiver: tests: simplify a bit further We don't need to risk failure and use time.ParseDuration to get 2 * time.Second. else if isn't really necessary if the conditions are simple enough and lead to the same result. * archiver: tests: resolve potential source of flakiness Increase all timeouts to 10 seconds; these aren't hard-coded sleeps, so there's no guarantee we'll actually take that long. If we need longer to not have a false-positive, then so be it. While here, various assert.{Not,}Equal arguments are flipped around so that the wording in error output reflects reality, where the expected argument is second and actual third. * archiver: setup infrastructure for notifying consumers of completion This API will *not* allow consumers to subscribe to specific requests being completed, just *any* request being completed. The caller is responsible for determining if their request is satisfied and waiting again if needed. * repo: archive: make GET endpoint synchronous again If the request isn't complete, this endpoint will now submit the request and wait for completion using the new API. This may still be susceptible to timeouts for larger repos, but other endpoints now exist that the web interface will use to negotiate its way through larger archive processes. * archiver: tests: amend test to include WaitForCompletion() This is a trivial one, so go ahead and include it. * archiver: tests: fix test by calling NewContext() The mutex is otherwise uninitialized, so we need to ensure that we're actually initializing it if we plan to test it. * archiver: tests: integrate new WaitForCompletion a little better We can use this to wait for archives to come in, rather than spinning and hoping with a timeout. * archiver: tests: combine numQueued declaration with next-instruction assignment * routers: repo: reap unused archiving flag from DownloadStatus() This had some planned usage before, indicating whether this request initiated the archival process or not. After several rounds of refactoring, this use was deemed not necessary for much of anything and got boiled down to !complete in all cases. * services: archiver: restructure to use a channel We now offer two forms of waiting for a request: - WaitForCompletion: wait for completion with no timeout - TimedWaitForCompletion: wait for completion with timeout In both cases, we wait for the given request's cchan to close; in the latter case, we do so with the caller-provided timeout. This completely removes the need for busy-wait loops in Download/InitiateDownload, as it's fairly clean to wait on a channel with timeout. * services: archiver: use defer to unlock now that we can This previously carried the lock into the goroutine, but an intermediate step just added the request to archiveInProgress outside of the new goroutine and removed the need for the goroutine to start out with it. * Revert "archiver: tests: combine numQueued declaration with next-instruction assignment" This reverts commit bcc52140238e16680f2e05e448e9be51372afdf5. Revert "archiver: tests: integrate new WaitForCompletion a little better" This reverts commit 9fc8bedb5667d24d3a3c7843dc28a229efffb1e6. Revert "archiver: tests: fix test by calling NewContext()" This reverts commit 709c35685eaaf261ebbb7d3420e3376a4ee8e7f2. Revert "archiver: tests: amend test to include WaitForCompletion()" This reverts commit 75261f56bc05d1fa8ff7e81dcbc0ccd93fdc9d50. * archiver: tests: first attempt at WaitForCompletion() tests * archiver: tests: slight improvement, less busy-loop Just wait for the requests to complete in order, instead of busy-waiting with a timeout. This is slightly less fragile. While here, reverse the arguments of a nearby assert.Equal() so that expected/actual are correct in any test output. * archiver: address lint nits * services: archiver: only close the channel once * services: archiver: use a struct{} for the wait channel This makes it obvious that the channel is only being used as a signal, rather than anything useful being piped through it. * archiver: tests: fix expectations Move the close of the channel into doArchive() itself; notably, before these goroutines move on to waiting on the Release cond. The tests are adjusted to reflect that we can't WaitForCompletion() after they've already completed, as WaitForCompletion() doesn't indicate that they've been released from the queue yet. * archiver: tests: set cchan to nil for comparison * archiver: move ctx.Error's back into the route handlers We shouldn't be setting this in a service, we should just be validating the request that we were handed. * services: archiver: use regex to match a hash This makes sure we don't try and use refName as a hash when it's clearly not one, e.g. heads/pull/foo. * routers: repo: remove the weird /archive/status endpoint We don't need to do this anymore, we can just continue POSTing to the archive/* endpoint until we're told the download's complete. This avoids a potential naming conflict, where a ref could start with "status/" * archiver: tests: bump reasonable timeout to 15s * archiver: tests: actually release timedReq * archiver: tests: run through inFlight instead of manually checking While we're here, add a test for manually re-processing an archive that's already been complete. Re-open the channel and mark it incomplete, so that doArchive can just mark it complete again. * initArchiveLinks: prevent default behavior from clicking * archiver: alias gitea's context, golang context import pending * archiver: simplify logic, just reconstruct slices While the previous logic was perhaps slightly more efficient, the new variant's readability is much improved. * archiver: don't block shutdown on waiting for archive The technique established launches a goroutine to do the wait, which will close a wait channel upon termination. For the timeout case, we also send back a value indicating whether the timeout was hit or not. The timeouts are expected to be relatively small, but still a multi- second delay to shutdown due to this could be unfortunate. * archiver: simplify shutdown logic We can just grab the shutdown channel from the graceful manager instead of constructing a channel to halt the caller and/or pass a result back. * Style issues * Fix mis-merge Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com> Co-authored-by: Lauris BH <lauris@nix.lv>
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
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
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812
  1. /* exported deleteDependencyModal, cancelCodeComment, onOAuthLoginClick */
  2. import './publicpath.js';
  3. import Vue from 'vue';
  4. import {htmlEscape} from 'escape-goat';
  5. import 'jquery.are-you-sure';
  6. import './vendor/semanticdropdown.js';
  7. import initMigration from './features/migration.js';
  8. import initContextPopups from './features/contextpopup.js';
  9. import initGitGraph from './features/gitgraph.js';
  10. import initClipboard from './features/clipboard.js';
  11. import initHeatmap from './features/heatmap.js';
  12. import initProject from './features/projects.js';
  13. import initServiceWorker from './features/serviceworker.js';
  14. import initMarkdownAnchors from './markdown/anchors.js';
  15. import renderMarkdownContent from './markdown/content.js';
  16. import attachTribute from './features/tribute.js';
  17. import createColorPicker from './features/colorpicker.js';
  18. import createDropzone from './features/dropzone.js';
  19. import initTableSort from './features/tablesort.js';
  20. import ActivityTopAuthors from './components/ActivityTopAuthors.vue';
  21. import {initNotificationsTable, initNotificationCount} from './features/notification.js';
  22. import {initStopwatch} from './features/stopwatch.js';
  23. import {createCodeEditor, createMonaco} from './features/codeeditor.js';
  24. import {svg, svgs} from './svg.js';
  25. import {stripTags} from './utils.js';
  26. const {AppSubUrl, StaticUrlPrefix, csrf} = window.config;
  27. let previewFileModes;
  28. const commentMDEditors = {};
  29. // Silence fomantic's error logging when tabs are used without a target content element
  30. $.fn.tab.settings.silent = true;
  31. function initCommentPreviewTab($form) {
  32. const $tabMenu = $form.find('.tabular.menu');
  33. $tabMenu.find('.item').tab();
  34. $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`).on('click', function () {
  35. const $this = $(this);
  36. $.post($this.data('url'), {
  37. _csrf: csrf,
  38. mode: 'comment',
  39. context: $this.data('context'),
  40. text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
  41. }, (data) => {
  42. const $previewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('preview')}"]`);
  43. $previewPanel.html(data);
  44. renderMarkdownContent();
  45. });
  46. });
  47. buttonsClickOnEnter();
  48. }
  49. function initEditPreviewTab($form) {
  50. const $tabMenu = $form.find('.tabular.menu');
  51. $tabMenu.find('.item').tab();
  52. const $previewTab = $tabMenu.find(`.item[data-tab="${$tabMenu.data('preview')}"]`);
  53. if ($previewTab.length) {
  54. previewFileModes = $previewTab.data('preview-file-modes').split(',');
  55. $previewTab.on('click', function () {
  56. const $this = $(this);
  57. let context = `${$this.data('context')}/`;
  58. const mode = $this.data('markdown-mode') || 'comment';
  59. const treePathEl = $form.find('input#tree_path');
  60. if (treePathEl.length > 0) {
  61. context += treePathEl.val();
  62. }
  63. context = context.substring(0, context.lastIndexOf('/'));
  64. $.post($this.data('url'), {
  65. _csrf: csrf,
  66. mode,
  67. context,
  68. text: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
  69. }, (data) => {
  70. const $previewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('preview')}"]`);
  71. $previewPanel.html(data);
  72. renderMarkdownContent();
  73. });
  74. });
  75. }
  76. }
  77. function initEditDiffTab($form) {
  78. const $tabMenu = $form.find('.tabular.menu');
  79. $tabMenu.find('.item').tab();
  80. $tabMenu.find(`.item[data-tab="${$tabMenu.data('diff')}"]`).on('click', function () {
  81. const $this = $(this);
  82. $.post($this.data('url'), {
  83. _csrf: csrf,
  84. context: $this.data('context'),
  85. content: $form.find(`.tab[data-tab="${$tabMenu.data('write')}"] textarea`).val()
  86. }, (data) => {
  87. const $diffPreviewPanel = $form.find(`.tab[data-tab="${$tabMenu.data('diff')}"]`);
  88. $diffPreviewPanel.html(data);
  89. });
  90. });
  91. }
  92. function initEditForm() {
  93. if ($('.edit.form').length === 0) {
  94. return;
  95. }
  96. initEditPreviewTab($('.edit.form'));
  97. initEditDiffTab($('.edit.form'));
  98. }
  99. function initBranchSelector() {
  100. const $selectBranch = $('.ui.select-branch');
  101. const $branchMenu = $selectBranch.find('.reference-list-menu');
  102. const $isNewIssue = $branchMenu.hasClass('new-issue');
  103. $branchMenu.find('.item:not(.no-select)').click(function () {
  104. const selectedValue = $(this).data('id');
  105. const editMode = $('#editing_mode').val();
  106. $($(this).data('id-selector')).val(selectedValue);
  107. if ($isNewIssue) {
  108. $selectBranch.find('.ui .branch-name').text($(this).data('name'));
  109. return;
  110. }
  111. if (editMode === 'true') {
  112. const form = $('#update_issueref_form');
  113. $.post(form.attr('action'), {
  114. _csrf: csrf,
  115. ref: selectedValue
  116. },
  117. () => {
  118. window.location.reload();
  119. });
  120. } else if (editMode === '') {
  121. $selectBranch.find('.ui .branch-name').text(selectedValue);
  122. }
  123. });
  124. $selectBranch.find('.reference.column').on('click', function () {
  125. $selectBranch.find('.scrolling.reference-list-menu').css('display', 'none');
  126. $selectBranch.find('.reference .text').removeClass('black');
  127. $($(this).data('target')).css('display', 'block');
  128. $(this).find('.text').addClass('black');
  129. return false;
  130. });
  131. }
  132. function initLabelEdit() {
  133. // Create label
  134. const $newLabelPanel = $('.new-label.segment');
  135. $('.new-label.button').on('click', () => {
  136. $newLabelPanel.show();
  137. });
  138. $('.new-label.segment .cancel').on('click', () => {
  139. $newLabelPanel.hide();
  140. });
  141. createColorPicker($('.color-picker'));
  142. $('.precolors .color').on('click', function () {
  143. const color_hex = $(this).data('color-hex');
  144. $('.color-picker').val(color_hex);
  145. $('.minicolors-swatch-color').css('background-color', color_hex);
  146. });
  147. $('.edit-label-button').on('click', function () {
  148. $('.edit-label .color-picker').minicolors('value', $(this).data('color'));
  149. $('#label-modal-id').val($(this).data('id'));
  150. $('.edit-label .new-label-input').val($(this).data('title'));
  151. $('.edit-label .new-label-desc-input').val($(this).data('description'));
  152. $('.edit-label .color-picker').val($(this).data('color'));
  153. $('.edit-label .minicolors-swatch-color').css('background-color', $(this).data('color'));
  154. $('.edit-label.modal').modal({
  155. onApprove() {
  156. $('.edit-label.form').trigger('submit');
  157. }
  158. }).modal('show');
  159. return false;
  160. });
  161. }
  162. function updateIssuesMeta(url, action, issueIds, elementId) {
  163. return new Promise(((resolve) => {
  164. $.ajax({
  165. type: 'POST',
  166. url,
  167. data: {
  168. _csrf: csrf,
  169. action,
  170. issue_ids: issueIds,
  171. id: elementId,
  172. },
  173. success: resolve
  174. });
  175. }));
  176. }
  177. function initRepoStatusChecker() {
  178. const migrating = $('#repo_migrating');
  179. $('#repo_migrating_failed').hide();
  180. $('#repo_migrating_failed_image').hide();
  181. if (migrating) {
  182. const task = migrating.attr('task');
  183. if (typeof task === 'undefined') {
  184. return;
  185. }
  186. $.ajax({
  187. type: 'GET',
  188. url: `${AppSubUrl}/user/task/${task}`,
  189. data: {
  190. _csrf: csrf,
  191. },
  192. complete(xhr) {
  193. if (xhr.status === 200 && xhr.responseJSON) {
  194. if (xhr.responseJSON.status === 4) {
  195. window.location.reload();
  196. return;
  197. } else if (xhr.responseJSON.status === 3) {
  198. $('#repo_migrating_progress').hide();
  199. $('#repo_migrating').hide();
  200. $('#repo_migrating_failed').show();
  201. $('#repo_migrating_failed_image').show();
  202. $('#repo_migrating_failed_error').text(xhr.responseJSON.err);
  203. return;
  204. }
  205. setTimeout(() => {
  206. initRepoStatusChecker();
  207. }, 2000);
  208. return;
  209. }
  210. $('#repo_migrating_progress').hide();
  211. $('#repo_migrating').hide();
  212. $('#repo_migrating_failed').show();
  213. $('#repo_migrating_failed_image').show();
  214. }
  215. });
  216. }
  217. }
  218. function initReactionSelector(parent) {
  219. let reactions = '';
  220. if (!parent) {
  221. parent = $(document);
  222. reactions = '.reactions > ';
  223. }
  224. parent.find(`${reactions}a.label`).popup({position: 'bottom left', metadata: {content: 'title', title: 'none'}});
  225. parent.find(`.select-reaction > .menu > .item, ${reactions}a.label`).on('click', function (e) {
  226. const vm = this;
  227. e.preventDefault();
  228. if ($(this).hasClass('disabled')) return;
  229. const actionURL = $(this).hasClass('item') ? $(this).closest('.select-reaction').data('action-url') : $(this).data('action-url');
  230. const url = `${actionURL}/${$(this).hasClass('blue') ? 'unreact' : 'react'}`;
  231. $.ajax({
  232. type: 'POST',
  233. url,
  234. data: {
  235. _csrf: csrf,
  236. content: $(this).data('content')
  237. }
  238. }).done((resp) => {
  239. if (resp && (resp.html || resp.empty)) {
  240. const content = $(vm).closest('.content');
  241. let react = content.find('.segment.reactions');
  242. if ((!resp.empty || resp.html === '') && react.length > 0) {
  243. react.remove();
  244. }
  245. if (!resp.empty) {
  246. react = $('<div class="ui attached segment reactions"></div>');
  247. const attachments = content.find('.segment.bottom:first');
  248. if (attachments.length > 0) {
  249. react.insertBefore(attachments);
  250. } else {
  251. react.appendTo(content);
  252. }
  253. react.html(resp.html);
  254. react.find('.dropdown').dropdown();
  255. initReactionSelector(react);
  256. }
  257. }
  258. });
  259. });
  260. }
  261. function insertAtCursor(field, value) {
  262. if (field.selectionStart || field.selectionStart === 0) {
  263. const startPos = field.selectionStart;
  264. const endPos = field.selectionEnd;
  265. field.value = field.value.substring(0, startPos) + value + field.value.substring(endPos, field.value.length);
  266. field.selectionStart = startPos + value.length;
  267. field.selectionEnd = startPos + value.length;
  268. } else {
  269. field.value += value;
  270. }
  271. }
  272. function replaceAndKeepCursor(field, oldval, newval) {
  273. if (field.selectionStart || field.selectionStart === 0) {
  274. const startPos = field.selectionStart;
  275. const endPos = field.selectionEnd;
  276. field.value = field.value.replace(oldval, newval);
  277. field.selectionStart = startPos + newval.length - oldval.length;
  278. field.selectionEnd = endPos + newval.length - oldval.length;
  279. } else {
  280. field.value = field.value.replace(oldval, newval);
  281. }
  282. }
  283. function getPastedImages(e) {
  284. if (!e.clipboardData) return [];
  285. const files = [];
  286. for (const item of e.clipboardData.items || []) {
  287. if (!item.type || !item.type.startsWith('image/')) continue;
  288. files.push(item.getAsFile());
  289. }
  290. if (files.length) {
  291. e.preventDefault();
  292. e.stopPropagation();
  293. }
  294. return files;
  295. }
  296. async function uploadFile(file) {
  297. const formData = new FormData();
  298. formData.append('file', file, file.name);
  299. const res = await fetch($('#dropzone').data('upload-url'), {
  300. method: 'POST',
  301. headers: {'X-Csrf-Token': csrf},
  302. body: formData,
  303. });
  304. return await res.json();
  305. }
  306. function reload() {
  307. window.location.reload();
  308. }
  309. function initImagePaste(target) {
  310. target.each(function () {
  311. const field = this;
  312. field.addEventListener('paste', async (e) => {
  313. for (const img of getPastedImages(e)) {
  314. const name = img.name.substr(0, img.name.lastIndexOf('.'));
  315. insertAtCursor(field, `![${name}]()`);
  316. const data = await uploadFile(img);
  317. replaceAndKeepCursor(field, `![${name}]()`, `![${name}](${AppSubUrl}/attachments/${data.uuid})`);
  318. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  319. $('.files').append(input);
  320. }
  321. }, false);
  322. });
  323. }
  324. function initSimpleMDEImagePaste(simplemde, files) {
  325. simplemde.codemirror.on('paste', async (_, e) => {
  326. for (const img of getPastedImages(e)) {
  327. const name = img.name.substr(0, img.name.lastIndexOf('.'));
  328. const data = await uploadFile(img);
  329. const pos = simplemde.codemirror.getCursor();
  330. simplemde.codemirror.replaceRange(`![${name}](${AppSubUrl}/attachments/${data.uuid})`, pos);
  331. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  332. files.append(input);
  333. }
  334. });
  335. }
  336. let autoSimpleMDE;
  337. function initCommentForm() {
  338. if ($('.comment.form').length === 0) {
  339. return;
  340. }
  341. autoSimpleMDE = setCommentSimpleMDE($('.comment.form textarea:not(.review-textarea)'));
  342. initBranchSelector();
  343. initCommentPreviewTab($('.comment.form'));
  344. initImagePaste($('.comment.form textarea'));
  345. // Listsubmit
  346. function initListSubmits(selector, outerSelector) {
  347. const $list = $(`.ui.${outerSelector}.list`);
  348. const $noSelect = $list.find('.no-select');
  349. const $listMenu = $(`.${selector} .menu`);
  350. let hasUpdateAction = $listMenu.data('action') === 'update';
  351. const items = {};
  352. $(`.${selector}`).dropdown('setting', 'onHide', () => {
  353. hasUpdateAction = $listMenu.data('action') === 'update'; // Update the var
  354. if (hasUpdateAction) {
  355. const promises = [];
  356. Object.keys(items).forEach((elementId) => {
  357. const item = items[elementId];
  358. const promise = updateIssuesMeta(
  359. item['update-url'],
  360. item.action,
  361. item['issue-id'],
  362. elementId,
  363. );
  364. promises.push(promise);
  365. });
  366. Promise.all(promises).then(reload);
  367. }
  368. });
  369. $listMenu.find('.item:not(.no-select)').on('click', function (e) {
  370. e.preventDefault();
  371. if ($(this).hasClass('ban-change')) {
  372. return false;
  373. }
  374. hasUpdateAction = $listMenu.data('action') === 'update'; // Update the var
  375. if ($(this).hasClass('checked')) {
  376. $(this).removeClass('checked');
  377. $(this).find('.octicon-check').addClass('invisible');
  378. if (hasUpdateAction) {
  379. if (!($(this).data('id') in items)) {
  380. items[$(this).data('id')] = {
  381. 'update-url': $listMenu.data('update-url'),
  382. action: 'detach',
  383. 'issue-id': $listMenu.data('issue-id'),
  384. };
  385. } else {
  386. delete items[$(this).data('id')];
  387. }
  388. }
  389. } else {
  390. $(this).addClass('checked');
  391. $(this).find('.octicon-check').removeClass('invisible');
  392. if (hasUpdateAction) {
  393. if (!($(this).data('id') in items)) {
  394. items[$(this).data('id')] = {
  395. 'update-url': $listMenu.data('update-url'),
  396. action: 'attach',
  397. 'issue-id': $listMenu.data('issue-id'),
  398. };
  399. } else {
  400. delete items[$(this).data('id')];
  401. }
  402. }
  403. }
  404. // TODO: Which thing should be done for choosing review requests
  405. // to make choosed items be shown on time here?
  406. if (selector === 'select-reviewers-modify' || selector === 'select-assignees-modify') {
  407. return false;
  408. }
  409. const listIds = [];
  410. $(this).parent().find('.item').each(function () {
  411. if ($(this).hasClass('checked')) {
  412. listIds.push($(this).data('id'));
  413. $($(this).data('id-selector')).removeClass('hide');
  414. } else {
  415. $($(this).data('id-selector')).addClass('hide');
  416. }
  417. });
  418. if (listIds.length === 0) {
  419. $noSelect.removeClass('hide');
  420. } else {
  421. $noSelect.addClass('hide');
  422. }
  423. $($(this).parent().data('id')).val(listIds.join(','));
  424. return false;
  425. });
  426. $listMenu.find('.no-select.item').on('click', function (e) {
  427. e.preventDefault();
  428. if (hasUpdateAction) {
  429. updateIssuesMeta(
  430. $listMenu.data('update-url'),
  431. 'clear',
  432. $listMenu.data('issue-id'),
  433. '',
  434. ).then(reload);
  435. }
  436. $(this).parent().find('.item').each(function () {
  437. $(this).removeClass('checked');
  438. $(this).find('.octicon').addClass('invisible');
  439. });
  440. if (selector === 'select-reviewers-modify' || selector === 'select-assignees-modify') {
  441. return false;
  442. }
  443. $list.find('.item').each(function () {
  444. $(this).addClass('hide');
  445. });
  446. $noSelect.removeClass('hide');
  447. $($(this).parent().data('id')).val('');
  448. });
  449. }
  450. // Init labels and assignees
  451. initListSubmits('select-label', 'labels');
  452. initListSubmits('select-assignees', 'assignees');
  453. initListSubmits('select-assignees-modify', 'assignees');
  454. initListSubmits('select-reviewers-modify', 'assignees');
  455. function selectItem(select_id, input_id) {
  456. const $menu = $(`${select_id} .menu`);
  457. const $list = $(`.ui${select_id}.list`);
  458. const hasUpdateAction = $menu.data('action') === 'update';
  459. $menu.find('.item:not(.no-select)').on('click', function () {
  460. $(this).parent().find('.item').each(function () {
  461. $(this).removeClass('selected active');
  462. });
  463. $(this).addClass('selected active');
  464. if (hasUpdateAction) {
  465. updateIssuesMeta(
  466. $menu.data('update-url'),
  467. '',
  468. $menu.data('issue-id'),
  469. $(this).data('id'),
  470. ).then(reload);
  471. }
  472. let icon = '';
  473. if (input_id === '#milestone_id') {
  474. icon = svg('octicon-milestone', 18, 'mr-3');
  475. } else if (input_id === '#project_id') {
  476. icon = svg('octicon-project', 18, 'mr-3');
  477. } else if (input_id === '#assignee_id') {
  478. icon = `<img class="ui avatar image mr-3" src=${$(this).data('avatar')}>`;
  479. }
  480. $list.find('.selected').html(`
  481. <a class="item muted sidebar-item-link" href=${$(this).data('href')}>
  482. ${icon}
  483. ${htmlEscape($(this).text())}
  484. </a>
  485. `);
  486. $(`.ui${select_id}.list .no-select`).addClass('hide');
  487. $(input_id).val($(this).data('id'));
  488. });
  489. $menu.find('.no-select.item').on('click', function () {
  490. $(this).parent().find('.item:not(.no-select)').each(function () {
  491. $(this).removeClass('selected active');
  492. });
  493. if (hasUpdateAction) {
  494. updateIssuesMeta(
  495. $menu.data('update-url'),
  496. '',
  497. $menu.data('issue-id'),
  498. $(this).data('id'),
  499. ).then(reload);
  500. }
  501. $list.find('.selected').html('');
  502. $list.find('.no-select').removeClass('hide');
  503. $(input_id).val('');
  504. });
  505. }
  506. // Milestone, Assignee, Project
  507. selectItem('.select-project', '#project_id');
  508. selectItem('.select-milestone', '#milestone_id');
  509. selectItem('.select-assignee', '#assignee_id');
  510. }
  511. function initInstall() {
  512. if ($('.install').length === 0) {
  513. return;
  514. }
  515. if ($('#db_host').val() === '') {
  516. $('#db_host').val('127.0.0.1:3306');
  517. $('#db_user').val('gitea');
  518. $('#db_name').val('gitea');
  519. }
  520. // Database type change detection.
  521. $('#db_type').on('change', function () {
  522. const sqliteDefault = 'data/gitea.db';
  523. const tidbDefault = 'data/gitea_tidb';
  524. const dbType = $(this).val();
  525. if (dbType === 'SQLite3') {
  526. $('#sql_settings').hide();
  527. $('#pgsql_settings').hide();
  528. $('#mysql_settings').hide();
  529. $('#sqlite_settings').show();
  530. if (dbType === 'SQLite3' && $('#db_path').val() === tidbDefault) {
  531. $('#db_path').val(sqliteDefault);
  532. }
  533. return;
  534. }
  535. const dbDefaults = {
  536. MySQL: '127.0.0.1:3306',
  537. PostgreSQL: '127.0.0.1:5432',
  538. MSSQL: '127.0.0.1:1433'
  539. };
  540. $('#sqlite_settings').hide();
  541. $('#sql_settings').show();
  542. $('#pgsql_settings').toggle(dbType === 'PostgreSQL');
  543. $('#mysql_settings').toggle(dbType === 'MySQL');
  544. $.each(dbDefaults, (_type, defaultHost) => {
  545. if ($('#db_host').val() === defaultHost) {
  546. $('#db_host').val(dbDefaults[dbType]);
  547. return false;
  548. }
  549. });
  550. });
  551. // TODO: better handling of exclusive relations.
  552. $('#offline-mode input').on('change', function () {
  553. if ($(this).is(':checked')) {
  554. $('#disable-gravatar').checkbox('check');
  555. $('#federated-avatar-lookup').checkbox('uncheck');
  556. }
  557. });
  558. $('#disable-gravatar input').on('change', function () {
  559. if ($(this).is(':checked')) {
  560. $('#federated-avatar-lookup').checkbox('uncheck');
  561. } else {
  562. $('#offline-mode').checkbox('uncheck');
  563. }
  564. });
  565. $('#federated-avatar-lookup input').on('change', function () {
  566. if ($(this).is(':checked')) {
  567. $('#disable-gravatar').checkbox('uncheck');
  568. $('#offline-mode').checkbox('uncheck');
  569. }
  570. });
  571. $('#enable-openid-signin input').on('change', function () {
  572. if ($(this).is(':checked')) {
  573. if (!$('#disable-registration input').is(':checked')) {
  574. $('#enable-openid-signup').checkbox('check');
  575. }
  576. } else {
  577. $('#enable-openid-signup').checkbox('uncheck');
  578. }
  579. });
  580. $('#disable-registration input').on('change', function () {
  581. if ($(this).is(':checked')) {
  582. $('#enable-captcha').checkbox('uncheck');
  583. $('#enable-openid-signup').checkbox('uncheck');
  584. } else {
  585. $('#enable-openid-signup').checkbox('check');
  586. }
  587. });
  588. $('#enable-captcha input').on('change', function () {
  589. if ($(this).is(':checked')) {
  590. $('#disable-registration').checkbox('uncheck');
  591. }
  592. });
  593. }
  594. function initIssueComments() {
  595. if ($('.repository.view.issue .timeline').length === 0) return;
  596. $('.re-request-review').on('click', function (event) {
  597. const url = $(this).data('update-url');
  598. const issueId = $(this).data('issue-id');
  599. const id = $(this).data('id');
  600. const isChecked = $(this).hasClass('checked');
  601. event.preventDefault();
  602. updateIssuesMeta(
  603. url,
  604. isChecked ? 'detach' : 'attach',
  605. issueId,
  606. id,
  607. ).then(reload);
  608. return false;
  609. });
  610. $('.dismiss-review-btn').on('click', function (e) {
  611. e.preventDefault();
  612. const $this = $(this);
  613. const $dismissReviewModal = $this.next();
  614. $dismissReviewModal.modal('show');
  615. });
  616. $(document).on('click', (event) => {
  617. const urlTarget = $(':target');
  618. if (urlTarget.length === 0) return;
  619. const urlTargetId = urlTarget.attr('id');
  620. if (!urlTargetId) return;
  621. if (!/^(issue|pull)(comment)?-\d+$/.test(urlTargetId)) return;
  622. const $target = $(event.target);
  623. if ($target.closest(`#${urlTargetId}`).length === 0) {
  624. const scrollPosition = $(window).scrollTop();
  625. window.location.hash = '';
  626. $(window).scrollTop(scrollPosition);
  627. window.history.pushState(null, null, ' ');
  628. }
  629. });
  630. }
  631. function getArchive($target, url, first) {
  632. $.ajax({
  633. url,
  634. type: 'POST',
  635. data: {
  636. _csrf: csrf,
  637. },
  638. complete(xhr) {
  639. if (xhr.status === 200) {
  640. if (!xhr.responseJSON) {
  641. // XXX Shouldn't happen?
  642. $target.closest('.dropdown').children('i').removeClass('loading');
  643. return;
  644. }
  645. if (!xhr.responseJSON.complete) {
  646. $target.closest('.dropdown').children('i').addClass('loading');
  647. // Wait for only three quarters of a second initially, in case it's
  648. // quickly archived.
  649. setTimeout(() => {
  650. getArchive($target, url, false);
  651. }, first ? 750 : 2000);
  652. } else {
  653. // We don't need to continue checking.
  654. $target.closest('.dropdown').children('i').removeClass('loading');
  655. window.location.href = url;
  656. }
  657. }
  658. }
  659. });
  660. }
  661. function initArchiveLinks() {
  662. if ($('.archive-link').length === 0) {
  663. return;
  664. }
  665. $('.archive-link').on('click', function (event) {
  666. const url = $(this).data('url');
  667. if (typeof url === 'undefined') {
  668. return;
  669. }
  670. event.preventDefault();
  671. getArchive($(event.target), url, true);
  672. });
  673. }
  674. async function initRepository() {
  675. if ($('.repository').length === 0) {
  676. return;
  677. }
  678. function initFilterSearchDropdown(selector) {
  679. const $dropdown = $(selector);
  680. $dropdown.dropdown({
  681. fullTextSearch: true,
  682. selectOnKeydown: false,
  683. onChange(_text, _value, $choice) {
  684. if ($choice.data('url')) {
  685. window.location.href = $choice.data('url');
  686. }
  687. },
  688. message: {noResults: $dropdown.data('no-results')}
  689. });
  690. }
  691. // Commit statuses
  692. $('.commit-statuses-trigger').each(function () {
  693. $(this)
  694. .popup({
  695. on: 'click',
  696. position: ($('.repository.file.list').length > 0 ? 'right center' : 'left center'),
  697. });
  698. });
  699. // File list and commits
  700. if ($('.repository.file.list').length > 0 || ('.repository.commits').length > 0) {
  701. initFilterBranchTagDropdown('.choose.reference .dropdown');
  702. }
  703. // Wiki
  704. if ($('.repository.wiki.view').length > 0) {
  705. initFilterSearchDropdown('.choose.page .dropdown');
  706. }
  707. // Options
  708. if ($('.repository.settings.options').length > 0) {
  709. // Enable or select internal/external wiki system and issue tracker.
  710. $('.enable-system').on('change', function () {
  711. if (this.checked) {
  712. $($(this).data('target')).removeClass('disabled');
  713. if (!$(this).data('context')) $($(this).data('context')).addClass('disabled');
  714. } else {
  715. $($(this).data('target')).addClass('disabled');
  716. if (!$(this).data('context')) $($(this).data('context')).removeClass('disabled');
  717. }
  718. });
  719. $('.enable-system-radio').on('change', function () {
  720. if (this.value === 'false') {
  721. $($(this).data('target')).addClass('disabled');
  722. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).removeClass('disabled');
  723. } else if (this.value === 'true') {
  724. $($(this).data('target')).removeClass('disabled');
  725. if (typeof $(this).data('context') !== 'undefined') $($(this).data('context')).addClass('disabled');
  726. }
  727. });
  728. }
  729. // Labels
  730. if ($('.repository.labels').length > 0) {
  731. initLabelEdit();
  732. }
  733. // Milestones
  734. if ($('.repository.new.milestone').length > 0) {
  735. $('#clear-date').on('click', () => {
  736. $('#deadline').val('');
  737. return false;
  738. });
  739. }
  740. // Repo Creation
  741. if ($('.repository.new.repo').length > 0) {
  742. $('input[name="gitignores"], input[name="license"]').on('change', () => {
  743. const gitignores = $('input[name="gitignores"]').val();
  744. const license = $('input[name="license"]').val();
  745. if (gitignores || license) {
  746. $('input[name="auto_init"]').prop('checked', true);
  747. }
  748. });
  749. }
  750. // Issues
  751. if ($('.repository.view.issue').length > 0) {
  752. // Edit issue title
  753. const $issueTitle = $('#issue-title');
  754. const $editInput = $('#edit-title-input input');
  755. const editTitleToggle = function () {
  756. $issueTitle.toggle();
  757. $('.not-in-edit').toggle();
  758. $('#edit-title-input').toggle();
  759. $('#pull-desc').toggle();
  760. $('#pull-desc-edit').toggle();
  761. $('.in-edit').toggle();
  762. $('#issue-title-wrapper').toggleClass('edit-active');
  763. $editInput.focus();
  764. return false;
  765. };
  766. const changeBranchSelect = function () {
  767. const selectionTextField = $('#pull-target-branch');
  768. const baseName = selectionTextField.data('basename');
  769. const branchNameNew = $(this).data('branch');
  770. const branchNameOld = selectionTextField.data('branch');
  771. // Replace branch name to keep translation from HTML template
  772. selectionTextField.html(selectionTextField.html().replace(
  773. `${baseName}:${branchNameOld}`,
  774. `${baseName}:${branchNameNew}`
  775. ));
  776. selectionTextField.data('branch', branchNameNew); // update branch name in setting
  777. };
  778. $('#branch-select > .item').on('click', changeBranchSelect);
  779. $('#edit-title').on('click', editTitleToggle);
  780. $('#cancel-edit-title').on('click', editTitleToggle);
  781. $('#save-edit-title').on('click', editTitleToggle).on('click', function () {
  782. const pullrequest_targetbranch_change = function (update_url) {
  783. const targetBranch = $('#pull-target-branch').data('branch');
  784. const $branchTarget = $('#branch_target');
  785. if (targetBranch === $branchTarget.text()) {
  786. return false;
  787. }
  788. $.post(update_url, {
  789. _csrf: csrf,
  790. target_branch: targetBranch
  791. }).done((data) => {
  792. $branchTarget.text(data.base_branch);
  793. }).always(() => {
  794. reload();
  795. });
  796. };
  797. const pullrequest_target_update_url = $(this).data('target-update-url');
  798. if ($editInput.val().length === 0 || $editInput.val() === $issueTitle.text()) {
  799. $editInput.val($issueTitle.text());
  800. pullrequest_targetbranch_change(pullrequest_target_update_url);
  801. } else {
  802. $.post($(this).data('update-url'), {
  803. _csrf: csrf,
  804. title: $editInput.val()
  805. }, (data) => {
  806. $editInput.val(data.title);
  807. $issueTitle.text(data.title);
  808. pullrequest_targetbranch_change(pullrequest_target_update_url);
  809. reload();
  810. });
  811. }
  812. return false;
  813. });
  814. // Issue Comments
  815. initIssueComments();
  816. // Issue/PR Context Menus
  817. $('.context-dropdown').dropdown({
  818. action: 'hide'
  819. });
  820. // Quote reply
  821. $(document).on('click', '.quote-reply', function (event) {
  822. $(this).closest('.dropdown').find('.menu').toggle('visible');
  823. const target = $(this).data('target');
  824. const quote = $(`#comment-${target}`).text().replace(/\n/g, '\n> ');
  825. const content = `> ${quote}\n\n`;
  826. let $simplemde = autoSimpleMDE;
  827. if ($(this).hasClass('quote-reply-diff')) {
  828. const $parent = $(this).closest('.comment-code-cloud');
  829. $parent.find('button.comment-form-reply').trigger('click');
  830. $simplemde = $parent.find('[name="content"]').data('simplemde');
  831. }
  832. if ($simplemde !== null) {
  833. if ($simplemde.value() !== '') {
  834. $simplemde.value(`${$simplemde.value()}\n\n${content}`);
  835. } else {
  836. $simplemde.value(`${content}`);
  837. }
  838. }
  839. requestAnimationFrame(() => {
  840. $simplemde.codemirror.focus();
  841. $simplemde.codemirror.setCursor($simplemde.codemirror.lineCount(), 0);
  842. });
  843. event.preventDefault();
  844. });
  845. // Reference issue
  846. $(document).on('click', '.reference-issue', function (event) {
  847. const $this = $(this);
  848. $this.closest('.dropdown').find('.menu').toggle('visible');
  849. const content = $(`#comment-${$this.data('target')}`).text();
  850. const subject = content.split('\n', 1)[0].slice(0, 255);
  851. const poster = $this.data('poster');
  852. const reference = $this.data('reference');
  853. const $modal = $($this.data('modal'));
  854. $modal.find('input[name="title"').val(subject);
  855. $modal.find('textarea[name="content"]').val(`${content}\n\n_Originally posted by @${poster} in ${reference}_`);
  856. $modal.modal('show');
  857. event.preventDefault();
  858. });
  859. // Edit issue or comment content
  860. $(document).on('click', '.edit-content', async function (event) {
  861. $(this).closest('.dropdown').find('.menu').toggle('visible');
  862. const $segment = $(this).closest('.header').next();
  863. const $editContentZone = $segment.find('.edit-content-zone');
  864. const $renderContent = $segment.find('.render-content');
  865. const $rawContent = $segment.find('.raw-content');
  866. let $textarea;
  867. let $simplemde;
  868. // Setup new form
  869. if ($editContentZone.html().length === 0) {
  870. $editContentZone.html($('#edit-content-form').html());
  871. $textarea = $editContentZone.find('textarea');
  872. attachTribute($textarea.get(), {mentions: true, emoji: true});
  873. let dz;
  874. const $dropzone = $editContentZone.find('.dropzone');
  875. const $files = $editContentZone.find('.comment-files');
  876. if ($dropzone.length > 0) {
  877. $dropzone.data('saved', false);
  878. const filenameDict = {};
  879. dz = await createDropzone($dropzone[0], {
  880. url: $dropzone.data('upload-url'),
  881. headers: {'X-Csrf-Token': csrf},
  882. maxFiles: $dropzone.data('max-file'),
  883. maxFilesize: $dropzone.data('max-size'),
  884. acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'),
  885. addRemoveLinks: true,
  886. dictDefaultMessage: $dropzone.data('default-message'),
  887. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  888. dictFileTooBig: $dropzone.data('file-too-big'),
  889. dictRemoveFile: $dropzone.data('remove-file'),
  890. timeout: 0,
  891. init() {
  892. this.on('success', (file, data) => {
  893. filenameDict[file.name] = {
  894. uuid: data.uuid,
  895. submitted: false
  896. };
  897. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  898. $files.append(input);
  899. });
  900. this.on('removedfile', (file) => {
  901. if (!(file.name in filenameDict)) {
  902. return;
  903. }
  904. $(`#${filenameDict[file.name].uuid}`).remove();
  905. if ($dropzone.data('remove-url') && !filenameDict[file.name].submitted) {
  906. $.post($dropzone.data('remove-url'), {
  907. file: filenameDict[file.name].uuid,
  908. _csrf: csrf,
  909. });
  910. }
  911. });
  912. this.on('submit', () => {
  913. $.each(filenameDict, (name) => {
  914. filenameDict[name].submitted = true;
  915. });
  916. });
  917. this.on('reload', () => {
  918. $.getJSON($editContentZone.data('attachment-url'), (data) => {
  919. dz.removeAllFiles(true);
  920. $files.empty();
  921. $.each(data, function () {
  922. const imgSrc = `${$dropzone.data('link-url')}/${this.uuid}`;
  923. dz.emit('addedfile', this);
  924. dz.emit('thumbnail', this, imgSrc);
  925. dz.emit('complete', this);
  926. dz.files.push(this);
  927. filenameDict[this.name] = {
  928. submitted: true,
  929. uuid: this.uuid
  930. };
  931. $dropzone.find(`img[src='${imgSrc}']`).css('max-width', '100%');
  932. const input = $(`<input id="${this.uuid}" name="files" type="hidden">`).val(this.uuid);
  933. $files.append(input);
  934. });
  935. });
  936. });
  937. }
  938. });
  939. dz.emit('reload');
  940. }
  941. // Give new write/preview data-tab name to distinguish from others
  942. const $editContentForm = $editContentZone.find('.ui.comment.form');
  943. const $tabMenu = $editContentForm.find('.tabular.menu');
  944. $tabMenu.attr('data-write', $editContentZone.data('write'));
  945. $tabMenu.attr('data-preview', $editContentZone.data('preview'));
  946. $tabMenu.find('.write.item').attr('data-tab', $editContentZone.data('write'));
  947. $tabMenu.find('.preview.item').attr('data-tab', $editContentZone.data('preview'));
  948. $editContentForm.find('.write').attr('data-tab', $editContentZone.data('write'));
  949. $editContentForm.find('.preview').attr('data-tab', $editContentZone.data('preview'));
  950. $simplemde = setCommentSimpleMDE($textarea);
  951. commentMDEditors[$editContentZone.data('write')] = $simplemde;
  952. initCommentPreviewTab($editContentForm);
  953. initSimpleMDEImagePaste($simplemde, $files);
  954. $editContentZone.find('.cancel.button').on('click', () => {
  955. $renderContent.show();
  956. $editContentZone.hide();
  957. if (dz) {
  958. dz.emit('reload');
  959. }
  960. });
  961. $editContentZone.find('.save.button').on('click', () => {
  962. $renderContent.show();
  963. $editContentZone.hide();
  964. const $attachments = $files.find('[name=files]').map(function () {
  965. return $(this).val();
  966. }).get();
  967. $.post($editContentZone.data('update-url'), {
  968. _csrf: csrf,
  969. content: $textarea.val(),
  970. context: $editContentZone.data('context'),
  971. files: $attachments
  972. }, (data) => {
  973. if (data.length === 0 || data.content.length === 0) {
  974. $renderContent.html($('#no-content').html());
  975. } else {
  976. $renderContent.html(data.content);
  977. }
  978. const $content = $segment;
  979. if (!$content.find('.dropzone-attachments').length) {
  980. if (data.attachments !== '') {
  981. $content.append(`
  982. <div class="dropzone-attachments">
  983. </div>
  984. `);
  985. $content.find('.dropzone-attachments').replaceWith(data.attachments);
  986. }
  987. } else if (data.attachments === '') {
  988. $content.find('.dropzone-attachments').remove();
  989. } else {
  990. $content.find('.dropzone-attachments').replaceWith(data.attachments);
  991. }
  992. if (dz) {
  993. dz.emit('submit');
  994. dz.emit('reload');
  995. }
  996. renderMarkdownContent();
  997. });
  998. });
  999. } else {
  1000. $textarea = $segment.find('textarea');
  1001. $simplemde = commentMDEditors[$editContentZone.data('write')];
  1002. }
  1003. // Show write/preview tab and copy raw content as needed
  1004. $editContentZone.show();
  1005. $renderContent.hide();
  1006. if ($textarea.val().length === 0) {
  1007. $textarea.val($rawContent.text());
  1008. $simplemde.value($rawContent.text());
  1009. }
  1010. requestAnimationFrame(() => {
  1011. $textarea.focus();
  1012. $simplemde.codemirror.focus();
  1013. });
  1014. event.preventDefault();
  1015. });
  1016. // Delete comment
  1017. $(document).on('click', '.delete-comment', function () {
  1018. const $this = $(this);
  1019. if (window.confirm($this.data('locale'))) {
  1020. $.post($this.data('url'), {
  1021. _csrf: csrf
  1022. }).done(() => {
  1023. const $conversationHolder = $this.closest('.conversation-holder');
  1024. $(`#${$this.data('comment-id')}`).remove();
  1025. if ($conversationHolder.length && !$conversationHolder.find('.comment').length) {
  1026. const path = $conversationHolder.data('path');
  1027. const side = $conversationHolder.data('side');
  1028. const idx = $conversationHolder.data('idx');
  1029. const lineType = $conversationHolder.closest('tr').data('line-type');
  1030. if (lineType === 'same') {
  1031. $(`a.add-code-comment[data-path="${path}"][data-idx="${idx}"]`).removeClass('invisible');
  1032. } else {
  1033. $(`a.add-code-comment[data-path="${path}"][data-side="${side}"][data-idx="${idx}"]`).removeClass('invisible');
  1034. }
  1035. $conversationHolder.remove();
  1036. }
  1037. });
  1038. }
  1039. return false;
  1040. });
  1041. // Change status
  1042. const $statusButton = $('#status-button');
  1043. $('#comment-form textarea').on('keyup', function () {
  1044. if ($(this).val().length === 0) {
  1045. $statusButton.text($statusButton.data('status'));
  1046. } else {
  1047. $statusButton.text($statusButton.data('status-and-comment'));
  1048. }
  1049. });
  1050. $statusButton.on('click', () => {
  1051. $('#status').val($statusButton.data('status-val'));
  1052. $('#comment-form').trigger('submit');
  1053. });
  1054. // Pull Request merge button
  1055. const $mergeButton = $('.merge-button > button');
  1056. $mergeButton.on('click', function (e) {
  1057. e.preventDefault();
  1058. $(`.${$(this).data('do')}-fields`).show();
  1059. $(this).parent().hide();
  1060. $('.instruct-toggle').hide();
  1061. $('.instruct-content').hide();
  1062. });
  1063. $('.merge-button > .dropdown').dropdown({
  1064. onChange(_text, _value, $choice) {
  1065. if ($choice.data('do')) {
  1066. $mergeButton.find('.button-text').text($choice.text());
  1067. $mergeButton.data('do', $choice.data('do'));
  1068. }
  1069. }
  1070. });
  1071. $('.merge-cancel').on('click', function (e) {
  1072. e.preventDefault();
  1073. $(this).closest('.form').hide();
  1074. $mergeButton.parent().show();
  1075. $('.instruct-toggle').show();
  1076. });
  1077. initReactionSelector();
  1078. }
  1079. // Quick start and repository home
  1080. $('#repo-clone-ssh').on('click', function () {
  1081. $('.clone-url').text($(this).data('link'));
  1082. $('#repo-clone-url').val($(this).data('link'));
  1083. $(this).addClass('primary');
  1084. $('#repo-clone-https').removeClass('primary');
  1085. localStorage.setItem('repo-clone-protocol', 'ssh');
  1086. });
  1087. $('#repo-clone-https').on('click', function () {
  1088. $('.clone-url').text($(this).data('link'));
  1089. $('#repo-clone-url').val($(this).data('link'));
  1090. $(this).addClass('primary');
  1091. if ($('#repo-clone-ssh').length > 0) {
  1092. $('#repo-clone-ssh').removeClass('primary');
  1093. localStorage.setItem('repo-clone-protocol', 'https');
  1094. }
  1095. });
  1096. $('#repo-clone-url').on('click', function () {
  1097. $(this).select();
  1098. });
  1099. // Pull request
  1100. const $repoComparePull = $('.repository.compare.pull');
  1101. if ($repoComparePull.length > 0) {
  1102. initFilterSearchDropdown('.choose.branch .dropdown');
  1103. // show pull request form
  1104. $repoComparePull.find('button.show-form').on('click', function (e) {
  1105. e.preventDefault();
  1106. $repoComparePull.find('.pullrequest-form').show();
  1107. autoSimpleMDE.codemirror.refresh();
  1108. $(this).parent().hide();
  1109. });
  1110. }
  1111. // Branches
  1112. if ($('.repository.settings.branches').length > 0) {
  1113. initFilterSearchDropdown('.protected-branches .dropdown');
  1114. $('.enable-protection, .enable-whitelist, .enable-statuscheck').on('change', function () {
  1115. if (this.checked) {
  1116. $($(this).data('target')).removeClass('disabled');
  1117. } else {
  1118. $($(this).data('target')).addClass('disabled');
  1119. }
  1120. });
  1121. $('.disable-whitelist').on('change', function () {
  1122. if (this.checked) {
  1123. $($(this).data('target')).addClass('disabled');
  1124. }
  1125. });
  1126. }
  1127. // Language stats
  1128. if ($('.language-stats').length > 0) {
  1129. $('.language-stats').on('click', (e) => {
  1130. e.preventDefault();
  1131. $('.language-stats-details, .repository-menu').slideToggle();
  1132. });
  1133. }
  1134. }
  1135. function initPullRequestMergeInstruction() {
  1136. $('.show-instruction').on('click', () => {
  1137. $('.instruct-content').toggle();
  1138. });
  1139. }
  1140. function initPullRequestReview() {
  1141. if (window.location.hash && window.location.hash.startsWith('#issuecomment-')) {
  1142. const commentDiv = $(window.location.hash);
  1143. if (commentDiv) {
  1144. // get the name of the parent id
  1145. const groupID = commentDiv.closest('div[id^="code-comments-"]').attr('id');
  1146. if (groupID && groupID.startsWith('code-comments-')) {
  1147. const id = groupID.substr(14);
  1148. $(`#show-outdated-${id}`).addClass('hide');
  1149. $(`#code-comments-${id}`).removeClass('hide');
  1150. $(`#code-preview-${id}`).removeClass('hide');
  1151. $(`#hide-outdated-${id}`).removeClass('hide');
  1152. $(window).scrollTop(commentDiv.offset().top);
  1153. }
  1154. }
  1155. }
  1156. $(document).on('click', '.show-outdated', function (e) {
  1157. e.preventDefault();
  1158. const id = $(this).data('comment');
  1159. $(this).addClass('hide');
  1160. $(`#code-comments-${id}`).removeClass('hide');
  1161. $(`#code-preview-${id}`).removeClass('hide');
  1162. $(`#hide-outdated-${id}`).removeClass('hide');
  1163. });
  1164. $(document).on('click', '.hide-outdated', function (e) {
  1165. e.preventDefault();
  1166. const id = $(this).data('comment');
  1167. $(this).addClass('hide');
  1168. $(`#code-comments-${id}`).addClass('hide');
  1169. $(`#code-preview-${id}`).addClass('hide');
  1170. $(`#show-outdated-${id}`).removeClass('hide');
  1171. });
  1172. $(document).on('click', 'button.comment-form-reply', function (e) {
  1173. e.preventDefault();
  1174. $(this).hide();
  1175. const form = $(this).parent().find('.comment-form');
  1176. form.removeClass('hide');
  1177. const $textarea = form.find('textarea');
  1178. let $simplemde;
  1179. if ($textarea.data('simplemde')) {
  1180. $simplemde = $textarea.data('simplemde');
  1181. } else {
  1182. attachTribute($textarea.get(), {mentions: true, emoji: true});
  1183. $simplemde = setCommentSimpleMDE($textarea);
  1184. $textarea.data('simplemde', $simplemde);
  1185. }
  1186. $textarea.focus();
  1187. $simplemde.codemirror.focus();
  1188. assingMenuAttributes(form.find('.menu'));
  1189. });
  1190. // The following part is only for diff views
  1191. if ($('.repository.pull.diff').length === 0) {
  1192. return;
  1193. }
  1194. $('.btn-review').on('click', function (e) {
  1195. e.preventDefault();
  1196. $(this).closest('.dropdown').find('.menu').toggle('visible');
  1197. }).closest('.dropdown').find('.close').on('click', function (e) {
  1198. e.preventDefault();
  1199. $(this).closest('.menu').toggle('visible');
  1200. });
  1201. $('a.add-code-comment').on('click', async function (e) {
  1202. if ($(e.target).hasClass('btn-add-single')) return; // https://github.com/go-gitea/gitea/issues/4745
  1203. e.preventDefault();
  1204. const isSplit = $(this).closest('.code-diff').hasClass('code-diff-split');
  1205. const side = $(this).data('side');
  1206. const idx = $(this).data('idx');
  1207. const path = $(this).data('path');
  1208. const tr = $(this).closest('tr');
  1209. const lineType = tr.data('line-type');
  1210. let ntr = tr.next();
  1211. if (!ntr.hasClass('add-comment')) {
  1212. ntr = $(`
  1213. <tr class="add-comment" data-line-type="${lineType}">
  1214. ${isSplit ? `
  1215. <td class="lines-num"></td>
  1216. <td class="lines-type-marker"></td>
  1217. <td class="add-comment-left"></td>
  1218. <td class="lines-num"></td>
  1219. <td class="lines-type-marker"></td>
  1220. <td class="add-comment-right"></td>
  1221. ` : `
  1222. <td colspan="2" class="lines-num"></td>
  1223. <td class="add-comment-left add-comment-right" colspan="2"></td>
  1224. `}
  1225. </tr>`);
  1226. tr.after(ntr);
  1227. }
  1228. const td = ntr.find(`.add-comment-${side}`);
  1229. let commentCloud = td.find('.comment-code-cloud');
  1230. if (commentCloud.length === 0 && !ntr.find('button[name="is_review"]').length) {
  1231. const data = await $.get($(this).data('new-comment-url'));
  1232. td.html(data);
  1233. commentCloud = td.find('.comment-code-cloud');
  1234. assingMenuAttributes(commentCloud.find('.menu'));
  1235. td.find("input[name='line']").val(idx);
  1236. td.find("input[name='side']").val(side === 'left' ? 'previous' : 'proposed');
  1237. td.find("input[name='path']").val(path);
  1238. const $textarea = commentCloud.find('textarea');
  1239. attachTribute($textarea.get(), {mentions: true, emoji: true});
  1240. const $simplemde = setCommentSimpleMDE($textarea);
  1241. $textarea.focus();
  1242. $simplemde.codemirror.focus();
  1243. }
  1244. });
  1245. }
  1246. function assingMenuAttributes(menu) {
  1247. const id = Math.floor(Math.random() * Math.floor(1000000));
  1248. menu.attr('data-write', menu.attr('data-write') + id);
  1249. menu.attr('data-preview', menu.attr('data-preview') + id);
  1250. menu.find('.item').each(function () {
  1251. const tab = $(this).attr('data-tab') + id;
  1252. $(this).attr('data-tab', tab);
  1253. });
  1254. menu.parent().find("*[data-tab='write']").attr('data-tab', `write${id}`);
  1255. menu.parent().find("*[data-tab='preview']").attr('data-tab', `preview${id}`);
  1256. initCommentPreviewTab(menu.parent('.form'));
  1257. return id;
  1258. }
  1259. function initRepositoryCollaboration() {
  1260. // Change collaborator access mode
  1261. $('.access-mode.menu .item').on('click', function () {
  1262. const $menu = $(this).parent();
  1263. $.post($menu.data('url'), {
  1264. _csrf: csrf,
  1265. uid: $menu.data('uid'),
  1266. mode: $(this).data('value')
  1267. });
  1268. });
  1269. }
  1270. function initTeamSettings() {
  1271. // Change team access mode
  1272. $('.organization.new.team input[name=permission]').on('change', () => {
  1273. const val = $('input[name=permission]:checked', '.organization.new.team').val();
  1274. if (val === 'admin') {
  1275. $('.organization.new.team .team-units').hide();
  1276. } else {
  1277. $('.organization.new.team .team-units').show();
  1278. }
  1279. });
  1280. }
  1281. function initWikiForm() {
  1282. const $editArea = $('.repository.wiki textarea#edit_area');
  1283. let sideBySideChanges = 0;
  1284. let sideBySideTimeout = null;
  1285. if ($editArea.length > 0) {
  1286. const simplemde = new SimpleMDE({
  1287. autoDownloadFontAwesome: false,
  1288. element: $editArea[0],
  1289. forceSync: true,
  1290. previewRender(plainText, preview) { // Async method
  1291. // FIXME: still send render request when return back to edit mode
  1292. const render = function () {
  1293. sideBySideChanges = 0;
  1294. if (sideBySideTimeout !== null) {
  1295. clearTimeout(sideBySideTimeout);
  1296. sideBySideTimeout = null;
  1297. }
  1298. $.post($editArea.data('url'), {
  1299. _csrf: csrf,
  1300. mode: 'gfm',
  1301. context: $editArea.data('context'),
  1302. text: plainText,
  1303. wiki: true
  1304. }, (data) => {
  1305. preview.innerHTML = `<div class="markdown ui segment">${data}</div>`;
  1306. renderMarkdownContent();
  1307. });
  1308. };
  1309. setTimeout(() => {
  1310. if (!simplemde.isSideBySideActive()) {
  1311. render();
  1312. } else {
  1313. // delay preview by keystroke counting
  1314. sideBySideChanges++;
  1315. if (sideBySideChanges > 10) {
  1316. render();
  1317. }
  1318. // or delay preview by timeout
  1319. if (sideBySideTimeout !== null) {
  1320. clearTimeout(sideBySideTimeout);
  1321. sideBySideTimeout = null;
  1322. }
  1323. sideBySideTimeout = setTimeout(render, 600);
  1324. }
  1325. }, 0);
  1326. if (!simplemde.isSideBySideActive()) {
  1327. return 'Loading...';
  1328. }
  1329. return preview.innerHTML;
  1330. },
  1331. renderingConfig: {
  1332. singleLineBreaks: false
  1333. },
  1334. indentWithTabs: false,
  1335. tabSize: 4,
  1336. spellChecker: false,
  1337. toolbar: ['bold', 'italic', 'strikethrough', '|',
  1338. 'heading-1', 'heading-2', 'heading-3', 'heading-bigger', 'heading-smaller', '|',
  1339. {
  1340. name: 'code-inline',
  1341. action(e) {
  1342. const cm = e.codemirror;
  1343. const selection = cm.getSelection();
  1344. cm.replaceSelection(`\`${selection}\``);
  1345. if (!selection) {
  1346. const cursorPos = cm.getCursor();
  1347. cm.setCursor(cursorPos.line, cursorPos.ch - 1);
  1348. }
  1349. cm.focus();
  1350. },
  1351. className: 'fa fa-angle-right',
  1352. title: 'Add Inline Code',
  1353. }, 'code', 'quote', '|', {
  1354. name: 'checkbox-empty',
  1355. action(e) {
  1356. const cm = e.codemirror;
  1357. cm.replaceSelection(`\n- [ ] ${cm.getSelection()}`);
  1358. cm.focus();
  1359. },
  1360. className: 'fa fa-square-o',
  1361. title: 'Add Checkbox (empty)',
  1362. },
  1363. {
  1364. name: 'checkbox-checked',
  1365. action(e) {
  1366. const cm = e.codemirror;
  1367. cm.replaceSelection(`\n- [x] ${cm.getSelection()}`);
  1368. cm.focus();
  1369. },
  1370. className: 'fa fa-check-square-o',
  1371. title: 'Add Checkbox (checked)',
  1372. }, '|',
  1373. 'unordered-list', 'ordered-list', '|',
  1374. 'link', 'image', 'table', 'horizontal-rule', '|',
  1375. 'clean-block', 'preview', 'fullscreen', 'side-by-side', '|',
  1376. {
  1377. name: 'revert-to-textarea',
  1378. action(e) {
  1379. e.toTextArea();
  1380. },
  1381. className: 'fa fa-file',
  1382. title: 'Revert to simple textarea',
  1383. },
  1384. ]
  1385. });
  1386. $(simplemde.codemirror.getInputField()).addClass('js-quick-submit');
  1387. setTimeout(() => {
  1388. const $bEdit = $('.repository.wiki.new .previewtabs a[data-tab="write"]');
  1389. const $bPrev = $('.repository.wiki.new .previewtabs a[data-tab="preview"]');
  1390. const $toolbar = $('.editor-toolbar');
  1391. const $bPreview = $('.editor-toolbar button.preview');
  1392. const $bSideBySide = $('.editor-toolbar a.fa-columns');
  1393. $bEdit.on('click', () => {
  1394. if ($toolbar.hasClass('disabled-for-preview')) {
  1395. $bPreview.trigger('click');
  1396. }
  1397. });
  1398. $bPrev.on('click', () => {
  1399. if (!$toolbar.hasClass('disabled-for-preview')) {
  1400. $bPreview.trigger('click');
  1401. }
  1402. });
  1403. $bPreview.on('click', () => {
  1404. setTimeout(() => {
  1405. if ($toolbar.hasClass('disabled-for-preview')) {
  1406. if ($bEdit.hasClass('active')) {
  1407. $bEdit.removeClass('active');
  1408. }
  1409. if (!$bPrev.hasClass('active')) {
  1410. $bPrev.addClass('active');
  1411. }
  1412. } else {
  1413. if (!$bEdit.hasClass('active')) {
  1414. $bEdit.addClass('active');
  1415. }
  1416. if ($bPrev.hasClass('active')) {
  1417. $bPrev.removeClass('active');
  1418. }
  1419. }
  1420. }, 0);
  1421. });
  1422. $bSideBySide.on('click', () => {
  1423. sideBySideChanges = 10;
  1424. });
  1425. }, 0);
  1426. }
  1427. }
  1428. // Adding function to get the cursor position in a text field to jQuery object.
  1429. $.fn.getCursorPosition = function () {
  1430. const el = $(this).get(0);
  1431. let pos = 0;
  1432. if ('selectionStart' in el) {
  1433. pos = el.selectionStart;
  1434. } else if ('selection' in document) {
  1435. el.focus();
  1436. const Sel = document.selection.createRange();
  1437. const SelLength = document.selection.createRange().text.length;
  1438. Sel.moveStart('character', -el.value.length);
  1439. pos = Sel.text.length - SelLength;
  1440. }
  1441. return pos;
  1442. };
  1443. function setCommentSimpleMDE($editArea) {
  1444. const simplemde = new SimpleMDE({
  1445. autoDownloadFontAwesome: false,
  1446. element: $editArea[0],
  1447. forceSync: true,
  1448. renderingConfig: {
  1449. singleLineBreaks: false
  1450. },
  1451. indentWithTabs: false,
  1452. tabSize: 4,
  1453. spellChecker: false,
  1454. toolbar: ['bold', 'italic', 'strikethrough', '|',
  1455. 'heading-1', 'heading-2', 'heading-3', 'heading-bigger', 'heading-smaller', '|',
  1456. 'code', 'quote', '|', {
  1457. name: 'checkbox-empty',
  1458. action(e) {
  1459. const cm = e.codemirror;
  1460. cm.replaceSelection(`\n- [ ] ${cm.getSelection()}`);
  1461. cm.focus();
  1462. },
  1463. className: 'fa fa-square-o',
  1464. title: 'Add Checkbox (empty)',
  1465. },
  1466. {
  1467. name: 'checkbox-checked',
  1468. action(e) {
  1469. const cm = e.codemirror;
  1470. cm.replaceSelection(`\n- [x] ${cm.getSelection()}`);
  1471. cm.focus();
  1472. },
  1473. className: 'fa fa-check-square-o',
  1474. title: 'Add Checkbox (checked)',
  1475. }, '|',
  1476. 'unordered-list', 'ordered-list', '|',
  1477. 'link', 'image', 'table', 'horizontal-rule', '|',
  1478. 'clean-block', '|',
  1479. {
  1480. name: 'revert-to-textarea',
  1481. action(e) {
  1482. e.toTextArea();
  1483. },
  1484. className: 'fa fa-file',
  1485. title: 'Revert to simple textarea',
  1486. },
  1487. ]
  1488. });
  1489. $(simplemde.codemirror.getInputField()).addClass('js-quick-submit');
  1490. simplemde.codemirror.setOption('extraKeys', {
  1491. Enter: () => {
  1492. const tributeContainer = document.querySelector('.tribute-container');
  1493. if (!tributeContainer || tributeContainer.style.display === 'none') {
  1494. return CodeMirror.Pass;
  1495. }
  1496. },
  1497. Backspace: (cm) => {
  1498. if (cm.getInputField().trigger) {
  1499. cm.getInputField().trigger('input');
  1500. }
  1501. cm.execCommand('delCharBefore');
  1502. }
  1503. });
  1504. attachTribute(simplemde.codemirror.getInputField(), {mentions: true, emoji: true});
  1505. return simplemde;
  1506. }
  1507. async function initEditor() {
  1508. $('.js-quick-pull-choice-option').on('change', function () {
  1509. if ($(this).val() === 'commit-to-new-branch') {
  1510. $('.quick-pull-branch-name').show();
  1511. $('.quick-pull-branch-name input').prop('required', true);
  1512. } else {
  1513. $('.quick-pull-branch-name').hide();
  1514. $('.quick-pull-branch-name input').prop('required', false);
  1515. }
  1516. $('#commit-button').text($(this).attr('button_text'));
  1517. });
  1518. const $editFilename = $('#file-name');
  1519. $editFilename.on('keyup', function (e) {
  1520. const $section = $('.breadcrumb span.section');
  1521. const $divider = $('.breadcrumb div.divider');
  1522. let value;
  1523. let parts;
  1524. if (e.keyCode === 8 && $(this).getCursorPosition() === 0 && $section.length > 0) {
  1525. value = $section.last().find('a').text();
  1526. $(this).val(value + $(this).val());
  1527. $(this)[0].setSelectionRange(value.length, value.length);
  1528. $section.last().remove();
  1529. $divider.last().remove();
  1530. }
  1531. if (e.keyCode === 191) {
  1532. parts = $(this).val().split('/');
  1533. for (let i = 0; i < parts.length; ++i) {
  1534. value = parts[i];
  1535. if (i < parts.length - 1) {
  1536. if (value.length) {
  1537. $(`<span class="section"><a href="#">${value}</a></span>`).insertBefore($(this));
  1538. $('<div class="divider"> / </div>').insertBefore($(this));
  1539. }
  1540. } else {
  1541. $(this).val(value);
  1542. }
  1543. $(this)[0].setSelectionRange(0, 0);
  1544. }
  1545. }
  1546. parts = [];
  1547. $('.breadcrumb span.section').each(function () {
  1548. const element = $(this);
  1549. if (element.find('a').length) {
  1550. parts.push(element.find('a').text());
  1551. } else {
  1552. parts.push(element.text());
  1553. }
  1554. });
  1555. if ($(this).val()) parts.push($(this).val());
  1556. $('#tree_path').val(parts.join('/'));
  1557. }).trigger('keyup');
  1558. const $editArea = $('.repository.editor textarea#edit_area');
  1559. if (!$editArea.length) return;
  1560. await createCodeEditor($editArea[0], $editFilename[0], previewFileModes);
  1561. // Using events from https://github.com/codedance/jquery.AreYouSure#advanced-usage
  1562. // to enable or disable the commit button
  1563. const $commitButton = $('#commit-button');
  1564. const $editForm = $('.ui.edit.form');
  1565. const dirtyFileClass = 'dirty-file';
  1566. // Disabling the button at the start
  1567. if ($('input[name="page_has_posted"]').val() !== 'true') {
  1568. $commitButton.prop('disabled', true);
  1569. }
  1570. // Registering a custom listener for the file path and the file content
  1571. $editForm.areYouSure({
  1572. silent: true,
  1573. dirtyClass: dirtyFileClass,
  1574. fieldSelector: ':input:not(.commit-form-wrapper :input)',
  1575. change() {
  1576. const dirty = $(this).hasClass(dirtyFileClass);
  1577. $commitButton.prop('disabled', !dirty);
  1578. }
  1579. });
  1580. $commitButton.on('click', (event) => {
  1581. // A modal which asks if an empty file should be committed
  1582. if ($editArea.val().length === 0) {
  1583. $('#edit-empty-content-modal').modal({
  1584. onApprove() {
  1585. $('.edit.form').trigger('submit');
  1586. }
  1587. }).modal('show');
  1588. event.preventDefault();
  1589. }
  1590. });
  1591. }
  1592. function initReleaseEditor() {
  1593. const $editor = $('.repository.new.release .content-editor');
  1594. if ($editor.length === 0) {
  1595. return false;
  1596. }
  1597. const $textarea = $editor.find('textarea');
  1598. attachTribute($textarea.get(), {mentions: false, emoji: true});
  1599. const $files = $editor.parent().find('.files');
  1600. const $simplemde = setCommentSimpleMDE($textarea);
  1601. initCommentPreviewTab($editor);
  1602. initSimpleMDEImagePaste($simplemde, $files);
  1603. }
  1604. function initOrganization() {
  1605. if ($('.organization').length === 0) {
  1606. return;
  1607. }
  1608. // Options
  1609. if ($('.organization.settings.options').length > 0) {
  1610. $('#org_name').on('keyup', function () {
  1611. const $prompt = $('#org-name-change-prompt');
  1612. const $prompt_redirect = $('#org-name-change-redirect-prompt');
  1613. if ($(this).val().toString().toLowerCase() !== $(this).data('org-name').toString().toLowerCase()) {
  1614. $prompt.show();
  1615. $prompt_redirect.show();
  1616. } else {
  1617. $prompt.hide();
  1618. $prompt_redirect.hide();
  1619. }
  1620. });
  1621. }
  1622. // Labels
  1623. if ($('.organization.settings.labels').length > 0) {
  1624. initLabelEdit();
  1625. }
  1626. }
  1627. function initUserSettings() {
  1628. // Options
  1629. if ($('.user.settings.profile').length > 0) {
  1630. $('#username').on('keyup', function () {
  1631. const $prompt = $('#name-change-prompt');
  1632. const $prompt_redirect = $('#name-change-redirect-prompt');
  1633. if ($(this).val().toString().toLowerCase() !== $(this).data('name').toString().toLowerCase()) {
  1634. $prompt.show();
  1635. $prompt_redirect.show();
  1636. } else {
  1637. $prompt.hide();
  1638. $prompt_redirect.hide();
  1639. }
  1640. });
  1641. }
  1642. }
  1643. async function initGithook() {
  1644. if ($('.edit.githook').length === 0) return;
  1645. const filename = document.querySelector('.hook-filename').textContent;
  1646. await createMonaco($('#content')[0], filename, {language: 'shell'});
  1647. }
  1648. function initWebhook() {
  1649. if ($('.new.webhook').length === 0) {
  1650. return;
  1651. }
  1652. $('.events.checkbox input').on('change', function () {
  1653. if ($(this).is(':checked')) {
  1654. $('.events.fields').show();
  1655. }
  1656. });
  1657. $('.non-events.checkbox input').on('change', function () {
  1658. if ($(this).is(':checked')) {
  1659. $('.events.fields').hide();
  1660. }
  1661. });
  1662. const updateContentType = function () {
  1663. const visible = $('#http_method').val() === 'POST';
  1664. $('#content_type').parent().parent()[visible ? 'show' : 'hide']();
  1665. };
  1666. updateContentType();
  1667. $('#http_method').on('change', () => {
  1668. updateContentType();
  1669. });
  1670. // Test delivery
  1671. $('#test-delivery').on('click', function () {
  1672. const $this = $(this);
  1673. $this.addClass('loading disabled');
  1674. $.post($this.data('link'), {
  1675. _csrf: csrf
  1676. }).done(
  1677. setTimeout(() => {
  1678. window.location.href = $this.data('redirect');
  1679. }, 5000)
  1680. );
  1681. });
  1682. }
  1683. function initAdmin() {
  1684. if ($('.admin').length === 0) {
  1685. return;
  1686. }
  1687. // New user
  1688. if ($('.admin.new.user').length > 0 || $('.admin.edit.user').length > 0) {
  1689. $('#login_type').on('change', function () {
  1690. if ($(this).val().substring(0, 1) === '0') {
  1691. $('#user_name').removeAttr('disabled');
  1692. $('#login_name').removeAttr('required');
  1693. $('.non-local').hide();
  1694. $('.local').show();
  1695. $('#user_name').focus();
  1696. if ($(this).data('password') === 'required') {
  1697. $('#password').attr('required', 'required');
  1698. }
  1699. } else {
  1700. $('#user_name').attr('disabled', 'disabled');
  1701. $('#login_name').attr('required', 'required');
  1702. $('.non-local').show();
  1703. $('.local').hide();
  1704. $('#login_name').focus();
  1705. $('#password').removeAttr('required');
  1706. }
  1707. });
  1708. }
  1709. function onSecurityProtocolChange() {
  1710. if ($('#security_protocol').val() > 0) {
  1711. $('.has-tls').show();
  1712. } else {
  1713. $('.has-tls').hide();
  1714. }
  1715. }
  1716. function onUsePagedSearchChange() {
  1717. if ($('#use_paged_search').prop('checked')) {
  1718. $('.search-page-size').show()
  1719. .find('input').attr('required', 'required');
  1720. } else {
  1721. $('.search-page-size').hide()
  1722. .find('input').removeAttr('required');
  1723. }
  1724. }
  1725. function onOAuth2Change(applyDefaultValues) {
  1726. $('.open_id_connect_auto_discovery_url, .oauth2_use_custom_url').hide();
  1727. $('.open_id_connect_auto_discovery_url input[required]').removeAttr('required');
  1728. const provider = $('#oauth2_provider').val();
  1729. switch (provider) {
  1730. case 'gitea':
  1731. case 'nextcloud':
  1732. case 'mastodon':
  1733. $('#oauth2_use_custom_url').attr('checked', 'checked');
  1734. // fallthrough intentional
  1735. case 'github':
  1736. case 'gitlab':
  1737. $('.oauth2_use_custom_url').show();
  1738. break;
  1739. case 'openidConnect':
  1740. $('.open_id_connect_auto_discovery_url input').attr('required', 'required');
  1741. $('.open_id_connect_auto_discovery_url').show();
  1742. break;
  1743. }
  1744. onOAuth2UseCustomURLChange(applyDefaultValues);
  1745. }
  1746. function onOAuth2UseCustomURLChange(applyDefaultValues) {
  1747. const provider = $('#oauth2_provider').val();
  1748. $('.oauth2_use_custom_url_field').hide();
  1749. $('.oauth2_use_custom_url_field input[required]').removeAttr('required');
  1750. if ($('#oauth2_use_custom_url').is(':checked')) {
  1751. if (applyDefaultValues) {
  1752. $('#oauth2_token_url').val($(`#${provider}_token_url`).val());
  1753. $('#oauth2_auth_url').val($(`#${provider}_auth_url`).val());
  1754. $('#oauth2_profile_url').val($(`#${provider}_profile_url`).val());
  1755. $('#oauth2_email_url').val($(`#${provider}_email_url`).val());
  1756. }
  1757. switch (provider) {
  1758. case 'github':
  1759. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input, .oauth2_email_url input').attr('required', 'required');
  1760. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url, .oauth2_email_url').show();
  1761. break;
  1762. case 'nextcloud':
  1763. case 'gitea':
  1764. case 'gitlab':
  1765. $('.oauth2_token_url input, .oauth2_auth_url input, .oauth2_profile_url input').attr('required', 'required');
  1766. $('.oauth2_token_url, .oauth2_auth_url, .oauth2_profile_url').show();
  1767. $('#oauth2_email_url').val('');
  1768. break;
  1769. case 'mastodon':
  1770. $('.oauth2_auth_url input').attr('required', 'required');
  1771. $('.oauth2_auth_url').show();
  1772. break;
  1773. }
  1774. }
  1775. }
  1776. function onVerifyGroupMembershipChange() {
  1777. if ($('#groups_enabled').is(':checked')) {
  1778. $('#groups_enabled_change').show();
  1779. } else {
  1780. $('#groups_enabled_change').hide();
  1781. }
  1782. }
  1783. // New authentication
  1784. if ($('.admin.new.authentication').length > 0) {
  1785. $('#auth_type').on('change', function () {
  1786. $('.ldap, .dldap, .smtp, .pam, .oauth2, .has-tls, .search-page-size, .sspi').hide();
  1787. $('.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]').removeAttr('required');
  1788. $('.binddnrequired').removeClass('required');
  1789. const authType = $(this).val();
  1790. switch (authType) {
  1791. case '2': // LDAP
  1792. $('.ldap').show();
  1793. $('.binddnrequired input, .ldap div.required:not(.dldap) input').attr('required', 'required');
  1794. $('.binddnrequired').addClass('required');
  1795. break;
  1796. case '3': // SMTP
  1797. $('.smtp').show();
  1798. $('.has-tls').show();
  1799. $('.smtp div.required input, .has-tls').attr('required', 'required');
  1800. break;
  1801. case '4': // PAM
  1802. $('.pam').show();
  1803. $('.pam input').attr('required', 'required');
  1804. break;
  1805. case '5': // LDAP
  1806. $('.dldap').show();
  1807. $('.dldap div.required:not(.ldap) input').attr('required', 'required');
  1808. break;
  1809. case '6': // OAuth2
  1810. $('.oauth2').show();
  1811. $('.oauth2 div.required:not(.oauth2_use_custom_url,.oauth2_use_custom_url_field,.open_id_connect_auto_discovery_url) input').attr('required', 'required');
  1812. onOAuth2Change(true);
  1813. break;
  1814. case '7': // SSPI
  1815. $('.sspi').show();
  1816. $('.sspi div.required input').attr('required', 'required');
  1817. break;
  1818. }
  1819. if (authType === '2' || authType === '5') {
  1820. onSecurityProtocolChange();
  1821. onVerifyGroupMembershipChange();
  1822. }
  1823. if (authType === '2') {
  1824. onUsePagedSearchChange();
  1825. }
  1826. });
  1827. $('#auth_type').trigger('change');
  1828. $('#security_protocol').on('change', onSecurityProtocolChange);
  1829. $('#use_paged_search').on('change', onUsePagedSearchChange);
  1830. $('#oauth2_provider').on('change', () => onOAuth2Change(true));
  1831. $('#oauth2_use_custom_url').on('change', () => onOAuth2UseCustomURLChange(true));
  1832. $('#groups_enabled').on('change', onVerifyGroupMembershipChange);
  1833. }
  1834. // Edit authentication
  1835. if ($('.admin.edit.authentication').length > 0) {
  1836. const authType = $('#auth_type').val();
  1837. if (authType === '2' || authType === '5') {
  1838. $('#security_protocol').on('change', onSecurityProtocolChange);
  1839. $('#groups_enabled').on('change', onVerifyGroupMembershipChange);
  1840. onVerifyGroupMembershipChange();
  1841. if (authType === '2') {
  1842. $('#use_paged_search').on('change', onUsePagedSearchChange);
  1843. }
  1844. } else if (authType === '6') {
  1845. $('#oauth2_provider').on('change', () => onOAuth2Change(true));
  1846. $('#oauth2_use_custom_url').on('change', () => onOAuth2UseCustomURLChange(false));
  1847. onOAuth2Change(false);
  1848. }
  1849. }
  1850. // Notice
  1851. if ($('.admin.notice')) {
  1852. const $detailModal = $('#detail-modal');
  1853. // Attach view detail modals
  1854. $('.view-detail').on('click', function () {
  1855. $detailModal.find('.content pre').text($(this).parents('tr').find('.notice-description').text());
  1856. $detailModal.find('.sub.header').text($(this).parents('tr').find('.notice-created-time').text());
  1857. $detailModal.modal('show');
  1858. return false;
  1859. });
  1860. // Select actions
  1861. const $checkboxes = $('.select.table .ui.checkbox');
  1862. $('.select.action').on('click', function () {
  1863. switch ($(this).data('action')) {
  1864. case 'select-all':
  1865. $checkboxes.checkbox('check');
  1866. break;
  1867. case 'deselect-all':
  1868. $checkboxes.checkbox('uncheck');
  1869. break;
  1870. case 'inverse':
  1871. $checkboxes.checkbox('toggle');
  1872. break;
  1873. }
  1874. });
  1875. $('#delete-selection').on('click', function () {
  1876. const $this = $(this);
  1877. $this.addClass('loading disabled');
  1878. const ids = [];
  1879. $checkboxes.each(function () {
  1880. if ($(this).checkbox('is checked')) {
  1881. ids.push($(this).data('id'));
  1882. }
  1883. });
  1884. $.post($this.data('link'), {
  1885. _csrf: csrf,
  1886. ids
  1887. }).done(() => {
  1888. window.location.href = $this.data('redirect');
  1889. });
  1890. });
  1891. }
  1892. }
  1893. function buttonsClickOnEnter() {
  1894. $('.ui.button').on('keypress', function (e) {
  1895. if (e.keyCode === 13 || e.keyCode === 32) { // enter key or space bar
  1896. $(this).trigger('click');
  1897. }
  1898. });
  1899. }
  1900. function searchUsers() {
  1901. const $searchUserBox = $('#search-user-box');
  1902. $searchUserBox.search({
  1903. minCharacters: 2,
  1904. apiSettings: {
  1905. url: `${AppSubUrl}/api/v1/users/search?q={query}`,
  1906. onResponse(response) {
  1907. const items = [];
  1908. $.each(response.data, (_i, item) => {
  1909. let title = item.login;
  1910. if (item.full_name && item.full_name.length > 0) {
  1911. title += ` (${htmlEscape(item.full_name)})`;
  1912. }
  1913. items.push({
  1914. title,
  1915. image: item.avatar_url
  1916. });
  1917. });
  1918. return {results: items};
  1919. }
  1920. },
  1921. searchFields: ['login', 'full_name'],
  1922. showNoResults: false
  1923. });
  1924. }
  1925. function searchTeams() {
  1926. const $searchTeamBox = $('#search-team-box');
  1927. $searchTeamBox.search({
  1928. minCharacters: 2,
  1929. apiSettings: {
  1930. url: `${AppSubUrl}/api/v1/orgs/${$searchTeamBox.data('org')}/teams/search?q={query}`,
  1931. headers: {'X-Csrf-Token': csrf},
  1932. onResponse(response) {
  1933. const items = [];
  1934. $.each(response.data, (_i, item) => {
  1935. const title = `${item.name} (${item.permission} access)`;
  1936. items.push({
  1937. title,
  1938. });
  1939. });
  1940. return {results: items};
  1941. }
  1942. },
  1943. searchFields: ['name', 'description'],
  1944. showNoResults: false
  1945. });
  1946. }
  1947. function searchRepositories() {
  1948. const $searchRepoBox = $('#search-repo-box');
  1949. $searchRepoBox.search({
  1950. minCharacters: 2,
  1951. apiSettings: {
  1952. url: `${AppSubUrl}/api/v1/repos/search?q={query}&uid=${$searchRepoBox.data('uid')}`,
  1953. onResponse(response) {
  1954. const items = [];
  1955. $.each(response.data, (_i, item) => {
  1956. items.push({
  1957. title: item.full_name.split('/')[1],
  1958. description: item.full_name
  1959. });
  1960. });
  1961. return {results: items};
  1962. }
  1963. },
  1964. searchFields: ['full_name'],
  1965. showNoResults: false
  1966. });
  1967. }
  1968. function initCodeView() {
  1969. if ($('.code-view .lines-num').length > 0) {
  1970. $(document).on('click', '.lines-num span', function (e) {
  1971. const $select = $(this);
  1972. let $list;
  1973. if ($('div.blame').length) {
  1974. $list = $('.code-view td.lines-code li');
  1975. } else {
  1976. $list = $('.code-view td.lines-code');
  1977. }
  1978. selectRange($list, $list.filter(`[rel=${$select.attr('id')}]`), (e.shiftKey ? $list.filter('.active').eq(0) : null));
  1979. deSelect();
  1980. });
  1981. $(window).on('hashchange', () => {
  1982. let m = window.location.hash.match(/^#(L\d+)-(L\d+)$/);
  1983. let $list;
  1984. if ($('div.blame').length) {
  1985. $list = $('.code-view td.lines-code li');
  1986. } else {
  1987. $list = $('.code-view td.lines-code');
  1988. }
  1989. let $first;
  1990. if (m) {
  1991. $first = $list.filter(`[rel=${m[1]}]`);
  1992. selectRange($list, $first, $list.filter(`[rel=${m[2]}]`));
  1993. $('html, body').scrollTop($first.offset().top - 200);
  1994. return;
  1995. }
  1996. m = window.location.hash.match(/^#(L|n)(\d+)$/);
  1997. if (m) {
  1998. $first = $list.filter(`[rel=L${m[2]}]`);
  1999. selectRange($list, $first);
  2000. $('html, body').scrollTop($first.offset().top - 200);
  2001. }
  2002. }).trigger('hashchange');
  2003. }
  2004. $(document).on('click', '.fold-file', ({currentTarget}) => {
  2005. const box = currentTarget.closest('.file-content');
  2006. const folded = box.dataset.folded !== 'true';
  2007. currentTarget.innerHTML = svg(`octicon-chevron-${folded ? 'right' : 'down'}`, 18);
  2008. box.dataset.folded = String(folded);
  2009. });
  2010. $(document).on('click', '.blob-excerpt', async ({currentTarget}) => {
  2011. const {url, query, anchor} = currentTarget.dataset;
  2012. if (!url) return;
  2013. const blob = await $.get(`${url}?${query}&anchor=${anchor}`);
  2014. currentTarget.closest('tr').outerHTML = blob;
  2015. });
  2016. }
  2017. function initU2FAuth() {
  2018. if ($('#wait-for-key').length === 0) {
  2019. return;
  2020. }
  2021. u2fApi.ensureSupport()
  2022. .then(() => {
  2023. $.getJSON(`${AppSubUrl}/user/u2f/challenge`).done((req) => {
  2024. u2fApi.sign(req.appId, req.challenge, req.registeredKeys, 30)
  2025. .then(u2fSigned)
  2026. .catch((err) => {
  2027. if (err === undefined) {
  2028. u2fError(1);
  2029. return;
  2030. }
  2031. u2fError(err.metaData.code);
  2032. });
  2033. });
  2034. }).catch(() => {
  2035. // Fallback in case browser do not support U2F
  2036. window.location.href = `${AppSubUrl}/user/two_factor`;
  2037. });
  2038. }
  2039. function u2fSigned(resp) {
  2040. $.ajax({
  2041. url: `${AppSubUrl}/user/u2f/sign`,
  2042. type: 'POST',
  2043. headers: {'X-Csrf-Token': csrf},
  2044. data: JSON.stringify(resp),
  2045. contentType: 'application/json; charset=utf-8',
  2046. }).done((res) => {
  2047. window.location.replace(res);
  2048. }).fail(() => {
  2049. u2fError(1);
  2050. });
  2051. }
  2052. function u2fRegistered(resp) {
  2053. if (checkError(resp)) {
  2054. return;
  2055. }
  2056. $.ajax({
  2057. url: `${AppSubUrl}/user/settings/security/u2f/register`,
  2058. type: 'POST',
  2059. headers: {'X-Csrf-Token': csrf},
  2060. data: JSON.stringify(resp),
  2061. contentType: 'application/json; charset=utf-8',
  2062. success() {
  2063. reload();
  2064. },
  2065. fail() {
  2066. u2fError(1);
  2067. }
  2068. });
  2069. }
  2070. function checkError(resp) {
  2071. if (!('errorCode' in resp)) {
  2072. return false;
  2073. }
  2074. if (resp.errorCode === 0) {
  2075. return false;
  2076. }
  2077. u2fError(resp.errorCode);
  2078. return true;
  2079. }
  2080. function u2fError(errorType) {
  2081. const u2fErrors = {
  2082. browser: $('#unsupported-browser'),
  2083. 1: $('#u2f-error-1'),
  2084. 2: $('#u2f-error-2'),
  2085. 3: $('#u2f-error-3'),
  2086. 4: $('#u2f-error-4'),
  2087. 5: $('.u2f_error_5')
  2088. };
  2089. u2fErrors[errorType].removeClass('hide');
  2090. Object.keys(u2fErrors).forEach((type) => {
  2091. if (type !== errorType) {
  2092. u2fErrors[type].addClass('hide');
  2093. }
  2094. });
  2095. $('#u2f-error').modal('show');
  2096. }
  2097. function initU2FRegister() {
  2098. $('#register-device').modal({allowMultiple: false});
  2099. $('#u2f-error').modal({allowMultiple: false});
  2100. $('#register-security-key').on('click', (e) => {
  2101. e.preventDefault();
  2102. u2fApi.ensureSupport()
  2103. .then(u2fRegisterRequest)
  2104. .catch(() => {
  2105. u2fError('browser');
  2106. });
  2107. });
  2108. }
  2109. function u2fRegisterRequest() {
  2110. $.post(`${AppSubUrl}/user/settings/security/u2f/request_register`, {
  2111. _csrf: csrf,
  2112. name: $('#nickname').val()
  2113. }).done((req) => {
  2114. $('#nickname').closest('div.field').removeClass('error');
  2115. $('#register-device').modal('show');
  2116. if (req.registeredKeys === null) {
  2117. req.registeredKeys = [];
  2118. }
  2119. u2fApi.register(req.appId, req.registerRequests, req.registeredKeys, 30)
  2120. .then(u2fRegistered)
  2121. .catch((reason) => {
  2122. if (reason === undefined) {
  2123. u2fError(1);
  2124. return;
  2125. }
  2126. u2fError(reason.metaData.code);
  2127. });
  2128. }).fail((xhr) => {
  2129. if (xhr.status === 409) {
  2130. $('#nickname').closest('div.field').addClass('error');
  2131. }
  2132. });
  2133. }
  2134. function initWipTitle() {
  2135. $('.title_wip_desc > a').on('click', (e) => {
  2136. e.preventDefault();
  2137. const $issueTitle = $('#issue_title');
  2138. $issueTitle.focus();
  2139. const value = $issueTitle.val().trim().toUpperCase();
  2140. const wipPrefixes = $('.title_wip_desc').data('wip-prefixes');
  2141. for (const prefix of wipPrefixes) {
  2142. if (value.startsWith(prefix.toUpperCase())) {
  2143. return;
  2144. }
  2145. }
  2146. $issueTitle.val(`${wipPrefixes[0]} ${$issueTitle.val()}`);
  2147. });
  2148. }
  2149. function initTemplateSearch() {
  2150. const $repoTemplate = $('#repo_template');
  2151. const checkTemplate = function () {
  2152. const $templateUnits = $('#template_units');
  2153. const $nonTemplate = $('#non_template');
  2154. if ($repoTemplate.val() !== '' && $repoTemplate.val() !== '0') {
  2155. $templateUnits.show();
  2156. $nonTemplate.hide();
  2157. } else {
  2158. $templateUnits.hide();
  2159. $nonTemplate.show();
  2160. }
  2161. };
  2162. $repoTemplate.on('change', checkTemplate);
  2163. checkTemplate();
  2164. const changeOwner = function () {
  2165. $('#repo_template_search')
  2166. .dropdown({
  2167. apiSettings: {
  2168. url: `${AppSubUrl}/api/v1/repos/search?q={query}&template=true&priority_owner_id=${$('#uid').val()}`,
  2169. onResponse(response) {
  2170. const filteredResponse = {success: true, results: []};
  2171. filteredResponse.results.push({
  2172. name: '',
  2173. value: ''
  2174. });
  2175. // Parse the response from the api to work with our dropdown
  2176. $.each(response.data, (_r, repo) => {
  2177. filteredResponse.results.push({
  2178. name: htmlEscape(repo.full_name),
  2179. value: repo.id
  2180. });
  2181. });
  2182. return filteredResponse;
  2183. },
  2184. cache: false,
  2185. },
  2186. fullTextSearch: true
  2187. });
  2188. };
  2189. $('#uid').on('change', changeOwner);
  2190. changeOwner();
  2191. }
  2192. function initIssueReferenceRepositorySearch() {
  2193. $('.issue_reference_repository_search')
  2194. .dropdown({
  2195. apiSettings: {
  2196. url: `${AppSubUrl}/api/v1/repos/search?q={query}&limit=20`,
  2197. onResponse(response) {
  2198. const filteredResponse = {success: true, results: []};
  2199. $.each(response.data, (_r, repo) => {
  2200. filteredResponse.results.push({
  2201. name: htmlEscape(repo.full_name),
  2202. value: repo.full_name
  2203. });
  2204. });
  2205. return filteredResponse;
  2206. },
  2207. cache: false,
  2208. },
  2209. onChange(_value, _text, $choice) {
  2210. const $form = $choice.closest('form');
  2211. $form.attr('action', `${AppSubUrl}/${_text}/issues/new`);
  2212. },
  2213. fullTextSearch: true
  2214. });
  2215. }
  2216. function initLinkAccountView() {
  2217. const $lnkUserPage = $('.page-content.user.link-account');
  2218. if ($lnkUserPage.length === 0) {
  2219. return false;
  2220. }
  2221. const $signinTab = $lnkUserPage.find('.item[data-tab="auth-link-signin-tab"]');
  2222. const $signUpTab = $lnkUserPage.find('.item[data-tab="auth-link-signup-tab"]');
  2223. const $signInView = $lnkUserPage.find('.tab[data-tab="auth-link-signin-tab"]');
  2224. const $signUpView = $lnkUserPage.find('.tab[data-tab="auth-link-signup-tab"]');
  2225. $signUpTab.on('click', () => {
  2226. $signinTab.removeClass('active');
  2227. $signInView.removeClass('active');
  2228. $signUpTab.addClass('active');
  2229. $signUpView.addClass('active');
  2230. return false;
  2231. });
  2232. $signinTab.on('click', () => {
  2233. $signUpTab.removeClass('active');
  2234. $signUpView.removeClass('active');
  2235. $signinTab.addClass('active');
  2236. $signInView.addClass('active');
  2237. });
  2238. }
  2239. $(document).ready(async () => {
  2240. // Show exact time
  2241. $('.time-since').each(function () {
  2242. $(this)
  2243. .addClass('poping up')
  2244. .attr('data-content', $(this).attr('title'))
  2245. .attr('data-variation', 'inverted tiny')
  2246. .attr('title', '');
  2247. });
  2248. // Semantic UI modules.
  2249. $('.dropdown:not(.custom)').dropdown({
  2250. fullTextSearch: 'exact'
  2251. });
  2252. $('.jump.dropdown').dropdown({
  2253. action: 'hide',
  2254. onShow() {
  2255. $('.poping.up').popup('hide');
  2256. },
  2257. fullTextSearch: 'exact'
  2258. });
  2259. $('.slide.up.dropdown').dropdown({
  2260. transition: 'slide up',
  2261. fullTextSearch: 'exact'
  2262. });
  2263. $('.upward.dropdown').dropdown({
  2264. direction: 'upward',
  2265. fullTextSearch: 'exact'
  2266. });
  2267. $('.ui.accordion').accordion();
  2268. $('.ui.checkbox').checkbox();
  2269. $('.ui.progress').progress({
  2270. showActivity: false
  2271. });
  2272. $('.poping.up').popup();
  2273. $('.top.menu .poping.up').popup({
  2274. onShow() {
  2275. if ($('.top.menu .menu.transition').hasClass('visible')) {
  2276. return false;
  2277. }
  2278. }
  2279. });
  2280. $('.tabular.menu .item').tab();
  2281. $('.tabable.menu .item').tab();
  2282. $('.toggle.button').on('click', function () {
  2283. $($(this).data('target')).slideToggle(100);
  2284. });
  2285. // make table <tr> element clickable like a link
  2286. $('tr[data-href]').on('click', function () {
  2287. window.location = $(this).data('href');
  2288. });
  2289. // make table <td> element clickable like a link
  2290. $('td[data-href]').click(function () {
  2291. window.location = $(this).data('href');
  2292. });
  2293. // link-account tab handle
  2294. initLinkAccountView();
  2295. // Dropzone
  2296. const $dropzone = $('#dropzone');
  2297. if ($dropzone.length > 0) {
  2298. const filenameDict = {};
  2299. await createDropzone('#dropzone', {
  2300. url: $dropzone.data('upload-url'),
  2301. headers: {'X-Csrf-Token': csrf},
  2302. maxFiles: $dropzone.data('max-file'),
  2303. maxFilesize: $dropzone.data('max-size'),
  2304. acceptedFiles: (['*/*', ''].includes($dropzone.data('accepts'))) ? null : $dropzone.data('accepts'),
  2305. addRemoveLinks: true,
  2306. dictDefaultMessage: $dropzone.data('default-message'),
  2307. dictInvalidFileType: $dropzone.data('invalid-input-type'),
  2308. dictFileTooBig: $dropzone.data('file-too-big'),
  2309. dictRemoveFile: $dropzone.data('remove-file'),
  2310. timeout: 0,
  2311. init() {
  2312. this.on('success', (file, data) => {
  2313. filenameDict[file.name] = data.uuid;
  2314. const input = $(`<input id="${data.uuid}" name="files" type="hidden">`).val(data.uuid);
  2315. $('.files').append(input);
  2316. });
  2317. this.on('removedfile', (file) => {
  2318. if (file.name in filenameDict) {
  2319. $(`#${filenameDict[file.name]}`).remove();
  2320. }
  2321. if ($dropzone.data('remove-url')) {
  2322. $.post($dropzone.data('remove-url'), {
  2323. file: filenameDict[file.name],
  2324. _csrf: csrf
  2325. });
  2326. }
  2327. });
  2328. },
  2329. });
  2330. }
  2331. // Helpers.
  2332. $('.delete-button').on('click', showDeletePopup);
  2333. $('.add-all-button').on('click', showAddAllPopup);
  2334. $('.link-action').on('click', linkAction);
  2335. $('.language-menu a[lang]').on('click', linkLanguageAction);
  2336. $('.link-email-action').on('click', linkEmailAction);
  2337. $('.delete-branch-button').on('click', showDeletePopup);
  2338. $('.undo-button').on('click', function () {
  2339. const $this = $(this);
  2340. $.post($this.data('url'), {
  2341. _csrf: csrf,
  2342. id: $this.data('id')
  2343. }).done((data) => {
  2344. window.location.href = data.redirect;
  2345. });
  2346. });
  2347. $('.show-panel.button').on('click', function () {
  2348. $($(this).data('panel')).show();
  2349. });
  2350. $('.show-modal.button').on('click', function () {
  2351. $($(this).data('modal')).modal('show');
  2352. });
  2353. $('.delete-post.button').on('click', function () {
  2354. const $this = $(this);
  2355. $.post($this.data('request-url'), {
  2356. _csrf: csrf
  2357. }).done(() => {
  2358. window.location.href = $this.data('done-url');
  2359. });
  2360. });
  2361. $('.issue-checkbox').on('click', () => {
  2362. const numChecked = $('.issue-checkbox').children('input:checked').length;
  2363. if (numChecked > 0) {
  2364. $('#issue-filters').addClass('hide');
  2365. $('#issue-actions').removeClass('hide');
  2366. } else {
  2367. $('#issue-filters').removeClass('hide');
  2368. $('#issue-actions').addClass('hide');
  2369. }
  2370. });
  2371. $('.issue-action').on('click', function () {
  2372. let {action} = this.dataset;
  2373. let {elementId} = this.dataset;
  2374. const issueIDs = $('.issue-checkbox').children('input:checked').map(function () {
  2375. return this.dataset.issueId;
  2376. }).get().join();
  2377. const {url} = this.dataset;
  2378. if (elementId === '0' && url.substr(-9) === '/assignee') {
  2379. elementId = '';
  2380. action = 'clear';
  2381. }
  2382. updateIssuesMeta(url, action, issueIDs, elementId, '').then(() => {
  2383. // NOTICE: This reset of checkbox state targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2384. if (action === 'close' || action === 'open') {
  2385. // uncheck all checkboxes
  2386. $('.issue-checkbox input[type="checkbox"]').each((_, e) => { e.checked = false });
  2387. }
  2388. reload();
  2389. });
  2390. });
  2391. // NOTICE: This event trigger targets Firefox caching behaviour, as the checkboxes stay checked after reload
  2392. // trigger ckecked event, if checkboxes are checked on load
  2393. $('.issue-checkbox input[type="checkbox"]:checked').first().each((_, e) => {
  2394. e.checked = false;
  2395. $(e).trigger('click');
  2396. });
  2397. $(document).on('click', '.resolve-conversation', async function (e) {
  2398. e.preventDefault();
  2399. const comment_id = $(this).data('comment-id');
  2400. const origin = $(this).data('origin');
  2401. const action = $(this).data('action');
  2402. const url = $(this).data('update-url');
  2403. const data = await $.post(url, {_csrf: csrf, origin, action, comment_id});
  2404. if ($(this).closest('.conversation-holder').length) {
  2405. const conversation = $(data);
  2406. $(this).closest('.conversation-holder').replaceWith(conversation);
  2407. conversation.find('.dropdown').dropdown();
  2408. initReactionSelector(conversation);
  2409. initClipboard();
  2410. } else {
  2411. reload();
  2412. }
  2413. });
  2414. buttonsClickOnEnter();
  2415. searchUsers();
  2416. searchTeams();
  2417. searchRepositories();
  2418. initMarkdownAnchors();
  2419. initCommentForm();
  2420. initInstall();
  2421. initArchiveLinks();
  2422. initRepository();
  2423. initMigration();
  2424. initWikiForm();
  2425. initEditForm();
  2426. initEditor();
  2427. initOrganization();
  2428. initWebhook();
  2429. initAdmin();
  2430. initCodeView();
  2431. initVueApp();
  2432. initTeamSettings();
  2433. initCtrlEnterSubmit();
  2434. initNavbarContentToggle();
  2435. initTopicbar();
  2436. initU2FAuth();
  2437. initU2FRegister();
  2438. initIssueList();
  2439. initIssueTimetracking();
  2440. initIssueDue();
  2441. initWipTitle();
  2442. initPullRequestReview();
  2443. initRepoStatusChecker();
  2444. initTemplateSearch();
  2445. initIssueReferenceRepositorySearch();
  2446. initContextPopups();
  2447. initTableSort();
  2448. initNotificationsTable();
  2449. initPullRequestMergeInstruction();
  2450. initReleaseEditor();
  2451. const routes = {
  2452. 'div.user.settings': initUserSettings,
  2453. 'div.repository.settings.collaboration': initRepositoryCollaboration
  2454. };
  2455. for (const [selector, fn] of Object.entries(routes)) {
  2456. if ($(selector).length > 0) {
  2457. fn();
  2458. break;
  2459. }
  2460. }
  2461. // parallel init of async loaded features
  2462. await Promise.all([
  2463. attachTribute(document.querySelectorAll('#content, .emoji-input')),
  2464. initGitGraph(),
  2465. initClipboard(),
  2466. initHeatmap(),
  2467. initProject(),
  2468. initServiceWorker(),
  2469. initNotificationCount(),
  2470. initStopwatch(),
  2471. renderMarkdownContent(),
  2472. initGithook(),
  2473. ]);
  2474. });
  2475. function changeHash(hash) {
  2476. if (window.history.pushState) {
  2477. window.history.pushState(null, null, hash);
  2478. } else {
  2479. window.location.hash = hash;
  2480. }
  2481. }
  2482. function deSelect() {
  2483. if (window.getSelection) {
  2484. window.getSelection().removeAllRanges();
  2485. } else {
  2486. document.selection.empty();
  2487. }
  2488. }
  2489. function selectRange($list, $select, $from) {
  2490. $list.removeClass('active');
  2491. if ($from) {
  2492. let a = parseInt($select.attr('rel').substr(1));
  2493. let b = parseInt($from.attr('rel').substr(1));
  2494. let c;
  2495. if (a !== b) {
  2496. if (a > b) {
  2497. c = a;
  2498. a = b;
  2499. b = c;
  2500. }
  2501. const classes = [];
  2502. for (let i = a; i <= b; i++) {
  2503. classes.push(`[rel=L${i}]`);
  2504. }
  2505. $list.filter(classes.join(',')).addClass('active');
  2506. changeHash(`#L${a}-L${b}`);
  2507. return;
  2508. }
  2509. }
  2510. $select.addClass('active');
  2511. changeHash(`#${$select.attr('rel')}`);
  2512. }
  2513. $(() => {
  2514. // Warn users that try to leave a page after entering data into a form.
  2515. // Except on sign-in pages, and for forms marked as 'ignore-dirty'.
  2516. if ($('.user.signin').length === 0) {
  2517. $('form:not(.ignore-dirty)').areYouSure();
  2518. }
  2519. // Parse SSH Key
  2520. $('#ssh-key-content').on('change paste keyup', function () {
  2521. const arrays = $(this).val().split(' ');
  2522. const $title = $('#ssh-key-title');
  2523. if ($title.val() === '' && arrays.length === 3 && arrays[2] !== '') {
  2524. $title.val(arrays[2]);
  2525. }
  2526. });
  2527. });
  2528. function showDeletePopup() {
  2529. const $this = $(this);
  2530. let filter = '';
  2531. if ($this.attr('id')) {
  2532. filter += `#${$this.attr('id')}`;
  2533. }
  2534. const dialog = $(`.delete.modal${filter}`);
  2535. dialog.find('.name').text($this.data('name'));
  2536. dialog.modal({
  2537. closable: false,
  2538. onApprove() {
  2539. if ($this.data('type') === 'form') {
  2540. $($this.data('form')).trigger('submit');
  2541. return;
  2542. }
  2543. $.post($this.data('url'), {
  2544. _csrf: csrf,
  2545. id: $this.data('id')
  2546. }).done((data) => {
  2547. window.location.href = data.redirect;
  2548. });
  2549. }
  2550. }).modal('show');
  2551. return false;
  2552. }
  2553. function showAddAllPopup() {
  2554. const $this = $(this);
  2555. let filter = '';
  2556. if ($this.attr('id')) {
  2557. filter += `#${$this.attr('id')}`;
  2558. }
  2559. const dialog = $(`.addall.modal${filter}`);
  2560. dialog.find('.name').text($this.data('name'));
  2561. dialog.modal({
  2562. closable: false,
  2563. onApprove() {
  2564. if ($this.data('type') === 'form') {
  2565. $($this.data('form')).trigger('submit');
  2566. return;
  2567. }
  2568. $.post($this.data('url'), {
  2569. _csrf: csrf,
  2570. id: $this.data('id')
  2571. }).done((data) => {
  2572. window.location.href = data.redirect;
  2573. });
  2574. }
  2575. }).modal('show');
  2576. return false;
  2577. }
  2578. function linkAction(e) {
  2579. e.preventDefault();
  2580. const $this = $(this);
  2581. const redirect = $this.data('redirect');
  2582. $.post($this.data('url'), {
  2583. _csrf: csrf
  2584. }).done((data) => {
  2585. if (data.redirect) {
  2586. window.location.href = data.redirect;
  2587. } else if (redirect) {
  2588. window.location.href = redirect;
  2589. } else {
  2590. window.location.reload();
  2591. }
  2592. });
  2593. }
  2594. function linkLanguageAction() {
  2595. const $this = $(this);
  2596. $.post($this.data('url')).always(() => {
  2597. window.location.reload();
  2598. });
  2599. }
  2600. function linkEmailAction(e) {
  2601. const $this = $(this);
  2602. $('#form-uid').val($this.data('uid'));
  2603. $('#form-email').val($this.data('email'));
  2604. $('#form-primary').val($this.data('primary'));
  2605. $('#form-activate').val($this.data('activate'));
  2606. $('#form-uid').val($this.data('uid'));
  2607. $('#change-email-modal').modal('show');
  2608. e.preventDefault();
  2609. }
  2610. function initVueComponents() {
  2611. // register svg icon vue components, e.g. <octicon-repo size="16"/>
  2612. for (const [name, htmlString] of Object.entries(svgs)) {
  2613. const template = htmlString
  2614. .replace(/height="[0-9]+"/, 'v-bind:height="size"')
  2615. .replace(/width="[0-9]+"/, 'v-bind:width="size"');
  2616. Vue.component(name, {
  2617. props: {
  2618. size: {
  2619. type: String,
  2620. default: '16',
  2621. },
  2622. },
  2623. template,
  2624. });
  2625. }
  2626. const vueDelimeters = ['${', '}'];
  2627. Vue.component('repo-search', {
  2628. delimiters: vueDelimeters,
  2629. props: {
  2630. searchLimit: {
  2631. type: Number,
  2632. default: 10
  2633. },
  2634. suburl: {
  2635. type: String,
  2636. required: true
  2637. },
  2638. uid: {
  2639. type: Number,
  2640. required: true
  2641. },
  2642. teamId: {
  2643. type: Number,
  2644. required: false,
  2645. default: 0
  2646. },
  2647. organizations: {
  2648. type: Array,
  2649. default: () => [],
  2650. },
  2651. isOrganization: {
  2652. type: Boolean,
  2653. default: true
  2654. },
  2655. canCreateOrganization: {
  2656. type: Boolean,
  2657. default: false
  2658. },
  2659. organizationsTotalCount: {
  2660. type: Number,
  2661. default: 0
  2662. },
  2663. moreReposLink: {
  2664. type: String,
  2665. default: ''
  2666. }
  2667. },
  2668. data() {
  2669. const params = new URLSearchParams(window.location.search);
  2670. let tab = params.get('repo-search-tab');
  2671. if (!tab) {
  2672. tab = 'repos';
  2673. }
  2674. let reposFilter = params.get('repo-search-filter');
  2675. if (!reposFilter) {
  2676. reposFilter = 'all';
  2677. }
  2678. let privateFilter = params.get('repo-search-private');
  2679. if (!privateFilter) {
  2680. privateFilter = 'both';
  2681. }
  2682. let archivedFilter = params.get('repo-search-archived');
  2683. if (!archivedFilter) {
  2684. archivedFilter = 'unarchived';
  2685. }
  2686. let searchQuery = params.get('repo-search-query');
  2687. if (!searchQuery) {
  2688. searchQuery = '';
  2689. }
  2690. let page = 1;
  2691. try {
  2692. page = parseInt(params.get('repo-search-page'));
  2693. } catch {
  2694. // noop
  2695. }
  2696. if (!page) {
  2697. page = 1;
  2698. }
  2699. return {
  2700. tab,
  2701. repos: [],
  2702. reposTotalCount: 0,
  2703. reposFilter,
  2704. archivedFilter,
  2705. privateFilter,
  2706. page,
  2707. finalPage: 1,
  2708. searchQuery,
  2709. isLoading: false,
  2710. staticPrefix: StaticUrlPrefix,
  2711. counts: {},
  2712. repoTypes: {
  2713. all: {
  2714. searchMode: '',
  2715. },
  2716. forks: {
  2717. searchMode: 'fork',
  2718. },
  2719. mirrors: {
  2720. searchMode: 'mirror',
  2721. },
  2722. sources: {
  2723. searchMode: 'source',
  2724. },
  2725. collaborative: {
  2726. searchMode: 'collaborative',
  2727. },
  2728. }
  2729. };
  2730. },
  2731. computed: {
  2732. showMoreReposLink() {
  2733. return this.repos.length > 0 && this.repos.length < this.counts[`${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`];
  2734. },
  2735. searchURL() {
  2736. return `${this.suburl}/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&team_id=${this.teamId}&q=${this.searchQuery
  2737. }&page=${this.page}&limit=${this.searchLimit}&mode=${this.repoTypes[this.reposFilter].searchMode
  2738. }${this.reposFilter !== 'all' ? '&exclusive=1' : ''
  2739. }${this.archivedFilter === 'archived' ? '&archived=true' : ''}${this.archivedFilter === 'unarchived' ? '&archived=false' : ''
  2740. }${this.privateFilter === 'private' ? '&is_private=true' : ''}${this.privateFilter === 'public' ? '&is_private=false' : ''
  2741. }`;
  2742. },
  2743. repoTypeCount() {
  2744. return this.counts[`${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`];
  2745. }
  2746. },
  2747. mounted() {
  2748. this.searchRepos(this.reposFilter);
  2749. $(this.$el).find('.poping.up').popup();
  2750. $(this.$el).find('.dropdown').dropdown();
  2751. this.setCheckboxes();
  2752. const self = this;
  2753. Vue.nextTick(() => {
  2754. self.$refs.search.focus();
  2755. });
  2756. },
  2757. methods: {
  2758. changeTab(t) {
  2759. this.tab = t;
  2760. this.updateHistory();
  2761. },
  2762. setCheckboxes() {
  2763. switch (this.archivedFilter) {
  2764. case 'unarchived':
  2765. $('#archivedFilterCheckbox').checkbox('set unchecked');
  2766. break;
  2767. case 'archived':
  2768. $('#archivedFilterCheckbox').checkbox('set checked');
  2769. break;
  2770. case 'both':
  2771. $('#archivedFilterCheckbox').checkbox('set indeterminate');
  2772. break;
  2773. default:
  2774. this.archivedFilter = 'unarchived';
  2775. $('#archivedFilterCheckbox').checkbox('set unchecked');
  2776. break;
  2777. }
  2778. switch (this.privateFilter) {
  2779. case 'public':
  2780. $('#privateFilterCheckbox').checkbox('set unchecked');
  2781. break;
  2782. case 'private':
  2783. $('#privateFilterCheckbox').checkbox('set checked');
  2784. break;
  2785. case 'both':
  2786. $('#privateFilterCheckbox').checkbox('set indeterminate');
  2787. break;
  2788. default:
  2789. this.privateFilter = 'both';
  2790. $('#privateFilterCheckbox').checkbox('set indeterminate');
  2791. break;
  2792. }
  2793. },
  2794. changeReposFilter(filter) {
  2795. this.reposFilter = filter;
  2796. this.repos = [];
  2797. this.page = 1;
  2798. Vue.set(this.counts, `${filter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2799. this.searchRepos();
  2800. },
  2801. updateHistory() {
  2802. const params = new URLSearchParams(window.location.search);
  2803. if (this.tab === 'repos') {
  2804. params.delete('repo-search-tab');
  2805. } else {
  2806. params.set('repo-search-tab', this.tab);
  2807. }
  2808. if (this.reposFilter === 'all') {
  2809. params.delete('repo-search-filter');
  2810. } else {
  2811. params.set('repo-search-filter', this.reposFilter);
  2812. }
  2813. if (this.privateFilter === 'both') {
  2814. params.delete('repo-search-private');
  2815. } else {
  2816. params.set('repo-search-private', this.privateFilter);
  2817. }
  2818. if (this.archivedFilter === 'unarchived') {
  2819. params.delete('repo-search-archived');
  2820. } else {
  2821. params.set('repo-search-archived', this.archivedFilter);
  2822. }
  2823. if (this.searchQuery === '') {
  2824. params.delete('repo-search-query');
  2825. } else {
  2826. params.set('repo-search-query', this.searchQuery);
  2827. }
  2828. if (this.page === 1) {
  2829. params.delete('repo-search-page');
  2830. } else {
  2831. params.set('repo-search-page', `${this.page}`);
  2832. }
  2833. const queryString = params.toString();
  2834. if (queryString) {
  2835. window.history.replaceState({}, '', `?${queryString}`);
  2836. } else {
  2837. window.history.replaceState({}, '', window.location.pathname);
  2838. }
  2839. },
  2840. toggleArchivedFilter() {
  2841. switch (this.archivedFilter) {
  2842. case 'both':
  2843. this.archivedFilter = 'unarchived';
  2844. break;
  2845. case 'unarchived':
  2846. this.archivedFilter = 'archived';
  2847. break;
  2848. case 'archived':
  2849. this.archivedFilter = 'both';
  2850. break;
  2851. default:
  2852. this.archivedFilter = 'unarchived';
  2853. break;
  2854. }
  2855. this.page = 1;
  2856. this.repos = [];
  2857. this.setCheckboxes();
  2858. Vue.set(this.counts, `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2859. this.searchRepos();
  2860. },
  2861. togglePrivateFilter() {
  2862. switch (this.privateFilter) {
  2863. case 'both':
  2864. this.privateFilter = 'public';
  2865. break;
  2866. case 'public':
  2867. this.privateFilter = 'private';
  2868. break;
  2869. case 'private':
  2870. this.privateFilter = 'both';
  2871. break;
  2872. default:
  2873. this.privateFilter = 'both';
  2874. break;
  2875. }
  2876. this.page = 1;
  2877. this.repos = [];
  2878. this.setCheckboxes();
  2879. Vue.set(this.counts, `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2880. this.searchRepos();
  2881. },
  2882. changePage(page) {
  2883. this.page = page;
  2884. if (this.page > this.finalPage) {
  2885. this.page = this.finalPage;
  2886. }
  2887. if (this.page < 1) {
  2888. this.page = 1;
  2889. }
  2890. this.repos = [];
  2891. Vue.set(this.counts, `${this.reposFilter}:${this.archivedFilter}:${this.privateFilter}`, 0);
  2892. this.searchRepos();
  2893. },
  2894. searchRepos() {
  2895. const self = this;
  2896. this.isLoading = true;
  2897. if (!this.reposTotalCount) {
  2898. const totalCountSearchURL = `${this.suburl}/api/v1/repos/search?sort=updated&order=desc&uid=${this.uid}&team_id=${this.teamId}&q=&page=1&mode=`;
  2899. $.getJSON(totalCountSearchURL, (_result, _textStatus, request) => {
  2900. self.reposTotalCount = request.getResponseHeader('X-Total-Count');
  2901. });
  2902. }
  2903. const searchedMode = this.repoTypes[this.reposFilter].searchMode;
  2904. const searchedURL = this.searchURL;
  2905. const searchedQuery = this.searchQuery;
  2906. $.getJSON(searchedURL, (result, _textStatus, request) => {
  2907. if (searchedURL === self.searchURL) {
  2908. self.repos = result.data;
  2909. const count = request.getResponseHeader('X-Total-Count');
  2910. if (searchedQuery === '' && searchedMode === '' && self.archivedFilter === 'both') {
  2911. self.reposTotalCount = count;
  2912. }
  2913. Vue.set(self.counts, `${self.reposFilter}:${self.archivedFilter}:${self.privateFilter}`, count);
  2914. self.finalPage = Math.floor(count / self.searchLimit) + 1;
  2915. self.updateHistory();
  2916. }
  2917. }).always(() => {
  2918. if (searchedURL === self.searchURL) {
  2919. self.isLoading = false;
  2920. }
  2921. });
  2922. },
  2923. repoIcon(repo) {
  2924. if (repo.fork) {
  2925. return 'octicon-repo-forked';
  2926. } else if (repo.mirror) {
  2927. return 'octicon-mirror';
  2928. } else if (repo.template) {
  2929. return `octicon-repo-template`;
  2930. } else if (repo.private) {
  2931. return 'octicon-lock';
  2932. } else if (repo.internal) {
  2933. return 'octicon-repo';
  2934. }
  2935. return 'octicon-repo';
  2936. }
  2937. }
  2938. });
  2939. }
  2940. function initCtrlEnterSubmit() {
  2941. $('.js-quick-submit').on('keydown', function (e) {
  2942. if (((e.ctrlKey && !e.altKey) || e.metaKey) && (e.keyCode === 13 || e.keyCode === 10)) {
  2943. $(this).closest('form').trigger('submit');
  2944. }
  2945. });
  2946. }
  2947. function initVueApp() {
  2948. const el = document.getElementById('app');
  2949. if (!el) {
  2950. return;
  2951. }
  2952. initVueComponents();
  2953. new Vue({
  2954. el,
  2955. delimiters: ['${', '}'],
  2956. components: {
  2957. ActivityTopAuthors,
  2958. },
  2959. data: () => {
  2960. return {
  2961. searchLimit: Number((document.querySelector('meta[name=_search_limit]') || {}).content),
  2962. suburl: AppSubUrl,
  2963. uid: Number((document.querySelector('meta[name=_context_uid]') || {}).content),
  2964. activityTopAuthors: window.ActivityTopAuthors || [],
  2965. };
  2966. },
  2967. });
  2968. }
  2969. function initIssueTimetracking() {
  2970. $(document).on('click', '.issue-add-time', () => {
  2971. $('.issue-start-time-modal').modal({
  2972. duration: 200,
  2973. onApprove() {
  2974. $('#add_time_manual_form').trigger('submit');
  2975. }
  2976. }).modal('show');
  2977. $('.issue-start-time-modal input').on('keydown', (e) => {
  2978. if ((e.keyCode || e.key) === 13) {
  2979. $('#add_time_manual_form').trigger('submit');
  2980. }
  2981. });
  2982. });
  2983. $(document).on('click', '.issue-start-time, .issue-stop-time', () => {
  2984. $('#toggle_stopwatch_form').trigger('submit');
  2985. });
  2986. $(document).on('click', '.issue-cancel-time', () => {
  2987. $('#cancel_stopwatch_form').trigger('submit');
  2988. });
  2989. $(document).on('click', 'button.issue-delete-time', function () {
  2990. const sel = `.issue-delete-time-modal[data-id="${$(this).data('id')}"]`;
  2991. $(sel).modal({
  2992. duration: 200,
  2993. onApprove() {
  2994. $(`${sel} form`).trigger('submit');
  2995. }
  2996. }).modal('show');
  2997. });
  2998. }
  2999. function initFilterBranchTagDropdown(selector) {
  3000. $(selector).each(function () {
  3001. const $dropdown = $(this);
  3002. const $data = $dropdown.find('.data');
  3003. const data = {
  3004. items: [],
  3005. mode: $data.data('mode'),
  3006. searchTerm: '',
  3007. noResults: '',
  3008. canCreateBranch: false,
  3009. menuVisible: false,
  3010. active: 0
  3011. };
  3012. $data.find('.item').each(function () {
  3013. data.items.push({
  3014. name: $(this).text(),
  3015. url: $(this).data('url'),
  3016. branch: $(this).hasClass('branch'),
  3017. tag: $(this).hasClass('tag'),
  3018. selected: $(this).hasClass('selected')
  3019. });
  3020. });
  3021. $data.remove();
  3022. new Vue({
  3023. el: this,
  3024. delimiters: ['${', '}'],
  3025. data,
  3026. computed: {
  3027. filteredItems() {
  3028. const items = this.items.filter((item) => {
  3029. return ((this.mode === 'branches' && item.branch) || (this.mode === 'tags' && item.tag)) &&
  3030. (!this.searchTerm || item.name.toLowerCase().includes(this.searchTerm.toLowerCase()));
  3031. });
  3032. // no idea how to fix this so linting rule is disabled instead
  3033. this.active = (items.length === 0 && this.showCreateNewBranch ? 0 : -1); // eslint-disable-line vue/no-side-effects-in-computed-properties
  3034. return items;
  3035. },
  3036. showNoResults() {
  3037. return this.filteredItems.length === 0 && !this.showCreateNewBranch;
  3038. },
  3039. showCreateNewBranch() {
  3040. if (!this.canCreateBranch || !this.searchTerm || this.mode === 'tags') {
  3041. return false;
  3042. }
  3043. return this.items.filter((item) => item.name.toLowerCase() === this.searchTerm.toLowerCase()).length === 0;
  3044. }
  3045. },
  3046. watch: {
  3047. menuVisible(visible) {
  3048. if (visible) {
  3049. this.focusSearchField();
  3050. }
  3051. }
  3052. },
  3053. beforeMount() {
  3054. this.noResults = this.$el.getAttribute('data-no-results');
  3055. this.canCreateBranch = this.$el.getAttribute('data-can-create-branch') === 'true';
  3056. document.body.addEventListener('click', (event) => {
  3057. if (this.$el.contains(event.target)) return;
  3058. if (this.menuVisible) {
  3059. Vue.set(this, 'menuVisible', false);
  3060. }
  3061. });
  3062. },
  3063. methods: {
  3064. selectItem(item) {
  3065. const prev = this.getSelected();
  3066. if (prev !== null) {
  3067. prev.selected = false;
  3068. }
  3069. item.selected = true;
  3070. window.location.href = item.url;
  3071. },
  3072. createNewBranch() {
  3073. if (!this.showCreateNewBranch) return;
  3074. $(this.$refs.newBranchForm).trigger('submit');
  3075. },
  3076. focusSearchField() {
  3077. Vue.nextTick(() => {
  3078. this.$refs.searchField.focus();
  3079. });
  3080. },
  3081. getSelected() {
  3082. for (let i = 0, j = this.items.length; i < j; ++i) {
  3083. if (this.items[i].selected) return this.items[i];
  3084. }
  3085. return null;
  3086. },
  3087. getSelectedIndexInFiltered() {
  3088. for (let i = 0, j = this.filteredItems.length; i < j; ++i) {
  3089. if (this.filteredItems[i].selected) return i;
  3090. }
  3091. return -1;
  3092. },
  3093. scrollToActive() {
  3094. let el = this.$refs[`listItem${this.active}`];
  3095. if (!el || !el.length) return;
  3096. if (Array.isArray(el)) {
  3097. el = el[0];
  3098. }
  3099. const cont = this.$refs.scrollContainer;
  3100. if (el.offsetTop < cont.scrollTop) {
  3101. cont.scrollTop = el.offsetTop;
  3102. } else if (el.offsetTop + el.clientHeight > cont.scrollTop + cont.clientHeight) {
  3103. cont.scrollTop = el.offsetTop + el.clientHeight - cont.clientHeight;
  3104. }
  3105. },
  3106. keydown(event) {
  3107. if (event.keyCode === 40) { // arrow down
  3108. event.preventDefault();
  3109. if (this.active === -1) {
  3110. this.active = this.getSelectedIndexInFiltered();
  3111. }
  3112. if (this.active + (this.showCreateNewBranch ? 0 : 1) >= this.filteredItems.length) {
  3113. return;
  3114. }
  3115. this.active++;
  3116. this.scrollToActive();
  3117. } else if (event.keyCode === 38) { // arrow up
  3118. event.preventDefault();
  3119. if (this.active === -1) {
  3120. this.active = this.getSelectedIndexInFiltered();
  3121. }
  3122. if (this.active <= 0) {
  3123. return;
  3124. }
  3125. this.active--;
  3126. this.scrollToActive();
  3127. } else if (event.keyCode === 13) { // enter
  3128. event.preventDefault();
  3129. if (this.active >= this.filteredItems.length) {
  3130. this.createNewBranch();
  3131. } else if (this.active >= 0) {
  3132. this.selectItem(this.filteredItems[this.active]);
  3133. }
  3134. } else if (event.keyCode === 27) { // escape
  3135. event.preventDefault();
  3136. this.menuVisible = false;
  3137. }
  3138. }
  3139. }
  3140. });
  3141. });
  3142. }
  3143. $('.commit-button').on('click', function (e) {
  3144. e.preventDefault();
  3145. $(this).parent().find('.commit-body').toggle();
  3146. });
  3147. function initNavbarContentToggle() {
  3148. const content = $('#navbar');
  3149. const toggle = $('#navbar-expand-toggle');
  3150. let isExpanded = false;
  3151. toggle.on('click', () => {
  3152. isExpanded = !isExpanded;
  3153. if (isExpanded) {
  3154. content.addClass('shown');
  3155. toggle.addClass('active');
  3156. } else {
  3157. content.removeClass('shown');
  3158. toggle.removeClass('active');
  3159. }
  3160. });
  3161. }
  3162. function initTopicbar() {
  3163. const mgrBtn = $('#manage_topic');
  3164. const editDiv = $('#topic_edit');
  3165. const viewDiv = $('#repo-topics');
  3166. const saveBtn = $('#save_topic');
  3167. const topicDropdown = $('#topic_edit .dropdown');
  3168. const topicForm = $('#topic_edit.ui.form');
  3169. const topicPrompts = getPrompts();
  3170. mgrBtn.on('click', () => {
  3171. viewDiv.hide();
  3172. editDiv.css('display', ''); // show Semantic UI Grid
  3173. });
  3174. function getPrompts() {
  3175. const hidePrompt = $('div.hide#validate_prompt');
  3176. const prompts = {
  3177. countPrompt: hidePrompt.children('#count_prompt').text(),
  3178. formatPrompt: hidePrompt.children('#format_prompt').text()
  3179. };
  3180. hidePrompt.remove();
  3181. return prompts;
  3182. }
  3183. saveBtn.on('click', () => {
  3184. const topics = $('input[name=topics]').val();
  3185. $.post(saveBtn.data('link'), {
  3186. _csrf: csrf,
  3187. topics
  3188. }, (_data, _textStatus, xhr) => {
  3189. if (xhr.responseJSON.status === 'ok') {
  3190. viewDiv.children('.topic').remove();
  3191. if (topics.length) {
  3192. const topicArray = topics.split(',');
  3193. const last = viewDiv.children('a').last();
  3194. for (let i = 0; i < topicArray.length; i++) {
  3195. const link = $('<a class="ui repo-topic large label topic"></a>');
  3196. link.attr('href', `${AppSubUrl}/explore/repos?q=${encodeURIComponent(topicArray[i])}&topic=1`);
  3197. link.text(topicArray[i]);
  3198. link.insertBefore(last);
  3199. }
  3200. }
  3201. editDiv.css('display', 'none');
  3202. viewDiv.show();
  3203. }
  3204. }).fail((xhr) => {
  3205. if (xhr.status === 422) {
  3206. if (xhr.responseJSON.invalidTopics.length > 0) {
  3207. topicPrompts.formatPrompt = xhr.responseJSON.message;
  3208. const {invalidTopics} = xhr.responseJSON;
  3209. const topicLables = topicDropdown.children('a.ui.label');
  3210. topics.split(',').forEach((value, index) => {
  3211. for (let i = 0; i < invalidTopics.length; i++) {
  3212. if (invalidTopics[i] === value) {
  3213. topicLables.eq(index).removeClass('green').addClass('red');
  3214. }
  3215. }
  3216. });
  3217. } else {
  3218. topicPrompts.countPrompt = xhr.responseJSON.message;
  3219. }
  3220. }
  3221. }).always(() => {
  3222. topicForm.form('validate form');
  3223. });
  3224. });
  3225. topicDropdown.dropdown({
  3226. allowAdditions: true,
  3227. forceSelection: false,
  3228. fullTextSearch: 'exact',
  3229. fields: {name: 'description', value: 'data-value'},
  3230. saveRemoteData: false,
  3231. label: {
  3232. transition: 'horizontal flip',
  3233. duration: 200,
  3234. variation: false,
  3235. blue: true,
  3236. basic: true,
  3237. },
  3238. className: {
  3239. label: 'ui small label'
  3240. },
  3241. apiSettings: {
  3242. url: `${AppSubUrl}/api/v1/topics/search?q={query}`,
  3243. throttle: 500,
  3244. cache: false,
  3245. onResponse(res) {
  3246. const formattedResponse = {
  3247. success: false,
  3248. results: [],
  3249. };
  3250. const query = stripTags(this.urlData.query.trim());
  3251. let found_query = false;
  3252. const current_topics = [];
  3253. topicDropdown.find('div.label.visible.topic,a.label.visible').each((_, e) => { current_topics.push(e.dataset.value) });
  3254. if (res.topics) {
  3255. let found = false;
  3256. for (let i = 0; i < res.topics.length; i++) {
  3257. // skip currently added tags
  3258. if (current_topics.includes(res.topics[i].topic_name)) {
  3259. continue;
  3260. }
  3261. if (res.topics[i].topic_name.toLowerCase() === query.toLowerCase()) {
  3262. found_query = true;
  3263. }
  3264. formattedResponse.results.push({description: res.topics[i].topic_name, 'data-value': res.topics[i].topic_name});
  3265. found = true;
  3266. }
  3267. formattedResponse.success = found;
  3268. }
  3269. if (query.length > 0 && !found_query) {
  3270. formattedResponse.success = true;
  3271. formattedResponse.results.unshift({description: query, 'data-value': query});
  3272. } else if (query.length > 0 && found_query) {
  3273. formattedResponse.results.sort((a, b) => {
  3274. if (a.description.toLowerCase() === query.toLowerCase()) return -1;
  3275. if (b.description.toLowerCase() === query.toLowerCase()) return 1;
  3276. if (a.description > b.description) return -1;
  3277. if (a.description < b.description) return 1;
  3278. return 0;
  3279. });
  3280. }
  3281. return formattedResponse;
  3282. },
  3283. },
  3284. onLabelCreate(value) {
  3285. value = value.toLowerCase().trim();
  3286. this.attr('data-value', value).contents().first().replaceWith(value);
  3287. return $(this);
  3288. },
  3289. onAdd(addedValue, _addedText, $addedChoice) {
  3290. addedValue = addedValue.toLowerCase().trim();
  3291. $($addedChoice).attr('data-value', addedValue);
  3292. $($addedChoice).attr('data-text', addedValue);
  3293. }
  3294. });
  3295. $.fn.form.settings.rules.validateTopic = function (_values, regExp) {
  3296. const topics = topicDropdown.children('a.ui.label');
  3297. const status = topics.length === 0 || topics.last().attr('data-value').match(regExp);
  3298. if (!status) {
  3299. topics.last().removeClass('green').addClass('red');
  3300. }
  3301. return status && topicDropdown.children('a.ui.label.red').length === 0;
  3302. };
  3303. topicForm.form({
  3304. on: 'change',
  3305. inline: true,
  3306. fields: {
  3307. topics: {
  3308. identifier: 'topics',
  3309. rules: [
  3310. {
  3311. type: 'validateTopic',
  3312. value: /^[a-z0-9][a-z0-9-]{0,35}$/,
  3313. prompt: topicPrompts.formatPrompt
  3314. },
  3315. {
  3316. type: 'maxCount[25]',
  3317. prompt: topicPrompts.countPrompt
  3318. }
  3319. ]
  3320. },
  3321. }
  3322. });
  3323. }
  3324. function updateDeadline(deadlineString) {
  3325. $('#deadline-err-invalid-date').hide();
  3326. $('#deadline-loader').addClass('loading');
  3327. let realDeadline = null;
  3328. if (deadlineString !== '') {
  3329. const newDate = Date.parse(deadlineString);
  3330. if (Number.isNaN(newDate)) {
  3331. $('#deadline-loader').removeClass('loading');
  3332. $('#deadline-err-invalid-date').show();
  3333. return false;
  3334. }
  3335. realDeadline = new Date(newDate);
  3336. }
  3337. $.ajax(`${$('#update-issue-deadline-form').attr('action')}/deadline`, {
  3338. data: JSON.stringify({
  3339. due_date: realDeadline,
  3340. }),
  3341. headers: {
  3342. 'X-Csrf-Token': csrf,
  3343. 'X-Remote': true,
  3344. },
  3345. contentType: 'application/json',
  3346. type: 'POST',
  3347. success() {
  3348. reload();
  3349. },
  3350. error() {
  3351. $('#deadline-loader').removeClass('loading');
  3352. $('#deadline-err-invalid-date').show();
  3353. }
  3354. });
  3355. }
  3356. function initIssueDue() {
  3357. $(document).on('click', '.issue-due-edit', () => {
  3358. $('#deadlineForm').fadeToggle(150);
  3359. });
  3360. $(document).on('click', '.issue-due-remove', () => {
  3361. updateDeadline('');
  3362. });
  3363. $(document).on('submit', '.issue-due-form', () => {
  3364. updateDeadline($('#deadlineDate').val());
  3365. return false;
  3366. });
  3367. }
  3368. window.deleteDependencyModal = function (id, type) {
  3369. $('.remove-dependency')
  3370. .modal({
  3371. closable: false,
  3372. duration: 200,
  3373. onApprove() {
  3374. $('#removeDependencyID').val(id);
  3375. $('#dependencyType').val(type);
  3376. $('#removeDependencyForm').trigger('submit');
  3377. }
  3378. }).modal('show');
  3379. };
  3380. function initIssueList() {
  3381. const repolink = $('#repolink').val();
  3382. const repoId = $('#repoId').val();
  3383. const crossRepoSearch = $('#crossRepoSearch').val();
  3384. const tp = $('#type').val();
  3385. let issueSearchUrl = `${AppSubUrl}/api/v1/repos/${repolink}/issues?q={query}&type=${tp}`;
  3386. if (crossRepoSearch === 'true') {
  3387. issueSearchUrl = `${AppSubUrl}/api/v1/repos/issues/search?q={query}&priority_repo_id=${repoId}&type=${tp}`;
  3388. }
  3389. $('#new-dependency-drop-list')
  3390. .dropdown({
  3391. apiSettings: {
  3392. url: issueSearchUrl,
  3393. onResponse(response) {
  3394. const filteredResponse = {success: true, results: []};
  3395. const currIssueId = $('#new-dependency-drop-list').data('issue-id');
  3396. // Parse the response from the api to work with our dropdown
  3397. $.each(response, (_i, issue) => {
  3398. // Don't list current issue in the dependency list.
  3399. if (issue.id === currIssueId) {
  3400. return;
  3401. }
  3402. filteredResponse.results.push({
  3403. name: `#${issue.number} ${htmlEscape(issue.title)
  3404. }<div class="text small dont-break-out">${htmlEscape(issue.repository.full_name)}</div>`,
  3405. value: issue.id
  3406. });
  3407. });
  3408. return filteredResponse;
  3409. },
  3410. cache: false,
  3411. },
  3412. fullTextSearch: true
  3413. });
  3414. $('.menu a.label-filter-item').each(function () {
  3415. $(this).on('click', function (e) {
  3416. if (e.altKey) {
  3417. e.preventDefault();
  3418. const href = $(this).attr('href');
  3419. const id = $(this).data('label-id');
  3420. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3421. const newStr = 'labels=$1-$2$3&';
  3422. window.location = href.replace(new RegExp(regStr), newStr);
  3423. }
  3424. });
  3425. });
  3426. $('.menu .ui.dropdown.label-filter').on('keydown', (e) => {
  3427. if (e.altKey && e.keyCode === 13) {
  3428. const selectedItems = $('.menu .ui.dropdown.label-filter .menu .item.selected');
  3429. if (selectedItems.length > 0) {
  3430. const item = $(selectedItems[0]);
  3431. const href = item.attr('href');
  3432. const id = item.data('label-id');
  3433. const regStr = `labels=(-?[0-9]+%2c)*(${id})(%2c-?[0-9]+)*&`;
  3434. const newStr = 'labels=$1-$2$3&';
  3435. window.location = href.replace(new RegExp(regStr), newStr);
  3436. }
  3437. }
  3438. });
  3439. }
  3440. $(document).on('click', 'button[name="is_review"]', (e) => {
  3441. $(e.target).closest('form').append('<input type="hidden" name="is_review" value="true">');
  3442. });
  3443. $(document).on('submit', '.conversation-holder form', async (e) => {
  3444. e.preventDefault();
  3445. const form = $(e.target);
  3446. const newConversationHolder = $(await $.post(form.attr('action'), form.serialize()));
  3447. const {path, side, idx} = newConversationHolder.data();
  3448. form.closest('.conversation-holder').replaceWith(newConversationHolder);
  3449. if (form.closest('tr').data('line-type') === 'same') {
  3450. $(`a.add-code-comment[data-path="${path}"][data-idx="${idx}"]`).addClass('invisible');
  3451. } else {
  3452. $(`a.add-code-comment[data-path="${path}"][data-side="${side}"][data-idx="${idx}"]`).addClass('invisible');
  3453. }
  3454. newConversationHolder.find('.dropdown').dropdown();
  3455. initReactionSelector(newConversationHolder);
  3456. initClipboard();
  3457. });
  3458. window.cancelCodeComment = function (btn) {
  3459. const form = $(btn).closest('form');
  3460. if (form.length > 0 && form.hasClass('comment-form')) {
  3461. form.addClass('hide');
  3462. form.parent().find('button.comment-form-reply').show();
  3463. } else {
  3464. form.closest('.comment-code-cloud').remove();
  3465. }
  3466. };
  3467. window.onOAuthLoginClick = function () {
  3468. const oauthLoader = $('#oauth2-login-loader');
  3469. const oauthNav = $('#oauth2-login-navigator');
  3470. oauthNav.hide();
  3471. oauthLoader.removeClass('disabled');
  3472. setTimeout(() => {
  3473. // recover previous content to let user try again
  3474. // usually redirection will be performed before this action
  3475. oauthLoader.addClass('disabled');
  3476. oauthNav.show();
  3477. }, 5000);
  3478. };