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 124 kB

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