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