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

3580 lines
108 KiB

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