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