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

index.js 111 kB

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