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

index.js 111 kB

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