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

3516 lines
105 KiB

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