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

3606 lines
109 KiB

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