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

index.js 107 kB

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