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.

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