diff --git a/README.md b/README.md index ce9923631..1a2a68249 100644 --- a/README.md +++ b/README.md @@ -427,6 +427,7 @@ BeeCount 和 BeeCount Cloud 由同一作者维护。如果这些项目对你有
*桥
¥12
birdnofoots
¥10
Charies
¥10
+
春风亭
¥9.99
*哥
¥6
紫风
¥5

diff --git a/README_EN.md b/README_EN.md index 89e79cc99..0f671ae2e 100644 --- a/README_EN.md +++ b/README_EN.md @@ -427,6 +427,7 @@ Address: `TKBV69B2AoU67p3vDhnJUbMJtZ1DxuUF5C`
*Qiao
¥12
birdnofoots
¥10
Charies
¥10
+
Chunfengting
¥9.99
*Ge
¥6
Zifeng
¥5

diff --git a/assets/community_skins/honey_jar.jpg b/assets/community_skins/honey_jar.jpg new file mode 100644 index 000000000..2bd0599ac Binary files /dev/null and b/assets/community_skins/honey_jar.jpg differ diff --git a/assets/community_skins/starlit_hive.jpg b/assets/community_skins/starlit_hive.jpg new file mode 100644 index 000000000..0bc075dc4 Binary files /dev/null and b/assets/community_skins/starlit_hive.jpg differ diff --git a/assets/community_skins/woodblock_lamp.jpg b/assets/community_skins/woodblock_lamp.jpg new file mode 100644 index 000000000..b895d8770 Binary files /dev/null and b/assets/community_skins/woodblock_lamp.jpg differ diff --git a/docs/donate/supporters.json b/docs/donate/supporters.json new file mode 100644 index 000000000..f0d7f0737 --- /dev/null +++ b/docs/donate/supporters.json @@ -0,0 +1,59 @@ +{ + "version": 1, + "updatedAt": "2026-12-01", + "maintainers": [ + "TNT-Likely" + ], + "tiers": { + "supporter": 1, + "goldPatron": 50, + "hiveGuardian": 150 + }, + "supporters": [ + { + "github": "fishdivinity", + "name": "fishdivinity", + "amountCny": 150 + }, + { + "github": "HowcanoeWang", + "name": "浩瀚猫", + "amountCny": 98 + }, + { + "github": "542474846", + "name": "542474846", + "amountCny": 66 + }, + { + "github": "JOHN-2025", + "name": "JOHN-2025", + "amountCny": 30 + }, + { + "github": "idedele", + "name": "刘源", + "amountCny": 28.88 + }, + { + "github": "birdnofoots", + "name": "birdnofoots", + "amountCny": 10 + }, + { + "github": "charieswang72-pro", + "name": "Charies", + "amountCny": 10 + }, + { + "github": "SeanHuang413", + "name": "春风亭", + "amountCny": 9.99 + }, + { + "github": "zifengfanzhuo", + "name": "紫风", + "amountCny": 5 + } + ] +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 7a3b77ebb..172afd6a5 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -5567,5 +5567,170 @@ }, "accountsEmptyTitle": "Track your assets & liabilities", "accountsEmptyDescription": "Add your everyday accounts to see net worth, balance trends, and multi-currency breakdown.", - "accountsEmptyAction": "Add your first account" + "accountsEmptyAction": "Add your first account", + "headerSkinGroupCommunity": "Community Collection", + "headerSkinCommunityWoodblockLamp": "Celadon Lamp", + "headerSkinCommunityHoneyJar": "Sunlit Honey", + "headerSkinCommunityStarlitHive": "Starlit Pavilion", + "githubCommunityTitle": "GitHub Community", + "githubRateLimitUpdateHint": "Anonymous GitHub API requests hit the 60/hr rate limit. Add a read-only GitHub token to raise it to 5,000/hr.", + "githubConfigureTokenAction": "Set Token", + "githubAboutEntrySubtitleWithUpdate": "Add a read-only token to lift update rate limits and unlock honors", + "githubAboutEntrySubtitleCommunityOnly": "Link a read-only token to view ecosystem contributions & honors", + "githubAboutEntryExpired": "Token expired — tap to update", + "githubUpdateBoostedSubtitle": "GitHub Token active (5,000 req/hr)", + "githubTokenSetupTitle": "Personal Access Token (PAT)", + "githubTokenExpiredTitle": "Token Expired", + "githubTokenExpiredTag": "Needs update", + "githubQuotaAnonTag": "Anon 60/h", + "githubTokenSetupDescWithUpdate": "Enter a zero-scope (public read-only) GitHub token to avoid 403 update rate limits and verify your contributions & donations across all BeeCount repos.", + "githubTokenSetupDescCommunityOnly": "Enter a zero-scope (public read-only) GitHub token to verify your contributions across BeeCount repositories and unlock community honors.", + "githubTokenExpiredDesc": "The saved token {token} has expired or been revoked. Replace or clear it below.", + "@githubTokenExpiredDesc": { + "placeholders": { + "token": { + "type": "String" + } + } + }, + "githubTokenInputLabel": "GitHub Personal Access Token", + "githubTokenVerifyAndSave": "Verify & Save", + "githubTokenVerifying": "Verifying...", + "githubTokenVerifySuccess": "GitHub account verified", + "githubTokenCreateAction": "Create", + "githubTokenSecurityNote": "Stored locally on this device only. No write scopes required. Never synced to cloud, exported, or logged.", + "githubTokenInvalidError": "Invalid or expired token (HTTP 401/403). Please check and try again.", + "githubRateLimitedError": "GitHub API rate limit reached. Please try again later.", + "githubNetworkError": "Unable to reach GitHub. Please check your network and try again.", + "githubRefreshAction": "Refresh", + "githubRefreshSuccess": "Community stats & quota refreshed", + "githubBenefitsTitle": "What You Unlock", + "githubBenefitQuotaTitle": "Update check API quota", + "githubBenefitReposTitle": "Ecosystem contributions", + "githubBenefitReposValue": "6 linked repos", + "githubBenefitDonationTitle": "Donation recognition", + "githubBenefitDonationValue": "Matched via supporters list", + "githubBenefitRewardsTitle": "Community honors & skins", + "githubBenefitRewardsValue": "Halo · Skins · Poster seal", + "githubStarredMain": "Starred BeeCount", + "githubNotStarredMain": "Not starred yet", + "githubApiQuotaLabel": "API Rate Limit (resets hourly)", + "githubContributionsTitle": "Ecosystem Contributions", + "githubReposCoverage": "{active} / {total} repos", + "@githubReposCoverage": { + "placeholders": { + "active": { + "type": "int" + }, + "total": { + "type": "int" + } + } + }, + "githubStatCommits": "Commits", + "githubStatMergedPrs": "Merged PRs", + "githubStatIssues": "Issues", + "githubContributionsEmpty": "No commits, PRs, or issues found yet across BeeCount repositories.", + "githubDonationTitle": "Project Support", + "githubDonationVerified": "Verified", + "githubDonationThanks": "Thank you for supporting BeeCount — every contribution helps the project grow steadily.", + "githubMaintainerHonorNote": "Project maintainer privilege: full Hive Co-Creator honors and all community skins unlocked.", + "githubDonationNotFound": "@{login} was not found in the supporters list yet.", + "@githubDonationNotFound": { + "placeholders": { + "login": { + "type": "String" + } + } + }, + "githubDonationRegisterAction": "Donated? Register on GitHub", + "githubRewardsTitle": "Community Rewards", + "githubRewardsOpenSkins": "View skins ({count})", + "@githubRewardsOpenSkins": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "githubRewardHaloTitle": "Profile Avatar Halo & Badge", + "githubRewardHaloDesc": "Display your honor ring and pill badge on the Mine screen", + "githubRewardGreetingTitle": "Community Greeting Subtitle", + "githubRewardGreetingDesc": "Replace the default Mine slogan with a personal thank-you line", + "githubRewardPosterChopTitle": "Share Poster Ink Seal", + "githubRewardPosterChopDesc": "Stamp your minimalist woodblock seal onto exported share cards & annual reports", + "githubRewardPosterChopPreview": "Preview on exported posters", + "githubCurrentTokenLabel": "Saved Token (Local Only)", + "githubUnbindAction": "Unlink", + "githubUnbindTitle": "Unlink GitHub Token", + "githubUnbindMessage": "This removes the locally saved token and resets any active community skins or honor decorations.", + "githubUnbindConfirm": "Unlink", + "githubUnboundToast": "GitHub token cleared", + "githubSkinLockedHintIOS": "Community Honor Exclusive", + "githubSkinUnlockAction": "Unlock in Community", + "githubTierCoCreator": "Hive Co-Creator", + "githubTierCoreContributor": "Core Bee", + "githubTierBuilder": "Hive Builder", + "githubTierHiveGuardian": "Hive Guardian", + "githubTierGoldPatron": "Gold Patron", + "githubTierSupporter": "Supporter", + "githubTierStargazer": "Stargazer", + "githubGreetingMaintainer": "Creator of BeeCount · @{login}", + "@githubGreetingMaintainer": { + "placeholders": { + "login": { + "type": "String" + } + } + }, + "githubGreetingCoCreator": "Co-creating BeeCount · {commits} commits · ¥{amount} supported", + "@githubGreetingCoCreator": { + "placeholders": { + "commits": { + "type": "int" + }, + "amount": { + "type": "String" + } + } + }, + "githubGreetingContributor": "Thank you for contributing · {commits} commits · {prs} PRs", + "@githubGreetingContributor": { + "placeholders": { + "commits": { + "type": "int" + }, + "prs": { + "type": "int" + } + } + }, + "githubGreetingSupporter": "Thank you for your warm support · {tier}", + "@githubGreetingSupporter": { + "placeholders": { + "tier": { + "type": "String" + } + } + }, + "githubGreetingStargazer": "Thanks for starring BeeCount", + "mineProfileBindGitHub": "Link GitHub", + "mineProfileBindGitHubSubtitle": "Unlock open-source badges, halos & skins", + "githubHonorTiersAction": "Honor Tiers", + "githubHonorTiersTitle": "Community Honor Tiers", + "githubHonorTiersSubtitle": "Earned through code contributions and project support; unlocks matching halos, badges, poster chops, and skins.", + "githubHonorTierCurrentHighest": "Current · Highest Tier", + "githubHonorTierCurrent": "Current Tier", + "githubHonorTierUnlocked": "Unlocked", + "githubHonorRuleStargazer": "Star the main repo TNT-Likely/BeeCount", + "githubHonorRuleBuilder": "≥1 commit or ≥1 merged PR across the 6 ecosystem repos (Issues excluded)", + "githubHonorRuleCoreContributor": "≥5 merged PRs, ≥20 commits, or code across ≥2 repos", + "githubHonorRuleSupporter": "Total support > ¥0 (matched in supporters registry)", + "githubHonorRuleGoldPatron": "Total support ≥ ¥50", + "githubHonorRuleHiveGuardian": "Total support ≥ ¥150", + "githubHonorRuleCoCreator": "Both code contribution & support, or project maintainer (highest tier)", + "githubHonorRewardStargazer": "Dotted star ring · Stargazer badge", + "githubHonorRewardCode": "Celadon/Indigo halo · Woodblock Lamp skin · Contributor chop", + "githubHonorRewardDonation": "Amber gold halo · Honey Jar skin · Supporter chop", + "githubHonorRewardCoCreator": "Double crown halo · All 3 collector skins · Vermilion Co-Creator chop" } diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart index 241c49492..656c498f4 100644 --- a/lib/l10n/app_localizations.dart +++ b/lib/l10n/app_localizations.dart @@ -19275,6 +19275,606 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Add your first account'** String get accountsEmptyAction; + + /// No description provided for @headerSkinGroupCommunity. + /// + /// In en, this message translates to: + /// **'Community Collection'** + String get headerSkinGroupCommunity; + + /// No description provided for @headerSkinCommunityWoodblockLamp. + /// + /// In en, this message translates to: + /// **'Celadon Lamp'** + String get headerSkinCommunityWoodblockLamp; + + /// No description provided for @headerSkinCommunityHoneyJar. + /// + /// In en, this message translates to: + /// **'Sunlit Honey'** + String get headerSkinCommunityHoneyJar; + + /// No description provided for @headerSkinCommunityStarlitHive. + /// + /// In en, this message translates to: + /// **'Starlit Pavilion'** + String get headerSkinCommunityStarlitHive; + + /// No description provided for @githubCommunityTitle. + /// + /// In en, this message translates to: + /// **'GitHub Community'** + String get githubCommunityTitle; + + /// No description provided for @githubRateLimitUpdateHint. + /// + /// In en, this message translates to: + /// **'Anonymous GitHub API requests hit the 60/hr rate limit. Add a read-only GitHub token to raise it to 5,000/hr.'** + String get githubRateLimitUpdateHint; + + /// No description provided for @githubConfigureTokenAction. + /// + /// In en, this message translates to: + /// **'Set Token'** + String get githubConfigureTokenAction; + + /// No description provided for @githubAboutEntrySubtitleWithUpdate. + /// + /// In en, this message translates to: + /// **'Add a read-only token to lift update rate limits and unlock honors'** + String get githubAboutEntrySubtitleWithUpdate; + + /// No description provided for @githubAboutEntrySubtitleCommunityOnly. + /// + /// In en, this message translates to: + /// **'Link a read-only token to view ecosystem contributions & honors'** + String get githubAboutEntrySubtitleCommunityOnly; + + /// No description provided for @githubAboutEntryExpired. + /// + /// In en, this message translates to: + /// **'Token expired — tap to update'** + String get githubAboutEntryExpired; + + /// No description provided for @githubUpdateBoostedSubtitle. + /// + /// In en, this message translates to: + /// **'GitHub Token active (5,000 req/hr)'** + String get githubUpdateBoostedSubtitle; + + /// No description provided for @githubTokenSetupTitle. + /// + /// In en, this message translates to: + /// **'Personal Access Token (PAT)'** + String get githubTokenSetupTitle; + + /// No description provided for @githubTokenExpiredTitle. + /// + /// In en, this message translates to: + /// **'Token Expired'** + String get githubTokenExpiredTitle; + + /// No description provided for @githubTokenExpiredTag. + /// + /// In en, this message translates to: + /// **'Needs update'** + String get githubTokenExpiredTag; + + /// No description provided for @githubQuotaAnonTag. + /// + /// In en, this message translates to: + /// **'Anon 60/h'** + String get githubQuotaAnonTag; + + /// No description provided for @githubTokenSetupDescWithUpdate. + /// + /// In en, this message translates to: + /// **'Enter a zero-scope (public read-only) GitHub token to avoid 403 update rate limits and verify your contributions & donations across all BeeCount repos.'** + String get githubTokenSetupDescWithUpdate; + + /// No description provided for @githubTokenSetupDescCommunityOnly. + /// + /// In en, this message translates to: + /// **'Enter a zero-scope (public read-only) GitHub token to verify your contributions across BeeCount repositories and unlock community honors.'** + String get githubTokenSetupDescCommunityOnly; + + /// No description provided for @githubTokenExpiredDesc. + /// + /// In en, this message translates to: + /// **'The saved token {token} has expired or been revoked. Replace or clear it below.'** + String githubTokenExpiredDesc(String token); + + /// No description provided for @githubTokenInputLabel. + /// + /// In en, this message translates to: + /// **'GitHub Personal Access Token'** + String get githubTokenInputLabel; + + /// No description provided for @githubTokenVerifyAndSave. + /// + /// In en, this message translates to: + /// **'Verify & Save'** + String get githubTokenVerifyAndSave; + + /// No description provided for @githubTokenVerifying. + /// + /// In en, this message translates to: + /// **'Verifying...'** + String get githubTokenVerifying; + + /// No description provided for @githubTokenVerifySuccess. + /// + /// In en, this message translates to: + /// **'GitHub account verified'** + String get githubTokenVerifySuccess; + + /// No description provided for @githubTokenCreateAction. + /// + /// In en, this message translates to: + /// **'Create'** + String get githubTokenCreateAction; + + /// No description provided for @githubTokenSecurityNote. + /// + /// In en, this message translates to: + /// **'Stored locally on this device only. No write scopes required. Never synced to cloud, exported, or logged.'** + String get githubTokenSecurityNote; + + /// No description provided for @githubTokenInvalidError. + /// + /// In en, this message translates to: + /// **'Invalid or expired token (HTTP 401/403). Please check and try again.'** + String get githubTokenInvalidError; + + /// No description provided for @githubRateLimitedError. + /// + /// In en, this message translates to: + /// **'GitHub API rate limit reached. Please try again later.'** + String get githubRateLimitedError; + + /// No description provided for @githubNetworkError. + /// + /// In en, this message translates to: + /// **'Unable to reach GitHub. Please check your network and try again.'** + String get githubNetworkError; + + /// No description provided for @githubRefreshAction. + /// + /// In en, this message translates to: + /// **'Refresh'** + String get githubRefreshAction; + + /// No description provided for @githubRefreshSuccess. + /// + /// In en, this message translates to: + /// **'Community stats & quota refreshed'** + String get githubRefreshSuccess; + + /// No description provided for @githubBenefitsTitle. + /// + /// In en, this message translates to: + /// **'What You Unlock'** + String get githubBenefitsTitle; + + /// No description provided for @githubBenefitQuotaTitle. + /// + /// In en, this message translates to: + /// **'Update check API quota'** + String get githubBenefitQuotaTitle; + + /// No description provided for @githubBenefitReposTitle. + /// + /// In en, this message translates to: + /// **'Ecosystem contributions'** + String get githubBenefitReposTitle; + + /// No description provided for @githubBenefitReposValue. + /// + /// In en, this message translates to: + /// **'6 linked repos'** + String get githubBenefitReposValue; + + /// No description provided for @githubBenefitDonationTitle. + /// + /// In en, this message translates to: + /// **'Donation recognition'** + String get githubBenefitDonationTitle; + + /// No description provided for @githubBenefitDonationValue. + /// + /// In en, this message translates to: + /// **'Matched via supporters list'** + String get githubBenefitDonationValue; + + /// No description provided for @githubBenefitRewardsTitle. + /// + /// In en, this message translates to: + /// **'Community honors & skins'** + String get githubBenefitRewardsTitle; + + /// No description provided for @githubBenefitRewardsValue. + /// + /// In en, this message translates to: + /// **'Halo · Skins · Poster seal'** + String get githubBenefitRewardsValue; + + /// No description provided for @githubStarredMain. + /// + /// In en, this message translates to: + /// **'Starred BeeCount'** + String get githubStarredMain; + + /// No description provided for @githubNotStarredMain. + /// + /// In en, this message translates to: + /// **'Not starred yet'** + String get githubNotStarredMain; + + /// No description provided for @githubApiQuotaLabel. + /// + /// In en, this message translates to: + /// **'API Rate Limit (resets hourly)'** + String get githubApiQuotaLabel; + + /// No description provided for @githubContributionsTitle. + /// + /// In en, this message translates to: + /// **'Ecosystem Contributions'** + String get githubContributionsTitle; + + /// No description provided for @githubReposCoverage. + /// + /// In en, this message translates to: + /// **'{active} / {total} repos'** + String githubReposCoverage(int active, int total); + + /// No description provided for @githubStatCommits. + /// + /// In en, this message translates to: + /// **'Commits'** + String get githubStatCommits; + + /// No description provided for @githubStatMergedPrs. + /// + /// In en, this message translates to: + /// **'Merged PRs'** + String get githubStatMergedPrs; + + /// No description provided for @githubStatIssues. + /// + /// In en, this message translates to: + /// **'Issues'** + String get githubStatIssues; + + /// No description provided for @githubContributionsEmpty. + /// + /// In en, this message translates to: + /// **'No commits, PRs, or issues found yet across BeeCount repositories.'** + String get githubContributionsEmpty; + + /// No description provided for @githubDonationTitle. + /// + /// In en, this message translates to: + /// **'Project Support'** + String get githubDonationTitle; + + /// No description provided for @githubDonationVerified. + /// + /// In en, this message translates to: + /// **'Verified'** + String get githubDonationVerified; + + /// No description provided for @githubDonationThanks. + /// + /// In en, this message translates to: + /// **'Thank you for supporting BeeCount — every contribution helps the project grow steadily.'** + String get githubDonationThanks; + + /// No description provided for @githubMaintainerHonorNote. + /// + /// In en, this message translates to: + /// **'Project maintainer privilege: full Hive Co-Creator honors and all community skins unlocked.'** + String get githubMaintainerHonorNote; + + /// No description provided for @githubDonationNotFound. + /// + /// In en, this message translates to: + /// **'@{login} was not found in the supporters list yet.'** + String githubDonationNotFound(String login); + + /// No description provided for @githubDonationRegisterAction. + /// + /// In en, this message translates to: + /// **'Donated? Register on GitHub'** + String get githubDonationRegisterAction; + + /// No description provided for @githubRewardsTitle. + /// + /// In en, this message translates to: + /// **'Community Rewards'** + String get githubRewardsTitle; + + /// No description provided for @githubRewardsOpenSkins. + /// + /// In en, this message translates to: + /// **'View skins ({count})'** + String githubRewardsOpenSkins(int count); + + /// No description provided for @githubRewardHaloTitle. + /// + /// In en, this message translates to: + /// **'Profile Avatar Halo & Badge'** + String get githubRewardHaloTitle; + + /// No description provided for @githubRewardHaloDesc. + /// + /// In en, this message translates to: + /// **'Display your honor ring and pill badge on the Mine screen'** + String get githubRewardHaloDesc; + + /// No description provided for @githubRewardGreetingTitle. + /// + /// In en, this message translates to: + /// **'Community Greeting Subtitle'** + String get githubRewardGreetingTitle; + + /// No description provided for @githubRewardGreetingDesc. + /// + /// In en, this message translates to: + /// **'Replace the default Mine slogan with a personal thank-you line'** + String get githubRewardGreetingDesc; + + /// No description provided for @githubRewardPosterChopTitle. + /// + /// In en, this message translates to: + /// **'Share Poster Ink Seal'** + String get githubRewardPosterChopTitle; + + /// No description provided for @githubRewardPosterChopDesc. + /// + /// In en, this message translates to: + /// **'Stamp your minimalist woodblock seal onto exported share cards & annual reports'** + String get githubRewardPosterChopDesc; + + /// No description provided for @githubRewardPosterChopPreview. + /// + /// In en, this message translates to: + /// **'Preview on exported posters'** + String get githubRewardPosterChopPreview; + + /// No description provided for @githubCurrentTokenLabel. + /// + /// In en, this message translates to: + /// **'Saved Token (Local Only)'** + String get githubCurrentTokenLabel; + + /// No description provided for @githubUnbindAction. + /// + /// In en, this message translates to: + /// **'Unlink'** + String get githubUnbindAction; + + /// No description provided for @githubUnbindTitle. + /// + /// In en, this message translates to: + /// **'Unlink GitHub Token'** + String get githubUnbindTitle; + + /// No description provided for @githubUnbindMessage. + /// + /// In en, this message translates to: + /// **'This removes the locally saved token and resets any active community skins or honor decorations.'** + String get githubUnbindMessage; + + /// No description provided for @githubUnbindConfirm. + /// + /// In en, this message translates to: + /// **'Unlink'** + String get githubUnbindConfirm; + + /// No description provided for @githubUnboundToast. + /// + /// In en, this message translates to: + /// **'GitHub token cleared'** + String get githubUnboundToast; + + /// No description provided for @githubSkinLockedHintIOS. + /// + /// In en, this message translates to: + /// **'Community Honor Exclusive'** + String get githubSkinLockedHintIOS; + + /// No description provided for @githubSkinUnlockAction. + /// + /// In en, this message translates to: + /// **'Unlock in Community'** + String get githubSkinUnlockAction; + + /// No description provided for @githubTierCoCreator. + /// + /// In en, this message translates to: + /// **'Hive Co-Creator'** + String get githubTierCoCreator; + + /// No description provided for @githubTierCoreContributor. + /// + /// In en, this message translates to: + /// **'Core Bee'** + String get githubTierCoreContributor; + + /// No description provided for @githubTierBuilder. + /// + /// In en, this message translates to: + /// **'Hive Builder'** + String get githubTierBuilder; + + /// No description provided for @githubTierHiveGuardian. + /// + /// In en, this message translates to: + /// **'Hive Guardian'** + String get githubTierHiveGuardian; + + /// No description provided for @githubTierGoldPatron. + /// + /// In en, this message translates to: + /// **'Gold Patron'** + String get githubTierGoldPatron; + + /// No description provided for @githubTierSupporter. + /// + /// In en, this message translates to: + /// **'Supporter'** + String get githubTierSupporter; + + /// No description provided for @githubTierStargazer. + /// + /// In en, this message translates to: + /// **'Stargazer'** + String get githubTierStargazer; + + /// No description provided for @githubGreetingMaintainer. + /// + /// In en, this message translates to: + /// **'Creator of BeeCount · @{login}'** + String githubGreetingMaintainer(String login); + + /// No description provided for @githubGreetingCoCreator. + /// + /// In en, this message translates to: + /// **'Co-creating BeeCount · {commits} commits · ¥{amount} supported'** + String githubGreetingCoCreator(int commits, String amount); + + /// No description provided for @githubGreetingContributor. + /// + /// In en, this message translates to: + /// **'Thank you for contributing · {commits} commits · {prs} PRs'** + String githubGreetingContributor(int commits, int prs); + + /// No description provided for @githubGreetingSupporter. + /// + /// In en, this message translates to: + /// **'Thank you for your warm support · {tier}'** + String githubGreetingSupporter(String tier); + + /// No description provided for @githubGreetingStargazer. + /// + /// In en, this message translates to: + /// **'Thanks for starring BeeCount'** + String get githubGreetingStargazer; + + /// No description provided for @mineProfileBindGitHub. + /// + /// In en, this message translates to: + /// **'Link GitHub'** + String get mineProfileBindGitHub; + + /// No description provided for @mineProfileBindGitHubSubtitle. + /// + /// In en, this message translates to: + /// **'Unlock open-source badges, halos & skins'** + String get mineProfileBindGitHubSubtitle; + + /// No description provided for @githubHonorTiersAction. + /// + /// In en, this message translates to: + /// **'Honor Tiers'** + String get githubHonorTiersAction; + + /// No description provided for @githubHonorTiersTitle. + /// + /// In en, this message translates to: + /// **'Community Honor Tiers'** + String get githubHonorTiersTitle; + + /// No description provided for @githubHonorTiersSubtitle. + /// + /// In en, this message translates to: + /// **'Earned through code contributions and project support; unlocks matching halos, badges, poster chops, and skins.'** + String get githubHonorTiersSubtitle; + + /// No description provided for @githubHonorTierCurrentHighest. + /// + /// In en, this message translates to: + /// **'Current · Highest Tier'** + String get githubHonorTierCurrentHighest; + + /// No description provided for @githubHonorTierCurrent. + /// + /// In en, this message translates to: + /// **'Current Tier'** + String get githubHonorTierCurrent; + + /// No description provided for @githubHonorTierUnlocked. + /// + /// In en, this message translates to: + /// **'Unlocked'** + String get githubHonorTierUnlocked; + + /// No description provided for @githubHonorRuleStargazer. + /// + /// In en, this message translates to: + /// **'Star the main repo TNT-Likely/BeeCount'** + String get githubHonorRuleStargazer; + + /// No description provided for @githubHonorRuleBuilder. + /// + /// In en, this message translates to: + /// **'≥1 commit or ≥1 merged PR across the 6 ecosystem repos (Issues excluded)'** + String get githubHonorRuleBuilder; + + /// No description provided for @githubHonorRuleCoreContributor. + /// + /// In en, this message translates to: + /// **'≥5 merged PRs, ≥20 commits, or code across ≥2 repos'** + String get githubHonorRuleCoreContributor; + + /// No description provided for @githubHonorRuleSupporter. + /// + /// In en, this message translates to: + /// **'Total support > ¥0 (matched in supporters registry)'** + String get githubHonorRuleSupporter; + + /// No description provided for @githubHonorRuleGoldPatron. + /// + /// In en, this message translates to: + /// **'Total support ≥ ¥50'** + String get githubHonorRuleGoldPatron; + + /// No description provided for @githubHonorRuleHiveGuardian. + /// + /// In en, this message translates to: + /// **'Total support ≥ ¥150'** + String get githubHonorRuleHiveGuardian; + + /// No description provided for @githubHonorRuleCoCreator. + /// + /// In en, this message translates to: + /// **'Both code contribution & support, or project maintainer (highest tier)'** + String get githubHonorRuleCoCreator; + + /// No description provided for @githubHonorRewardStargazer. + /// + /// In en, this message translates to: + /// **'Dotted star ring · Stargazer badge'** + String get githubHonorRewardStargazer; + + /// No description provided for @githubHonorRewardCode. + /// + /// In en, this message translates to: + /// **'Celadon/Indigo halo · Woodblock Lamp skin · Contributor chop'** + String get githubHonorRewardCode; + + /// No description provided for @githubHonorRewardDonation. + /// + /// In en, this message translates to: + /// **'Amber gold halo · Honey Jar skin · Supporter chop'** + String get githubHonorRewardDonation; + + /// No description provided for @githubHonorRewardCoCreator. + /// + /// In en, this message translates to: + /// **'Double crown halo · All 3 collector skins · Vermilion Co-Creator chop'** + String get githubHonorRewardCoCreator; } class _AppLocalizationsDelegate extends LocalizationsDelegate { diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart index 745d586f5..c319ecf31 100644 --- a/lib/l10n/app_localizations_en.dart +++ b/lib/l10n/app_localizations_en.dart @@ -10381,4 +10381,320 @@ class AppLocalizationsEn extends AppLocalizations { @override String get accountsEmptyAction => 'Add your first account'; + + @override + String get headerSkinGroupCommunity => 'Community Collection'; + + @override + String get headerSkinCommunityWoodblockLamp => 'Celadon Lamp'; + + @override + String get headerSkinCommunityHoneyJar => 'Sunlit Honey'; + + @override + String get headerSkinCommunityStarlitHive => 'Starlit Pavilion'; + + @override + String get githubCommunityTitle => 'GitHub Community'; + + @override + String get githubRateLimitUpdateHint => 'Anonymous GitHub API requests hit the 60/hr rate limit. Add a read-only GitHub token to raise it to 5,000/hr.'; + + @override + String get githubConfigureTokenAction => 'Set Token'; + + @override + String get githubAboutEntrySubtitleWithUpdate => 'Add a read-only token to lift update rate limits and unlock honors'; + + @override + String get githubAboutEntrySubtitleCommunityOnly => 'Link a read-only token to view ecosystem contributions & honors'; + + @override + String get githubAboutEntryExpired => 'Token expired — tap to update'; + + @override + String get githubUpdateBoostedSubtitle => 'GitHub Token active (5,000 req/hr)'; + + @override + String get githubTokenSetupTitle => 'Personal Access Token (PAT)'; + + @override + String get githubTokenExpiredTitle => 'Token Expired'; + + @override + String get githubTokenExpiredTag => 'Needs update'; + + @override + String get githubQuotaAnonTag => 'Anon 60/h'; + + @override + String get githubTokenSetupDescWithUpdate => 'Enter a zero-scope (public read-only) GitHub token to avoid 403 update rate limits and verify your contributions & donations across all BeeCount repos.'; + + @override + String get githubTokenSetupDescCommunityOnly => 'Enter a zero-scope (public read-only) GitHub token to verify your contributions across BeeCount repositories and unlock community honors.'; + + @override + String githubTokenExpiredDesc(String token) { + return 'The saved token $token has expired or been revoked. Replace or clear it below.'; + } + + @override + String get githubTokenInputLabel => 'GitHub Personal Access Token'; + + @override + String get githubTokenVerifyAndSave => 'Verify & Save'; + + @override + String get githubTokenVerifying => 'Verifying...'; + + @override + String get githubTokenVerifySuccess => 'GitHub account verified'; + + @override + String get githubTokenCreateAction => 'Create'; + + @override + String get githubTokenSecurityNote => 'Stored locally on this device only. No write scopes required. Never synced to cloud, exported, or logged.'; + + @override + String get githubTokenInvalidError => 'Invalid or expired token (HTTP 401/403). Please check and try again.'; + + @override + String get githubRateLimitedError => 'GitHub API rate limit reached. Please try again later.'; + + @override + String get githubNetworkError => 'Unable to reach GitHub. Please check your network and try again.'; + + @override + String get githubRefreshAction => 'Refresh'; + + @override + String get githubRefreshSuccess => 'Community stats & quota refreshed'; + + @override + String get githubBenefitsTitle => 'What You Unlock'; + + @override + String get githubBenefitQuotaTitle => 'Update check API quota'; + + @override + String get githubBenefitReposTitle => 'Ecosystem contributions'; + + @override + String get githubBenefitReposValue => '6 linked repos'; + + @override + String get githubBenefitDonationTitle => 'Donation recognition'; + + @override + String get githubBenefitDonationValue => 'Matched via supporters list'; + + @override + String get githubBenefitRewardsTitle => 'Community honors & skins'; + + @override + String get githubBenefitRewardsValue => 'Halo · Skins · Poster seal'; + + @override + String get githubStarredMain => 'Starred BeeCount'; + + @override + String get githubNotStarredMain => 'Not starred yet'; + + @override + String get githubApiQuotaLabel => 'API Rate Limit (resets hourly)'; + + @override + String get githubContributionsTitle => 'Ecosystem Contributions'; + + @override + String githubReposCoverage(int active, int total) { + return '$active / $total repos'; + } + + @override + String get githubStatCommits => 'Commits'; + + @override + String get githubStatMergedPrs => 'Merged PRs'; + + @override + String get githubStatIssues => 'Issues'; + + @override + String get githubContributionsEmpty => 'No commits, PRs, or issues found yet across BeeCount repositories.'; + + @override + String get githubDonationTitle => 'Project Support'; + + @override + String get githubDonationVerified => 'Verified'; + + @override + String get githubDonationThanks => 'Thank you for supporting BeeCount — every contribution helps the project grow steadily.'; + + @override + String get githubMaintainerHonorNote => 'Project maintainer privilege: full Hive Co-Creator honors and all community skins unlocked.'; + + @override + String githubDonationNotFound(String login) { + return '@$login was not found in the supporters list yet.'; + } + + @override + String get githubDonationRegisterAction => 'Donated? Register on GitHub'; + + @override + String get githubRewardsTitle => 'Community Rewards'; + + @override + String githubRewardsOpenSkins(int count) { + return 'View skins ($count)'; + } + + @override + String get githubRewardHaloTitle => 'Profile Avatar Halo & Badge'; + + @override + String get githubRewardHaloDesc => 'Display your honor ring and pill badge on the Mine screen'; + + @override + String get githubRewardGreetingTitle => 'Community Greeting Subtitle'; + + @override + String get githubRewardGreetingDesc => 'Replace the default Mine slogan with a personal thank-you line'; + + @override + String get githubRewardPosterChopTitle => 'Share Poster Ink Seal'; + + @override + String get githubRewardPosterChopDesc => 'Stamp your minimalist woodblock seal onto exported share cards & annual reports'; + + @override + String get githubRewardPosterChopPreview => 'Preview on exported posters'; + + @override + String get githubCurrentTokenLabel => 'Saved Token (Local Only)'; + + @override + String get githubUnbindAction => 'Unlink'; + + @override + String get githubUnbindTitle => 'Unlink GitHub Token'; + + @override + String get githubUnbindMessage => 'This removes the locally saved token and resets any active community skins or honor decorations.'; + + @override + String get githubUnbindConfirm => 'Unlink'; + + @override + String get githubUnboundToast => 'GitHub token cleared'; + + @override + String get githubSkinLockedHintIOS => 'Community Honor Exclusive'; + + @override + String get githubSkinUnlockAction => 'Unlock in Community'; + + @override + String get githubTierCoCreator => 'Hive Co-Creator'; + + @override + String get githubTierCoreContributor => 'Core Bee'; + + @override + String get githubTierBuilder => 'Hive Builder'; + + @override + String get githubTierHiveGuardian => 'Hive Guardian'; + + @override + String get githubTierGoldPatron => 'Gold Patron'; + + @override + String get githubTierSupporter => 'Supporter'; + + @override + String get githubTierStargazer => 'Stargazer'; + + @override + String githubGreetingMaintainer(String login) { + return 'Creator of BeeCount · @$login'; + } + + @override + String githubGreetingCoCreator(int commits, String amount) { + return 'Co-creating BeeCount · $commits commits · ¥$amount supported'; + } + + @override + String githubGreetingContributor(int commits, int prs) { + return 'Thank you for contributing · $commits commits · $prs PRs'; + } + + @override + String githubGreetingSupporter(String tier) { + return 'Thank you for your warm support · $tier'; + } + + @override + String get githubGreetingStargazer => 'Thanks for starring BeeCount'; + + @override + String get mineProfileBindGitHub => 'Link GitHub'; + + @override + String get mineProfileBindGitHubSubtitle => 'Unlock open-source badges, halos & skins'; + + @override + String get githubHonorTiersAction => 'Honor Tiers'; + + @override + String get githubHonorTiersTitle => 'Community Honor Tiers'; + + @override + String get githubHonorTiersSubtitle => 'Earned through code contributions and project support; unlocks matching halos, badges, poster chops, and skins.'; + + @override + String get githubHonorTierCurrentHighest => 'Current · Highest Tier'; + + @override + String get githubHonorTierCurrent => 'Current Tier'; + + @override + String get githubHonorTierUnlocked => 'Unlocked'; + + @override + String get githubHonorRuleStargazer => 'Star the main repo TNT-Likely/BeeCount'; + + @override + String get githubHonorRuleBuilder => '≥1 commit or ≥1 merged PR across the 6 ecosystem repos (Issues excluded)'; + + @override + String get githubHonorRuleCoreContributor => '≥5 merged PRs, ≥20 commits, or code across ≥2 repos'; + + @override + String get githubHonorRuleSupporter => 'Total support > ¥0 (matched in supporters registry)'; + + @override + String get githubHonorRuleGoldPatron => 'Total support ≥ ¥50'; + + @override + String get githubHonorRuleHiveGuardian => 'Total support ≥ ¥150'; + + @override + String get githubHonorRuleCoCreator => 'Both code contribution & support, or project maintainer (highest tier)'; + + @override + String get githubHonorRewardStargazer => 'Dotted star ring · Stargazer badge'; + + @override + String get githubHonorRewardCode => 'Celadon/Indigo halo · Woodblock Lamp skin · Contributor chop'; + + @override + String get githubHonorRewardDonation => 'Amber gold halo · Honey Jar skin · Supporter chop'; + + @override + String get githubHonorRewardCoCreator => 'Double crown halo · All 3 collector skins · Vermilion Co-Creator chop'; } diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart index 3cf58f428..28a93f1d7 100644 --- a/lib/l10n/app_localizations_ko.dart +++ b/lib/l10n/app_localizations_ko.dart @@ -10381,4 +10381,320 @@ class AppLocalizationsKo extends AppLocalizations { @override String get accountsEmptyAction => 'Add your first account'; + + @override + String get headerSkinGroupCommunity => 'Community Collection'; + + @override + String get headerSkinCommunityWoodblockLamp => 'Celadon Lamp'; + + @override + String get headerSkinCommunityHoneyJar => 'Sunlit Honey'; + + @override + String get headerSkinCommunityStarlitHive => 'Starlit Pavilion'; + + @override + String get githubCommunityTitle => 'GitHub Community'; + + @override + String get githubRateLimitUpdateHint => 'Anonymous GitHub API requests hit the 60/hr rate limit. Add a read-only GitHub token to raise it to 5,000/hr.'; + + @override + String get githubConfigureTokenAction => 'Set Token'; + + @override + String get githubAboutEntrySubtitleWithUpdate => 'Add a read-only token to lift update rate limits and unlock honors'; + + @override + String get githubAboutEntrySubtitleCommunityOnly => 'Link a read-only token to view ecosystem contributions & honors'; + + @override + String get githubAboutEntryExpired => 'Token expired — tap to update'; + + @override + String get githubUpdateBoostedSubtitle => 'GitHub Token active (5,000 req/hr)'; + + @override + String get githubTokenSetupTitle => 'Personal Access Token (PAT)'; + + @override + String get githubTokenExpiredTitle => 'Token Expired'; + + @override + String get githubTokenExpiredTag => 'Needs update'; + + @override + String get githubQuotaAnonTag => 'Anon 60/h'; + + @override + String get githubTokenSetupDescWithUpdate => 'Enter a zero-scope (public read-only) GitHub token to avoid 403 update rate limits and verify your contributions & donations across all BeeCount repos.'; + + @override + String get githubTokenSetupDescCommunityOnly => 'Enter a zero-scope (public read-only) GitHub token to verify your contributions across BeeCount repositories and unlock community honors.'; + + @override + String githubTokenExpiredDesc(String token) { + return 'The saved token $token has expired or been revoked. Replace or clear it below.'; + } + + @override + String get githubTokenInputLabel => 'GitHub Personal Access Token'; + + @override + String get githubTokenVerifyAndSave => 'Verify & Save'; + + @override + String get githubTokenVerifying => 'Verifying...'; + + @override + String get githubTokenVerifySuccess => 'GitHub account verified'; + + @override + String get githubTokenCreateAction => 'Create'; + + @override + String get githubTokenSecurityNote => 'Stored locally on this device only. No write scopes required. Never synced to cloud, exported, or logged.'; + + @override + String get githubTokenInvalidError => 'Invalid or expired token (HTTP 401/403). Please check and try again.'; + + @override + String get githubRateLimitedError => 'GitHub API rate limit reached. Please try again later.'; + + @override + String get githubNetworkError => 'Unable to reach GitHub. Please check your network and try again.'; + + @override + String get githubRefreshAction => 'Refresh'; + + @override + String get githubRefreshSuccess => 'Community stats & quota refreshed'; + + @override + String get githubBenefitsTitle => 'What You Unlock'; + + @override + String get githubBenefitQuotaTitle => 'Update check API quota'; + + @override + String get githubBenefitReposTitle => 'Ecosystem contributions'; + + @override + String get githubBenefitReposValue => '6 linked repos'; + + @override + String get githubBenefitDonationTitle => 'Donation recognition'; + + @override + String get githubBenefitDonationValue => 'Matched via supporters list'; + + @override + String get githubBenefitRewardsTitle => 'Community honors & skins'; + + @override + String get githubBenefitRewardsValue => 'Halo · Skins · Poster seal'; + + @override + String get githubStarredMain => 'Starred BeeCount'; + + @override + String get githubNotStarredMain => 'Not starred yet'; + + @override + String get githubApiQuotaLabel => 'API Rate Limit (resets hourly)'; + + @override + String get githubContributionsTitle => 'Ecosystem Contributions'; + + @override + String githubReposCoverage(int active, int total) { + return '$active / $total repos'; + } + + @override + String get githubStatCommits => 'Commits'; + + @override + String get githubStatMergedPrs => 'Merged PRs'; + + @override + String get githubStatIssues => 'Issues'; + + @override + String get githubContributionsEmpty => 'No commits, PRs, or issues found yet across BeeCount repositories.'; + + @override + String get githubDonationTitle => 'Project Support'; + + @override + String get githubDonationVerified => 'Verified'; + + @override + String get githubDonationThanks => 'Thank you for supporting BeeCount — every contribution helps the project grow steadily.'; + + @override + String get githubMaintainerHonorNote => 'Project maintainer privilege: full Hive Co-Creator honors and all community skins unlocked.'; + + @override + String githubDonationNotFound(String login) { + return '@$login was not found in the supporters list yet.'; + } + + @override + String get githubDonationRegisterAction => 'Donated? Register on GitHub'; + + @override + String get githubRewardsTitle => 'Community Rewards'; + + @override + String githubRewardsOpenSkins(int count) { + return 'View skins ($count)'; + } + + @override + String get githubRewardHaloTitle => 'Profile Avatar Halo & Badge'; + + @override + String get githubRewardHaloDesc => 'Display your honor ring and pill badge on the Mine screen'; + + @override + String get githubRewardGreetingTitle => 'Community Greeting Subtitle'; + + @override + String get githubRewardGreetingDesc => 'Replace the default Mine slogan with a personal thank-you line'; + + @override + String get githubRewardPosterChopTitle => 'Share Poster Ink Seal'; + + @override + String get githubRewardPosterChopDesc => 'Stamp your minimalist woodblock seal onto exported share cards & annual reports'; + + @override + String get githubRewardPosterChopPreview => 'Preview on exported posters'; + + @override + String get githubCurrentTokenLabel => 'Saved Token (Local Only)'; + + @override + String get githubUnbindAction => 'Unlink'; + + @override + String get githubUnbindTitle => 'Unlink GitHub Token'; + + @override + String get githubUnbindMessage => 'This removes the locally saved token and resets any active community skins or honor decorations.'; + + @override + String get githubUnbindConfirm => 'Unlink'; + + @override + String get githubUnboundToast => 'GitHub token cleared'; + + @override + String get githubSkinLockedHintIOS => 'Community Honor Exclusive'; + + @override + String get githubSkinUnlockAction => 'Unlock in Community'; + + @override + String get githubTierCoCreator => 'Hive Co-Creator'; + + @override + String get githubTierCoreContributor => 'Core Bee'; + + @override + String get githubTierBuilder => 'Hive Builder'; + + @override + String get githubTierHiveGuardian => 'Hive Guardian'; + + @override + String get githubTierGoldPatron => 'Gold Patron'; + + @override + String get githubTierSupporter => 'Supporter'; + + @override + String get githubTierStargazer => 'Stargazer'; + + @override + String githubGreetingMaintainer(String login) { + return 'Creator of BeeCount · @$login'; + } + + @override + String githubGreetingCoCreator(int commits, String amount) { + return 'Co-creating BeeCount · $commits commits · ¥$amount supported'; + } + + @override + String githubGreetingContributor(int commits, int prs) { + return 'Thank you for contributing · $commits commits · $prs PRs'; + } + + @override + String githubGreetingSupporter(String tier) { + return 'Thank you for your warm support · $tier'; + } + + @override + String get githubGreetingStargazer => 'Thanks for starring BeeCount'; + + @override + String get mineProfileBindGitHub => 'Link GitHub'; + + @override + String get mineProfileBindGitHubSubtitle => 'Unlock open-source badges, halos & skins'; + + @override + String get githubHonorTiersAction => 'Honor Tiers'; + + @override + String get githubHonorTiersTitle => 'Community Honor Tiers'; + + @override + String get githubHonorTiersSubtitle => 'Earned through code contributions and project support; unlocks matching halos, badges, poster chops, and skins.'; + + @override + String get githubHonorTierCurrentHighest => 'Current · Highest Tier'; + + @override + String get githubHonorTierCurrent => 'Current Tier'; + + @override + String get githubHonorTierUnlocked => 'Unlocked'; + + @override + String get githubHonorRuleStargazer => 'Star the main repo TNT-Likely/BeeCount'; + + @override + String get githubHonorRuleBuilder => '≥1 commit or ≥1 merged PR across the 6 ecosystem repos (Issues excluded)'; + + @override + String get githubHonorRuleCoreContributor => '≥5 merged PRs, ≥20 commits, or code across ≥2 repos'; + + @override + String get githubHonorRuleSupporter => 'Total support > ¥0 (matched in supporters registry)'; + + @override + String get githubHonorRuleGoldPatron => 'Total support ≥ ¥50'; + + @override + String get githubHonorRuleHiveGuardian => 'Total support ≥ ¥150'; + + @override + String get githubHonorRuleCoCreator => 'Both code contribution & support, or project maintainer (highest tier)'; + + @override + String get githubHonorRewardStargazer => 'Dotted star ring · Stargazer badge'; + + @override + String get githubHonorRewardCode => 'Celadon/Indigo halo · Woodblock Lamp skin · Contributor chop'; + + @override + String get githubHonorRewardDonation => 'Amber gold halo · Honey Jar skin · Supporter chop'; + + @override + String get githubHonorRewardCoCreator => 'Double crown halo · All 3 collector skins · Vermilion Co-Creator chop'; } diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart index 03c6ff74c..8fab53fd6 100644 --- a/lib/l10n/app_localizations_ru.dart +++ b/lib/l10n/app_localizations_ru.dart @@ -10835,4 +10835,320 @@ class AppLocalizationsRu extends AppLocalizations { @override String get accountsEmptyAction => 'Add your first account'; + + @override + String get headerSkinGroupCommunity => 'Community Collection'; + + @override + String get headerSkinCommunityWoodblockLamp => 'Celadon Lamp'; + + @override + String get headerSkinCommunityHoneyJar => 'Sunlit Honey'; + + @override + String get headerSkinCommunityStarlitHive => 'Starlit Pavilion'; + + @override + String get githubCommunityTitle => 'GitHub Community'; + + @override + String get githubRateLimitUpdateHint => 'Anonymous GitHub API requests hit the 60/hr rate limit. Add a read-only GitHub token to raise it to 5,000/hr.'; + + @override + String get githubConfigureTokenAction => 'Set Token'; + + @override + String get githubAboutEntrySubtitleWithUpdate => 'Add a read-only token to lift update rate limits and unlock honors'; + + @override + String get githubAboutEntrySubtitleCommunityOnly => 'Link a read-only token to view ecosystem contributions & honors'; + + @override + String get githubAboutEntryExpired => 'Token expired — tap to update'; + + @override + String get githubUpdateBoostedSubtitle => 'GitHub Token active (5,000 req/hr)'; + + @override + String get githubTokenSetupTitle => 'Personal Access Token (PAT)'; + + @override + String get githubTokenExpiredTitle => 'Token Expired'; + + @override + String get githubTokenExpiredTag => 'Needs update'; + + @override + String get githubQuotaAnonTag => 'Anon 60/h'; + + @override + String get githubTokenSetupDescWithUpdate => 'Enter a zero-scope (public read-only) GitHub token to avoid 403 update rate limits and verify your contributions & donations across all BeeCount repos.'; + + @override + String get githubTokenSetupDescCommunityOnly => 'Enter a zero-scope (public read-only) GitHub token to verify your contributions across BeeCount repositories and unlock community honors.'; + + @override + String githubTokenExpiredDesc(String token) { + return 'The saved token $token has expired or been revoked. Replace or clear it below.'; + } + + @override + String get githubTokenInputLabel => 'GitHub Personal Access Token'; + + @override + String get githubTokenVerifyAndSave => 'Verify & Save'; + + @override + String get githubTokenVerifying => 'Verifying...'; + + @override + String get githubTokenVerifySuccess => 'GitHub account verified'; + + @override + String get githubTokenCreateAction => 'Create'; + + @override + String get githubTokenSecurityNote => 'Stored locally on this device only. No write scopes required. Never synced to cloud, exported, or logged.'; + + @override + String get githubTokenInvalidError => 'Invalid or expired token (HTTP 401/403). Please check and try again.'; + + @override + String get githubRateLimitedError => 'GitHub API rate limit reached. Please try again later.'; + + @override + String get githubNetworkError => 'Unable to reach GitHub. Please check your network and try again.'; + + @override + String get githubRefreshAction => 'Refresh'; + + @override + String get githubRefreshSuccess => 'Community stats & quota refreshed'; + + @override + String get githubBenefitsTitle => 'What You Unlock'; + + @override + String get githubBenefitQuotaTitle => 'Update check API quota'; + + @override + String get githubBenefitReposTitle => 'Ecosystem contributions'; + + @override + String get githubBenefitReposValue => '6 linked repos'; + + @override + String get githubBenefitDonationTitle => 'Donation recognition'; + + @override + String get githubBenefitDonationValue => 'Matched via supporters list'; + + @override + String get githubBenefitRewardsTitle => 'Community honors & skins'; + + @override + String get githubBenefitRewardsValue => 'Halo · Skins · Poster seal'; + + @override + String get githubStarredMain => 'Starred BeeCount'; + + @override + String get githubNotStarredMain => 'Not starred yet'; + + @override + String get githubApiQuotaLabel => 'API Rate Limit (resets hourly)'; + + @override + String get githubContributionsTitle => 'Ecosystem Contributions'; + + @override + String githubReposCoverage(int active, int total) { + return '$active / $total repos'; + } + + @override + String get githubStatCommits => 'Commits'; + + @override + String get githubStatMergedPrs => 'Merged PRs'; + + @override + String get githubStatIssues => 'Issues'; + + @override + String get githubContributionsEmpty => 'No commits, PRs, or issues found yet across BeeCount repositories.'; + + @override + String get githubDonationTitle => 'Project Support'; + + @override + String get githubDonationVerified => 'Verified'; + + @override + String get githubDonationThanks => 'Thank you for supporting BeeCount — every contribution helps the project grow steadily.'; + + @override + String get githubMaintainerHonorNote => 'Project maintainer privilege: full Hive Co-Creator honors and all community skins unlocked.'; + + @override + String githubDonationNotFound(String login) { + return '@$login was not found in the supporters list yet.'; + } + + @override + String get githubDonationRegisterAction => 'Donated? Register on GitHub'; + + @override + String get githubRewardsTitle => 'Community Rewards'; + + @override + String githubRewardsOpenSkins(int count) { + return 'View skins ($count)'; + } + + @override + String get githubRewardHaloTitle => 'Profile Avatar Halo & Badge'; + + @override + String get githubRewardHaloDesc => 'Display your honor ring and pill badge on the Mine screen'; + + @override + String get githubRewardGreetingTitle => 'Community Greeting Subtitle'; + + @override + String get githubRewardGreetingDesc => 'Replace the default Mine slogan with a personal thank-you line'; + + @override + String get githubRewardPosterChopTitle => 'Share Poster Ink Seal'; + + @override + String get githubRewardPosterChopDesc => 'Stamp your minimalist woodblock seal onto exported share cards & annual reports'; + + @override + String get githubRewardPosterChopPreview => 'Preview on exported posters'; + + @override + String get githubCurrentTokenLabel => 'Saved Token (Local Only)'; + + @override + String get githubUnbindAction => 'Unlink'; + + @override + String get githubUnbindTitle => 'Unlink GitHub Token'; + + @override + String get githubUnbindMessage => 'This removes the locally saved token and resets any active community skins or honor decorations.'; + + @override + String get githubUnbindConfirm => 'Unlink'; + + @override + String get githubUnboundToast => 'GitHub token cleared'; + + @override + String get githubSkinLockedHintIOS => 'Community Honor Exclusive'; + + @override + String get githubSkinUnlockAction => 'Unlock in Community'; + + @override + String get githubTierCoCreator => 'Hive Co-Creator'; + + @override + String get githubTierCoreContributor => 'Core Bee'; + + @override + String get githubTierBuilder => 'Hive Builder'; + + @override + String get githubTierHiveGuardian => 'Hive Guardian'; + + @override + String get githubTierGoldPatron => 'Gold Patron'; + + @override + String get githubTierSupporter => 'Supporter'; + + @override + String get githubTierStargazer => 'Stargazer'; + + @override + String githubGreetingMaintainer(String login) { + return 'Creator of BeeCount · @$login'; + } + + @override + String githubGreetingCoCreator(int commits, String amount) { + return 'Co-creating BeeCount · $commits commits · ¥$amount supported'; + } + + @override + String githubGreetingContributor(int commits, int prs) { + return 'Thank you for contributing · $commits commits · $prs PRs'; + } + + @override + String githubGreetingSupporter(String tier) { + return 'Thank you for your warm support · $tier'; + } + + @override + String get githubGreetingStargazer => 'Thanks for starring BeeCount'; + + @override + String get mineProfileBindGitHub => 'Link GitHub'; + + @override + String get mineProfileBindGitHubSubtitle => 'Unlock open-source badges, halos & skins'; + + @override + String get githubHonorTiersAction => 'Honor Tiers'; + + @override + String get githubHonorTiersTitle => 'Community Honor Tiers'; + + @override + String get githubHonorTiersSubtitle => 'Earned through code contributions and project support; unlocks matching halos, badges, poster chops, and skins.'; + + @override + String get githubHonorTierCurrentHighest => 'Current · Highest Tier'; + + @override + String get githubHonorTierCurrent => 'Current Tier'; + + @override + String get githubHonorTierUnlocked => 'Unlocked'; + + @override + String get githubHonorRuleStargazer => 'Star the main repo TNT-Likely/BeeCount'; + + @override + String get githubHonorRuleBuilder => '≥1 commit or ≥1 merged PR across the 6 ecosystem repos (Issues excluded)'; + + @override + String get githubHonorRuleCoreContributor => '≥5 merged PRs, ≥20 commits, or code across ≥2 repos'; + + @override + String get githubHonorRuleSupporter => 'Total support > ¥0 (matched in supporters registry)'; + + @override + String get githubHonorRuleGoldPatron => 'Total support ≥ ¥50'; + + @override + String get githubHonorRuleHiveGuardian => 'Total support ≥ ¥150'; + + @override + String get githubHonorRuleCoCreator => 'Both code contribution & support, or project maintainer (highest tier)'; + + @override + String get githubHonorRewardStargazer => 'Dotted star ring · Stargazer badge'; + + @override + String get githubHonorRewardCode => 'Celadon/Indigo halo · Woodblock Lamp skin · Contributor chop'; + + @override + String get githubHonorRewardDonation => 'Amber gold halo · Honey Jar skin · Supporter chop'; + + @override + String get githubHonorRewardCoCreator => 'Double crown halo · All 3 collector skins · Vermilion Co-Creator chop'; } diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart index bbf07b429..6d0bb9ee4 100644 --- a/lib/l10n/app_localizations_zh.dart +++ b/lib/l10n/app_localizations_zh.dart @@ -10313,6 +10313,322 @@ class AppLocalizationsZh extends AppLocalizations { @override String get accountsEmptyAction => '添加第一个账户'; + + @override + String get headerSkinGroupCommunity => '社区荣誉典藏'; + + @override + String get headerSkinCommunityWoodblockLamp => '青灯刻木'; + + @override + String get headerSkinCommunityHoneyJar => '松间采蜜'; + + @override + String get headerSkinCommunityStarlitHive => '星野归巢'; + + @override + String get githubCommunityTitle => 'GitHub 社区'; + + @override + String get githubRateLimitUpdateHint => 'GitHub 匿名请求已达速率上限(60 次/小时)。配置只读 GitHub Token 可提升至 5,000 次/小时。'; + + @override + String get githubConfigureTokenAction => '配置 Token'; + + @override + String get githubAboutEntrySubtitleWithUpdate => '配置只读 Token 解除更新限流,并查看社区贡献与荣誉'; + + @override + String get githubAboutEntrySubtitleCommunityOnly => '关联只读 Token 查看生态项目贡献与社区荣誉'; + + @override + String get githubAboutEntryExpired => 'Token 已失效,请重新配置'; + + @override + String get githubUpdateBoostedSubtitle => '已启用 GitHub Token 加速(5,000 次/小时)'; + + @override + String get githubTokenSetupTitle => '配置个人访问令牌 (PAT)'; + + @override + String get githubTokenExpiredTitle => 'Token 已失效'; + + @override + String get githubTokenExpiredTag => '需重新配置'; + + @override + String get githubQuotaAnonTag => '匿名 60/h'; + + @override + String get githubTokenSetupDescWithUpdate => '填写零写权限(公共仓库只读)的 GitHub Token,即可解除检查更新 403 限流,并自动统计你在 BeeCount 家族全部项目的贡献与捐赠荣誉。'; + + @override + String get githubTokenSetupDescCommunityOnly => '填写零写权限(公共仓库只读)的 GitHub Token,自动统计你在 BeeCount 家族全部项目的贡献并解锁对应社区荣誉。'; + + @override + String githubTokenExpiredDesc(String token) { + return '当前保存的令牌 $token 已过期或被撤销,请更换新令牌或清除。'; + } + + @override + String get githubTokenInputLabel => 'GitHub Personal Access Token'; + + @override + String get githubTokenVerifyAndSave => '验证并保存'; + + @override + String get githubTokenVerifying => '正在验证…'; + + @override + String get githubTokenVerifySuccess => 'GitHub 身份已验证并保存'; + + @override + String get githubTokenCreateAction => '去生成'; + + @override + String get githubTokenSecurityNote => '令牌仅保存于本机,无需勾选任何写权限,绝不上传云同步、导出配置或写入日志。'; + + @override + String get githubTokenInvalidError => 'Token 无效或已过期(HTTP 401/403),请检查后重试。'; + + @override + String get githubRateLimitedError => '当前 GitHub API 配额已用尽,请稍后再试。'; + + @override + String get githubNetworkError => '无法连接 GitHub,请检查网络环境后重试。'; + + @override + String get githubRefreshAction => '刷新数据'; + + @override + String get githubRefreshSuccess => '社区贡献与配额已更新'; + + @override + String get githubBenefitsTitle => '关联后可获得'; + + @override + String get githubBenefitQuotaTitle => '检查更新 API 速率配额'; + + @override + String get githubBenefitReposTitle => '生态项目贡献聚合'; + + @override + String get githubBenefitReposValue => '6 个关联仓库'; + + @override + String get githubBenefitDonationTitle => '项目捐赠支持核验'; + + @override + String get githubBenefitDonationValue => '自动匹配支持者名单'; + + @override + String get githubBenefitRewardsTitle => '社区荣誉与典藏皮肤'; + + @override + String get githubBenefitRewardsValue => '光环 · 皮肤 · 落款印'; + + @override + String get githubStarredMain => '已 Star 主仓库'; + + @override + String get githubNotStarredMain => '未 Star 主仓库'; + + @override + String get githubApiQuotaLabel => 'API 速率配额(每小时重置)'; + + @override + String get githubContributionsTitle => '生态项目贡献统计'; + + @override + String githubReposCoverage(int active, int total) { + return '覆盖 $active / $total 个仓库'; + } + + @override + String get githubStatCommits => 'Commits'; + + @override + String get githubStatMergedPrs => '已合并 PR'; + + @override + String get githubStatIssues => 'Issues 反馈'; + + @override + String get githubContributionsEmpty => '暂未在 BeeCount 及关联仓库中检索到代码或 Issue 记录。'; + + @override + String get githubDonationTitle => '项目捐赠支持'; + + @override + String get githubDonationVerified => '已核验'; + + @override + String get githubDonationThanks => '感谢你的慷慨支持,每一份心意都在让蜜蜂记账走得更稳更远。'; + + @override + String get githubMaintainerHonorNote => '项目维护者特权:自动享有最高级「蜂巢共创者」荣誉与全部社区典藏奖励。'; + + @override + String githubDonationNotFound(String login) { + return '暂未在支持者名单中匹配到 @$login。'; + } + + @override + String get githubDonationRegisterAction => '已捐赠?前往登记'; + + @override + String get githubRewardsTitle => '社区荣誉奖励'; + + @override + String githubRewardsOpenSkins(int count) { + return '查看典藏皮肤 ($count)'; + } + + @override + String get githubRewardHaloTitle => '「我的」页头像光环与徽章'; + + @override + String get githubRewardHaloDesc => '在个人资料卡展示专属荣誉光环与身份胶囊'; + + @override + String get githubRewardGreetingTitle => '社区致谢副标题'; + + @override + String get githubRewardGreetingDesc => '在「我的」页替换默认标语,展示同行纪念语'; + + @override + String get githubRewardPosterChopTitle => '分享海报纸面落款印'; + + @override + String get githubRewardPosterChopDesc => '在分享卡片与年度报告右下角加盖对应身份方印'; + + @override + String get githubRewardPosterChopPreview => '导出分享卡片时落款示意'; + + @override + String get githubCurrentTokenLabel => '当前令牌(仅本机)'; + + @override + String get githubUnbindAction => '解绑'; + + @override + String get githubUnbindTitle => '解除 GitHub 关联'; + + @override + String get githubUnbindMessage => '解绑后将清除本机保存的 Token,已启用的社区典藏皮肤与荣誉装饰将自动恢复默认。'; + + @override + String get githubUnbindConfirm => '确认解绑'; + + @override + String get githubUnboundToast => '已清除 GitHub Token'; + + @override + String get githubSkinLockedHintIOS => '社区共创荣誉限定'; + + @override + String get githubSkinUnlockAction => '前往社区页解锁'; + + @override + String get githubTierCoCreator => '蜂巢共创者'; + + @override + String get githubTierCoreContributor => '核心工蜂'; + + @override + String get githubTierBuilder => '筑巢者'; + + @override + String get githubTierHiveGuardian => '蜂巢守护者'; + + @override + String get githubTierGoldPatron => '黄金蜜友'; + + @override + String get githubTierSupporter => '暖心赞助者'; + + @override + String get githubTierStargazer => '社区星友'; + + @override + String githubGreetingMaintainer(String login) { + return 'BeeCount 创建者 · @$login'; + } + + @override + String githubGreetingCoCreator(int commits, String amount) { + return '与蜜蜂记账共创同行 · $commits 次提交 · 已支持 ¥$amount'; + } + + @override + String githubGreetingContributor(int commits, int prs) { + return '感谢你的开源贡献 · $commits 次提交 · $prs 个 PR'; + } + + @override + String githubGreetingSupporter(String tier) { + return '感谢你的温暖支持 · $tier'; + } + + @override + String get githubGreetingStargazer => '感谢点亮 Star · 与蜜蜂记账同行'; + + @override + String get mineProfileBindGitHub => '绑定 GitHub'; + + @override + String get mineProfileBindGitHubSubtitle => '关联开源贡献、荣誉光环与典藏皮肤'; + + @override + String get githubHonorTiersAction => '荣誉等级体系'; + + @override + String get githubHonorTiersTitle => '社区荣誉等级体系'; + + @override + String get githubHonorTiersSubtitle => '按代码贡献与项目支持双轨累计;达成后自动解锁对应头像光环、徽章、落款印与典藏皮肤。'; + + @override + String get githubHonorTierCurrentHighest => '当前 · 最高等级'; + + @override + String get githubHonorTierCurrent => '当前等级'; + + @override + String get githubHonorTierUnlocked => '已达成'; + + @override + String get githubHonorRuleStargazer => 'Star 主仓库 TNT-Likely/BeeCount'; + + @override + String get githubHonorRuleBuilder => '生态 6 仓 ≥1 次 Commit 或 ≥1 个已合并 PR(不含 Issue)'; + + @override + String get githubHonorRuleCoreContributor => '≥5 个已合并 PR / ≥20 次 Commit / 跨 ≥2 个生态仓库'; + + @override + String get githubHonorRuleSupporter => '累计支持 > ¥0(匹配支持者名单)'; + + @override + String get githubHonorRuleGoldPatron => '累计支持 ≥ ¥50'; + + @override + String get githubHonorRuleHiveGuardian => '累计支持 ≥ ¥150'; + + @override + String get githubHonorRuleCoCreator => '同时达成代码贡献 + 项目支持,或项目维护者(最高荣誉)'; + + @override + String get githubHonorRewardStargazer => '星点虚线环 · 社区星友徽章'; + + @override + String get githubHonorRewardCode => '青瓷/靛青环 · 解锁「青灯刻木」皮肤 · 筑巢落款印'; + + @override + String get githubHonorRewardDonation => '琥珀金环 · 解锁「松间采蜜」皮肤 · 暖蜜落款印'; + + @override + String get githubHonorRewardCoCreator => '双层金青皇冠环 · 解锁全部 3 套典藏皮肤 · 共创朱砂落款印'; } /// The translations for Chinese, as used in Taiwan (`zh_TW`). @@ -20456,4 +20772,320 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get accountsEmptyAction => '新增第一個帳戶'; + + @override + String get headerSkinGroupCommunity => '社群榮譽典藏'; + + @override + String get headerSkinCommunityWoodblockLamp => '青燈刻木'; + + @override + String get headerSkinCommunityHoneyJar => '松間採蜜'; + + @override + String get headerSkinCommunityStarlitHive => '星野歸巢'; + + @override + String get githubCommunityTitle => 'GitHub 社群'; + + @override + String get githubRateLimitUpdateHint => 'GitHub 匿名請求已達速率上限(60 次/小時)。設定唯讀 GitHub Token 可提升至 5,000 次/小時。'; + + @override + String get githubConfigureTokenAction => '設定 Token'; + + @override + String get githubAboutEntrySubtitleWithUpdate => '設定唯讀 Token 解除更新限流,並查看社群貢獻與榮譽'; + + @override + String get githubAboutEntrySubtitleCommunityOnly => '連結唯讀 Token 查看生態專案貢獻與社群榮譽'; + + @override + String get githubAboutEntryExpired => 'Token 已失效,請重新設定'; + + @override + String get githubUpdateBoostedSubtitle => '已啟用 GitHub Token 加速(5,000 次/小時)'; + + @override + String get githubTokenSetupTitle => '設定個人存取權杖 (PAT)'; + + @override + String get githubTokenExpiredTitle => 'Token 已失效'; + + @override + String get githubTokenExpiredTag => '需重新設定'; + + @override + String get githubQuotaAnonTag => '匿名 60/h'; + + @override + String get githubTokenSetupDescWithUpdate => '填寫零寫入權限(公開倉庫唯讀)的 GitHub Token,即可解除檢查更新 403 限流,並自動統計你在 BeeCount 家族全部專案的貢獻與贊助榮譽。'; + + @override + String get githubTokenSetupDescCommunityOnly => '填寫零寫入權限(公開倉庫唯讀)的 GitHub Token,自動統計你在 BeeCount 家族全部專案的貢獻並解鎖對應社群榮譽。'; + + @override + String githubTokenExpiredDesc(String token) { + return '目前儲存的權杖 $token 已過期或被撤銷,請更換新權杖或清除。'; + } + + @override + String get githubTokenInputLabel => 'GitHub Personal Access Token'; + + @override + String get githubTokenVerifyAndSave => '驗證並儲存'; + + @override + String get githubTokenVerifying => '正在驗證…'; + + @override + String get githubTokenVerifySuccess => 'GitHub 身分已驗證並儲存'; + + @override + String get githubTokenCreateAction => '前往產生'; + + @override + String get githubTokenSecurityNote => '權杖僅儲存於本機,無須勾選任何寫入權限,絕不上傳雲端同步、匯出設定或寫入日誌。'; + + @override + String get githubTokenInvalidError => 'Token 無效或已過期(HTTP 401/403),請檢查後重試。'; + + @override + String get githubRateLimitedError => '目前 GitHub API 配額已用盡,請稍後再試。'; + + @override + String get githubNetworkError => '無法連線 GitHub,請檢查網路環境後重試。'; + + @override + String get githubRefreshAction => '重新整理資料'; + + @override + String get githubRefreshSuccess => '社群貢獻與配額已更新'; + + @override + String get githubBenefitsTitle => '連結後可獲得'; + + @override + String get githubBenefitQuotaTitle => '檢查更新 API 速率配額'; + + @override + String get githubBenefitReposTitle => '生態專案貢獻彙整'; + + @override + String get githubBenefitReposValue => '6 個關聯倉庫'; + + @override + String get githubBenefitDonationTitle => '專案贊助支持核驗'; + + @override + String get githubBenefitDonationValue => '自動比對支持者名單'; + + @override + String get githubBenefitRewardsTitle => '社群榮譽與典藏皮膚'; + + @override + String get githubBenefitRewardsValue => '光環 · 皮膚 · 落款印'; + + @override + String get githubStarredMain => '已 Star 主倉庫'; + + @override + String get githubNotStarredMain => '未 Star 主倉庫'; + + @override + String get githubApiQuotaLabel => 'API 速率配額(每小時重置)'; + + @override + String get githubContributionsTitle => '生態專案貢獻統計'; + + @override + String githubReposCoverage(int active, int total) { + return '涵蓋 $active / $total 個倉庫'; + } + + @override + String get githubStatCommits => 'Commits'; + + @override + String get githubStatMergedPrs => '已合併 PR'; + + @override + String get githubStatIssues => 'Issues 回饋'; + + @override + String get githubContributionsEmpty => '暫未在 BeeCount 及關聯倉庫中檢索到程式碼或 Issue 紀錄。'; + + @override + String get githubDonationTitle => '專案贊助支持'; + + @override + String get githubDonationVerified => '已核驗'; + + @override + String get githubDonationThanks => '感謝你的慷慨支持,每一份心意都在讓蜜蜂記帳走得更穩更遠。'; + + @override + String get githubMaintainerHonorNote => '專案維護者特權:自動享有最高級「蜂巢共創者」榮譽與全部社群典藏獎勵。'; + + @override + String githubDonationNotFound(String login) { + return '暫未在支持者名單中比對到 @$login。'; + } + + @override + String get githubDonationRegisterAction => '已贊助?前往登記'; + + @override + String get githubRewardsTitle => '社群榮譽獎勵'; + + @override + String githubRewardsOpenSkins(int count) { + return '查看典藏皮膚 ($count)'; + } + + @override + String get githubRewardHaloTitle => '「我的」頁頭像光環與徽章'; + + @override + String get githubRewardHaloDesc => '在個人資料卡展示專屬榮譽光環與身分膠囊'; + + @override + String get githubRewardGreetingTitle => '社群致謝副標題'; + + @override + String get githubRewardGreetingDesc => '在「我的」頁取代預設標語,展示同行紀念語'; + + @override + String get githubRewardPosterChopTitle => '分享海報紙面落款印'; + + @override + String get githubRewardPosterChopDesc => '在分享卡片與年度報告右下角加蓋對應身分方印'; + + @override + String get githubRewardPosterChopPreview => '匯出分享卡片時落款示意'; + + @override + String get githubCurrentTokenLabel => '目前權杖(僅本機)'; + + @override + String get githubUnbindAction => '解除連結'; + + @override + String get githubUnbindTitle => '解除 GitHub 連結'; + + @override + String get githubUnbindMessage => '解除後將清除本機儲存的 Token,已啟用的社群典藏皮膚與榮譽裝飾將自動恢復預設。'; + + @override + String get githubUnbindConfirm => '確認解除'; + + @override + String get githubUnboundToast => '已清除 GitHub Token'; + + @override + String get githubSkinLockedHintIOS => '社群共創榮譽限定'; + + @override + String get githubSkinUnlockAction => '前往社群頁解鎖'; + + @override + String get githubTierCoCreator => '蜂巢共創者'; + + @override + String get githubTierCoreContributor => '核心工蜂'; + + @override + String get githubTierBuilder => '築巢者'; + + @override + String get githubTierHiveGuardian => '蜂巢守護者'; + + @override + String get githubTierGoldPatron => '黃金蜜友'; + + @override + String get githubTierSupporter => '暖心贊助者'; + + @override + String get githubTierStargazer => '社群星友'; + + @override + String githubGreetingMaintainer(String login) { + return 'BeeCount 建立者 · @$login'; + } + + @override + String githubGreetingCoCreator(int commits, String amount) { + return '與蜜蜂記帳共創同行 · $commits 次提交 · 已支持 ¥$amount'; + } + + @override + String githubGreetingContributor(int commits, int prs) { + return '感謝你的開源貢獻 · $commits 次提交 · $prs 個 PR'; + } + + @override + String githubGreetingSupporter(String tier) { + return '感謝你的溫暖支持 · $tier'; + } + + @override + String get githubGreetingStargazer => '感謝點亮 Star · 與蜜蜂記帳同行'; + + @override + String get mineProfileBindGitHub => '綁定 GitHub'; + + @override + String get mineProfileBindGitHubSubtitle => '關聯開源貢獻、榮譽光環與典藏皮膚'; + + @override + String get githubHonorTiersAction => '榮譽等級體系'; + + @override + String get githubHonorTiersTitle => '社群榮譽等級體系'; + + @override + String get githubHonorTiersSubtitle => '依程式碼貢獻與專案支持雙軌累計;達成後自動解鎖對應頭像光環、徽章、落款印與典藏皮膚。'; + + @override + String get githubHonorTierCurrentHighest => '目前 · 最高等級'; + + @override + String get githubHonorTierCurrent => '目前等級'; + + @override + String get githubHonorTierUnlocked => '已達成'; + + @override + String get githubHonorRuleStargazer => 'Star 主倉庫 TNT-Likely/BeeCount'; + + @override + String get githubHonorRuleBuilder => '生態 6 倉 ≥1 次 Commit 或 ≥1 個已合併 PR(不含 Issue)'; + + @override + String get githubHonorRuleCoreContributor => '≥5 個已合併 PR / ≥20 次 Commit / 跨 ≥2 個生態倉庫'; + + @override + String get githubHonorRuleSupporter => '累計支持 > ¥0(比對支持者名單)'; + + @override + String get githubHonorRuleGoldPatron => '累計支持 ≥ ¥50'; + + @override + String get githubHonorRuleHiveGuardian => '累計支持 ≥ ¥150'; + + @override + String get githubHonorRuleCoCreator => '同時達成程式碼貢獻 + 專案支持,或專案維護者(最高榮譽)'; + + @override + String get githubHonorRewardStargazer => '星點虛線環 · 社群星友徽章'; + + @override + String get githubHonorRewardCode => '青瓷/靛青環 · 解鎖「青燈刻木」皮膚 · 築巢落款印'; + + @override + String get githubHonorRewardDonation => '琥珀金環 · 解鎖「松間採蜜」皮膚 · 暖蜜落款印'; + + @override + String get githubHonorRewardCoCreator => '雙層金青皇冠環 · 解鎖全部 3 套典藏皮膚 · 共創硃砂落款印'; } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index f9e53248e..4611193bb 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -4650,5 +4650,105 @@ "cloudTestVersionRecommendCloud": "连接成功(BeeCount Cloud v{version}),但低于推荐版本 v{target},建议先升级服务端。仍可保存并继续使用。", "cloudTestVersionRequireCloud": "已连通 BeeCount Cloud v{version},但低于本版 App 最低要求 v{target}。请先升级服务端再开启同步。", "cloudTestVersionRecommendApp": "连接成功(BeeCount Cloud v{version}),服务端推荐搭配 App v{target}+,建议稍后更新应用。", - "cloudTestVersionRequireApp": "已连通 BeeCount Cloud v{version},但服务端最低要求 App v{target}。请先更新 App 后再同步。" + "cloudTestVersionRequireApp": "已连通 BeeCount Cloud v{version},但服务端最低要求 App v{target}。请先更新 App 后再同步。", + "headerSkinGroupCommunity": "社区荣誉典藏", + "headerSkinCommunityWoodblockLamp": "青灯刻木", + "headerSkinCommunityHoneyJar": "松间采蜜", + "headerSkinCommunityStarlitHive": "星野归巢", + "githubCommunityTitle": "GitHub 社区", + "githubRateLimitUpdateHint": "GitHub 匿名请求已达速率上限(60 次/小时)。配置只读 GitHub Token 可提升至 5,000 次/小时。", + "githubConfigureTokenAction": "配置 Token", + "githubAboutEntrySubtitleWithUpdate": "配置只读 Token 解除更新限流,并查看社区贡献与荣誉", + "githubAboutEntrySubtitleCommunityOnly": "关联只读 Token 查看生态项目贡献与社区荣誉", + "githubAboutEntryExpired": "Token 已失效,请重新配置", + "githubUpdateBoostedSubtitle": "已启用 GitHub Token 加速(5,000 次/小时)", + "githubTokenSetupTitle": "配置个人访问令牌 (PAT)", + "githubTokenExpiredTitle": "Token 已失效", + "githubTokenExpiredTag": "需重新配置", + "githubQuotaAnonTag": "匿名 60/h", + "githubTokenSetupDescWithUpdate": "填写零写权限(公共仓库只读)的 GitHub Token,即可解除检查更新 403 限流,并自动统计你在 BeeCount 家族全部项目的贡献与捐赠荣誉。", + "githubTokenSetupDescCommunityOnly": "填写零写权限(公共仓库只读)的 GitHub Token,自动统计你在 BeeCount 家族全部项目的贡献并解锁对应社区荣誉。", + "githubTokenExpiredDesc": "当前保存的令牌 {token} 已过期或被撤销,请更换新令牌或清除。", + "githubTokenInputLabel": "GitHub Personal Access Token", + "githubTokenVerifyAndSave": "验证并保存", + "githubTokenVerifying": "正在验证…", + "githubTokenVerifySuccess": "GitHub 身份已验证并保存", + "githubTokenCreateAction": "去生成", + "githubTokenSecurityNote": "令牌仅保存于本机,无需勾选任何写权限,绝不上传云同步、导出配置或写入日志。", + "githubTokenInvalidError": "Token 无效或已过期(HTTP 401/403),请检查后重试。", + "githubRateLimitedError": "当前 GitHub API 配额已用尽,请稍后再试。", + "githubNetworkError": "无法连接 GitHub,请检查网络环境后重试。", + "githubRefreshAction": "刷新数据", + "githubRefreshSuccess": "社区贡献与配额已更新", + "githubBenefitsTitle": "关联后可获得", + "githubBenefitQuotaTitle": "检查更新 API 速率配额", + "githubBenefitReposTitle": "生态项目贡献聚合", + "githubBenefitReposValue": "6 个关联仓库", + "githubBenefitDonationTitle": "项目捐赠支持核验", + "githubBenefitDonationValue": "自动匹配支持者名单", + "githubBenefitRewardsTitle": "社区荣誉与典藏皮肤", + "githubBenefitRewardsValue": "光环 · 皮肤 · 落款印", + "githubStarredMain": "已 Star 主仓库", + "githubNotStarredMain": "未 Star 主仓库", + "githubApiQuotaLabel": "API 速率配额(每小时重置)", + "githubContributionsTitle": "生态项目贡献统计", + "githubReposCoverage": "覆盖 {active} / {total} 个仓库", + "githubStatCommits": "Commits", + "githubStatMergedPrs": "已合并 PR", + "githubStatIssues": "Issues 反馈", + "githubContributionsEmpty": "暂未在 BeeCount 及关联仓库中检索到代码或 Issue 记录。", + "githubDonationTitle": "项目捐赠支持", + "githubDonationVerified": "已核验", + "githubDonationThanks": "感谢你的慷慨支持,每一份心意都在让蜜蜂记账走得更稳更远。", + "githubMaintainerHonorNote": "项目维护者特权:自动享有最高级「蜂巢共创者」荣誉与全部社区典藏奖励。", + "githubDonationNotFound": "暂未在支持者名单中匹配到 @{login}。", + "githubDonationRegisterAction": "已捐赠?前往登记", + "githubRewardsTitle": "社区荣誉奖励", + "githubRewardsOpenSkins": "查看典藏皮肤 ({count})", + "githubRewardHaloTitle": "「我的」页头像光环与徽章", + "githubRewardHaloDesc": "在个人资料卡展示专属荣誉光环与身份胶囊", + "githubRewardGreetingTitle": "社区致谢副标题", + "githubRewardGreetingDesc": "在「我的」页替换默认标语,展示同行纪念语", + "githubRewardPosterChopTitle": "分享海报纸面落款印", + "githubRewardPosterChopDesc": "在分享卡片与年度报告右下角加盖对应身份方印", + "githubRewardPosterChopPreview": "导出分享卡片时落款示意", + "githubCurrentTokenLabel": "当前令牌(仅本机)", + "githubUnbindAction": "解绑", + "githubUnbindTitle": "解除 GitHub 关联", + "githubUnbindMessage": "解绑后将清除本机保存的 Token,已启用的社区典藏皮肤与荣誉装饰将自动恢复默认。", + "githubUnbindConfirm": "确认解绑", + "githubUnboundToast": "已清除 GitHub Token", + "githubSkinLockedHintIOS": "社区共创荣誉限定", + "githubSkinUnlockAction": "前往社区页解锁", + "githubTierCoCreator": "蜂巢共创者", + "githubTierCoreContributor": "核心工蜂", + "githubTierBuilder": "筑巢者", + "githubTierHiveGuardian": "蜂巢守护者", + "githubTierGoldPatron": "黄金蜜友", + "githubTierSupporter": "暖心赞助者", + "githubTierStargazer": "社区星友", + "githubGreetingMaintainer": "BeeCount 创建者 · @{login}", + "githubGreetingCoCreator": "与蜜蜂记账共创同行 · {commits} 次提交 · 已支持 ¥{amount}", + "githubGreetingContributor": "感谢你的开源贡献 · {commits} 次提交 · {prs} 个 PR", + "githubGreetingSupporter": "感谢你的温暖支持 · {tier}", + "githubGreetingStargazer": "感谢点亮 Star · 与蜜蜂记账同行", + "mineProfileBindGitHub": "绑定 GitHub", + "mineProfileBindGitHubSubtitle": "关联开源贡献、荣誉光环与典藏皮肤", + "githubHonorTiersAction": "荣誉等级体系", + "githubHonorTiersTitle": "社区荣誉等级体系", + "githubHonorTiersSubtitle": "按代码贡献与项目支持双轨累计;达成后自动解锁对应头像光环、徽章、落款印与典藏皮肤。", + "githubHonorTierCurrentHighest": "当前 · 最高等级", + "githubHonorTierCurrent": "当前等级", + "githubHonorTierUnlocked": "已达成", + "githubHonorRuleStargazer": "Star 主仓库 TNT-Likely/BeeCount", + "githubHonorRuleBuilder": "生态 6 仓 ≥1 次 Commit 或 ≥1 个已合并 PR(不含 Issue)", + "githubHonorRuleCoreContributor": "≥5 个已合并 PR / ≥20 次 Commit / 跨 ≥2 个生态仓库", + "githubHonorRuleSupporter": "累计支持 > ¥0(匹配支持者名单)", + "githubHonorRuleGoldPatron": "累计支持 ≥ ¥50", + "githubHonorRuleHiveGuardian": "累计支持 ≥ ¥150", + "githubHonorRuleCoCreator": "同时达成代码贡献 + 项目支持,或项目维护者(最高荣誉)", + "githubHonorRewardStargazer": "星点虚线环 · 社区星友徽章", + "githubHonorRewardCode": "青瓷/靛青环 · 解锁「青灯刻木」皮肤 · 筑巢落款印", + "githubHonorRewardDonation": "琥珀金环 · 解锁「松间采蜜」皮肤 · 暖蜜落款印", + "githubHonorRewardCoCreator": "双层金青皇冠环 · 解锁全部 3 套典藏皮肤 · 共创朱砂落款印" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index 2452e86ff..1583ce70b 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -3968,5 +3968,105 @@ "cloudTestVersionRequireApp": "已連通 BeeCount Cloud v{version},但伺服器端最低要求 App v{target}。請先更新 App 後再同步。", "accountsEmptyTitle": "開始管理你的資產與負債", "accountsEmptyDescription": "新增常用帳戶後,即可自動彙總淨資產、追蹤餘額趨勢與多幣別分布。", - "accountsEmptyAction": "新增第一個帳戶" + "accountsEmptyAction": "新增第一個帳戶", + "headerSkinGroupCommunity": "社群榮譽典藏", + "headerSkinCommunityWoodblockLamp": "青燈刻木", + "headerSkinCommunityHoneyJar": "松間採蜜", + "headerSkinCommunityStarlitHive": "星野歸巢", + "githubCommunityTitle": "GitHub 社群", + "githubRateLimitUpdateHint": "GitHub 匿名請求已達速率上限(60 次/小時)。設定唯讀 GitHub Token 可提升至 5,000 次/小時。", + "githubConfigureTokenAction": "設定 Token", + "githubAboutEntrySubtitleWithUpdate": "設定唯讀 Token 解除更新限流,並查看社群貢獻與榮譽", + "githubAboutEntrySubtitleCommunityOnly": "連結唯讀 Token 查看生態專案貢獻與社群榮譽", + "githubAboutEntryExpired": "Token 已失效,請重新設定", + "githubUpdateBoostedSubtitle": "已啟用 GitHub Token 加速(5,000 次/小時)", + "githubTokenSetupTitle": "設定個人存取權杖 (PAT)", + "githubTokenExpiredTitle": "Token 已失效", + "githubTokenExpiredTag": "需重新設定", + "githubQuotaAnonTag": "匿名 60/h", + "githubTokenSetupDescWithUpdate": "填寫零寫入權限(公開倉庫唯讀)的 GitHub Token,即可解除檢查更新 403 限流,並自動統計你在 BeeCount 家族全部專案的貢獻與贊助榮譽。", + "githubTokenSetupDescCommunityOnly": "填寫零寫入權限(公開倉庫唯讀)的 GitHub Token,自動統計你在 BeeCount 家族全部專案的貢獻並解鎖對應社群榮譽。", + "githubTokenExpiredDesc": "目前儲存的權杖 {token} 已過期或被撤銷,請更換新權杖或清除。", + "githubTokenInputLabel": "GitHub Personal Access Token", + "githubTokenVerifyAndSave": "驗證並儲存", + "githubTokenVerifying": "正在驗證…", + "githubTokenVerifySuccess": "GitHub 身分已驗證並儲存", + "githubTokenCreateAction": "前往產生", + "githubTokenSecurityNote": "權杖僅儲存於本機,無須勾選任何寫入權限,絕不上傳雲端同步、匯出設定或寫入日誌。", + "githubTokenInvalidError": "Token 無效或已過期(HTTP 401/403),請檢查後重試。", + "githubRateLimitedError": "目前 GitHub API 配額已用盡,請稍後再試。", + "githubNetworkError": "無法連線 GitHub,請檢查網路環境後重試。", + "githubRefreshAction": "重新整理資料", + "githubRefreshSuccess": "社群貢獻與配額已更新", + "githubBenefitsTitle": "連結後可獲得", + "githubBenefitQuotaTitle": "檢查更新 API 速率配額", + "githubBenefitReposTitle": "生態專案貢獻彙整", + "githubBenefitReposValue": "6 個關聯倉庫", + "githubBenefitDonationTitle": "專案贊助支持核驗", + "githubBenefitDonationValue": "自動比對支持者名單", + "githubBenefitRewardsTitle": "社群榮譽與典藏皮膚", + "githubBenefitRewardsValue": "光環 · 皮膚 · 落款印", + "githubStarredMain": "已 Star 主倉庫", + "githubNotStarredMain": "未 Star 主倉庫", + "githubApiQuotaLabel": "API 速率配額(每小時重置)", + "githubContributionsTitle": "生態專案貢獻統計", + "githubReposCoverage": "涵蓋 {active} / {total} 個倉庫", + "githubStatCommits": "Commits", + "githubStatMergedPrs": "已合併 PR", + "githubStatIssues": "Issues 回饋", + "githubContributionsEmpty": "暫未在 BeeCount 及關聯倉庫中檢索到程式碼或 Issue 紀錄。", + "githubDonationTitle": "專案贊助支持", + "githubDonationVerified": "已核驗", + "githubDonationThanks": "感謝你的慷慨支持,每一份心意都在讓蜜蜂記帳走得更穩更遠。", + "githubMaintainerHonorNote": "專案維護者特權:自動享有最高級「蜂巢共創者」榮譽與全部社群典藏獎勵。", + "githubDonationNotFound": "暫未在支持者名單中比對到 @{login}。", + "githubDonationRegisterAction": "已贊助?前往登記", + "githubRewardsTitle": "社群榮譽獎勵", + "githubRewardsOpenSkins": "查看典藏皮膚 ({count})", + "githubRewardHaloTitle": "「我的」頁頭像光環與徽章", + "githubRewardHaloDesc": "在個人資料卡展示專屬榮譽光環與身分膠囊", + "githubRewardGreetingTitle": "社群致謝副標題", + "githubRewardGreetingDesc": "在「我的」頁取代預設標語,展示同行紀念語", + "githubRewardPosterChopTitle": "分享海報紙面落款印", + "githubRewardPosterChopDesc": "在分享卡片與年度報告右下角加蓋對應身分方印", + "githubRewardPosterChopPreview": "匯出分享卡片時落款示意", + "githubCurrentTokenLabel": "目前權杖(僅本機)", + "githubUnbindAction": "解除連結", + "githubUnbindTitle": "解除 GitHub 連結", + "githubUnbindMessage": "解除後將清除本機儲存的 Token,已啟用的社群典藏皮膚與榮譽裝飾將自動恢復預設。", + "githubUnbindConfirm": "確認解除", + "githubUnboundToast": "已清除 GitHub Token", + "githubSkinLockedHintIOS": "社群共創榮譽限定", + "githubSkinUnlockAction": "前往社群頁解鎖", + "githubTierCoCreator": "蜂巢共創者", + "githubTierCoreContributor": "核心工蜂", + "githubTierBuilder": "築巢者", + "githubTierHiveGuardian": "蜂巢守護者", + "githubTierGoldPatron": "黃金蜜友", + "githubTierSupporter": "暖心贊助者", + "githubTierStargazer": "社群星友", + "githubGreetingMaintainer": "BeeCount 建立者 · @{login}", + "githubGreetingCoCreator": "與蜜蜂記帳共創同行 · {commits} 次提交 · 已支持 ¥{amount}", + "githubGreetingContributor": "感謝你的開源貢獻 · {commits} 次提交 · {prs} 個 PR", + "githubGreetingSupporter": "感謝你的溫暖支持 · {tier}", + "githubGreetingStargazer": "感謝點亮 Star · 與蜜蜂記帳同行", + "mineProfileBindGitHub": "綁定 GitHub", + "mineProfileBindGitHubSubtitle": "關聯開源貢獻、榮譽光環與典藏皮膚", + "githubHonorTiersAction": "榮譽等級體系", + "githubHonorTiersTitle": "社群榮譽等級體系", + "githubHonorTiersSubtitle": "依程式碼貢獻與專案支持雙軌累計;達成後自動解鎖對應頭像光環、徽章、落款印與典藏皮膚。", + "githubHonorTierCurrentHighest": "目前 · 最高等級", + "githubHonorTierCurrent": "目前等級", + "githubHonorTierUnlocked": "已達成", + "githubHonorRuleStargazer": "Star 主倉庫 TNT-Likely/BeeCount", + "githubHonorRuleBuilder": "生態 6 倉 ≥1 次 Commit 或 ≥1 個已合併 PR(不含 Issue)", + "githubHonorRuleCoreContributor": "≥5 個已合併 PR / ≥20 次 Commit / 跨 ≥2 個生態倉庫", + "githubHonorRuleSupporter": "累計支持 > ¥0(比對支持者名單)", + "githubHonorRuleGoldPatron": "累計支持 ≥ ¥50", + "githubHonorRuleHiveGuardian": "累計支持 ≥ ¥150", + "githubHonorRuleCoCreator": "同時達成程式碼貢獻 + 專案支持,或專案維護者(最高榮譽)", + "githubHonorRewardStargazer": "星點虛線環 · 社群星友徽章", + "githubHonorRewardCode": "青瓷/靛青環 · 解鎖「青燈刻木」皮膚 · 築巢落款印", + "githubHonorRewardDonation": "琥珀金環 · 解鎖「松間採蜜」皮膚 · 暖蜜落款印", + "githubHonorRewardCoCreator": "雙層金青皇冠環 · 解鎖全部 3 套典藏皮膚 · 共創硃砂落款印" } diff --git a/lib/pages/main/mine/widgets/mine_profile.dart b/lib/pages/main/mine/widgets/mine_profile.dart index 68197ca56..91e13efb2 100644 --- a/lib/pages/main/mine/widgets/mine_profile.dart +++ b/lib/pages/main/mine/widgets/mine_profile.dart @@ -14,7 +14,10 @@ import '../../../../services/system/logger_service.dart'; import '../../../../services/ui/avatar_service.dart'; import '../../../../providers/avatar_providers.dart'; import '../../../../providers/sync_providers.dart' as sp; +import '../../../../services/github/github_community_models.dart'; import '../../../../l10n/app_localizations.dart'; +import '../../../settings/github_community_page.dart'; +import '../../../shared/widgets/community_honor_widgets.dart'; /// Profile edits retain the existing avatar, nickname and cloud update services. class _EditDisplayNameDialog extends StatefulWidget { @@ -117,6 +120,16 @@ class MineProfileBindingState extends ConsumerState { Future _showProfileOptions() async { final l10n = AppLocalizations.of(context); + final community = ref.read(githubCommunityProvider); + final communityProfile = community.isBound ? community.profile : null; + final githubSubtitle = communityProfile != null + ? [ + '@${communityProfile.login}', + if (communityProfile.primaryTier != GitHubHonorTier.none) + communityTierTitle(l10n, communityProfile.primaryTier), + ].join(' · ') + : l10n.mineProfileBindGitHubSubtitle; + final result = await showDialog( context: context, builder: (context) => BeeDialog( @@ -139,6 +152,15 @@ class MineProfileBindingState extends ConsumerState { title: l10n.mineAvatarFromCamera, onTap: () => Navigator.pop(context, 'camera'), ), + BeeMenuRow( + key: const ValueKey('mine-profile-bind-github'), + leading: const BeeLineIcon('GitMerge', size: 19), + title: communityProfile != null + ? l10n.githubCommunityTitle + : l10n.mineProfileBindGitHub, + subtitle: githubSubtitle, + onTap: () => Navigator.pop(context, 'github'), + ), if (_avatarPath != null) BeeMenuRow( danger: true, @@ -163,6 +185,14 @@ class MineProfileBindingState extends ConsumerState { await _showEditDisplayName(); return; } + if (result == 'github') { + await Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const GitHubCommunityPage(), + ), + ); + return; + } try { if (result == 'gallery') { @@ -300,22 +330,52 @@ class MineProfileBindingState extends ConsumerState { ref.watch(currentBalanceProvider(ledgerId)).valueOrNull ?? 0.0; final hidden = ref.watch(hideAmountsProvider); final name = ref.watch(displayNameProvider); + final community = ref.watch(githubCommunityProvider); + final communityProfile = community.isBound ? community.profile : null; + final activeTier = communityProfile?.primaryTier ?? GitHubHonorTier.none; + final showHalo = community.prefs.showHaloAndBadge && + activeTier != GitHubHonorTier.none; + final showGreeting = community.prefs.showCustomGreeting && + communityProfile != null && + activeTier != GitHubHonorTier.none; final l10n = AppLocalizations.of(context); + final rawAvatar = _isLoadingAvatar + ? const CircularProgressIndicator(strokeWidth: 2) + : avatar == null + ? const MineDefaultAvatar() + : Image.file(File(avatar), + key: ValueKey(avatar), + fit: BoxFit.cover, + errorBuilder: (_, __, ___) => const MineDefaultAvatar()); return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ BeeProfile( profileLabel: l10n.mineProfileEditTitle, editLabel: l10n.mineDisplayNameEditTitle, nickname: name.isEmpty ? l10n.appTitle : name, greeting: name.isEmpty ? null : _greeting(l10n).text, - subtitle: l10n.mineSlogan, - avatar: _isLoadingAvatar - ? const CircularProgressIndicator(strokeWidth: 2) - : avatar == null - ? const MineDefaultAvatar() - : Image.file(File(avatar), - key: ValueKey(avatar), - fit: BoxFit.cover, - errorBuilder: (_, __, ___) => const MineDefaultAvatar()), + subtitle: showGreeting + ? communityGreetingSubtitle(l10n, communityProfile) + : l10n.mineSlogan, + clipAvatar: !showHalo, + avatar: showHalo + ? CommunityAvatarHalo( + tier: activeTier, + size: 48, + avatar: rawAvatar, + ) + : rawAvatar, + badge: showHalo + ? CommunityHonorBadge( + key: const ValueKey('mine-community-badge'), + tier: activeTier, + compact: true, + onTap: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const GitHubCommunityPage(), + ), + ), + ) + : null, onEdit: _showEditDisplayName, onTap: _showProfileOptions), const SizedBox(height: 12), diff --git a/lib/pages/report/annual/bindings/annual_poster_projection.dart b/lib/pages/report/annual/bindings/annual_poster_projection.dart index bcd5c2662..4237fe19f 100644 --- a/lib/pages/report/annual/bindings/annual_poster_projection.dart +++ b/lib/pages/report/annual/bindings/annual_poster_projection.dart @@ -17,12 +17,14 @@ class AnnualReportPoster extends StatelessWidget { required this.primaryColor, this.hideIncome = false, this.monthStartDay = 1, - this.now}); + this.now, + this.communityMark}); final AnnualReportData data; final Color primaryColor; final bool hideIncome; final int monthStartDay; final DateTime? now; + final Widget? communityMark; @override Widget build(BuildContext context) { final l = AppLocalizations.of(context), today = now ?? DateTime.now(); @@ -72,6 +74,7 @@ class AnnualReportPoster extends StatelessWidget { return BeeAnnualReportPoster( header: posterHeader(l, primaryColor, 'ANNUAL REPORT / ${data.year}'), footer: posterFooter(l), + communityMark: communityMark, year: '${data.year}', subtitle: l.annualReportPage1Subtitle(data.year), expenseLabel: '${l.annualReportTotalExpense} · ${data.currencyCode}', diff --git a/lib/pages/report/annual_report_page.dart b/lib/pages/report/annual_report_page.dart index 58b210d36..7c58bc313 100644 --- a/lib/pages/report/annual_report_page.dart +++ b/lib/pages/report/annual_report_page.dart @@ -15,6 +15,7 @@ import 'annual/bindings/annual_poster_projection.dart'; import '../../data/db.dart'; import '../../services/export/share_poster_types.dart'; import '../../services/export/share_poster_service.dart'; +import '../shared/widgets/community_honor_widgets.dart'; /// 年度账单数据 class AnnualReportData { @@ -437,6 +438,12 @@ class _AnnualReportPageState extends ConsumerState { await precacheImage(const AssetImage('assets/logo2.png'), context); // Create poster widget + final community = ref.read(githubCommunityProvider); + final Widget? communityMark = (community.isBound && + community.prefs.showPosterStamp && + community.profile!.hasPosterChopHonor) + ? CommunityPosterChop(profile: community.profile!) + : null; final posterKey = GlobalKey(); final poster = RepaintBoundary( key: posterKey, @@ -444,6 +451,7 @@ class _AnnualReportPageState extends ConsumerState { data: data, primaryColor: primaryColor, monthStartDay: monthStartDay, + communityMark: communityMark, ), ); @@ -463,6 +471,7 @@ class _AnnualReportPageState extends ConsumerState { data: data, primaryColor: primaryColor, monthStartDay: monthStartDay, + communityMark: communityMark, ), ); } catch (e) { @@ -520,12 +529,14 @@ class _AnnualReportPosterPreview extends StatefulWidget { final AnnualReportData data; final Color primaryColor; final int monthStartDay; + final Widget? communityMark; const _AnnualReportPosterPreview({ required this.initialImageBytes, required this.data, required this.primaryColor, required this.monthStartDay, + this.communityMark, }); @override @@ -564,6 +575,7 @@ class _AnnualReportPosterPreviewState primaryColor: widget.primaryColor, hideIncome: _hideIncome, monthStartDay: widget.monthStartDay, + communityMark: widget.communityMark, ), ); diff --git a/lib/pages/report/share/bindings/share_card_renderer.dart b/lib/pages/report/share/bindings/share_card_renderer.dart index 84ad70b8b..b3c8d1421 100644 --- a/lib/pages/report/share/bindings/share_card_renderer.dart +++ b/lib/pages/report/share/bindings/share_card_renderer.dart @@ -14,6 +14,7 @@ import '../../../shared/sharing/bindings/ledger_summary_poster.dart'; import '../../../shared/sharing/bindings/month_summary_poster.dart'; import '../../../shared/sharing/bindings/user_profile_poster.dart'; import '../../../shared/sharing/bindings/year_summary_poster.dart'; +import '../../../shared/widgets/community_honor_widgets.dart'; final shareCardRendererProvider = Provider((ref) => const ShareCardRenderer()); @@ -33,15 +34,26 @@ class ShareCardRenderer { }) async { final data = SharePosterDataService(ref.read(repositoryProvider)); final color = ref.read(primaryColorProvider); + final community = ref.read(githubCommunityProvider); + final Widget? communityMark = (community.isBound && + community.prefs.showPosterStamp && + community.profile!.hasPosterChopHonor) + ? CommunityPosterChop(profile: community.profile!) + : null; final l = AppLocalizations.of(context); final now = DateTime.now(); final Widget poster; switch (type) { case PosterType.appPromo: - poster = AppPromoPoster(l10n: l, primaryColor: color); + poster = AppPromoPoster( + l10n: l, primaryColor: color, communityMark: communityMark); case PosterType.userProfile: final value = await data.calculateUserProfile(ledgerId: ledgerId); - poster = UserProfilePoster(data: value, l10n: l, primaryColor: color); + poster = UserProfilePoster( + data: value, + l10n: l, + primaryColor: color, + communityMark: communityMark); case PosterType.yearSummary: final value = await data.calculateYearSummary( ledgerId: ledgerId, year: year ?? now.year); @@ -49,6 +61,7 @@ class ShareCardRenderer { data: value, primaryColor: color, hideIncome: hideIncome, + communityMark: communityMark, currencyCode: (await ref.read(repositoryProvider).getLedgerById(ledgerId)) ?.currency ?? @@ -62,6 +75,7 @@ class ShareCardRenderer { data: value, primaryColor: color, hideIncome: hideIncome, + communityMark: communityMark, currencyCode: (await ref.read(repositoryProvider).getLedgerById(ledgerId)) ?.currency ?? @@ -72,6 +86,7 @@ class ShareCardRenderer { data: value, primaryColor: color, hideIncome: hideIncome, + communityMark: communityMark, currencyCode: (await ref.read(repositoryProvider).getLedgerById(ledgerId)) ?.currency ?? diff --git a/lib/pages/settings/about/bindings/support_about_controls.dart b/lib/pages/settings/about/bindings/support_about_controls.dart index 81ef8b35b..4749f33c3 100644 --- a/lib/pages/settings/about/bindings/support_about_controls.dart +++ b/lib/pages/settings/about/bindings/support_about_controls.dart @@ -9,12 +9,15 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_svg/flutter_svg.dart'; import '../../../../l10n/app_localizations.dart'; import '../../../../providers.dart'; +import '../../../../services/github/github_community_models.dart'; +import '../../github_community_page.dart'; import '../../help_center_page.dart'; import '../../log_center_page.dart'; import '../../privacy_policy_page.dart'; import '../../../../services/marketing/product_promos.dart'; import '../../../../utils/website_urls.dart'; import '../../../shared/branding/bee_artwork.dart'; +import '../../../shared/widgets/community_honor_widgets.dart'; import '../../../../dev/component_gallery/component_gallery_page.dart'; import '../../support/bindings/feedback_link.dart'; import '../../support/bindings/support_frame.dart'; @@ -162,11 +165,35 @@ class _SupportAboutControlsState extends ConsumerState { : null), onTap: () => open(url)); final loading = ref.watch(checkUpdateLoadingProvider), - progress = ref.watch(updateProgressProvider); + progress = ref.watch(updateProgressProvider), + community = ref.watch(githubCommunityProvider); + final profile = community.isBound ? community.profile : null; + final showUpdateRow = !platform.isIOS && !platform.isGooglePlay; + final rate = profile?.rateLimit; final products = [ (beeAssetsPromo(context), buildPromoTexts(context, l.aboutBeeAssets)), (beeDnsPromo(context), buildPromoTexts(context, l.aboutBeeDNS)) ]; + String communitySubtitle() { + if (community.loading) return l.githubTokenVerifying; + if (community.tokenInvalid && community.hasToken) { + return l.githubAboutEntryExpired; + } + if (profile != null) { + final parts = ['@${profile.login}']; + if (profile.primaryTier != GitHubHonorTier.none) { + parts.add(communityTierTitle(l, profile.primaryTier)); + } + if (showUpdateRow && rate != null) { + parts.add('${rate.remaining}/${rate.limit}'); + } + return parts.join(' · '); + } + return showUpdateRow + ? l.githubAboutEntrySubtitleWithUpdate + : l.githubAboutEntrySubtitleCommunityOnly; + } + return SupportFrame( title: l.aboutPageTitle, subtitle: l.aboutPageSubtitle, @@ -200,8 +227,70 @@ class _SupportAboutControlsState extends ConsumerState { 'https://v.douyin.com/YG7tUweYYyQ/', asset: 'assets/icons/social/douyin.svg'), ]), + if (profile != null && profile.primaryTier != GitHubHonorTier.none) + InkWell( + key: const ValueKey('support-github-passport'), + borderRadius: BorderRadius.circular(18), + onTap: () => _page(const GitHubCommunityPage()), + child: BeeSurface( + child: Row( + children: [ + CommunityAvatarHalo( + tier: profile.primaryTier, + size: 40, + enabled: community.prefs.showHaloAndBadge, + avatar: CommunityGitHubAvatar( + profile: profile, + size: 40, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 6, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + '@${profile.login}', + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + CommunityHonorBadge( + tier: profile.primaryTier, + compact: true, + ), + ], + ), + const SizedBox(height: 3), + Text( + communityGreetingSubtitle(l, profile), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: 11.5, + color: Theme.of(context).hintColor, + ), + ), + ], + ), + ), + BeeLineIcon( + 'ChevronRight', + size: 16, + color: Theme.of(context).hintColor, + ), + ], + ), + ), + ), BeeSupportActions(actions: [ - if (!platform.isIOS && !platform.isGooglePlay) + if (showUpdateRow) BeeSupportAction( key: const ValueKey('support-update'), title: loading @@ -213,7 +302,9 @@ class _SupportAboutControlsState extends ConsumerState { ? l.mineCheckUpdateSubtitleDetecting : progress.isActive ? progress.status - : null, + : (profile != null + ? l.githubUpdateBoostedSubtitle + : null), leading: const BeeLineIcon('RefreshCw'), trailing: loading || progress.isActive ? SizedBox( @@ -228,17 +319,34 @@ class _SupportAboutControlsState extends ConsumerState { : () async { final container = ProviderScope.containerOf(context, listen: false); - await platform.checkUpdate(context, - setLoading: (value) => container - .read(checkUpdateLoadingProvider.notifier) - .state = value, - setProgress: (value, status) => container - .read(updateProgressProvider.notifier) - .state = - status.isEmpty - ? UpdateProgress.idle() - : UpdateProgress.active(value, status)); + await platform.checkUpdate( + context, + setLoading: (value) => container + .read(checkUpdateLoadingProvider.notifier) + .state = value, + setProgress: (value, status) => container + .read(updateProgressProvider.notifier) + .state = + status.isEmpty + ? UpdateProgress.idle() + : UpdateProgress.active(value, status), + onConfigureGitHubToken: () => + _page(const GitHubCommunityPage()), + ); }), + BeeSupportAction( + key: const ValueKey('support-github-community'), + title: l.githubCommunityTitle, + subtitle: communitySubtitle(), + leading: const BeeLineIcon('LockKeyhole'), + trailing: profile != null && + profile.primaryTier != GitHubHonorTier.none + ? CommunityHonorBadge( + tier: profile.primaryTier, + compact: true, + ) + : null, + onTap: () => _page(const GitHubCommunityPage())), BeeSupportAction( key: const ValueKey('support-development'), title: l.aboutSupportDevelopment, diff --git a/lib/pages/settings/appearance/bindings/skin_choices.dart b/lib/pages/settings/appearance/bindings/skin_choices.dart index 4a501330d..8aea7d110 100644 --- a/lib/pages/settings/appearance/bindings/skin_choices.dart +++ b/lib/pages/settings/appearance/bindings/skin_choices.dart @@ -27,6 +27,7 @@ BeeSkinChoice skinChoice(BuildContext context, String skinGroupLabel(AppLocalizations l, HeaderSkinGroup group) => switch (group) { HeaderSkinGroup.anniversary => l.headerSkinGroupAnniversary, + HeaderSkinGroup.community => l.headerSkinGroupCommunity, HeaderSkinGroup.gradient => l.headerSkinGroupGradient, HeaderSkinGroup.scene => l.headerSkinGroupScene, HeaderSkinGroup.pattern => l.headerSkinGroupPattern, diff --git a/lib/pages/settings/appearance/skin_editor.dart b/lib/pages/settings/appearance/skin_editor.dart index f25d11332..e03a22341 100644 --- a/lib/pages/settings/appearance/skin_editor.dart +++ b/lib/pages/settings/appearance/skin_editor.dart @@ -3,9 +3,12 @@ import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../../l10n/app_localizations.dart'; +import '../../../providers/github_community_provider.dart'; import '../../../providers/theme_providers.dart'; import '../../../skins/premium_skins.dart'; import '../../../styles/header_skins.dart'; +import '../github_community_page.dart'; +import '../support/bindings/support_platform.dart'; import 'bindings/skin_choices.dart'; import 'skin_store_actions.dart'; import 'skin_trial_page.dart'; @@ -98,6 +101,11 @@ class _SkinEditorState extends ConsumerState { bool _canEdit(PremiumSkins runtime, String current) { if (widget.editingActive && current != widget.skinId) return false; if (pack != null) return runtime.ownsPack(pack!.id); + if (free?.isCommunityHonor == true) { + return ref + .read(githubCommunityProvider) + .isCommunitySkinUnlocked(widget.skinId); + } return widget.skinId == kHeaderSkinNone || free != null; } @@ -181,6 +189,10 @@ class _SkinEditorState extends ConsumerState { final enabled = ref.watch(headerSkinsEnabledProvider); final current = activeSkinId(freeId, runtime); final collection = pack; + final community = ref.watch(githubCommunityProvider); + final platform = ref.watch(supportPlatformProvider); + final communityLocked = free?.isCommunityHonor == true && + !community.isCommunitySkinUnlocked(widget.skinId); final locked = collection != null && !runtime.ownsPack(collection.id); final base = Theme.of(context); final skin = paid; @@ -239,22 +251,41 @@ class _SkinEditorState extends ConsumerState { const SizedBox(width: 8), Expanded( child: FilledButton( - key: ValueKey( - locked ? 'official-buy-pack' : 'official-apply'), + key: ValueKey(locked + ? 'official-buy-pack' + : (communityLocked + ? 'community-skin-locked' + : 'official-apply')), onPressed: !enabled || _working ? null : locked ? runtime.canPurchasePack(collection) ? () => _buy(runtime) : null - : _canEdit(runtime, current) - ? () => _save(runtime) - : null, + : communityLocked + ? (platform.isIOS + ? null + : () { + Navigator.of(context).pop(); + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => + const GitHubCommunityPage(), + ), + ); + }) + : _canEdit(runtime, current) + ? () => _save(runtime) + : null, child: Text(locked ? skinPurchaseLabel(context, runtime, collection) - : widget.editingActive - ? skinText(context, '保存设置', 'Save settings') - : skinText(context, '应用皮肤', 'Apply skin')), + : communityLocked + ? (platform.isIOS + ? l.githubSkinLockedHintIOS + : l.githubSkinUnlockAction) + : widget.editingActive + ? skinText(context, '保存设置', 'Save settings') + : skinText(context, '应用皮肤', 'Apply skin')), ), ), ]), diff --git a/lib/pages/settings/github_community_page.dart b/lib/pages/settings/github_community_page.dart new file mode 100644 index 000000000..b8ffd8f2f --- /dev/null +++ b/lib/pages/settings/github_community_page.dart @@ -0,0 +1,958 @@ +import 'package:beecount_ui/beecount_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../../l10n/app_localizations.dart'; +import '../../providers/github_community_provider.dart'; +import '../../providers/theme_providers.dart'; +import '../../services/github/github_community_models.dart'; +import '../shared/scaffold/widgets/page_scaffold.dart'; +import '../shared/widgets/community_honor_widgets.dart'; +import 'header_skin_page.dart'; +import 'support/bindings/support_platform.dart'; + +/// GitHub Token 配置、生态贡献统计、捐赠核验与社区荣誉奖励管理页。 +class GitHubCommunityPage extends ConsumerStatefulWidget { + const GitHubCommunityPage({super.key}); + + @override + ConsumerState createState() => + _GitHubCommunityPageState(); +} + +class _GitHubCommunityPageState extends ConsumerState { + final _tokenController = TextEditingController(); + bool _obscureToken = true; + + static const String _createTokenUrl = + 'https://github.com/settings/tokens/new?description=BeeCount&scopes='; + static const String _donationIssueUrl = + 'https://github.com/TNT-Likely/BeeCount/issues/new?template=donation_info.yml'; + + @override + void dispose() { + _tokenController.dispose(); + super.dispose(); + } + + Future _submitToken() async { + final raw = _tokenController.text.trim(); + if (raw.isEmpty) return; + FocusScope.of(context).unfocus(); + final ok = + await ref.read(githubCommunityProvider.notifier).saveAndVerifyToken(raw); + if (!mounted) return; + final l = AppLocalizations.of(context); + if (ok) { + _tokenController.clear(); + showBeeToast(context, l.githubTokenVerifySuccess, tone: BeeTone.success); + } + } + + Future _confirmUnbind() async { + final l = AppLocalizations.of(context); + final confirmed = await showDialog( + context: context, + builder: (dialogContext) => BeeDialog( + title: Text(l.githubUnbindTitle), + content: Text(l.githubUnbindMessage), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(l.commonCancel), + ), + TextButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text( + l.githubUnbindConfirm, + style: TextStyle(color: Theme.of(dialogContext).colorScheme.error), + ), + ), + ], + ), + ); + if (confirmed == true && mounted) { + await ref.read(githubCommunityProvider.notifier).clearToken(); + if (mounted) { + showBeeToast(context, l.githubUnboundToast, tone: BeeTone.success); + } + } + } + + Future _openUrl(String url) async { + final opened = await ref.read(supportPlatformProvider).open(Uri.parse(url)); + if (!opened && mounted) { + showBeeToast(context, AppLocalizations.of(context).updateCannotOpenLink, + tone: BeeTone.error); + } + } + + String _repoRole(GitHubEcosystemRepo repo, Locale locale) { + if (locale.languageCode != 'zh') return repo.roleEn; + final traditional = locale.scriptCode == 'Hant' || + const {'TW', 'HK', 'MO'}.contains(locale.countryCode); + return traditional ? repo.roleZhTw : repo.roleZh; + } + + String _errorMessage(AppLocalizations l, GitHubCommunityState state) { + return switch (state.errorKind) { + GitHubCommunityErrorKind.invalidToken => l.githubTokenInvalidError, + GitHubCommunityErrorKind.rateLimited => l.githubRateLimitedError, + GitHubCommunityErrorKind.network => l.githubNetworkError, + GitHubCommunityErrorKind.none => '', + }; + } + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context); + final state = ref.watch(githubCommunityProvider); + final platform = ref.watch(supportPlatformProvider); + final showUpdateBoost = !platform.isIOS && !platform.isGooglePlay; + final locale = Localizations.localeOf(context); + final theme = Theme.of(context); + final colors = theme.colorScheme; + + return V4PageScaffold( + body: Column( + children: [ + BeePageHeader( + title: l.githubCommunityTitle, + leading: const BackButton(), + actions: [ + if (state.isBound) + BeeIconButton( + key: const ValueKey('github-refresh-btn'), + label: l.githubRefreshAction, + icon: state.loading + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const BeeLineIcon('RefreshCw', size: 19), + onPressed: state.loading + ? null + : () async { + final ok = await ref + .read(githubCommunityProvider.notifier) + .refresh(); + if (ok && context.mounted) { + showBeeToast(context, l.githubRefreshSuccess, + tone: BeeTone.success); + } + }, + ), + ], + ), + Expanded( + child: ListView( + padding: EdgeInsets.fromLTRB( + 17, + 8, + 17, + MediaQuery.paddingOf(context).bottom + 24, + ), + children: [ + if (!state.isBound) + _buildBindSection( + context, + l, + state, + showUpdateBoost: showUpdateBoost, + ) + else ...[ + _buildPassportCard( + context, + l, + state.profile!, + state.prefs, + showUpdateBoost: showUpdateBoost, + ), + const SizedBox(height: 14), + _buildContributionCard(context, l, state.profile!, locale), + const SizedBox(height: 14), + _buildDonationCard( + context, + l, + state.profile!, + allowExternalDonorForm: !platform.isIOS, + ), + const SizedBox(height: 14), + _buildRewardsCard(context, l, state), + const SizedBox(height: 14), + _buildTokenManageCard(context, l, state), + ], + if (state.errorKind != GitHubCommunityErrorKind.none && + !state.loading) ...[ + const SizedBox(height: 12), + BeeSurface( + child: Row( + children: [ + Icon(Icons.error_outline, + size: 18, color: colors.error), + const SizedBox(width: 8), + Expanded( + child: Text( + _errorMessage(l, state), + style: TextStyle( + fontSize: 12.5, + color: colors.error, + height: 1.45, + ), + ), + ), + ], + ), + ), + ], + ], + ), + ), + ], + ), + ); + } + + Widget _buildBindSection( + BuildContext context, + AppLocalizations l, + GitHubCommunityState state, { + required bool showUpdateBoost, + }) { + final theme = Theme.of(context); + final hint = theme.hintColor; + final invalid = state.tokenInvalid && state.hasToken; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + BeeSurface( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + invalid + ? l.githubTokenExpiredTitle + : l.githubTokenSetupTitle, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w600, + ), + ), + ), + if (showUpdateBoost) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: (invalid + ? theme.colorScheme.error + : const Color(0xFFD97706)) + .withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + invalid ? l.githubTokenExpiredTag : l.githubQuotaAnonTag, + style: TextStyle( + fontSize: 10.5, + fontWeight: FontWeight.w600, + color: invalid + ? theme.colorScheme.error + : const Color(0xFFD97706), + ), + ), + ), + ], + ), + const SizedBox(height: 8), + Text( + invalid + ? l.githubTokenExpiredDesc(state.maskedToken) + : (showUpdateBoost + ? l.githubTokenSetupDescWithUpdate + : l.githubTokenSetupDescCommunityOnly), + style: TextStyle(fontSize: 12.5, height: 1.55, color: hint), + ), + const SizedBox(height: 14), + BeeField( + key: const ValueKey('github-token-input'), + controller: _tokenController, + label: l.githubTokenInputLabel, + hint: 'ghp_... / github_pat_...', + obscure: _obscureToken, + textInputAction: TextInputAction.done, + onSubmitted: (_) => _submitToken(), + suffixIcon: IconButton( + onPressed: () => + setState(() => _obscureToken = !_obscureToken), + icon: Icon( + _obscureToken + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + size: 18, + ), + ), + ), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: BeeButton( + key: const ValueKey('github-token-verify-btn'), + label: state.loading + ? l.githubTokenVerifying + : l.githubTokenVerifyAndSave, + onPressed: state.loading ? null : _submitToken, + ), + ), + const SizedBox(width: 8), + BeeButton( + key: const ValueKey('github-token-create-btn'), + label: l.githubTokenCreateAction, + kind: BeeButtonKind.secondary, + onPressed: () => _openUrl(_createTokenUrl), + ), + ], + ), + if (invalid) ...[ + const SizedBox(height: 8), + BeeButton( + label: l.githubUnbindConfirm, + kind: BeeButtonKind.quiet, + onPressed: state.loading ? null : _confirmUnbind, + ), + ], + const SizedBox(height: 10), + Text( + l.githubTokenSecurityNote, + style: TextStyle(fontSize: 11.5, height: 1.5, color: hint), + ), + ], + ), + ), + const SizedBox(height: 14), + BeeSurface( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + l.githubBenefitsTitle, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w600, + ), + ), + ), + TextButton( + key: const ValueKey('github-honor-tiers-btn-unbound'), + onPressed: () => showCommunityHonorTiersSheet(context), + style: TextButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 8, vertical: 2), + minimumSize: Size.zero, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + child: Text( + l.githubHonorTiersAction, + style: const TextStyle(fontSize: 12.5), + ), + ), + ], + ), + const SizedBox(height: 10), + if (showUpdateBoost) + _BenefitLine( + icon: 'Zap', + title: l.githubBenefitQuotaTitle, + trailing: '60 → 5,000 / h', + ), + _BenefitLine( + icon: 'GitMerge', + title: l.githubBenefitReposTitle, + trailing: l.githubBenefitReposValue, + ), + _BenefitLine( + icon: 'Heart', + title: l.githubBenefitDonationTitle, + trailing: l.githubBenefitDonationValue, + ), + _BenefitLine( + icon: 'Sparkles', + title: l.githubBenefitRewardsTitle, + trailing: l.githubBenefitRewardsValue, + ), + ], + ), + ), + ], + ); + } + + Widget _buildPassportCard( + BuildContext context, + AppLocalizations l, + GitHubCommunityProfile profile, + GitHubRewardPreferences prefs, { + required bool showUpdateBoost, + }) { + final theme = Theme.of(context); + final hint = theme.hintColor; + final rate = profile.rateLimit; + final name = (profile.displayName?.isNotEmpty == true) + ? profile.displayName! + : profile.login; + + return BeeSurface( + key: const ValueKey('github-passport-card'), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + CommunityAvatarHalo( + tier: profile.primaryTier, + size: 48, + enabled: prefs.showHaloAndBadge, + avatar: CommunityGitHubAvatar( + profile: profile, + size: 48, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 6, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + name, + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.w700, + ), + ), + CommunityHonorBadge( + tier: profile.primaryTier, + onTap: () => showCommunityHonorTiersSheet( + context, + profile: profile, + ), + ), + ], + ), + const SizedBox(height: 3), + Row( + children: [ + Expanded( + child: Text( + '@${profile.login} · ${profile.starredMainRepo ? l.githubStarredMain : l.githubNotStarredMain}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 12, color: hint), + ), + ), + const SizedBox(width: 6), + GestureDetector( + key: const ValueKey('github-honor-tiers-btn'), + onTap: () => showCommunityHonorTiersSheet( + context, + profile: profile, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + l.githubHonorTiersAction, + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w600, + color: theme.colorScheme.primary, + ), + ), + Icon( + Icons.chevron_right_rounded, + size: 15, + color: theme.colorScheme.primary, + ), + ], + ), + ), + ], + ), + ], + ), + ), + ], + ), + if (rate != null && showUpdateBoost) ...[ + const SizedBox(height: 14), + const BeeDivider(height: 0.6), + const SizedBox(height: 11), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + l.githubApiQuotaLabel, + style: TextStyle(fontSize: 12, color: hint), + ), + Text( + '${rate.remaining} / ${rate.limit}', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: rate.remaining > 100 + ? const Color(0xFF16A34A) + : theme.colorScheme.error, + ), + ), + ], + ), + const SizedBox(height: 6), + ClipRRect( + borderRadius: BorderRadius.circular(99), + child: LinearProgressIndicator( + value: rate.ratio, + minHeight: 6, + backgroundColor: BeeCardTheme.of(context).soft, + color: rate.remaining > 100 + ? const Color(0xFF16A34A) + : theme.colorScheme.error, + ), + ), + ], + ], + ), + ); + } + + Widget _buildContributionCard( + BuildContext context, + AppLocalizations l, + GitHubCommunityProfile profile, + Locale locale, + ) { + final hint = Theme.of(context).hintColor; + final activeRepos = profile.nonEmptyContributions; + final repoByName = {for (final r in kBeeCountEcosystemRepos) r.name: r}; + + return BeeSurface( + key: const ValueKey('github-contributions-card'), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + l.githubContributionsTitle, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w600, + ), + ), + ), + Text( + l.githubReposCoverage( + activeRepos.length, + kBeeCountEcosystemRepos.length, + ), + style: TextStyle(fontSize: 11.5, color: hint), + ), + ], + ), + const SizedBox(height: 12), + Row( + children: [ + Expanded( + child: _StatTile( + value: '${profile.totalCommits}', + label: l.githubStatCommits, + ), + ), + const SizedBox(width: 8), + Expanded( + child: _StatTile( + value: '${profile.totalMergedPrs}', + label: l.githubStatMergedPrs, + ), + ), + const SizedBox(width: 8), + Expanded( + child: _StatTile( + value: '${profile.totalIssues}', + label: l.githubStatIssues, + ), + ), + ], + ), + if (activeRepos.isNotEmpty) ...[ + const SizedBox(height: 12), + for (var i = 0; i < activeRepos.length; i++) ...[ + if (i > 0) const BeeDivider(height: 0.6), + Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'TNT-Likely/${activeRepos[i].repo}', + style: const TextStyle( + fontSize: 12.5, + fontWeight: FontWeight.w600, + ), + ), + if (repoByName[activeRepos[i].repo] != null) + Text( + _repoRole( + repoByName[activeRepos[i].repo]!, locale), + style: TextStyle(fontSize: 11, color: hint), + ), + ], + ), + ), + const SizedBox(width: 8), + Text( + [ + if (activeRepos[i].commits > 0) + '${activeRepos[i].commits} commits', + if (activeRepos[i].mergedPrs > 0) + '${activeRepos[i].mergedPrs} PR', + if (activeRepos[i].issues > 0) + '${activeRepos[i].issues} Issue', + ].join(' · '), + style: TextStyle(fontSize: 11.5, color: hint), + ), + ], + ), + ), + ], + ] else ...[ + const SizedBox(height: 10), + Text( + l.githubContributionsEmpty, + style: TextStyle(fontSize: 12, color: hint, height: 1.5), + ), + ], + ], + ), + ); + } + + Widget _buildDonationCard( + BuildContext context, + AppLocalizations l, + GitHubCommunityProfile profile, { + required bool allowExternalDonorForm, + }) { + final hint = Theme.of(context).hintColor; + final donation = profile.donation; + final hasDonorRecord = donation != null && donation.amountCny > 0; + + return BeeSurface( + key: const ValueKey('github-donation-card'), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + l.githubDonationTitle, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w600, + ), + ), + ), + if (profile.hasDonationHonor) + CommunityHonorBadge( + tier: profile.isMaintainer && !hasDonorRecord + ? GitHubHonorTier.coCreator + : profile.donationTier, + compact: true, + ), + ], + ), + const SizedBox(height: 8), + if (hasDonorRecord) ...[ + Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + '¥${donation.amountCny == donation.amountCny.roundToDouble() ? donation.amountCny.toInt() : donation.amountCny.toStringAsFixed(2)}', + style: const TextStyle( + fontSize: 22, + fontWeight: FontWeight.w700, + color: Color(0xFFD97706), + ), + ), + const SizedBox(width: 8), + Text( + l.githubDonationVerified, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Color(0xFF16A34A), + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + l.githubDonationThanks, + style: TextStyle(fontSize: 12, color: hint, height: 1.5), + ), + ] else if (profile.isMaintainer) ...[ + Text( + l.githubMaintainerHonorNote, + style: TextStyle(fontSize: 12.5, color: hint, height: 1.5), + ), + ] else ...[ + Text( + l.githubDonationNotFound(profile.login), + style: TextStyle(fontSize: 12, color: hint, height: 1.5), + ), + if (allowExternalDonorForm) ...[ + const SizedBox(height: 10), + Align( + alignment: Alignment.centerLeft, + child: BeeButton( + label: l.githubDonationRegisterAction, + kind: BeeButtonKind.secondary, + onPressed: () => _openUrl(_donationIssueUrl), + ), + ), + ], + ], + ], + ), + ); + } + + Widget _buildRewardsCard( + BuildContext context, + AppLocalizations l, + GitHubCommunityState state, + ) { + final profile = state.profile!; + final notifier = ref.read(githubCommunityProvider.notifier); + final skinsEnabled = ref.watch(headerSkinsEnabledProvider); + final unlockedCount = profile.unlockedCommunitySkinIds.length; + + return BeeSurface( + key: const ValueKey('github-rewards-card'), + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(10, 4, 10, 6), + child: Row( + children: [ + Expanded( + child: Text( + l.githubRewardsTitle, + style: const TextStyle( + fontSize: 14.5, + fontWeight: FontWeight.w600, + ), + ), + ), + if (skinsEnabled && unlockedCount > 0) + TextButton( + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => const HeaderSkinPage(), + ), + ), + child: Text(l.githubRewardsOpenSkins(unlockedCount)), + ), + ], + ), + ), + BeeToggleRow( + title: l.githubRewardHaloTitle, + subtitle: l.githubRewardHaloDesc, + leading: const BeeLineIcon('Award', size: 19), + value: state.prefs.showHaloAndBadge, + onChanged: (v) => notifier.updatePreferences(showHaloAndBadge: v), + ), + const BeeDivider(inset: 12, height: 0.6), + BeeToggleRow( + title: l.githubRewardGreetingTitle, + subtitle: l.githubRewardGreetingDesc, + leading: const BeeLineIcon('Sparkles', size: 19), + value: state.prefs.showCustomGreeting, + onChanged: (v) => + notifier.updatePreferences(showCustomGreeting: v), + ), + if (profile.hasPosterChopHonor) ...[ + const BeeDivider(inset: 12, height: 0.6), + BeeToggleRow( + title: l.githubRewardPosterChopTitle, + subtitle: l.githubRewardPosterChopDesc, + leading: const BeeLineIcon('Bookmark', size: 19), + value: state.prefs.showPosterStamp, + onChanged: (v) => notifier.updatePreferences(showPosterStamp: v), + ), + if (state.prefs.showPosterStamp) + Padding( + padding: const EdgeInsets.fromLTRB(12, 4, 12, 10), + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: const Color(0xFFFFFEFA), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: const Color(0xFFE8E7DD)), + ), + child: Row( + children: [ + Expanded( + child: Text( + l.githubRewardPosterChopPreview, + style: const TextStyle( + fontSize: 11.5, + color: Color(0xFF8C8D88), + ), + ), + ), + CommunityPosterChop(profile: profile, scale: 0.56), + ], + ), + ), + ), + ], + ], + ), + ); + } + + Widget _buildTokenManageCard( + BuildContext context, + AppLocalizations l, + GitHubCommunityState state, + ) { + final hint = Theme.of(context).hintColor; + return BeeSurface( + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + l.githubCurrentTokenLabel, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + ), + ), + const SizedBox(height: 3), + Text( + state.maskedToken, + style: TextStyle( + fontSize: 12, + fontFamily: 'monospace', + color: hint, + ), + ), + ], + ), + ), + TextButton( + key: const ValueKey('github-unbind-btn'), + onPressed: state.loading ? null : _confirmUnbind, + child: Text( + l.githubUnbindAction, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ), + ], + ), + ); + } +} + +class _StatTile extends StatelessWidget { + const _StatTile({required this.value, required this.label}); + final String value; + final String label; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 6), + decoration: BoxDecoration( + color: BeeCardTheme.of(context).soft, + borderRadius: BorderRadius.circular(12), + ), + child: Column( + children: [ + Text( + value, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700), + ), + const SizedBox(height: 2), + Text( + label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11, color: Theme.of(context).hintColor), + ), + ], + ), + ); + } +} + +class _BenefitLine extends StatelessWidget { + const _BenefitLine({ + required this.icon, + required this.title, + required this.trailing, + }); + + final String icon; + final String title; + final String trailing; + + @override + Widget build(BuildContext context) { + final hint = Theme.of(context).hintColor; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 5), + child: Row( + children: [ + BeeLineIcon(icon, size: 16, color: hint), + const SizedBox(width: 8), + Expanded( + child: Text(title, style: const TextStyle(fontSize: 12.5)), + ), + Text( + trailing, + style: TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w600, + color: hint, + ), + ), + ], + ), + ); + } +} diff --git a/lib/pages/settings/header_skin_page.dart b/lib/pages/settings/header_skin_page.dart index 54d1595be..2a7e2f352 100644 --- a/lib/pages/settings/header_skin_page.dart +++ b/lib/pages/settings/header_skin_page.dart @@ -6,6 +6,7 @@ import 'package:visibility_detector/visibility_detector.dart'; import '../../l10n/app_localizations.dart'; import '../../providers/feature_highlight_providers.dart'; +import '../../providers/github_community_provider.dart'; import '../../providers/theme_providers.dart'; import '../../skins/premium_skins.dart'; import '../../styles/header_skins.dart'; @@ -60,11 +61,16 @@ class _HeaderSkinPageState extends ConsumerState { } final active = activeSkinId(ref.watch(headerSkinProvider), runtime); final primary = ref.watch(primaryColorProvider); + final community = ref.watch(githubCommunityProvider); final collections = _filter == HeaderSkinFilter.static_ ? const [] : runtime.collections.where((pack) => pack.skins.isNotEmpty); - Widget grid(Iterable items, {bool locked = false}) => + Widget grid( + Iterable items, { + bool locked = false, + bool Function(String id)? isItemLocked, + }) => LayoutBuilder(builder: (_, bounds) { final width = (bounds.maxWidth - 10) / 2; return Wrap(spacing: 10, runSpacing: 10, children: [ @@ -76,7 +82,7 @@ class _HeaderSkinPageState extends ConsumerState { key: ValueKey('skin-card-${item.id}'), item: item, selected: item.id == active, - locked: locked, + locked: isItemLocked?.call(item.id) ?? locked, onTap: () => showSkinEditor(context, item.id, editingActive: item.id == active), ), @@ -84,12 +90,16 @@ class _HeaderSkinPageState extends ConsumerState { ]); }); - Widget freeGroup(String title, Iterable ids) => Column( + Widget freeGroup(String title, Iterable ids, + {bool Function(String id)? isItemLocked}) => + Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ BeeSectionLabel(title), grid( - ids.map((id) => skinChoice(context, id: id, primary: primary))), + ids.map((id) => skinChoice(context, id: id, primary: primary)), + isItemLocked: isItemLocked, + ), const SizedBox(height: 16), ], ); @@ -166,8 +176,13 @@ class _HeaderSkinPageState extends ConsumerState { freeGroup(l.headerSkinGroupBasic, const [kHeaderSkinNone]), for (final group in kHeaderSkinGroupOrder) ...[ if (_freeInGroup(group).isNotEmpty) - freeGroup(skinGroupLabel(l, group), - _freeInGroup(group).map((skin) => skin.id)), + freeGroup( + skinGroupLabel(l, group), + _freeInGroup(group).map((skin) => skin.id), + isItemLocked: group == HeaderSkinGroup.community + ? (id) => !community.isCommunitySkinUnlocked(id) + : null, + ), if (group == HeaderSkinGroup.anniversary) for (final pack in collections) paidGroup(pack), ], @@ -208,7 +223,9 @@ class _SkinTile extends StatelessWidget { ].join(' · '); Widget badge(String title) => DecoratedBox( decoration: BoxDecoration( - color: card.soft.withValues(alpha: 1), + // 整页皮肤启用时 soft 是半透明白(暗色 6%),直接拉满 alpha 会变成 + // 纯白底配白字。先合成到不透明卡片底色上,无皮肤时 soft 本身不透明、结果不变。 + color: Color.alphaBlend(card.soft, card.overlay), borderRadius: BorderRadius.circular(7)), child: Padding( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3), diff --git a/lib/pages/settings/support/bindings/support_platform.dart b/lib/pages/settings/support/bindings/support_platform.dart index d0c475934..55b4a1c0b 100644 --- a/lib/pages/settings/support/bindings/support_platform.dart +++ b/lib/pages/settings/support/bindings/support_platform.dart @@ -60,9 +60,12 @@ class SupportPlatform { Future checkUpdate(BuildContext context, {required void Function(bool) setLoading, - required void Function(double, String) setProgress}) => + required void Function(double, String) setProgress, + VoidCallback? onConfigureGitHubToken}) => UpdateService.checkUpdateWithUI(context, - setLoading: setLoading, setProgress: setProgress); + setLoading: setLoading, + setProgress: setProgress, + onConfigureGitHubToken: onConfigureGitHubToken); Future product( BuildContext context, ProductPromo info, ProductPromoTexts texts) => ProductPromoLauncher.open(context, info, texts); diff --git a/lib/pages/shared/sharing/bindings/app_promo_poster.dart b/lib/pages/shared/sharing/bindings/app_promo_poster.dart index 7fc07f186..01a0596d5 100644 --- a/lib/pages/shared/sharing/bindings/app_promo_poster.dart +++ b/lib/pages/shared/sharing/bindings/app_promo_poster.dart @@ -5,15 +5,20 @@ import 'poster_projection.dart'; class AppPromoPoster extends StatelessWidget { const AppPromoPoster( - {super.key, required this.l10n, required this.primaryColor}); + {super.key, + required this.l10n, + required this.primaryColor, + this.communityMark}); final AppLocalizations l10n; final Color primaryColor; + final Widget? communityMark; @override Widget build(BuildContext context) => MediaQuery.withNoTextScaling( child: BeeAppSharePoster( header: posterHeader(l10n, primaryColor, 'OPEN SOURCE · BEECOUNT'), footer: posterFooter(l10n, qr: false), + communityMark: communityMark, title: l10n.sharePosterSlogan.replaceFirst(',', ',\n'), accent: primaryColor, invitation: l10n.v4SharePosterPromoInvite, diff --git a/lib/pages/shared/sharing/bindings/ledger_summary_poster.dart b/lib/pages/shared/sharing/bindings/ledger_summary_poster.dart index 798def5ac..fd3c2ecb8 100644 --- a/lib/pages/shared/sharing/bindings/ledger_summary_poster.dart +++ b/lib/pages/shared/sharing/bindings/ledger_summary_poster.dart @@ -11,11 +11,13 @@ class LedgerSummaryPoster extends StatelessWidget { required this.data, required this.primaryColor, this.hideIncome = false, - this.currencyCode = 'CNY'}); + this.currencyCode = 'CNY', + this.communityMark}); final LedgerSummaryPosterData data; final Color primaryColor; final bool hideIncome; final String currencyCode; + final Widget? communityMark; @override Widget build(BuildContext context) { final l = AppLocalizations.of(context); @@ -25,6 +27,7 @@ class LedgerSummaryPoster extends StatelessWidget { child: BeeFinancialSharePoster( header: posterHeader(l, primaryColor, 'OUR SHARED DAYS'), footer: posterFooter(l), + communityMark: communityMark, title: data.ledgerName, subtitle: l.sharePosterLedgerTitle, titleIcon: const Icon(Icons.menu_book_outlined), diff --git a/lib/pages/shared/sharing/bindings/month_summary_poster.dart b/lib/pages/shared/sharing/bindings/month_summary_poster.dart index 8f1c3f500..a6e565ff7 100644 --- a/lib/pages/shared/sharing/bindings/month_summary_poster.dart +++ b/lib/pages/shared/sharing/bindings/month_summary_poster.dart @@ -11,11 +11,13 @@ class MonthSummaryPoster extends StatelessWidget { required this.data, required this.primaryColor, this.hideIncome = false, - this.currencyCode = 'CNY'}); + this.currencyCode = 'CNY', + this.communityMark}); final MonthSummaryPosterData data; final Color primaryColor; final bool hideIncome; final String currencyCode; + final Widget? communityMark; @override Widget build(BuildContext context) { final l = AppLocalizations.of(context); @@ -26,6 +28,7 @@ class MonthSummaryPoster extends StatelessWidget { child: BeeFinancialSharePoster( header: posterHeader(l, primaryColor, 'MONTH IN REVIEW'), footer: posterFooter(l), + communityMark: communityMark, title: DateFormat.yMMMM(l.localeName) .format(DateTime(data.year, data.month)), subtitle: l.sharePosterMonthSubtitle, diff --git a/lib/pages/shared/sharing/bindings/user_profile_poster.dart b/lib/pages/shared/sharing/bindings/user_profile_poster.dart index f0775ca4f..ff1d33f3c 100644 --- a/lib/pages/shared/sharing/bindings/user_profile_poster.dart +++ b/lib/pages/shared/sharing/bindings/user_profile_poster.dart @@ -13,10 +13,12 @@ class UserProfilePoster extends StatelessWidget { {super.key, required this.data, required this.l10n, - required this.primaryColor}); + required this.primaryColor, + this.communityMark}); final UserProfilePosterData data; final AppLocalizations l10n; final Color primaryColor; + final Widget? communityMark; String get journey => data.recordDays >= 730 ? l10n.userProfileJourneyYears((data.recordDays / 365).floor()) : data.recordDays >= 365 @@ -39,6 +41,7 @@ class UserProfilePoster extends StatelessWidget { header: posterHeader(l10n, primaryColor, 'MY DAILY NOTES'), footer: posterFooter(l10n, campaign: 'user_profile'), accent: primaryColor, + communityMark: communityMark, eyebrow: l10n.v4SharePosterProfileEyebrow, title: data.ledgerName, avatar: data.avatarPath == null diff --git a/lib/pages/shared/sharing/bindings/year_summary_poster.dart b/lib/pages/shared/sharing/bindings/year_summary_poster.dart index 0ca2fbad3..ff15c81a7 100644 --- a/lib/pages/shared/sharing/bindings/year_summary_poster.dart +++ b/lib/pages/shared/sharing/bindings/year_summary_poster.dart @@ -11,11 +11,13 @@ class YearSummaryPoster extends StatelessWidget { required this.data, required this.primaryColor, this.hideIncome = false, - this.currencyCode = 'CNY'}); + this.currencyCode = 'CNY', + this.communityMark}); final YearSummaryPosterData data; final Color primaryColor; final bool hideIncome; final String currencyCode; + final Widget? communityMark; @override Widget build(BuildContext context) { final l = AppLocalizations.of(context); @@ -25,6 +27,7 @@ class YearSummaryPoster extends StatelessWidget { child: BeeFinancialSharePoster( header: posterHeader(l, primaryColor, 'YEAR IN REVIEW'), footer: posterFooter(l), + communityMark: communityMark, title: '${data.year}', subtitle: l.sharePosterYearSubtitle, year: true, diff --git a/lib/pages/shared/widgets/community_honor_widgets.dart b/lib/pages/shared/widgets/community_honor_widgets.dart new file mode 100644 index 000000000..193544d7d --- /dev/null +++ b/lib/pages/shared/widgets/community_honor_widgets.dart @@ -0,0 +1,912 @@ +import 'dart:math' as math; +import 'package:beecount_ui/beecount_ui.dart'; +import 'package:flutter/material.dart'; +import '../../../l10n/app_localizations.dart'; +import '../../../services/github/github_community_models.dart'; + +/// 荣誉等级文案本地化。 +String communityTierTitle(AppLocalizations l, GitHubHonorTier tier) => + switch (tier) { + GitHubHonorTier.coCreator => l.githubTierCoCreator, + GitHubHonorTier.coreContributor => l.githubTierCoreContributor, + GitHubHonorTier.builder => l.githubTierBuilder, + GitHubHonorTier.hiveGuardian => l.githubTierHiveGuardian, + GitHubHonorTier.goldPatron => l.githubTierGoldPatron, + GitHubHonorTier.supporter => l.githubTierSupporter, + GitHubHonorTier.stargazer => l.githubTierStargazer, + GitHubHonorTier.none => '', + }; + +/// 荣誉副标题(我的页致谢问候语)。 +String communityGreetingSubtitle( + AppLocalizations l, GitHubCommunityProfile profile) { + if (profile.isMaintainer) { + return l.githubGreetingMaintainer(profile.login); + } + if (profile.isCoCreator) { + return l.githubGreetingCoCreator( + profile.totalCommits, + _formatYuan(profile.donation?.amountCny ?? 0), + ); + } + if (profile.hasCodeHonor) { + return l.githubGreetingContributor( + profile.totalCommits, profile.totalMergedPrs); + } + if (profile.hasDonationHonor) { + return l.githubGreetingSupporter( + communityTierTitle(l, profile.donationTier)); + } + return l.githubGreetingStargazer; +} + +String _formatYuan(double amount) { + if (amount == amount.roundToDouble()) return amount.toInt().toString(); + return amount.toStringAsFixed(2); +} + +IconData communityTierIcon(GitHubHonorTier tier) => switch (tier) { + GitHubHonorTier.coCreator => Icons.workspace_premium_rounded, + GitHubHonorTier.coreContributor => Icons.bolt_rounded, + GitHubHonorTier.builder => Icons.code_rounded, + GitHubHonorTier.hiveGuardian => Icons.shield_rounded, + GitHubHonorTier.goldPatron => Icons.favorite_rounded, + GitHubHonorTier.supporter => Icons.local_cafe_rounded, + GitHubHonorTier.stargazer => Icons.star_rounded, + GitHubHonorTier.none => Icons.person_outline_rounded, + }; + +/// 专属等级图标(最高级「蜂巢共创者」使用手绘三峰皇冠,清晰区别于其余等级)。 +class CommunityTierGlyph extends StatelessWidget { + const CommunityTierGlyph({ + super.key, + required this.tier, + required this.size, + required this.color, + }); + + final GitHubHonorTier tier; + final double size; + final Color color; + + @override + Widget build(BuildContext context) { + if (tier == GitHubHonorTier.coCreator) { + return SizedBox( + width: size, + height: size, + child: CustomPaint(painter: _CrownGlyphPainter(color)), + ); + } + return Icon(communityTierIcon(tier), size: size, color: color); + } +} + +class _CrownGlyphPainter extends CustomPainter { + const _CrownGlyphPainter(this.color); + final Color color; + + @override + void paint(Canvas canvas, Size size) { + final w = size.width; + final h = size.height; + final crown = Path() + ..moveTo(w * 0.10, h * 0.78) + ..lineTo(w * 0.06, h * 0.34) + ..lineTo(w * 0.30, h * 0.54) + ..lineTo(w * 0.50, h * 0.22) + ..lineTo(w * 0.70, h * 0.54) + ..lineTo(w * 0.94, h * 0.34) + ..lineTo(w * 0.90, h * 0.78) + ..close(); + canvas.drawPath(crown, Paint()..color = color); + // 底座横条 + canvas.drawRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH(w * 0.12, h * 0.80, w * 0.76, h * 0.11), + Radius.circular(h * 0.05), + ), + Paint()..color = color, + ); + // 三峰微珠 + for (final (fx, fy) in const [(0.07, 0.28), (0.50, 0.16), (0.93, 0.28)]) { + canvas.drawCircle(Offset(w * fx, h * fy), w * 0.06, Paint()..color = color); + } + } + + @override + bool shouldRepaint(covariant _CrownGlyphPainter old) => old.color != color; +} + +/// 社区护照卡与关于页共用的真实 GitHub 头像(无网或测试环境优雅回退首字母)。 +class CommunityGitHubAvatar extends StatelessWidget { + const CommunityGitHubAvatar({ + super.key, + required this.profile, + this.size = 48, + }); + + final GitHubCommunityProfile profile; + final double size; + + static String? resolvedUrlFor(GitHubCommunityProfile profile) { + final explicit = profile.avatarUrl?.trim(); + if (explicit != null && explicit.isNotEmpty) return explicit; + final login = profile.login.trim(); + if (login.isEmpty) return null; + return 'https://github.com/${Uri.encodeComponent(login)}.png?size=160'; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final display = (profile.displayName?.isNotEmpty == true) + ? profile.displayName! + : profile.login; + final initial = + display.isNotEmpty ? display.characters.first.toUpperCase() : 'B'; + final fallback = Container( + width: size, + height: size, + color: theme.colorScheme.primary.withValues(alpha: 0.18), + alignment: Alignment.center, + child: Text( + initial, + style: TextStyle( + fontSize: size * 0.40, + fontWeight: FontWeight.w700, + color: theme.colorScheme.onSurface, + ), + ), + ); + + final url = resolvedUrlFor(profile); + if (url == null) return fallback; + + return Image.network( + url, + width: size, + height: size, + fit: BoxFit.cover, + gaplessPlayback: true, + frameBuilder: (context, child, frame, wasSync) { + if (wasSync || frame != null) return child; + return fallback; + }, + errorBuilder: (_, __, ___) => fallback, + ); + } +} + +/// 荣誉胶囊徽章(用于「我的」页昵称旁、关于页护照卡与社区详情页)。 +class CommunityHonorBadge extends StatelessWidget { + const CommunityHonorBadge({ + super.key, + required this.tier, + this.compact = false, + this.onTap, + }); + + final GitHubHonorTier tier; + final bool compact; + final VoidCallback? onTap; + + @override + Widget build(BuildContext context) { + if (tier == GitHubHonorTier.none) return const SizedBox.shrink(); + final l = AppLocalizations.of(context); + final dark = Theme.of(context).brightness == Brightness.dark; + final palette = _badgePalette(tier, dark); + + final badge = Container( + padding: EdgeInsets.symmetric( + horizontal: compact ? 7 : 9, + vertical: compact ? 2 : 3, + ), + decoration: BoxDecoration( + gradient: palette.gradient, + color: palette.gradient == null ? palette.bg : null, + borderRadius: BorderRadius.circular(999), + border: Border.all(color: palette.border, width: 0.9), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + CommunityTierGlyph( + tier: tier, + size: compact ? 11.5 : 13, + color: palette.icon, + ), + const SizedBox(width: 4), + Text( + communityTierTitle(l, tier), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: TextStyle( + fontSize: compact ? 10 : 11, + fontWeight: FontWeight.w600, + height: 1.25, + color: palette.fg, + ), + ), + ], + ), + ); + + if (onTap == null) return badge; + return GestureDetector(onTap: onTap, child: badge); + } +} + +/// 头像外圈荣誉光环 + 右下角微型角标(不裁切外圈光环,内部圆裁头像)。 +class CommunityAvatarHalo extends StatelessWidget { + const CommunityAvatarHalo({ + super.key, + required this.tier, + required this.avatar, + this.size = 48, + this.enabled = true, + }); + + final GitHubHonorTier tier; + final Widget avatar; + final double size; + final bool enabled; + + @override + Widget build(BuildContext context) { + final active = enabled && tier != GitHubHonorTier.none; + if (!active) { + return SizedBox( + width: size, + height: size, + child: ClipOval(child: avatar), + ); + } + final dark = Theme.of(context).brightness == Brightness.dark; + final ringPadding = tier == GitHubHonorTier.coCreator + ? 4.8 + : (tier == GitHubHonorTier.hiveGuardian ? 4.5 : 3.5); + final total = size + ringPadding * 2; + final dotSize = (size * 0.36).clamp(15.0, 20.0); + final palette = _badgePalette(tier, dark); + + return SizedBox( + width: total, + height: total, + child: Stack( + clipBehavior: Clip.none, + alignment: Alignment.center, + children: [ + Positioned.fill( + child: CustomPaint( + painter: _AvatarHaloRingPainter(tier: tier, dark: dark), + ), + ), + SizedBox( + width: size, + height: size, + child: ClipOval(child: avatar), + ), + Positioned( + right: -1, + bottom: -1, + child: Container( + width: dotSize, + height: dotSize, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: dark ? const Color(0xFF1E242C) : Colors.white, + border: Border.all( + color: tier == GitHubHonorTier.coCreator + ? const Color(0xFFF8C91C).withValues(alpha: 0.72) + : (dark + ? Colors.white.withValues(alpha: 0.18) + : Colors.black.withValues(alpha: 0.08)), + width: 1.2, + ), + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: dark ? 0.35 : 0.14), + blurRadius: 4, + offset: const Offset(0, 1), + ), + ], + ), + alignment: Alignment.center, + child: CommunityTierGlyph( + tier: tier, + size: dotSize * 0.60, + color: palette.icon, + ), + ), + ), + ], + ), + ); + } +} + +class _AvatarHaloRingPainter extends CustomPainter { + const _AvatarHaloRingPainter({required this.tier, required this.dark}); + + final GitHubHonorTier tier; + final bool dark; + + @override + void paint(Canvas canvas, Size size) { + final center = Offset(size.width / 2, size.height / 2); + final radius = math.min(size.width, size.height) / 2 - 1.5; + + if (tier == GitHubHonorTier.stargazer) { + final paint = Paint() + ..color = (dark ? const Color(0xFF94A3B8) : const Color(0xFF64748B)) + .withValues(alpha: 0.72) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.6; + const dashes = 18; + const step = (math.pi * 2) / dashes; + for (var i = 0; i < dashes; i++) { + canvas.drawArc( + Rect.fromCircle(center: center, radius: radius), + i * step, + step * 0.56, + false, + paint, + ); + } + return; + } + + final colors = switch (tier) { + GitHubHonorTier.coCreator => const [ + Color(0xFFF8C91C), + Color(0xFFD97706), + Color(0xFF2E7D78), + Color(0xFF5FB4AD), + Color(0xFF3B5284), + Color(0xFFF8C91C), + ], + GitHubHonorTier.coreContributor => const [ + Color(0xFF2E7D78), + Color(0xFF5FB4AD), + Color(0xFF3B5284), + Color(0xFF7C96D6), + Color(0xFF2E7D78), + ], + GitHubHonorTier.builder => const [ + Color(0xFF2E7D78), + Color(0xFF67B8B0), + Color(0xFF2E7D78), + ], + GitHubHonorTier.hiveGuardian => const [ + Color(0xFFB86B11), + Color(0xFFF8C91C), + Color(0xFFFFF3C4), + Color(0xFFD97706), + Color(0xFFB86B11), + ], + GitHubHonorTier.goldPatron => const [ + Color(0xFFC87A19), + Color(0xFFF8C91C), + Color(0xFFFDE68A), + Color(0xFFB45309), + Color(0xFFC87A19), + ], + GitHubHonorTier.supporter => const [ + Color(0xFFE5B869), + Color(0xFFF3D598), + Color(0xFFC87A19), + Color(0xFFE5B869), + ], + _ => const [Color(0xFFF8C91C), Color(0xFFF8C91C)], + }; + + final strokeWidth = switch (tier) { + GitHubHonorTier.coCreator => 3.0, + GitHubHonorTier.coreContributor || GitHubHonorTier.goldPatron => 2.6, + GitHubHonorTier.hiveGuardian => 2.2, + _ => 2.0, + }; + + final rect = Rect.fromCircle(center: center, radius: radius); + final paint = Paint() + ..shader = SweepGradient(colors: colors).createShader(rect) + ..style = PaintingStyle.stroke + ..strokeWidth = strokeWidth; + canvas.drawCircle(center, radius, paint); + + // 蜂巢守护者与蜂巢共创者额外增加外圈极细金丝线,突出最高级尊荣质感 + if (tier == GitHubHonorTier.hiveGuardian || + tier == GitHubHonorTier.coCreator) { + final outer = Paint() + ..color = const Color(0xFFF8C91C).withValues(alpha: dark ? 0.72 : 0.62) + ..style = PaintingStyle.stroke + ..strokeWidth = 0.95; + canvas.drawCircle(center, radius + 1.5, outer); + } + } + + @override + bool shouldRepaint(covariant _AvatarHaloRingPainter old) => + old.tier != tier || old.dark != dark; +} + +class _BadgePalette { + const _BadgePalette({ + required this.fg, + required this.icon, + required this.border, + this.bg, + this.gradient, + }); + + final Color fg; + final Color icon; + final Color border; + final Color? bg; + final Gradient? gradient; +} + +_BadgePalette _badgePalette(GitHubHonorTier tier, bool dark) { + switch (tier) { + case GitHubHonorTier.coCreator: + return _BadgePalette( + fg: dark ? const Color(0xFFFFF5D6) : const Color(0xFF1B2832), + icon: dark ? const Color(0xFFF8C91C) : const Color(0xFFC47A10), + border: const Color(0xFFD9931E).withValues(alpha: dark ? 0.62 : 0.52), + gradient: LinearGradient( + colors: dark + ? const [Color(0x4DF8C91C), Color(0x425FB4AD)] + : const [Color(0x52F8C91C), Color(0x3D2E7D78)], + ), + ); + case GitHubHonorTier.coreContributor: + return _BadgePalette( + fg: dark ? const Color(0xFFB5D6F5) : const Color(0xFF244A5C), + icon: dark ? const Color(0xFF7ED4CC) : const Color(0xFF2E7D78), + border: (dark ? const Color(0xFF7C96D6) : const Color(0xFF2E7D78)) + .withValues(alpha: 0.36), + gradient: LinearGradient( + colors: dark + ? const [Color(0x385FB4AD), Color(0x387C96D6)] + : const [Color(0x2E2E7D78), Color(0x2E3B5284)], + ), + ); + case GitHubHonorTier.builder: + return _BadgePalette( + fg: dark ? const Color(0xFF86DCD4) : const Color(0xFF1F635E), + icon: dark ? const Color(0xFF86DCD4) : const Color(0xFF2E7D78), + border: (dark ? const Color(0xFF5FB4AD) : const Color(0xFF2E7D78)) + .withValues(alpha: 0.32), + bg: (dark ? const Color(0xFF5FB4AD) : const Color(0xFF2E7D78)) + .withValues(alpha: dark ? 0.18 : 0.13), + ); + case GitHubHonorTier.hiveGuardian: + return _BadgePalette( + fg: dark ? const Color(0xFFFDE08A) : const Color(0xFF8C450C), + icon: dark ? const Color(0xFFF8C91C) : const Color(0xFFB86814), + border: (dark ? const Color(0xFFF8C91C) : const Color(0xFFC87A19)) + .withValues(alpha: 0.44), + gradient: LinearGradient( + colors: dark + ? const [Color(0x3DF8C91C), Color(0x33E07466)] + : const [Color(0x3DF8C91C), Color(0x29B84A42)], + ), + ); + case GitHubHonorTier.goldPatron: + case GitHubHonorTier.supporter: + return _BadgePalette( + fg: dark ? const Color(0xFFF8CA6B) : const Color(0xFF9A580A), + icon: dark ? const Color(0xFFF8CA6B) : const Color(0xFFC87A19), + border: (dark ? const Color(0xFFF5B84E) : const Color(0xFFC87A19)) + .withValues(alpha: 0.34), + bg: (dark ? const Color(0xFFF5B84E) : const Color(0xFFC87A19)) + .withValues(alpha: dark ? 0.18 : 0.13), + ); + case GitHubHonorTier.stargazer: + case GitHubHonorTier.none: + return _BadgePalette( + fg: dark ? const Color(0xFFCBD5E1) : const Color(0xFF475569), + icon: dark ? const Color(0xFFCBD5E1) : const Color(0xFF64748B), + border: (dark ? const Color(0xFF94A3B8) : const Color(0xFF64748B)) + .withValues(alpha: 0.25), + bg: (dark ? const Color(0xFF94A3B8) : const Color(0xFF64748B)) + .withValues(alpha: 0.14), + ); + } +} + +/// 方案 A · 纸面落款印(供 750pt 瑞士印刷风分享海报与年度报告封底使用)。 +/// +/// 在 `#FFFFFA` 暖纸右下留白处以极简双字宋体细框方印 + 英文身份/GitHub ID 呈现: +/// - 双重共创者 / 作者:朱砂印「共创」(`#B34237`) + `CO-CREATOR` +/// - 代码贡献者:靛青印「筑巢」(`#2C6B66`) + `CONTRIBUTOR` +/// - 捐赠支持者:琥珀印「暖蜜」(`#B86814`) + `SUPPORTER` +class CommunityPosterChop extends StatelessWidget { + const CommunityPosterChop({ + super.key, + required this.profile, + this.scale = 1.0, + }); + + final GitHubCommunityProfile profile; + final double scale; + + @override + Widget build(BuildContext context) { + if (!profile.hasPosterChopHonor) return const SizedBox.shrink(); + + final String chopChars; + final String roleLabel; + final Color inkColor; + if (profile.isCoCreator) { + chopChars = '共创'; + roleLabel = 'CO-CREATOR'; + inkColor = const Color(0xFFB34237); + } else if (profile.hasCodeHonor) { + chopChars = '筑巢'; + roleLabel = 'CONTRIBUTOR'; + inkColor = const Color(0xFF2C6B66); + } else { + chopChars = '暖蜜'; + roleLabel = 'SUPPORTER'; + inkColor = const Color(0xFFB86814); + } + + final boxSize = 72.0 * scale; + + return Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text( + roleLabel, + style: TextStyle( + fontSize: 16 * scale, + fontWeight: FontWeight.w700, + letterSpacing: 1.5 * scale, + height: 1.25, + color: inkColor, + ), + ), + SizedBox(height: 3 * scale), + Text( + '@${profile.login}', + style: TextStyle( + fontSize: 15 * scale, + height: 1.25, + fontFamily: 'monospace', + color: const Color(0xFF8C8D88), + ), + ), + ], + ), + SizedBox(width: 14 * scale), + SizedBox( + width: boxSize, + height: boxSize, + child: CustomPaint( + painter: _WoodblockChopPainter( + inkColor: inkColor, + topChar: chopChars[0], + bottomChar: chopChars[1], + ), + ), + ), + ], + ); + } +} + +class _WoodblockChopPainter extends CustomPainter { + const _WoodblockChopPainter({ + required this.inkColor, + required this.topChar, + required this.bottomChar, + }); + + final Color inkColor; + final String topChar; + final String bottomChar; + + @override + void paint(Canvas canvas, Size size) { + final s = size.width; + final outer = RRect.fromRectAndRadius( + Rect.fromLTWH(s * 0.05, s * 0.05, s * 0.90, s * 0.90), + Radius.circular(s * 0.125), + ); + final inner = RRect.fromRectAndRadius( + Rect.fromLTWH(s * 0.125, s * 0.125, s * 0.75, s * 0.75), + Radius.circular(s * 0.075), + ); + + canvas.drawRRect( + outer, + Paint()..color = inkColor.withValues(alpha: 0.06), + ); + canvas.drawRRect( + outer, + Paint() + ..color = inkColor + ..style = PaintingStyle.stroke + ..strokeWidth = (s * 0.042).clamp(1.2, 3.2), + ); + canvas.drawRRect( + inner, + Paint() + ..color = inkColor.withValues(alpha: 0.55) + ..style = PaintingStyle.stroke + ..strokeWidth = (s * 0.016).clamp(0.6, 1.4), + ); + + void paintChar(String ch, double centerY) { + final tp = TextPainter( + text: TextSpan( + text: ch, + style: TextStyle( + color: inkColor, + fontSize: s * 0.295, + fontWeight: FontWeight.w700, + height: 1.0, + fontFamily: 'Songti SC', + fontFamilyFallback: const [ + 'STSong', + 'Noto Serif CJK SC', + 'Georgia', + 'serif', + ], + ), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(canvas, Offset((s - tp.width) / 2, centerY - tp.height / 2)); + } + + paintChar(topChar, s * 0.34); + paintChar(bottomChar, s * 0.67); + } + + @override + bool shouldRepaint(covariant _WoodblockChopPainter old) => + old.inkColor != inkColor || + old.topChar != topChar || + old.bottomChar != bottomChar; +} + +/// 展示完整的 7 级社区荣誉体系(头像光环 + 徽章 + 解锁条件 + 对应皮肤/落款印)。 +Future showCommunityHonorTiersSheet( + BuildContext context, { + GitHubCommunityProfile? profile, +}) { + final l = AppLocalizations.of(context); + return showBeeSheet( + context, + title: l.githubHonorTiersTitle, + child: _CommunityHonorTiersBody(profile: profile), + ); +} + +class _CommunityHonorTiersBody extends StatelessWidget { + const _CommunityHonorTiersBody({this.profile}); + + final GitHubCommunityProfile? profile; + + @override + Widget build(BuildContext context) { + final l = AppLocalizations.of(context); + final theme = Theme.of(context); + final hint = theme.hintColor; + final dark = theme.brightness == Brightness.dark; + final cardSoft = BeeCardTheme.of(context).soft; + + final entries = <({ + GitHubHonorTier tier, + String badgeChar, + String rule, + String reward, + })>[ + ( + tier: GitHubHonorTier.stargazer, + badgeChar: '星', + rule: l.githubHonorRuleStargazer, + reward: l.githubHonorRewardStargazer, + ), + ( + tier: GitHubHonorTier.builder, + badgeChar: '筑', + rule: l.githubHonorRuleBuilder, + reward: l.githubHonorRewardCode, + ), + ( + tier: GitHubHonorTier.coreContributor, + badgeChar: '核', + rule: l.githubHonorRuleCoreContributor, + reward: l.githubHonorRewardCode, + ), + ( + tier: GitHubHonorTier.supporter, + badgeChar: '暖', + rule: l.githubHonorRuleSupporter, + reward: l.githubHonorRewardDonation, + ), + ( + tier: GitHubHonorTier.goldPatron, + badgeChar: '金', + rule: l.githubHonorRuleGoldPatron, + reward: l.githubHonorRewardDonation, + ), + ( + tier: GitHubHonorTier.hiveGuardian, + badgeChar: '守', + rule: l.githubHonorRuleHiveGuardian, + reward: l.githubHonorRewardDonation, + ), + ( + tier: GitHubHonorTier.coCreator, + badgeChar: '共', + rule: l.githubHonorRuleCoCreator, + reward: l.githubHonorRewardCoCreator, + ), + ]; + + return ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.72, + ), + child: SingleChildScrollView( + key: const ValueKey('community-honor-tiers-scroll'), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + l.githubHonorTiersSubtitle, + style: TextStyle(fontSize: 12.5, height: 1.5, color: hint), + ), + const SizedBox(height: 12), + for (final item in entries) ...[ + _buildTierRow( + context, + l, + item.tier, + item.badgeChar, + item.rule, + item.reward, + dark: dark, + cardSoft: cardSoft, + ), + const SizedBox(height: 10), + ], + ], + ), + ), + ); + } + + Widget _buildTierRow( + BuildContext context, + AppLocalizations l, + GitHubHonorTier tier, + String badgeChar, + String rule, + String reward, { + required bool dark, + required Color cardSoft, + }) { + final theme = Theme.of(context); + final hint = theme.hintColor; + final isCurrent = profile != null && profile!.primaryTier == tier; + final isUnlocked = profile != null && profile!.hasUnlockedTier(tier); + final isSupreme = tier == GitHubHonorTier.coCreator; + + String? statusLabel; + Color statusColor = const Color(0xFF16A34A); + if (isCurrent) { + statusLabel = isSupreme + ? l.githubHonorTierCurrentHighest + : l.githubHonorTierCurrent; + statusColor = isSupreme ? const Color(0xFFC47A10) : const Color(0xFF16A34A); + } else if (isUnlocked) { + statusLabel = l.githubHonorTierUnlocked; + statusColor = const Color(0xFF16A34A); + } + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 11), + decoration: BoxDecoration( + color: isCurrent + ? (dark + ? const Color(0x22F8C91C) + : const Color(0x1CF8C91C)) + : cardSoft.withValues(alpha: dark ? 0.55 : 0.72), + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: isCurrent + ? const Color(0xFFD9931E).withValues(alpha: 0.65) + : theme.dividerColor.withValues(alpha: dark ? 0.22 : 0.35), + width: isCurrent ? 1.25 : 0.8, + ), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 2), + child: CommunityAvatarHalo( + tier: tier, + size: 38, + avatar: Container( + color: const Color(0xFFF8C91C).withValues(alpha: dark ? 0.24 : 0.28), + alignment: Alignment.center, + child: Text( + badgeChar, + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w700, + color: dark ? const Color(0xFFFFF4CC) : const Color(0xFF5A3B08), + ), + ), + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 6, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + CommunityHonorBadge(tier: tier, compact: true), + if (statusLabel != null) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, vertical: 1.5), + decoration: BoxDecoration( + color: statusColor.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(999), + ), + child: Text( + statusLabel, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: statusColor, + ), + ), + ), + ], + ), + const SizedBox(height: 5), + Text( + rule, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + height: 1.35, + ), + ), + const SizedBox(height: 2), + Text( + reward, + style: TextStyle( + fontSize: 11, + color: hint, + height: 1.35, + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/lib/providers/all_providers.dart b/lib/providers/all_providers.dart index 53c332e0f..a259a2ffa 100644 --- a/lib/providers/all_providers.dart +++ b/lib/providers/all_providers.dart @@ -44,3 +44,4 @@ export 'attachment_settings_providers.dart'; export 'home_summary_providers.dart'; export 'recording_category_columns_provider.dart'; +export 'github_community_provider.dart'; diff --git a/lib/providers/github_community_provider.dart b/lib/providers/github_community_provider.dart new file mode 100644 index 000000000..7d00cc663 --- /dev/null +++ b/lib/providers/github_community_provider.dart @@ -0,0 +1,303 @@ +import 'dart:async'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import '../services/github/github_community_models.dart'; +import '../services/github/github_community_service.dart'; +import '../services/github/github_token_store.dart'; +import '../services/system/logger_service.dart'; +import '../styles/header_skins.dart'; +import 'theme_providers.dart'; + +enum GitHubCommunityErrorKind { + none, + invalidToken, + rateLimited, + network, +} + +class GitHubCommunityState { + const GitHubCommunityState({ + this.initialized = false, + this.token, + this.profile, + this.loading = false, + this.tokenInvalid = false, + this.errorKind = GitHubCommunityErrorKind.none, + this.errorDetail, + this.prefs = const GitHubRewardPreferences(), + }); + + final bool initialized; + final String? token; + final GitHubCommunityProfile? profile; + final bool loading; + final bool tokenInvalid; + final GitHubCommunityErrorKind errorKind; + final String? errorDetail; + final GitHubRewardPreferences prefs; + + bool get hasToken => token != null && token!.trim().isNotEmpty; + bool get isBound => hasToken && !tokenInvalid && profile != null; + + String get maskedToken => + token == null ? '' : GitHubTokenStore.maskToken(token!); + + GitHubHonorTier get activeTier => + isBound ? profile!.primaryTier : GitHubHonorTier.none; + + Set get unlockedCommunitySkinIds => + isBound ? profile!.unlockedCommunitySkinIds : const {}; + + bool isCommunitySkinUnlocked(String skinId) => + unlockedCommunitySkinIds.contains(skinId); + + GitHubCommunityState copyWith({ + bool? initialized, + String? token, + bool clearToken = false, + GitHubCommunityProfile? profile, + bool clearProfile = false, + bool? loading, + bool? tokenInvalid, + GitHubCommunityErrorKind? errorKind, + String? errorDetail, + bool clearError = false, + GitHubRewardPreferences? prefs, + }) => + GitHubCommunityState( + initialized: initialized ?? this.initialized, + token: clearToken ? null : (token ?? this.token), + profile: clearProfile ? null : (profile ?? this.profile), + loading: loading ?? this.loading, + tokenInvalid: tokenInvalid ?? this.tokenInvalid, + errorKind: clearError + ? GitHubCommunityErrorKind.none + : (errorKind ?? this.errorKind), + errorDetail: clearError ? null : (errorDetail ?? this.errorDetail), + prefs: prefs ?? this.prefs, + ); +} + +final githubCommunityServiceProvider = + Provider((ref) => GitHubCommunityService()); + +final githubCommunityProvider = + StateNotifierProvider( + (ref) => GitHubCommunityNotifier(ref), +); + +class GitHubCommunityNotifier extends StateNotifier { + GitHubCommunityNotifier(this._ref) : super(const GitHubCommunityState()) { + unawaited(_load()); + } + + final Ref _ref; + bool _disposed = false; + + @override + void dispose() { + _disposed = true; + super.dispose(); + } + + void _safeSet(GitHubCommunityState next) { + if (!_disposed) state = next; + } + + Future _load() async { + try { + final results = await Future.wait([ + GitHubTokenStore.getToken(), + GitHubTokenStore.getCachedProfile(), + GitHubTokenStore.getRewardPreferences(), + GitHubTokenStore.isTokenMarkedInvalid(), + ]); + final token = results[0] as String?; + final cached = results[1] as GitHubCommunityProfile?; + final prefs = results[2] as GitHubRewardPreferences; + final invalid = results[3] as bool; + + _safeSet(state.copyWith( + initialized: true, + token: token, + clearToken: token == null, + profile: cached, + clearProfile: cached == null, + tokenInvalid: invalid, + prefs: prefs, + )); + + _reconcileActiveCommunitySkin(); + + // 缓存超过 24 小时且 Token 有效时静默刷新 + if (token != null && !invalid) { + final stale = cached == null || + DateTime.now().difference(cached.fetchedAt) > + GitHubTokenStore.cacheTtl; + if (stale) { + unawaited(refresh(silent: true)); + } + } + } catch (e) { + logger.warning('GitHubCommunity', 'Failed to load state: $e'); + _safeSet(state.copyWith(initialized: true)); + } + } + + /// 验证并保存用户输入的 GitHub PAT,成功后拉取完整社区身份与跨项目贡献。 + Future saveAndVerifyToken(String rawToken) async { + final trimmed = rawToken.trim(); + if (trimmed.isEmpty) return false; + _safeSet(state.copyWith(loading: true, clearError: true)); + try { + final service = _ref.read(githubCommunityServiceProvider); + final profile = await service.verifyAndFetchProfile(trimmed); + await GitHubTokenStore.saveToken(trimmed); + await GitHubTokenStore.saveCachedProfile(profile); + await GitHubTokenStore.markTokenInvalid(false); + _safeSet(state.copyWith( + initialized: true, + token: trimmed, + profile: profile, + loading: false, + tokenInvalid: false, + clearError: true, + )); + _reconcileActiveCommunitySkin(); + return true; + } on GitHubTokenInvalidException catch (e) { + _safeSet(state.copyWith( + loading: false, + errorKind: GitHubCommunityErrorKind.invalidToken, + errorDetail: e.message, + )); + return false; + } on GitHubRateLimitExceededException catch (e) { + _safeSet(state.copyWith( + loading: false, + errorKind: GitHubCommunityErrorKind.rateLimited, + errorDetail: e.message, + )); + return false; + } catch (e) { + logger.warning('GitHubCommunity', 'Verify token failed: $e'); + _safeSet(state.copyWith( + loading: false, + errorKind: GitHubCommunityErrorKind.network, + errorDetail: e.toString(), + )); + return false; + } + } + + /// 重新拉取当前已保存 Token 的社区身份、6 仓贡献与捐赠记录。 + Future refresh({bool silent = false}) async { + final token = state.token ?? await GitHubTokenStore.getToken(); + if (token == null || token.isEmpty) return false; + if (!silent) { + _safeSet(state.copyWith(loading: true, clearError: true)); + } + try { + final service = _ref.read(githubCommunityServiceProvider); + final profile = await service.verifyAndFetchProfile(token); + await GitHubTokenStore.saveCachedProfile(profile); + await GitHubTokenStore.markTokenInvalid(false); + _safeSet(state.copyWith( + token: token, + profile: profile, + loading: false, + tokenInvalid: false, + clearError: true, + )); + _reconcileActiveCommunitySkin(); + return true; + } on GitHubTokenInvalidException catch (e) { + await GitHubTokenStore.markTokenInvalid(true); + _safeSet(state.copyWith( + loading: false, + tokenInvalid: true, + errorKind: GitHubCommunityErrorKind.invalidToken, + errorDetail: e.message, + )); + _reconcileActiveCommunitySkin(); + return false; + } on GitHubRateLimitExceededException catch (e) { + if (!silent) { + _safeSet(state.copyWith( + loading: false, + errorKind: GitHubCommunityErrorKind.rateLimited, + errorDetail: e.message, + )); + } + return false; + } catch (e) { + logger.warning('GitHubCommunity', 'Refresh failed: $e'); + if (!silent) { + _safeSet(state.copyWith( + loading: false, + errorKind: GitHubCommunityErrorKind.network, + errorDetail: e.toString(), + )); + } + return false; + } + } + + /// 更新缓存中的速率配额(供检查更新等请求顺带同步)。 + void updateRateLimit(GitHubRateLimit rateLimit) { + final current = state.profile; + if (current == null) return; + final updated = current.copyWith(rateLimit: rateLimit); + _safeSet(state.copyWith(profile: updated)); + unawaited(GitHubTokenStore.saveCachedProfile(updated)); + } + + /// 外部请求(如检查更新)遇到 HTTP 401 时调用,将 Token 标记为失效并回退社区皮肤。 + Future markTokenUnauthorized() async { + if (!state.hasToken) return; + await GitHubTokenStore.markTokenInvalid(true); + _safeSet(state.copyWith( + tokenInvalid: true, + errorKind: GitHubCommunityErrorKind.invalidToken, + )); + _reconcileActiveCommunitySkin(); + } + + /// 清除已保存的 Token 并干净回退所有社区奖励装饰与社区皮肤。 + Future clearToken() async { + await GitHubTokenStore.clearTokenAndProfile(); + _safeSet(state.copyWith( + clearToken: true, + clearProfile: true, + loading: false, + tokenInvalid: false, + clearError: true, + )); + _reconcileActiveCommunitySkin(); + } + + Future updatePreferences({ + bool? showHaloAndBadge, + bool? showCustomGreeting, + bool? showPosterStamp, + }) async { + final next = state.prefs.copyWith( + showHaloAndBadge: showHaloAndBadge, + showCustomGreeting: showCustomGreeting, + showPosterStamp: showPosterStamp, + ); + _safeSet(state.copyWith(prefs: next)); + await GitHubTokenStore.saveRewardPreferences(next); + } + + /// 若当前正在使用社区典藏皮肤但已解绑/失效,自动回退为纯色并恢复用户自选主题色。 + void _reconcileActiveCommunitySkin() { + try { + final activeId = _ref.read(headerSkinProvider); + if (kAllCommunitySkinIds.contains(activeId) && + !state.isCommunitySkinUnlocked(activeId)) { + applyHeaderSkinWith(_ref.read, kHeaderSkinNone); + } + } catch (_) {} + } +} diff --git a/lib/providers/github_star_provider.dart b/lib/providers/github_star_provider.dart index 0b70e6ee9..38093b1f9 100644 --- a/lib/providers/github_star_provider.dart +++ b/lib/providers/github_star_provider.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; +import '../services/github/github_token_store.dart'; import '../services/system/logger_service.dart'; /// GitHub Star 数量 Provider @@ -26,12 +27,22 @@ final githubStarCountProvider = FutureProvider((ref) async { } } - // 从GitHub API获取 + // 从GitHub API获取(优先携带本机已配置的 GitHub Token 解除 60/h 限流) try { - final response = await http - .get(Uri.parse('https://api.github.com/repos/TNT-Likely/BeeCount')) + final markedInvalid = await GitHubTokenStore.isTokenMarkedInvalid(); + final token = markedInvalid ? null : await GitHubTokenStore.getToken(); + final uri = Uri.parse('https://api.github.com/repos/TNT-Likely/BeeCount'); + var response = await http + .get(uri, headers: GitHubTokenStore.buildHeaders(token: token)) .timeout(const Duration(seconds: 5)); + if (response.statusCode == 401 && token != null) { + await GitHubTokenStore.markTokenInvalid(true); + response = await http + .get(uri, headers: GitHubTokenStore.buildHeaders()) + .timeout(const Duration(seconds: 5)); + } + if (response.statusCode == 200) { final data = jsonDecode(response.body); final starCount = data['stargazers_count'] as int? ?? 0; diff --git a/lib/services/github/github_community_models.dart b/lib/services/github/github_community_models.dart new file mode 100644 index 000000000..0b4d51e52 --- /dev/null +++ b/lib/services/github/github_community_models.dart @@ -0,0 +1,438 @@ +// BeeCount GitHub 社区身份、跨项目贡献统计与捐赠荣誉数据模型。 +// +// 覆盖主仓库与所有关联生态项目;项目作者(`TNT-Likely` 或清单中登记的维护者) +// 特判享有最高级「蜂巢共创者」荣誉与全部社区典藏奖励。 + +const String kCommunitySkinWoodblockLamp = 'community_woodblock_lamp'; +const String kCommunitySkinHoneyJar = 'community_honey_jar'; +const String kCommunitySkinStarlitHive = 'community_starlit_hive'; + +const Set kAllCommunitySkinIds = { + kCommunitySkinWoodblockLamp, + kCommunitySkinHoneyJar, + kCommunitySkinStarlitHive, +}; + +/// 内置维护者特判(忽略大小写),确保离线或远端 JSON 未就绪时作者仍享有最高荣誉。 +const Set kBuiltInMaintainerLogins = {'tnt-likely'}; + +class GitHubEcosystemRepo { + const GitHubEcosystemRepo({ + required this.owner, + required this.name, + required this.roleZh, + required this.roleZhTw, + required this.roleEn, + }); + + final String owner; + final String name; + final String roleZh; + final String roleZhTw; + final String roleEn; + + String get fullName => '$owner/$name'; +} + +/// BeeCount 家族全部关联仓库(与 README 相关项目对齐)。 +const List kBeeCountEcosystemRepos = [ + GitHubEcosystemRepo( + owner: 'TNT-Likely', + name: 'BeeCount', + roleZh: '蜜蜂记账主 App', + roleZhTw: '蜜蜂記帳主 App', + roleEn: 'Main App', + ), + GitHubEcosystemRepo( + owner: 'TNT-Likely', + name: 'BeeCount-Cloud', + roleZh: '自建云同步服务端 + Web', + roleZhTw: '自建雲同步服務端 + Web', + roleEn: 'Self-hosted Cloud & Web', + ), + GitHubEcosystemRepo( + owner: 'TNT-Likely', + name: 'BeeCount-Website', + roleZh: '官网与文档', + roleZhTw: '官網與文件', + roleEn: 'Website & Docs', + ), + GitHubEcosystemRepo( + owner: 'TNT-Likely', + name: 'BeeCount-Design', + roleZh: '4.0 设计源与组件规范', + roleZhTw: '4.0 設計源與元件規範', + roleEn: '4.0 Design System', + ), + GitHubEcosystemRepo( + owner: 'TNT-Likely', + name: 'beecount-openharmony', + roleZh: '鸿蒙版本(历史项目)', + roleZhTw: '鴻蒙版本(歷史專案)', + roleEn: 'OpenHarmony (Archived)', + ), + GitHubEcosystemRepo( + owner: 'TNT-Likely', + name: 'honeycomb', + roleZh: '开发脚手架插件市场', + roleZhTw: '開發腳手架外掛市場', + roleEn: 'Dev Skills Marketplace', + ), +]; + +/// GitHub API 速率限制状态(由响应头 X-RateLimit-* 解析)。 +class GitHubRateLimit { + const GitHubRateLimit({ + required this.limit, + required this.remaining, + this.resetAt, + }); + + final int limit; + final int remaining; + final DateTime? resetAt; + + double get ratio => limit <= 0 ? 0 : (remaining / limit).clamp(0.0, 1.0); + bool get isAuthenticatedQuota => limit >= 1000; + + Map toJson() => { + 'limit': limit, + 'remaining': remaining, + if (resetAt != null) 'resetAt': resetAt!.millisecondsSinceEpoch, + }; + + factory GitHubRateLimit.fromJson(Map json) => + GitHubRateLimit( + limit: (json['limit'] as num?)?.toInt() ?? 60, + remaining: (json['remaining'] as num?)?.toInt() ?? 0, + resetAt: json['resetAt'] is num + ? DateTime.fromMillisecondsSinceEpoch( + (json['resetAt'] as num).toInt()) + : null, + ); +} + +/// 单个关联仓库的贡献明细。 +class GitHubRepoContribution { + const GitHubRepoContribution({ + required this.repo, + this.commits = 0, + this.mergedPrs = 0, + this.issues = 0, + }); + + final String repo; + final int commits; + final int mergedPrs; + final int issues; + + bool get hasAnyActivity => commits > 0 || mergedPrs > 0 || issues > 0; + bool get hasCode => commits > 0 || mergedPrs > 0; + + Map toJson() => { + 'repo': repo, + 'commits': commits, + 'mergedPrs': mergedPrs, + 'issues': issues, + }; + + factory GitHubRepoContribution.fromJson(Map json) => + GitHubRepoContribution( + repo: json['repo']?.toString() ?? '', + commits: (json['commits'] as num?)?.toInt() ?? 0, + mergedPrs: (json['mergedPrs'] as num?)?.toInt() ?? 0, + issues: (json['issues'] as num?)?.toInt() ?? 0, + ); +} + +/// 捐赠支持者档位阈值(优先从 docs/donate/supporters.json 读取)。 +class GitHubDonationThresholds { + const GitHubDonationThresholds({ + this.supporter = 1, + this.goldPatron = 50, + this.hiveGuardian = 150, + }); + + final double supporter; + final double goldPatron; + final double hiveGuardian; + + Map toJson() => { + 'supporter': supporter, + 'goldPatron': goldPatron, + 'hiveGuardian': hiveGuardian, + }; + + factory GitHubDonationThresholds.fromJson(Map? json) { + if (json == null) return const GitHubDonationThresholds(); + return GitHubDonationThresholds( + supporter: (json['supporter'] as num?)?.toDouble() ?? 1, + goldPatron: (json['goldPatron'] as num?)?.toDouble() ?? 50, + hiveGuardian: (json['hiveGuardian'] as num?)?.toDouble() ?? 150, + ); + } +} + +/// 匹配到的捐赠信息。 +class GitHubDonationInfo { + const GitHubDonationInfo({ + required this.amountCny, + this.displayName, + this.since, + }); + + final double amountCny; + final String? displayName; + final String? since; + + Map toJson() => { + 'amountCny': amountCny, + if (displayName != null) 'displayName': displayName, + if (since != null) 'since': since, + }; + + factory GitHubDonationInfo.fromJson(Map json) => + GitHubDonationInfo( + amountCny: (json['amountCny'] as num?)?.toDouble() ?? 0, + displayName: json['displayName']?.toString(), + since: json['since']?.toString(), + ); +} + +/// 荣誉等级。 +enum GitHubHonorTier { + none, + stargazer, + builder, + coreContributor, + supporter, + goldPatron, + hiveGuardian, + coCreator, +} + +/// 社区 UI 奖励展示开关(全部本地持久化,可随时单独关闭)。 +class GitHubRewardPreferences { + const GitHubRewardPreferences({ + this.showHaloAndBadge = true, + this.showCustomGreeting = true, + this.showPosterStamp = true, + }); + + final bool showHaloAndBadge; + final bool showCustomGreeting; + final bool showPosterStamp; + + GitHubRewardPreferences copyWith({ + bool? showHaloAndBadge, + bool? showCustomGreeting, + bool? showPosterStamp, + }) => + GitHubRewardPreferences( + showHaloAndBadge: showHaloAndBadge ?? this.showHaloAndBadge, + showCustomGreeting: showCustomGreeting ?? this.showCustomGreeting, + showPosterStamp: showPosterStamp ?? this.showPosterStamp, + ); + + Map toJson() => { + 'showHaloAndBadge': showHaloAndBadge, + 'showCustomGreeting': showCustomGreeting, + 'showPosterStamp': showPosterStamp, + }; + + factory GitHubRewardPreferences.fromJson(Map? json) { + if (json == null) return const GitHubRewardPreferences(); + return GitHubRewardPreferences( + showHaloAndBadge: json['showHaloAndBadge'] as bool? ?? true, + showCustomGreeting: json['showCustomGreeting'] as bool? ?? true, + showPosterStamp: json['showPosterStamp'] as bool? ?? true, + ); + } +} + +/// 完整的 GitHub 社区身份快照(可序列化缓存 24 小时)。 +class GitHubCommunityProfile { + const GitHubCommunityProfile({ + required this.login, + this.displayName, + this.avatarUrl, + this.isMaintainer = false, + this.starredMainRepo = false, + this.contributions = const [], + this.donation, + this.donationThresholds = const GitHubDonationThresholds(), + this.rateLimit, + required this.fetchedAt, + }); + + final String login; + final String? displayName; + final String? avatarUrl; + final bool isMaintainer; + final bool starredMainRepo; + final List contributions; + final GitHubDonationInfo? donation; + final GitHubDonationThresholds donationThresholds; + final GitHubRateLimit? rateLimit; + final DateTime fetchedAt; + + int get totalCommits => + contributions.fold(0, (sum, item) => sum + item.commits); + int get totalMergedPrs => + contributions.fold(0, (sum, item) => sum + item.mergedPrs); + int get totalIssues => + contributions.fold(0, (sum, item) => sum + item.issues); + int get activeCodeRepoCount => contributions.where((c) => c.hasCode).length; + List get nonEmptyContributions => + contributions.where((c) => c.hasAnyActivity).toList(); + + /// 是否达到代码贡献者门槛(≥1 次 Commit 或 ≥1 个已合并 PR,或项目维护者特判)。 + /// 提 Issue 不计入代码贡献门槛。 + bool get hasCodeHonor => + isMaintainer || totalCommits > 0 || totalMergedPrs > 0; + + /// 是否达到捐赠支持者门槛(匹配到支持者名单且金额 > 0,或项目维护者特判)。 + bool get hasDonationHonor => + isMaintainer || (donation != null && donation!.amountCny >= donationThresholds.supporter); + + /// 代码贡献细分等级。 + GitHubHonorTier get codeTier { + if (isMaintainer || + totalMergedPrs >= 5 || + totalCommits >= 20 || + activeCodeRepoCount >= 2) { + return GitHubHonorTier.coreContributor; + } + if (hasCodeHonor) { + return GitHubHonorTier.builder; + } + return GitHubHonorTier.none; + } + + /// 捐赠支持细分等级。 + GitHubHonorTier get donationTier { + if (isMaintainer) return GitHubHonorTier.hiveGuardian; + final amount = donation?.amountCny ?? 0; + if (amount >= donationThresholds.hiveGuardian) { + return GitHubHonorTier.hiveGuardian; + } + if (amount >= donationThresholds.goldPatron) { + return GitHubHonorTier.goldPatron; + } + if (amount >= donationThresholds.supporter) { + return GitHubHonorTier.supporter; + } + return GitHubHonorTier.none; + } + + /// 是否同时具备代码贡献与捐赠支持(或作者特判)。 + bool get isCoCreator => isMaintainer || (hasCodeHonor && hasDonationHonor); + + /// 对外展示的最高主身份等级。 + GitHubHonorTier get primaryTier { + if (isCoCreator) return GitHubHonorTier.coCreator; + if (hasCodeHonor) return codeTier; + if (hasDonationHonor) return donationTier; + if (starredMainRepo) return GitHubHonorTier.stargazer; + return GitHubHonorTier.none; + } + + /// 判断用户是否已达成指定荣誉等级(用于荣誉体系总览高亮)。 + bool hasUnlockedTier(GitHubHonorTier tier) { + if (isMaintainer) return tier != GitHubHonorTier.none; + return switch (tier) { + GitHubHonorTier.none => true, + GitHubHonorTier.stargazer => + starredMainRepo || hasCodeHonor || hasDonationHonor, + GitHubHonorTier.builder => hasCodeHonor, + GitHubHonorTier.coreContributor => + codeTier == GitHubHonorTier.coreContributor, + GitHubHonorTier.supporter => hasDonationHonor, + GitHubHonorTier.goldPatron => + donationTier == GitHubHonorTier.goldPatron || + donationTier == GitHubHonorTier.hiveGuardian, + GitHubHonorTier.hiveGuardian => + donationTier == GitHubHonorTier.hiveGuardian, + GitHubHonorTier.coCreator => isCoCreator, + }; + } + + /// 是否有资格在分享海报上加盖落款印(代码贡献者、捐赠者或作者)。 + bool get hasPosterChopHonor => + isCoCreator || hasCodeHonor || hasDonationHonor; + + /// 已解锁的社区典藏皮肤 ID 集合。 + Set get unlockedCommunitySkinIds { + if (isCoCreator) { + return kAllCommunitySkinIds; + } + return { + if (hasCodeHonor) kCommunitySkinWoodblockLamp, + if (hasDonationHonor) kCommunitySkinHoneyJar, + }; + } + + GitHubCommunityProfile copyWith({ + GitHubRateLimit? rateLimit, + }) => + GitHubCommunityProfile( + login: login, + displayName: displayName, + avatarUrl: avatarUrl, + isMaintainer: isMaintainer, + starredMainRepo: starredMainRepo, + contributions: contributions, + donation: donation, + donationThresholds: donationThresholds, + rateLimit: rateLimit ?? this.rateLimit, + fetchedAt: fetchedAt, + ); + + Map toJson() => { + 'login': login, + if (displayName != null) 'displayName': displayName, + if (avatarUrl != null) 'avatarUrl': avatarUrl, + 'isMaintainer': isMaintainer, + 'starredMainRepo': starredMainRepo, + 'contributions': [for (final c in contributions) c.toJson()], + if (donation != null) 'donation': donation!.toJson(), + 'donationThresholds': donationThresholds.toJson(), + if (rateLimit != null) 'rateLimit': rateLimit!.toJson(), + 'fetchedAt': fetchedAt.millisecondsSinceEpoch, + }; + + factory GitHubCommunityProfile.fromJson(Map json) { + final login = json['login']?.toString() ?? ''; + final isMaintainer = (json['isMaintainer'] as bool? ?? false) || + kBuiltInMaintainerLogins.contains(login.toLowerCase()); + final rawContributions = json['contributions'] as List? ?? const []; + return GitHubCommunityProfile( + login: login, + displayName: json['displayName']?.toString(), + avatarUrl: json['avatarUrl']?.toString(), + isMaintainer: isMaintainer, + starredMainRepo: json['starredMainRepo'] as bool? ?? false, + contributions: [ + for (final item in rawContributions) + if (item is Map) + GitHubRepoContribution.fromJson(Map.from(item)) + ], + donation: json['donation'] is Map + ? GitHubDonationInfo.fromJson( + Map.from(json['donation'] as Map)) + : null, + donationThresholds: json['donationThresholds'] is Map + ? GitHubDonationThresholds.fromJson( + Map.from(json['donationThresholds'] as Map)) + : const GitHubDonationThresholds(), + rateLimit: json['rateLimit'] is Map + ? GitHubRateLimit.fromJson( + Map.from(json['rateLimit'] as Map)) + : null, + fetchedAt: json['fetchedAt'] is num + ? DateTime.fromMillisecondsSinceEpoch( + (json['fetchedAt'] as num).toInt()) + : DateTime.now(), + ); + } +} diff --git a/lib/services/github/github_community_service.dart b/lib/services/github/github_community_service.dart new file mode 100644 index 000000000..78e16f5d1 --- /dev/null +++ b/lib/services/github/github_community_service.dart @@ -0,0 +1,434 @@ +import 'dart:convert'; +import 'package:dio/dio.dart'; +import 'package:flutter/foundation.dart' show visibleForTesting; +import 'package:flutter/services.dart' show rootBundle; +import '../system/logger_service.dart'; +import 'github_community_models.dart'; +import 'github_token_store.dart'; + +class GitHubTokenInvalidException implements Exception { + const GitHubTokenInvalidException([this.message = 'Unauthorized']); + final String message; + @override + String toString() => 'GitHubTokenInvalidException: $message'; +} + +class GitHubRateLimitExceededException implements Exception { + const GitHubRateLimitExceededException([this.message = 'Rate limit exceeded']); + final String message; + @override + String toString() => 'GitHubRateLimitExceededException: $message'; +} + +/// 解析后的支持者清单(含维护者特判名单、档位阈值与支持者记录)。 +class ParsedSupportersRegistry { + const ParsedSupportersRegistry({ + this.maintainers = const {}, + this.thresholds = const GitHubDonationThresholds(), + this.supportersByLogin = const {}, + }); + + final Set maintainers; + final GitHubDonationThresholds thresholds; + final Map supportersByLogin; +} + +/// GitHub 社区身份核验、跨 6 仓贡献汇总与捐赠名单匹配服务。 +class GitHubCommunityService { + GitHubCommunityService({ + Dio? dio, + Future Function()? bundledSupportersLoader, + Future Function()? cachedSupportersLoader, + Future Function(String rawJson)? cachedSupportersSaver, + }) : _dio = dio ?? + Dio(BaseOptions( + connectTimeout: const Duration(seconds: 20), + receiveTimeout: const Duration(seconds: 25), + sendTimeout: const Duration(seconds: 20), + validateStatus: (status) => status != null && status < 500, + )), + _bundledSupportersLoader = + bundledSupportersLoader ?? _defaultBundledSupportersLoader, + _cachedSupportersLoader = + cachedSupportersLoader ?? GitHubTokenStore.getCachedSupportersJson, + _cachedSupportersSaver = + cachedSupportersSaver ?? GitHubTokenStore.saveCachedSupportersJson; + + final Dio _dio; + final Future Function() _bundledSupportersLoader; + final Future Function() _cachedSupportersLoader; + final Future Function(String rawJson) _cachedSupportersSaver; + + static const String _apiBase = 'https://api.github.com'; + static const String bundledSupportersAssetPath = + 'docs/donate/supporters.json'; + + static Future _defaultBundledSupportersLoader() async { + try { + return await rootBundle.loadString(bundledSupportersAssetPath); + } catch (_) { + return null; + } + } + + /// 使用用户填写的只读 PAT 校验身份并聚合 6 个关联项目贡献与捐赠记录。 + Future verifyAndFetchProfile(String rawToken) async { + final token = rawToken.trim(); + if (token.isEmpty) { + throw const GitHubTokenInvalidException('Token is empty'); + } + final headers = GitHubTokenStore.buildHeaders(token: token); + final options = Options(headers: headers); + + // 1. 校验 Token 并获取用户身份与实时速率配额 + final userResp = await _dio.get('$_apiBase/user', options: options); + final userRateLimit = + GitHubTokenStore.parseRateLimitHeaders(userResp.headers.map); + if (userResp.statusCode == 401) { + throw const GitHubTokenInvalidException('HTTP 401'); + } + if (userResp.statusCode == 403 || userResp.statusCode == 429) { + if (userRateLimit != null && userRateLimit.remaining == 0) { + throw const GitHubRateLimitExceededException(); + } + throw const GitHubTokenInvalidException('HTTP 403'); + } + if (userResp.statusCode != 200 || userResp.data is! Map) { + throw Exception('GitHub /user failed: HTTP ${userResp.statusCode}'); + } + + final userMap = Map.from(userResp.data as Map); + final login = userMap['login']?.toString().trim() ?? ''; + if (login.isEmpty) { + throw const GitHubTokenInvalidException('Missing login'); + } + final displayName = userMap['name']?.toString().trim(); + final avatarUrl = userMap['avatar_url']?.toString().trim(); + + // 2. 并行拉取:已合并 PR、Issue、各仓 Commit 数、Star 状态与支持者清单 + final prFuture = _fetchSearchRepoCounts( + query: _buildRepoSearchQuery(login: login, type: 'pr', mergedOnly: true), + options: options, + ); + final issueFuture = _fetchSearchRepoCounts( + query: _buildRepoSearchQuery(login: login, type: 'issue', mergedOnly: false), + options: options, + ); + final commitFutures = [ + for (final repo in kBeeCountEcosystemRepos) + _fetchRepoCommitCount(repo: repo, login: login, options: options) + ]; + final starFuture = _fetchStarredMainRepo(options: options); + final supportersFuture = _fetchSupportersRegistry(options: options); + + final results = await Future.wait([ + prFuture, + issueFuture, + Future.wait(commitFutures), + starFuture, + supportersFuture, + ]); + + final prByRepo = results[0] as Map; + final issueByRepo = results[1] as Map; + final commitCounts = results[2] as List; + final starred = results[3] as bool; + final registry = results[4] as ParsedSupportersRegistry; + + final contributions = []; + for (var i = 0; i < kBeeCountEcosystemRepos.length; i++) { + final repo = kBeeCountEcosystemRepos[i]; + final key = repo.fullName.toLowerCase(); + contributions.add(GitHubRepoContribution( + repo: repo.name, + commits: commitCounts[i], + mergedPrs: prByRepo[key] ?? 0, + issues: issueByRepo[key] ?? 0, + )); + } + + final loginLower = login.toLowerCase(); + final isMaintainer = kBuiltInMaintainerLogins.contains(loginLower) || + registry.maintainers.contains(loginLower); + final donation = registry.supportersByLogin[loginLower]; + + return GitHubCommunityProfile( + login: login, + displayName: (displayName == null || displayName.isEmpty) ? null : displayName, + avatarUrl: (avatarUrl == null || avatarUrl.isEmpty) ? null : avatarUrl, + isMaintainer: isMaintainer, + starredMainRepo: starred, + contributions: contributions, + donation: donation, + donationThresholds: registry.thresholds, + rateLimit: userRateLimit, + fetchedAt: DateTime.now(), + ); + } + + String _buildRepoSearchQuery({ + required String login, + required String type, + required bool mergedOnly, + }) { + final repoClause = + kBeeCountEcosystemRepos.map((r) => 'repo:${r.fullName}').join(' '); + final merged = mergedOnly ? ' is:merged' : ''; + return 'type:$type$merged author:$login $repoClause'; + } + + /// 通过 GitHub Search API 一次性按仓库聚合 PR 或 Issue 数量。 + Future> _fetchSearchRepoCounts({ + required String query, + required Options options, + }) async { + final counts = {}; + try { + final resp = await _dio.get( + '$_apiBase/search/issues', + queryParameters: {'q': query, 'per_page': 100}, + options: options, + ); + if (resp.statusCode != 200 || resp.data is! Map) return counts; + final items = resp.data['items'] as List? ?? const []; + for (final item in items) { + if (item is! Map) continue; + final repoUrl = item['repository_url']?.toString() ?? ''; + final match = RegExp(r'/repos/([^/]+/[^/]+)$').firstMatch(repoUrl); + if (match != null) { + final fullName = match.group(1)!.toLowerCase(); + counts[fullName] = (counts[fullName] ?? 0) + 1; + } + } + } catch (e) { + logger.warning('GitHubCommunity', 'Search API query failed: $e'); + } + return counts; + } + + /// 查询单仓 Commit 数量:使用 per_page=1 + Link 头 rel="last" 页码,极轻量。 + Future _fetchRepoCommitCount({ + required GitHubEcosystemRepo repo, + required String login, + required Options options, + }) async { + try { + final resp = await _dio.get( + '$_apiBase/repos/${repo.fullName}/commits', + queryParameters: {'author': login, 'per_page': 1}, + options: options, + ); + if (resp.statusCode != 200) return 0; + final data = resp.data; + if (data is! List || data.isEmpty) return 0; + final link = resp.headers.value('link'); + final lastPage = parseLastPageFromLinkHeader(link); + return lastPage ?? data.length; + } catch (e) { + logger.warning( + 'GitHubCommunity', 'Commit count query failed (${repo.name}): $e'); + return 0; + } + } + + /// 检查是否已 Star 主仓库。 + Future _fetchStarredMainRepo({required Options options}) async { + try { + final resp = await _dio.get( + '$_apiBase/user/starred/TNT-Likely/BeeCount', + options: options, + ); + return resp.statusCode == 204; + } catch (_) { + return false; + } + } + + /// 三级策略加载支持者清单: + /// 1. 优先联网动态拉取 GitHub main 分支最新 `docs/donate/supporters.json` 并刷新本地动态缓存(无需发版即可生效); + /// 2. 远端不可用时回退到本地动态缓存(若有); + /// 3. 若远端 `supporters.json` 尚未合入但 `README.md` 可达,解析 `README.md` 并与随包打包的基线配置合并; + /// 4. 最终兜底读取随包打包的本地 `docs/donate/supporters.json`。 + Future _fetchSupportersRegistry({ + required Options options, + }) async { + ParsedSupportersRegistry? bundled; + try { + final rawBundled = await _bundledSupportersLoader(); + if (rawBundled != null && rawBundled.trim().isNotEmpty) { + bundled = parseSupportersJson(rawBundled); + } + } catch (e) { + logger.warning( + 'GitHubCommunity', 'Bundled supporters.json load failed: $e'); + } + + // 1. 动态拉取远端最新版 docs/donate/supporters.json + try { + final resp = await _dio.get( + '$_apiBase/repos/TNT-Likely/BeeCount/contents/docs/donate/supporters.json', + options: options, + ); + if (resp.statusCode == 200 && resp.data is Map) { + final decoded = _decodeGitHubFileContent(resp.data as Map); + if (decoded != null && decoded.trim().isNotEmpty) { + final parsed = parseSupportersJson(decoded); + try { + await _cachedSupportersSaver(decoded); + } catch (_) {} + return _mergeWithBundledBaseline(parsed, bundled); + } + } + } catch (e) { + logger.warning('GitHubCommunity', 'supporters.json fetch failed: $e'); + } + + // 2. 优先使用本机之前动态更新缓存过的最新版 JSON + try { + final cachedRaw = await _cachedSupportersLoader(); + if (cachedRaw != null && cachedRaw.trim().isNotEmpty) { + return _mergeWithBundledBaseline( + parseSupportersJson(cachedRaw), + bundled, + ); + } + } catch (e) { + logger.warning('GitHubCommunity', 'Cached supporters.json load failed: $e'); + } + + // 3. 回退解析远端 README.md 中的「感谢支持者」表格(并与本地打包基线合并) + try { + final resp = await _dio.get( + '$_apiBase/repos/TNT-Likely/BeeCount/contents/README.md', + options: options, + ); + if (resp.statusCode == 200 && resp.data is Map) { + final decoded = _decodeGitHubFileContent(resp.data as Map); + if (decoded != null && decoded.isNotEmpty) { + final fromReadme = parseReadmeSupporters(decoded); + if (fromReadme.supportersByLogin.isNotEmpty) { + return _mergeWithBundledBaseline(fromReadme, bundled); + } + } + } + } catch (e) { + logger.warning('GitHubCommunity', 'README.md fallback fetch failed: $e'); + } + + // 4. 离线 / 兜底:返回随包打包的本地 docs/donate/supporters.json + return bundled ?? const ParsedSupportersRegistry(); + } + + static ParsedSupportersRegistry _mergeWithBundledBaseline( + ParsedSupportersRegistry primary, + ParsedSupportersRegistry? baseline, + ) { + if (baseline == null) return primary; + final mergedMaintainers = { + ...baseline.maintainers, + ...primary.maintainers, + }; + final mergedSupporters = { + ...baseline.supportersByLogin, + ...primary.supportersByLogin, + }; + return ParsedSupportersRegistry( + maintainers: mergedMaintainers, + thresholds: primary.supportersByLogin.isNotEmpty || + primary.maintainers.isNotEmpty + ? primary.thresholds + : baseline.thresholds, + supportersByLogin: mergedSupporters, + ); + } + + static String? _decodeGitHubFileContent(Map body) { + final content = body['content']?.toString(); + if (content == null || content.isEmpty) return null; + final encoding = body['encoding']?.toString(); + if (encoding == 'base64') { + final normalized = content.replaceAll(RegExp(r'\s+'), ''); + return utf8.decode(base64Decode(normalized), allowMalformed: true); + } + return content; + } + + /// 解析 Link 响应头中 `rel="last"` 的页码。 + @visibleForTesting + static int? parseLastPageFromLinkHeader(String? linkHeader) { + if (linkHeader == null || linkHeader.isEmpty) return null; + final match = + RegExp(r'[?&]page=(\d+)[^>]*>;\s*rel="last"').firstMatch(linkHeader); + if (match == null) return null; + return int.tryParse(match.group(1) ?? ''); + } + + /// 解析结构化 `docs/donate/supporters.json`。 + @visibleForTesting + static ParsedSupportersRegistry parseSupportersJson(String rawJson) { + final decoded = jsonDecode(rawJson); + if (decoded is! Map) return const ParsedSupportersRegistry(); + final map = Map.from(decoded); + + final maintainers = {}; + final rawMaintainers = map['maintainers'] as List? ?? const []; + for (final m in rawMaintainers) { + final login = m?.toString().trim().toLowerCase(); + if (login != null && login.isNotEmpty) maintainers.add(login); + } + + final thresholds = map['tiers'] is Map + ? GitHubDonationThresholds.fromJson( + Map.from(map['tiers'] as Map)) + : const GitHubDonationThresholds(); + + final supporters = {}; + final rawList = map['supporters'] as List? ?? const []; + for (final entry in rawList) { + if (entry is! Map) continue; + final github = entry['github']?.toString().trim().toLowerCase(); + if (github == null || github.isEmpty) continue; + final amount = (entry['amountCny'] as num?)?.toDouble() ?? 0; + if (amount <= 0) continue; + final existing = supporters[github]; + supporters[github] = GitHubDonationInfo( + amountCny: (existing?.amountCny ?? 0) + amount, + displayName: entry['name']?.toString().trim() ?? existing?.displayName, + since: entry['since']?.toString().trim() ?? existing?.since, + ); + } + + return ParsedSupportersRegistry( + maintainers: maintainers, + thresholds: thresholds, + supportersByLogin: supporters, + ); + } + + /// 兼容回退:从 README.md 的「感谢支持者」HTML 表格中提取带 GitHub 链接的支持者与金额。 + @visibleForTesting + static ParsedSupportersRegistry parseReadmeSupporters(String markdown) { + final supporters = {}; + final pattern = RegExp( + r'href="https://github\.com/([A-Za-z0-9-]+)"[^>]*>.*?alt="([^"]*)"[^>]*>.*?\s*[¥¥]([0-9]+(?:\.[0-9]+)?)', + caseSensitive: false, + dotAll: true, + ); + for (final match in pattern.allMatches(markdown)) { + final login = match.group(1)?.trim().toLowerCase(); + final name = match.group(2)?.trim(); + final amount = double.tryParse(match.group(3) ?? ''); + if (login == null || login.isEmpty || amount == null || amount <= 0) { + continue; + } + final existing = supporters[login]; + supporters[login] = GitHubDonationInfo( + amountCny: (existing?.amountCny ?? 0) + amount, + displayName: (name != null && name.isNotEmpty) + ? name + : existing?.displayName, + ); + } + return ParsedSupportersRegistry(supportersByLogin: supporters); + } +} diff --git a/lib/services/github/github_token_store.dart b/lib/services/github/github_token_store.dart new file mode 100644 index 000000000..7822aa2b4 --- /dev/null +++ b/lib/services/github/github_token_store.dart @@ -0,0 +1,175 @@ +import 'dart:convert'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'github_community_models.dart'; + +/// 本机专用 GitHub Token 与社区缓存存储。 +/// +/// 严格仅存于本机 SharedPreferences,不参与云同步、配置导入导出与日志输出。 +class GitHubTokenStore { + GitHubTokenStore._(); + + static const String _keyToken = 'github_community_pat_v1'; + static const String _keyProfile = 'github_community_profile_v1'; + static const String _keyPrefs = 'github_community_reward_prefs_v1'; + static const String _keyInvalid = 'github_community_token_invalid_v1'; + static const String _keySupportersJson = 'github_community_supporters_json_v1'; + + /// 缓存有效期:24 小时,期间可随时手动刷新。 + static const Duration cacheTtl = Duration(hours: 24); + + /// 脱敏展示 Token,例如 `ghp_12••••cdef`。 + static String maskToken(String token) { + final trimmed = token.trim(); + if (trimmed.isEmpty) return ''; + if (trimmed.length <= 8) return '••••••••'; + final prefixLen = trimmed.startsWith('github_pat_') ? 11 : 6; + final safePrefix = + trimmed.length > prefixLen + 4 ? trimmed.substring(0, prefixLen) : trimmed.substring(0, 4); + final suffix = trimmed.substring(trimmed.length - 4); + return '$safePrefix••••••$suffix'; + } + + /// 构造统一的 GitHub REST API 请求头。 + static Map buildHeaders({ + String? token, + String? userAgent, + }) { + final headers = { + 'Accept': 'application/vnd.github+json', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': userAgent ?? 'BeeCount-App', + }; + final trimmed = token?.trim(); + if (trimmed != null && trimmed.isNotEmpty) { + headers['Authorization'] = 'Bearer $trimmed'; + } + return headers; + } + + /// 从响应头解析 X-RateLimit-*。 + static GitHubRateLimit? parseRateLimitHeaders(Map headers) { + String? first(String name) { + for (final entry in headers.entries) { + if (entry.key.toLowerCase() == name.toLowerCase()) { + final v = entry.value; + if (v is List && v.isNotEmpty) return v.first?.toString(); + return v?.toString(); + } + } + return null; + } + + final limit = int.tryParse(first('x-ratelimit-limit') ?? ''); + final remaining = int.tryParse(first('x-ratelimit-remaining') ?? ''); + if (limit == null || remaining == null) return null; + final resetSec = int.tryParse(first('x-ratelimit-reset') ?? ''); + return GitHubRateLimit( + limit: limit, + remaining: remaining, + resetAt: resetSec != null + ? DateTime.fromMillisecondsSinceEpoch(resetSec * 1000) + : null, + ); + } + + static Future getToken() async { + final prefs = await SharedPreferences.getInstance(); + final value = prefs.getString(_keyToken)?.trim(); + if (value == null || value.isEmpty) return null; + return value; + } + + static Future saveToken(String token) async { + final prefs = await SharedPreferences.getInstance(); + final trimmed = token.trim(); + if (trimmed.isEmpty) { + await prefs.remove(_keyToken); + } else { + await prefs.setString(_keyToken, trimmed); + } + await prefs.setBool(_keyInvalid, false); + } + + static Future isTokenMarkedInvalid() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getBool(_keyInvalid) ?? false; + } + + static Future markTokenInvalid(bool invalid) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setBool(_keyInvalid, invalid); + } + + static Future getCachedProfile() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_keyProfile); + if (raw == null || raw.isEmpty) return null; + try { + final decoded = jsonDecode(raw); + if (decoded is Map) { + return GitHubCommunityProfile.fromJson(decoded); + } + if (decoded is Map) { + return GitHubCommunityProfile.fromJson( + Map.from(decoded)); + } + } catch (_) {} + return null; + } + + static Future saveCachedProfile(GitHubCommunityProfile profile) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyProfile, jsonEncode(profile.toJson())); + } + + /// 更新缓存中的速率配额(供检查更新等请求顺带刷新配额展示)。 + static Future updateCachedRateLimit(GitHubRateLimit rateLimit) async { + final cached = await getCachedProfile(); + if (cached == null) return; + await saveCachedProfile(cached.copyWith(rateLimit: rateLimit)); + } + + static Future getRewardPreferences() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_keyPrefs); + if (raw == null || raw.isEmpty) return const GitHubRewardPreferences(); + try { + final decoded = jsonDecode(raw); + if (decoded is Map) { + return GitHubRewardPreferences.fromJson( + Map.from(decoded)); + } + } catch (_) {} + return const GitHubRewardPreferences(); + } + + static Future saveRewardPreferences( + GitHubRewardPreferences rewardPrefs) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyPrefs, jsonEncode(rewardPrefs.toJson())); + } + + /// 读取本机动态缓存的最新版 supporters.json。 + static Future getCachedSupportersJson() async { + final prefs = await SharedPreferences.getInstance(); + final raw = prefs.getString(_keySupportersJson); + if (raw == null || raw.trim().isEmpty) return null; + return raw; + } + + /// 保存从远端动态拉取的最新 supporters.json(不发版也能实时更新支持者名单)。 + static Future saveCachedSupportersJson(String rawJson) async { + final trimmed = rawJson.trim(); + if (trimmed.isEmpty) return; + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keySupportersJson, trimmed); + } + + /// 彻底清除 Token 与社区身份缓存(保留用户偏好开关)。 + static Future clearTokenAndProfile() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_keyToken); + await prefs.remove(_keyProfile); + await prefs.remove(_keyInvalid); + } +} diff --git a/lib/services/system/update_service.dart b/lib/services/system/update_service.dart index 50fbaf185..708559f42 100644 --- a/lib/services/system/update_service.dart +++ b/lib/services/system/update_service.dart @@ -51,6 +51,8 @@ String _localizeUpdateMessage(BuildContext context, String? message) { return AppLocalizations.of(context).updateNoApkFound; case '__UPDATE_ALREADY_LATEST_SIMPLE__': return AppLocalizations.of(context).updateAlreadyLatest; + case '__UPDATE_CHECK_RATE_LIMITED__': + return AppLocalizations.of(context).githubRateLimitUpdateHint; default: return message; } @@ -309,6 +311,7 @@ class UpdateService { BuildContext context, { required Function(bool loading) setLoading, required Function(double progress, String status) setProgress, + VoidCallback? onConfigureGitHubToken, }) async { // 防重复点击 if (Platform.isAndroid) { @@ -325,12 +328,19 @@ class UpdateService { // 检查是否是网络错误或API错误,提供兜底方案 final localizedMessage = _localizeUpdateMessage(context, checkResult.message); final message = localizedMessage.isEmpty ? AppLocalizations.of(context).updateCurrentLatestVersion : localizedMessage; - final isNetworkError = message.contains(AppLocalizations.of(context).updateCheckFailedGeneric) || + final isRateLimited = + checkResult.message == '__UPDATE_CHECK_RATE_LIMITED__'; + final isNetworkError = isRateLimited || + message.contains(AppLocalizations.of(context).updateCheckFailedGeneric) || message.contains('HTTP') || checkResult.message?.startsWith('__UPDATE_CHECK') == true; if (isNetworkError) { - // 网络错误或API错误,提供去GitHub的兜底选项 - await UpdateDialogs.showUpdateErrorWithFallback(context, message); + // 网络错误或API错误,提供去GitHub与配置Token的兜底选项 + await UpdateDialogs.showUpdateErrorWithFallback( + context, + message, + onConfigureToken: onConfigureGitHubToken, + ); } else { // 正常情况(已是最新版本) await AppDialog.info( diff --git a/lib/services/update/update_checker.dart b/lib/services/update/update_checker.dart index 0d540304b..3e89f8d4e 100644 --- a/lib/services/update/update_checker.dart +++ b/lib/services/update/update_checker.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/foundation.dart' show visibleForTesting; import 'package:dio/dio.dart'; import 'package:package_info_plus/package_info_plus.dart'; +import '../github/github_token_store.dart'; import '../system/logger_service.dart'; import 'update_result.dart'; @@ -10,6 +11,8 @@ class UpdateChecker { UpdateChecker._(); static final Dio _dio = Dio(); + static const String latestReleaseApiUrl = + 'https://api.github.com/repos/TNT-Likely/BeeCount/releases/latest'; /// 清理 release notes,移除 commit hash 和链接 static String _cleanReleaseNotes(String body) { @@ -82,56 +85,132 @@ class UpdateChecker { } /// 检查更新信息 - static Future checkUpdate() async { + static Future checkUpdate({ + Dio? dio, + String? tokenOverride, + Future Function()? currentVersionOverride, + }) async { try { // 获取当前版本信息 - final currentInfo = await _getAppInfo(); - final currentVersion = _normalizeVersion(currentInfo.version); + final currentVersion = currentVersionOverride != null + ? _normalizeVersion(await currentVersionOverride()) + : _normalizeVersion((await _getAppInfo()).version); logger.info('UpdateChecker', '当前版本: $currentVersion'); - // 配置Dio超时 - _dio.options.connectTimeout = const Duration(seconds: 30); - _dio.options.receiveTimeout = const Duration(minutes: 2); - _dio.options.sendTimeout = const Duration(minutes: 2); + final client = dio ?? _dio; + if (dio == null) { + // 配置Dio超时 + client.options.connectTimeout = const Duration(seconds: 30); + client.options.receiveTimeout = const Duration(minutes: 2); + client.options.sendTimeout = const Duration(minutes: 2); + } + + // 读取本机保存的 GitHub Token(失效标记为 true 时直接走匿名,不浪费一次 401) + String? activeToken = tokenOverride?.trim(); + if (activeToken == null) { + final markedInvalid = await GitHubTokenStore.isTokenMarkedInvalid(); + if (!markedInvalid) { + activeToken = await GitHubTokenStore.getToken(); + } + } + if (activeToken != null && activeToken.isEmpty) { + activeToken = null; + } - // 获取最新 release 信息 - 添加重试机制 - logger.info('UpdateChecker', '开始请求GitHub API...'); + // 获取最新 release 信息 - 添加重试机制与 401 降级、403/429 限流识别 + logger.info('UpdateChecker', + '开始请求GitHub API (${activeToken != null ? "已配置Token" : "匿名"})...'); Response? resp; int attempts = 0; const maxAttempts = 3; + bool retriedAfterUnauthorized = false; while (attempts < maxAttempts) { attempts++; try { logger.info('UpdateChecker', '尝试第$attempts次请求GitHub API...'); - resp = await _dio.get( - 'https://api.github.com/repos/TNT-Likely/BeeCount/releases/latest', + final headers = GitHubTokenStore.buildHeaders( + token: activeToken, + userAgent: _generateRandomUserAgent(), + ); + resp = await client.get( + latestReleaseApiUrl, options: Options( - headers: { - 'Accept': 'application/vnd.github+json', - 'User-Agent': _generateRandomUserAgent(), - }, + headers: headers, + validateStatus: (status) => status != null && status < 500, ), ); - // 如果是成功响应,跳出循环 + + final rateLimit = + GitHubTokenStore.parseRateLimitHeaders(resp.headers.map); + if (rateLimit != null && activeToken != null) { + unawaited(GitHubTokenStore.updateCachedRateLimit(rateLimit)); + } + if (resp.statusCode == 200) { logger.info('UpdateChecker', 'GitHub API请求成功'); break; - } else { + } + + // Token 失效(HTTP 401):标记失效并立刻降级为匿名重试一次 + if (resp.statusCode == 401 && + activeToken != null && + !retriedAfterUnauthorized) { + logger.warning( + 'UpdateChecker', 'GitHub Token 已失效 (HTTP 401),自动降级为匿名检查'); + await GitHubTokenStore.markTokenInvalid(true); + activeToken = null; + retriedAfterUnauthorized = true; + attempts--; // 不消耗正常重试次数 + continue; + } + + // 命中速率限制(403 remaining==0 或 429):立刻返回限流提示,不再无意义重试 + if (_isRateLimitedResponse(resp)) { + logger.warning('UpdateChecker', + 'GitHub API 触发速率限制 (HTTP ${resp.statusCode})'); + return UpdateResult( + hasUpdate: false, + message: '__UPDATE_CHECK_RATE_LIMITED__', + ); + } + + logger.warning( + 'UpdateChecker', '第$attempts次请求返回错误状态码: ${resp.statusCode}'); + if (attempts == maxAttempts) { + break; + } + await Future.delayed(const Duration(seconds: 1)); + } on DioException catch (e) { + final status = e.response?.statusCode; + if (status == 401 && + activeToken != null && + !retriedAfterUnauthorized) { logger.warning( - 'UpdateChecker', '第$attempts次请求返回错误状态码: ${resp.statusCode}'); - if (attempts == maxAttempts) { - break; // 最后一次尝试,不再重试 - } - await Future.delayed(const Duration(seconds: 1)); + 'UpdateChecker', 'GitHub Token 鉴权失败 (401),降级为匿名检查'); + await GitHubTokenStore.markTokenInvalid(true); + activeToken = null; + retriedAfterUnauthorized = true; + attempts--; + continue; } + if (e.response != null && _isRateLimitedResponse(e.response!)) { + return UpdateResult( + hasUpdate: false, + message: '__UPDATE_CHECK_RATE_LIMITED__', + ); + } + logger.error('UpdateChecker', '第$attempts次请求失败', e); + if (attempts == maxAttempts) { + rethrow; + } + await Future.delayed(const Duration(seconds: 1)); } catch (e) { logger.error('UpdateChecker', '第$attempts次请求失败', e); if (attempts == maxAttempts) { - rethrow; // 最后一次尝试失败时抛出异常 + rethrow; } - // 等待1秒后重试 await Future.delayed(const Duration(seconds: 1)); } } @@ -188,6 +267,16 @@ class UpdateChecker { } } + static bool _isRateLimitedResponse(Response resp) { + final code = resp.statusCode; + if (code == 429) return true; + if (code != 403) return false; + final rl = GitHubTokenStore.parseRateLimitHeaders(resp.headers.map); + if (rl != null && rl.remaining == 0) return true; + final body = resp.data?.toString().toLowerCase() ?? ''; + return body.contains('rate limit'); + } + /// 从 GitHub Release assets 列表里挑出适配当前设备的 APK。 /// /// v3.2.1 起 Release 含多个按 ABI 拆分的 APK: diff --git a/lib/services/update/update_dialogs.dart b/lib/services/update/update_dialogs.dart index 9fd783df4..08b5be74f 100644 --- a/lib/services/update/update_dialogs.dart +++ b/lib/services/update/update_dialogs.dart @@ -154,12 +154,13 @@ class UpdateDialogs { return result ?? false; } - /// 显示更新检测失败的错误弹窗,提供去GitHub的兜底选项 + /// 显示更新检测失败的错误弹窗,提供去GitHub与配置Token的兜底选项 static Future showUpdateErrorWithFallback( BuildContext context, - String error, - ) async { - final result = await showDialog( + String error, { + VoidCallback? onConfigureToken, + }) async { + final result = await showDialog( context: context, builder: (context) => AlertDialog( title: Text(AppLocalizations.of(context).updateCheckFailedTitle), @@ -173,17 +174,32 @@ class UpdateDialogs { borderRadius: BorderRadius.circular(10), ), ), - onPressed: () => Navigator.of(context).pop(false), + onPressed: () => Navigator.of(context).pop('cancel'), child: Text(AppLocalizations.of(context).updateCancelButton), ), - const SizedBox(width: 12), + if (onConfigureToken != null) ...[ + const SizedBox(width: 8), + OutlinedButton.icon( + style: OutlinedButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.primary, + side: BorderSide(color: Theme.of(context).colorScheme.primary), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + onPressed: () => Navigator.of(context).pop('token'), + icon: const Icon(Icons.key_rounded, size: 17), + label: Text(AppLocalizations.of(context).githubConfigureTokenAction), + ), + ], + const SizedBox(width: 8), FilledButton.icon( style: FilledButton.styleFrom( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), ), - onPressed: () => Navigator.of(context).pop(true), + onPressed: () => Navigator.of(context).pop('github'), icon: const Icon(Icons.open_in_new, size: 18), label: Text(AppLocalizations.of(context).updateGoToGitHub), ), @@ -191,8 +207,11 @@ class UpdateDialogs { ), ); - if (result == true) { + if (!context.mounted) return; + if (result == 'github') { await launchGitHubReleases(context); + } else if (result == 'token') { + onConfigureToken?.call(); } } diff --git a/lib/styles/header_skins.dart b/lib/styles/header_skins.dart index f23485814..b31cdc6b3 100644 --- a/lib/styles/header_skins.dart +++ b/lib/styles/header_skins.dart @@ -9,6 +9,7 @@ part 'header_skins/skin_common.dart'; part 'header_skins/anniversary_skin.dart'; part 'header_skins/aurora_skin.dart'; part 'header_skins/mountains_skin.dart'; +part 'header_skins/community_skins.dart'; part 'header_skins/page_composition.dart'; /// 皮肤系统:皮肤 = 叠在「主题色底」之上的装饰层(渲染在 PrimaryHeader)。 @@ -33,6 +34,9 @@ enum HeaderSkinGroup { /// 周年纪念款,永远置顶。 anniversary, + /// 开源共创与社区支持者荣誉典藏款。 + community, + /// 主题色渐变。 gradient, @@ -49,6 +53,7 @@ enum HeaderSkinGroup { /// 分组在选择页里的先后顺序。 const List kHeaderSkinGroupOrder = [ HeaderSkinGroup.anniversary, + HeaderSkinGroup.community, HeaderSkinGroup.gradient, HeaderSkinGroup.scene, HeaderSkinGroup.pattern, @@ -96,6 +101,9 @@ class HeaderSkin { /// 皮肤是否自带配色(= 绑定了主题色)。 bool get hasFixedPalette => boundPrimary != null; + /// 是否为社区荣誉限定皮肤(需验证 GitHub 贡献/捐赠或作者身份解锁)。 + bool get isCommunityHonor => group == HeaderSkinGroup.community; + /// 选择页卡片左上角小徽标(如周年款的「1st」),null 不显示。 final String? badge; @@ -153,6 +161,45 @@ final List kHeaderSkins = [ isAnimated: true, boundPrimary: _kCakeCandleL, badge: '1st'), + HeaderSkin( + id: 'community_woodblock_lamp', + group: HeaderSkinGroup.community, + nameOf: (l) => l.headerSkinCommunityWoodblockLamp, + builder: (p, d) => _CommunityArtworkScene( + spec: _kWoodblockLampSpec, isDark: d, isPageScene: false), + pageBuilder: (p, d) => _CommunityArtworkScene( + spec: _kWoodblockLampSpec, isDark: d, isPageScene: true), + tabBarBuilder: (p, d) => _CommunityTabDeco( + specId: _kWoodblockLampSpec.id, isDark: d), + isAnimated: true, + boundPrimary: _kWoodblockLampSpec.accentDay, + badge: 'OSS'), + HeaderSkin( + id: 'community_honey_jar', + group: HeaderSkinGroup.community, + nameOf: (l) => l.headerSkinCommunityHoneyJar, + builder: (p, d) => _CommunityArtworkScene( + spec: _kHoneyJarSpec, isDark: d, isPageScene: false), + pageBuilder: (p, d) => _CommunityArtworkScene( + spec: _kHoneyJarSpec, isDark: d, isPageScene: true), + tabBarBuilder: (p, d) => _CommunityTabDeco( + specId: _kHoneyJarSpec.id, isDark: d), + isAnimated: true, + boundPrimary: _kHoneyJarSpec.accentDay, + badge: 'Patron'), + HeaderSkin( + id: 'community_starlit_hive', + group: HeaderSkinGroup.community, + nameOf: (l) => l.headerSkinCommunityStarlitHive, + builder: (p, d) => _CommunityArtworkScene( + spec: _kStarlitHiveSpec, isDark: d, isPageScene: false), + pageBuilder: (p, d) => _CommunityArtworkScene( + spec: _kStarlitHiveSpec, isDark: d, isPageScene: true), + tabBarBuilder: (p, d) => _CommunityTabDeco( + specId: _kStarlitHiveSpec.id, isDark: d), + isAnimated: true, + boundPrimary: _kStarlitHiveSpec.accentDay, + badge: 'Co-Creator'), HeaderSkin( id: 'aurora', group: HeaderSkinGroup.gradient, diff --git a/lib/styles/header_skins/community_skins.dart b/lib/styles/header_skins/community_skins.dart new file mode 100644 index 000000000..7a3014ab3 --- /dev/null +++ b/lib/styles/header_skins/community_skins.dart @@ -0,0 +1,1319 @@ +part of '../header_skins.dart'; + +// ============ 社区荣誉典藏皮肤(对标「冬日手记」日夜动态版画) ============ +// +// 1. 青灯刻木 (`community_woodblock_lamp`) — 代码贡献者限定(筑巢者 / 核心工蜂) +// 2. 松间采蜜 (`community_honey_jar`) — 捐赠支持者限定(暖心 / 黄金 / 守护者) +// 3. 星野归巢 (`community_starlit_hive`) — 双重共创者 / 作者典藏 +// +// 架构特点: +// - 全屏版画原图 + 底部自然羽化过渡到宣纸/深色底 +// - 暗黑模式采用与冬日手记一致的「冷暗降明度底图 + 暖光焦点局部留光」双层合成 +// - 轻量单 AnimationController 驱动柔和微动效(尊重减弱动态效果与动画开关) +// - 56dp 悬浮底栏微缩插画(景物避开 5 枚等宽图标,落于缝隙与两端) + +class _CommunitySkinSpec { + const _CommunitySkinSpec({ + required this.id, + required this.assetPath, + required this.paperDay, + required this.paperNight, + required this.accentDay, + required this.accentNight, + required this.washNight, + required this.focalEllipses, + required this.keepOpacity, + }); + + final String id; + final String assetPath; + final Color paperDay; + final Color paperNight; + final Color accentDay; + final Color accentNight; + final Color washNight; + final List<_FocalSpot> focalEllipses; + final double keepOpacity; +} + +class _FocalSpot { + const _FocalSpot(this.cx, this.cy, this.rx, this.ry, {this.peak = 1.0}); + final double cx, cy, rx, ry, peak; +} + +const _kWoodblockLampSpec = _CommunitySkinSpec( + id: 'community_woodblock_lamp', + assetPath: 'assets/community_skins/woodblock_lamp.jpg', + paperDay: Color(0xFFE3EBEE), + paperNight: Color(0xFF16212C), + accentDay: Color(0xFF2E7D78), + accentNight: Color(0xFF7ED4CC), + washNight: Color(0xFF1B314A), + focalEllipses: [ + _FocalSpot(0.75, 0.30, 0.28, 0.34, peak: 1.0), + _FocalSpot(0.69, 0.76, 0.32, 0.26, peak: 0.9), + ], + keepOpacity: 0.94, +); + +const _kHoneyJarSpec = _CommunitySkinSpec( + id: 'community_honey_jar', + assetPath: 'assets/community_skins/honey_jar.jpg', + paperDay: Color(0xFFF5EAD8), + paperNight: Color(0xFF281E18), + accentDay: Color(0xFFB46914), + accentNight: Color(0xFFF3BE6D), + washNight: Color(0xFF4E301D), + focalEllipses: [ + _FocalSpot(0.70, 0.62, 0.24, 0.30, peak: 1.0), + _FocalSpot(0.59, 0.52, 0.12, 0.16, peak: 0.88), + ], + keepOpacity: 0.96, +); + +const _kStarlitHiveSpec = _CommunitySkinSpec( + id: 'community_starlit_hive', + assetPath: 'assets/community_skins/starlit_hive.jpg', + paperDay: Color(0xFFE3ECEF), + paperNight: Color(0xFF14222F), + accentDay: Color(0xFF2D6373), + accentNight: Color(0xFF8FD2D8), + washNight: Color(0xFF152B42), + focalEllipses: [ + _FocalSpot(0.79, 0.58, 0.18, 0.22, peak: 1.0), + _FocalSpot(0.46, 0.24, 0.42, 0.20, peak: 0.65), + ], + keepOpacity: 0.96, +); + +_CommunitySkinSpec? _communitySpecFor(String id) => switch (id) { + 'community_woodblock_lamp' => _kWoodblockLampSpec, + 'community_honey_jar' => _kHoneyJarSpec, + 'community_starlit_hive' => _kStarlitHiveSpec, + _ => null, + }; + +bool isCommunitySkinId(String id) => _communitySpecFor(id) != null; + +List? _communityPageColors(String id, bool dark) { + final spec = _communitySpecFor(id); + if (spec == null) return null; + if (dark) { + final mid = Color.lerp(spec.paperNight, const Color(0xFF14181E), 0.45)!; + return [spec.paperNight, mid, const Color(0xFF121519)]; + } + final mid = Color.lerp(spec.paperDay, const Color(0xFFFAF9F5), 0.52)!; + return [spec.paperDay, mid, const Color(0xFFFAF9F5)]; +} + +/// 暗黑降明度与增强对比度的 ColorMatrix(等效 CSS brightness(0.40) contrast(1.12))。 +const List _kNightGradeMatrix = [ + 0.44, 0, 0, 0, -14, + 0, 0.44, 0, 0, -14, + 0, 0, 0.46, 0, -10, + 0, 0, 0, 1, 0, +]; + +class _CommunityArtworkScene extends StatelessWidget { + const _CommunityArtworkScene({ + required this.spec, + required this.isDark, + required this.isPageScene, + }); + + final _CommunitySkinSpec spec; + final bool isDark; + final bool isPageScene; + + Widget _imagePlate() => Image.asset( + spec.assetPath, + fit: BoxFit.cover, + alignment: isPageScene + ? const Alignment(0, 0.22) + : const Alignment(0, 0.12), + filterQuality: FilterQuality.medium, + gaplessPlayback: true, + errorBuilder: (_, __, ___) => ColoredBox( + color: isDark ? spec.paperNight : spec.paperDay, + ), + ); + + @override + Widget build(BuildContext context) { + Widget artwork = Stack( + fit: StackFit.expand, + children: [ + if (!isDark) + _imagePlate() + else ...[ + ColorFiltered( + colorFilter: const ColorFilter.matrix(_kNightGradeMatrix), + child: _imagePlate(), + ), + ColoredBox(color: spec.washNight.withValues(alpha: 0.34)), + Opacity( + opacity: spec.keepOpacity, + child: ShaderMask( + blendMode: BlendMode.dstIn, + shaderCallback: (rect) => _buildFocalMaskShader(rect, spec), + child: _imagePlate(), + ), + ), + ], + _AnimSkinShell( + seconds: 10, + staticFrame: 0.38, + painterFor: (anim) => _CommunityAmbientPainter( + specId: spec.id, + isDark: isDark, + anim: anim, + ), + ), + ], + ); + + if (!isPageScene) { + return artwork; + } + + // 整页模式:上半区 360pt 完整展现版画,底部柔和羽化融入纸面 + return LayoutBuilder(builder: (context, box) { + final sceneHeight = math.min(box.maxHeight, 376.0); + return Align( + alignment: Alignment.topCenter, + child: SizedBox( + width: box.maxWidth, + height: sceneHeight, + child: ShaderMask( + blendMode: BlendMode.dstIn, + shaderCallback: (rect) => const LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + Colors.white, + Colors.white, + Color(0x99FFFFFF), + Colors.transparent, + ], + stops: [0.0, 0.62, 0.84, 1.0], + ).createShader(rect), + child: artwork, + ), + ), + ); + }); + } + + Shader _buildFocalMaskShader(Rect rect, _CommunitySkinSpec spec) { + final main = spec.focalEllipses.first; + final center = Alignment(main.cx * 2 - 1, main.cy * 2 - 1); + final radius = math.max(main.rx, main.ry) * 1.45; + return RadialGradient( + center: center, + radius: radius, + colors: [ + Colors.white.withValues(alpha: main.peak), + Colors.white.withValues(alpha: main.peak * 0.78), + Colors.transparent, + ], + stops: const [0.0, 0.48, 1.0], + ).createShader(rect); + } +} + +/// 三款典藏皮肤的丰富微动效画笔(单 Controller,整数倍频无缝循环,无 blur)。 +class _CommunityAmbientPainter extends CustomPainter { + _CommunityAmbientPainter({ + required this.specId, + required this.isDark, + required this.anim, + }) : super(repaint: anim); + + final String specId; + final bool isDark; + final Animation anim; + + void _drawStar4(Canvas canvas, Offset c, double r, Color color) { + final path = Path() + ..moveTo(c.dx, c.dy - r) + ..quadraticBezierTo(c.dx + r * 0.16, c.dy - r * 0.16, c.dx + r, c.dy) + ..quadraticBezierTo(c.dx + r * 0.16, c.dy + r * 0.16, c.dx, c.dy + r) + ..quadraticBezierTo(c.dx - r * 0.16, c.dy + r * 0.16, c.dx - r, c.dy) + ..quadraticBezierTo(c.dx - r * 0.16, c.dy - r * 0.16, c.dx, c.dy - r) + ..close(); + canvas.drawPath(path, Paint()..color = color); + } + + void _drawMiniBee( + Canvas canvas, + Offset pos, + double angle, + double wingPhase, + double scale, + ) { + canvas.save(); + canvas.translate(pos.dx, pos.dy); + canvas.rotate(angle); + final flap = math.sin(wingPhase) * 0.55; + // 半透明振翅 + for (final side in const [-1.0, 1.0]) { + canvas.save(); + canvas.translate(-0.8 * scale, -2.6 * scale); + canvas.rotate(side * (0.45 + flap * 0.55)); + canvas.drawOval( + Rect.fromCenter( + center: Offset(side * 1.4 * scale, -2.2 * scale), + width: 4.8 * scale, + height: 2.7 * scale, + ), + Paint()..color = Colors.white.withValues(alpha: isDark ? 0.72 : 0.85), + ); + canvas.restore(); + } + // 金色小身躯 + 墨纹 + canvas.drawOval( + Rect.fromCenter( + center: Offset.zero, + width: 7.4 * scale, + height: 4.6 * scale, + ), + Paint()..color = const Color(0xFFF5B72F), + ); + final stripe = Paint() + ..color = const Color(0xFF3E260C).withValues(alpha: 0.82) + ..strokeWidth = 1.15 * scale; + canvas.drawLine( + Offset(-1.1 * scale, -2.0 * scale), + Offset(-1.1 * scale, 2.0 * scale), + stripe, + ); + canvas.drawLine( + Offset(1.1 * scale, -2.0 * scale), + Offset(1.1 * scale, 2.0 * scale), + stripe, + ); + canvas.restore(); + } + + @override + void paint(Canvas canvas, Size size) { + if (size.isEmpty) return; + final t = anim.value; + final w = size.width; + final h = size.height; + + if (specId == 'community_woodblock_lamp') { + // 1. 摇曳呼吸的暖金台灯光锥 + 核心焦光 + final breath = 0.5 + 0.5 * math.sin(t * math.pi * 2); + final flicker = 0.5 + 0.5 * math.sin(t * math.pi * 2 * 3 + 0.6); + final conePath = Path() + ..moveTo(w * 0.68, h * 0.28) + ..lineTo(w * 0.82, h * 0.28) + ..lineTo(w * 0.96, h * 0.88) + ..lineTo(w * 0.42, h * 0.88) + ..close(); + canvas.drawPath( + conePath, + Paint() + ..shader = LinearGradient( + begin: const Alignment(0.45, -0.45), + end: const Alignment(0.15, 0.85), + colors: [ + const Color(0xFFFFDF8A).withValues( + alpha: (isDark ? 0.24 : 0.14) + breath * 0.08 + flicker * 0.03, + ), + const Color(0xFFFFC152).withValues( + alpha: (isDark ? 0.10 : 0.06) + breath * 0.04, + ), + const Color(0xFFFFBA4A).withValues(alpha: 0), + ], + stops: const [0.0, 0.52, 1.0], + ).createShader(Offset.zero & size), + ); + + final glowCenter = Offset(w * 0.74, h * 0.36); + final glowR = math.max(w, h) * 0.36; + canvas.drawCircle( + glowCenter, + glowR, + Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFFFFDC82) + .withValues(alpha: (isDark ? 0.28 : 0.18) + breath * 0.10), + const Color(0xFFFFBA4A).withValues(alpha: 0), + ], + ).createShader(Rect.fromCircle(center: glowCenter, radius: glowR)), + ); + + // 2. 两缕缓缓升腾摇曳的松烟/木屑细烟丝 + for (var i = 0; i < 2; i++) { + final baseX = w * (0.50 + i * 0.09); + final sway1 = math.sin((t + i * 0.4) * math.pi * 2) * 10; + final sway2 = math.cos((t * 2 + i * 0.5) * math.pi * 2) * 8; + final wisp = Path() + ..moveTo(baseX, h * 0.80) + ..cubicTo( + baseX + sway1, + h * 0.65, + baseX - sway2, + h * 0.50, + baseX + sway1 * 0.7, + h * 0.34, + ); + canvas.drawPath( + wisp, + Paint() + ..shader = LinearGradient( + begin: Alignment.bottomCenter, + end: Alignment.topCenter, + colors: [ + const Color(0xFFFFEAC0).withValues(alpha: 0), + const Color(0xFFFFEAC0) + .withValues(alpha: isDark ? 0.16 : 0.20), + const Color(0xFFFFEAC0).withValues(alpha: 0), + ], + ).createShader(Rect.fromLTWH(baseX - 24, h * 0.32, 48, h * 0.50)) + ..style = PaintingStyle.stroke + ..strokeWidth = 2.0 - i * 0.4 + ..strokeCap = StrokeCap.round, + ); + } + + // 3. 14 粒在灯锥内缓缓浮升的温暖金尘(含柔和光晕与轻柔摆动) + const motes = [ + (0.54, 0.80, 2.2, 0.00, 1), + (0.62, 0.74, 1.8, 0.11, 2), + (0.68, 0.82, 2.4, 0.20, 1), + (0.73, 0.68, 1.6, 0.29, 2), + (0.79, 0.76, 2.1, 0.38, 1), + (0.58, 0.66, 1.5, 0.46, 2), + (0.65, 0.78, 2.5, 0.54, 1), + (0.76, 0.62, 1.7, 0.62, 2), + (0.83, 0.72, 1.9, 0.70, 1), + (0.60, 0.84, 1.6, 0.78, 1), + (0.70, 0.58, 2.0, 0.85, 2), + (0.86, 0.66, 1.5, 0.91, 1), + (0.50, 0.72, 1.4, 0.33, 1), + (0.74, 0.86, 1.8, 0.66, 2), + ]; + for (final (fx, fy, r, phase, speed) in motes) { + final p = (t * speed + phase) % 1.0; + final op = (p < 0.18 ? p / 0.18 : (p > 0.82 ? (1 - p) / 0.18 : 1.0)) + .clamp(0.0, 1.0); + final sway = math.sin((t * 2 + phase) * math.pi * 2) * 7.5; + final pos = Offset(w * fx + sway - p * 6, h * fy - p * h * 0.28); + canvas.drawCircle( + pos, + r * 2.6, + Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFFFFE599) + .withValues(alpha: op * (isDark ? 0.36 : 0.24)), + const Color(0xFFFFE599).withValues(alpha: 0), + ], + ).createShader(Rect.fromCircle(center: pos, radius: r * 2.6)), + ); + canvas.drawCircle( + pos, + r, + Paint() + ..color = const Color(0xFFFFF1C1) + .withValues(alpha: op * (isDark ? 0.88 : 0.70)), + ); + } + + // 4. 铜灯沿与刻刀刃的四角微闪光斑 + for (final (fx, fy, phase) in const [ + (0.77, 0.24, 0.12), + (0.66, 0.73, 0.48), + (0.84, 0.60, 0.78), + ]) { + final twinkle = + math.pow(0.5 + 0.5 * math.sin((t * 2 + phase) * math.pi * 2), 3) + .toDouble(); + if (twinkle > 0.15) { + _drawStar4( + canvas, + Offset(w * fx, h * fy), + 3.2 + twinkle * 4.2, + const Color(0xFFFFF4CC) + .withValues(alpha: twinkle * (isDark ? 0.90 : 0.72)), + ); + } + } + return; + } + + if (specId == 'community_honey_jar') { + // 1. 斜照暖阳呼吸光束 + final pulse = 0.5 + 0.5 * math.sin(t * math.pi * 2); + final shaftShift = math.sin(t * math.pi * 2) * 10; + final sunBeam = Path() + ..moveTo(w * 0.08 + shaftShift, 0) + ..lineTo(w * 0.46 + shaftShift, 0) + ..lineTo(w * 0.92 + shaftShift * 0.6, h * 0.92) + ..lineTo(w * 0.48 + shaftShift * 0.6, h * 0.92) + ..close(); + canvas.drawPath( + sunBeam, + Paint() + ..shader = LinearGradient( + begin: Alignment.topLeft, + end: Alignment.bottomRight, + colors: [ + const Color(0xFFFFE59D) + .withValues(alpha: (isDark ? 0.14 : 0.22) + pulse * 0.08), + const Color(0xFFFFCE67) + .withValues(alpha: (isDark ? 0.08 : 0.10) + pulse * 0.04), + const Color(0xFFFFCE67).withValues(alpha: 0), + ], + stops: const [0.0, 0.55, 1.0], + ).createShader(Offset.zero & size), + ); + + // 2. 琥珀蜜罐内部柔光呼吸 + final jarCenter = Offset(w * 0.72, h * 0.60); + final jarR = math.max(w, h) * 0.26; + canvas.drawCircle( + jarCenter, + jarR, + Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFFFFC547) + .withValues(alpha: (isDark ? 0.30 : 0.18) + pulse * 0.12), + const Color(0xFFF0941A).withValues(alpha: 0), + ], + ).createShader(Rect.fromCircle(center: jarCenter, radius: jarR)), + ); + + // 3. 蜂蜜棒末端缓慢拉丝滴落的动态琥珀蜜滴 + 落杯涟漪(每周期 2 滴) + final dp = (t * 2) % 1.0; + final dropX = w * 0.605; + final startY = h * 0.46; + final landY = h * 0.66; + if (dp < 0.72) { + final fallP = (dp / 0.72).clamp(0.0, 1.0); + // 前 40% 缓慢拉长聚集,后 60% 加速落入杯中 + final dropY = fallP < 0.42 + ? startY + (fallP / 0.42) * 10 + : startY + 10 + math.pow((fallP - 0.42) / 0.58, 2.0) * (landY - startY - 10); + final dropR = fallP < 0.42 ? 2.2 + (fallP / 0.42) * 2.0 : 3.8; + final stretch = fallP < 0.42 ? 1.5 : 1.9; + final dropPath = Path() + ..moveTo(dropX, dropY - dropR * stretch) + ..cubicTo( + dropX + dropR, + dropY - dropR * 0.2, + dropX + dropR, + dropY + dropR, + dropX, + dropY + dropR, + ) + ..cubicTo( + dropX - dropR, + dropY + dropR, + dropX - dropR, + dropY - dropR * 0.2, + dropX, + dropY - dropR * stretch, + ) + ..close(); + canvas.drawPath( + dropPath, + Paint()..color = const Color(0xFFF0A21B).withValues(alpha: 0.92), + ); + canvas.drawCircle( + Offset(dropX - dropR * 0.3, dropY + dropR * 0.1), + dropR * 0.32, + Paint()..color = const Color(0xFFFFF4C8).withValues(alpha: 0.85), + ); + } else { + // 蜜滴落入后的金色扩散微涟漪 + final ripP = ((dp - 0.72) / 0.28).clamp(0.0, 1.0); + final ripAlpha = (1 - ripP) * 0.75; + canvas.drawOval( + Rect.fromCenter( + center: Offset(dropX, landY), + width: 8 + ripP * 26, + height: 3.5 + ripP * 10, + ), + Paint() + ..color = const Color(0xFFFFD56B).withValues(alpha: ripAlpha) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.4, + ); + } + + // 4. 12 粒斜阳花粉 + 轻旋白花瓣 + const particles = [ + (0.24, 0.26, 2.0, 0.00, false), + (0.38, 0.44, 1.7, 0.12, false), + (0.52, 0.34, 2.4, 0.24, true), + (0.64, 0.48, 1.8, 0.35, false), + (0.45, 0.58, 2.2, 0.46, true), + (0.76, 0.40, 1.9, 0.56, false), + (0.32, 0.62, 2.1, 0.64, false), + (0.58, 0.24, 2.6, 0.72, true), + (0.84, 0.54, 1.6, 0.80, false), + (0.18, 0.48, 1.8, 0.88, false), + (0.68, 0.68, 2.0, 0.18, false), + (0.42, 0.20, 2.5, 0.52, true), + ]; + for (final (fx, fy, r, phase, isPetal) in particles) { + final p = (t + phase) % 1.0; + final op = (p < 0.16 ? p / 0.16 : (p > 0.84 ? (1 - p) / 0.16 : 1.0)) + .clamp(0.0, 1.0); + final pos = Offset( + w * fx + p * 34 + math.sin((t * 2 + phase) * math.pi * 2) * 5, + h * fy + (isPetal ? p * 26 : -p * 18), + ); + if (isPetal) { + canvas.save(); + canvas.translate(pos.dx, pos.dy); + canvas.rotate((t * 2 + phase) * math.pi * 2); + canvas.drawOval( + Rect.fromCenter(center: Offset.zero, width: r * 2.4, height: r * 1.3), + Paint() + ..color = const Color(0xFFFFFBF0) + .withValues(alpha: op * (isDark ? 0.68 : 0.86)), + ); + canvas.restore(); + } else { + canvas.drawCircle( + pos, + r * 2.2, + Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFFFFE599) + .withValues(alpha: op * (isDark ? 0.42 : 0.30)), + const Color(0xFFFFE599).withValues(alpha: 0), + ], + ).createShader(Rect.fromCircle(center: pos, radius: r * 2.2)), + ); + canvas.drawCircle( + pos, + r, + Paint() + ..color = const Color(0xFFFFF6D6) + .withValues(alpha: op * (isDark ? 0.86 : 0.74)), + ); + } + } + + // 5. 两只绕蜜罐与花枝翩跹飞舞的迷你金蜂(整数倍频 8 字轨迹 + 高速振翅) + final a1 = t * math.pi * 2; + final bee1 = Offset( + w * 0.52 + math.cos(a1) * w * 0.11, + h * 0.36 + math.sin(a1 * 2) * h * 0.055, + ); + final vx1 = -math.sin(a1) * w * 0.11; + final vy1 = 2 * math.cos(a1 * 2) * h * 0.055; + _drawMiniBee(canvas, bee1, math.atan2(vy1, vx1) * 0.35, t * math.pi * 2 * 24, 1.05); + + final a2 = (t + 0.5) * math.pi * 2; + final bee2 = Offset( + w * 0.80 + math.cos(a2) * w * 0.07, + h * 0.48 + math.sin(a2) * h * 0.05, + ); + _drawMiniBee(canvas, bee2, math.sin(a2) * 0.25, t * math.pi * 2 * 28 + 1.2, 0.82); + return; + } + + // community_starlit_hive:流动双层极光绸带 + 闪烁星群 + 2 颗错峰流星 + 6 只灯阁萤火 + 阁楼暖光呼吸 + final wave = 0.5 + 0.5 * math.sin(t * math.pi * 2); + + // 1. 双层起伏流动极光绸带(青碧 + 微金) + for (var layer = 0; layer < 2; layer++) { + final phase = layer * 0.45; + final dy1 = math.sin((t + phase) * math.pi * 2) * 14; + final dy2 = math.cos((t + phase) * math.pi * 2) * 12; + final ribbon = Path() + ..moveTo(-w * 0.05, h * (0.16 + layer * 0.07) + dy1) + ..cubicTo( + w * 0.24, + h * (0.04 + layer * 0.06) - dy2, + w * 0.48, + h * (0.28 + layer * 0.05) + dy1, + w * 0.78, + h * (0.10 + layer * 0.04) - dy1 * 0.6, + ); + canvas.drawPath( + ribbon, + Paint() + ..shader = LinearGradient( + colors: layer == 0 + ? [ + const Color(0xFF5EEAD4).withValues(alpha: 0), + const Color(0xFF6CE6D8).withValues( + alpha: (isDark ? 0.24 : 0.16) + wave * 0.08, + ), + const Color(0xFF99F6E4).withValues( + alpha: (isDark ? 0.18 : 0.12) + wave * 0.05, + ), + const Color(0xFF5EEAD4).withValues(alpha: 0), + ] + : [ + const Color(0xFFFBD97C).withValues(alpha: 0), + const Color(0xFFFBD97C).withValues( + alpha: (isDark ? 0.18 : 0.12) + (1 - wave) * 0.07, + ), + const Color(0xFF7CE4D6).withValues( + alpha: (isDark ? 0.14 : 0.09), + ), + const Color(0xFFFBD97C).withValues(alpha: 0), + ], + ).createShader(Rect.fromLTWH(0, 0, w * 0.85, h * 0.42)) + ..style = PaintingStyle.stroke + ..strokeWidth = layer == 0 ? 28 : 18 + ..strokeCap = StrokeCap.round, + ); + } + + // 2. 阁楼暖窗呼吸柔光 + final lanternCenter = Offset(w * 0.79, h * 0.56); + final lanternR = math.max(w, h) * 0.22; + canvas.drawCircle( + lanternCenter, + lanternR, + Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFFFFD670) + .withValues(alpha: (isDark ? 0.28 : 0.14) + wave * 0.10), + const Color(0xFFFFB84A).withValues(alpha: 0), + ], + ).createShader(Rect.fromCircle(center: lanternCenter, radius: lanternR)), + ); + + // 3. 14 颗错峰闪烁的星点与四角星芒 + const stars = [ + (0.10, 0.14, 1.5, 0.00, true), + (0.22, 0.22, 1.2, 0.15, false), + (0.31, 0.10, 2.0, 0.28, true), + (0.42, 0.19, 1.4, 0.42, false), + (0.53, 0.12, 1.8, 0.55, true), + (0.62, 0.24, 1.3, 0.68, false), + (0.16, 0.31, 1.3, 0.78, false), + (0.37, 0.29, 1.6, 0.86, true), + (0.49, 0.32, 1.2, 0.34, false), + (0.68, 0.16, 1.5, 0.92, false), + (0.08, 0.26, 1.2, 0.48, false), + (0.26, 0.16, 1.4, 0.62, false), + (0.58, 0.08, 1.3, 0.20, false), + (0.45, 0.09, 1.7, 0.74, true), + ]; + for (final (fx, fy, r, phase, cross) in stars) { + final tw = 0.25 + 0.75 * (0.5 + 0.5 * math.sin((t * 2 + phase) * math.pi * 2)); + final pos = Offset(w * fx, h * fy); + if (cross) { + _drawStar4( + canvas, + pos, + r * (1.8 + tw * 1.4), + const Color(0xFFFFF7D6).withValues(alpha: tw * (isDark ? 0.92 : 0.74)), + ); + } else { + canvas.drawCircle( + pos, + r, + Paint() + ..color = const Color(0xFFFFF8DC) + .withValues(alpha: tw * (isDark ? 0.85 : 0.68)), + ); + } + } + + // 4. 6 只绕灯阁翩跹飞舞的暖金萤火虫 + const fireflies = [ + (0.68, 0.56, 0.00, 1.0), + (0.84, 0.50, 0.18, 0.9), + (0.63, 0.66, 0.36, 1.1), + (0.75, 0.46, 0.54, 0.85), + (0.89, 0.62, 0.72, 0.95), + (0.56, 0.58, 0.88, 0.80), + ]; + for (final (fx, fy, phase, sc) in fireflies) { + final angle = (t * 2 + phase) * math.pi * 2; + final glow = 0.35 + 0.65 * (0.5 + 0.5 * math.sin(angle * 1.5)); + final pos = Offset( + w * fx + math.cos(angle) * 11 * sc, + h * fy + math.sin(angle * 0.5) * 9 * sc, + ); + canvas.drawCircle( + pos, + 8.5 * sc, + Paint() + ..shader = RadialGradient( + colors: [ + const Color(0xFFFFE08A).withValues(alpha: glow * 0.62), + const Color(0xFFFFE08A).withValues(alpha: 0), + ], + ).createShader(Rect.fromCircle(center: pos, radius: 8.5 * sc)), + ); + canvas.drawCircle( + pos, + 1.9 * sc, + Paint()..color = const Color(0xFFFFF6D0).withValues(alpha: glow), + ); + } + + // 5. 两颗错峰划过星空的流星 + void drawMeteor(double startT, double spanT, double sx, double sy, double dx, double dy) { + if (t < startT || t > startT + spanT) return; + final p = (t - startT) / spanT; + final alpha = math.sin(math.pi * p) * (isDark ? 0.92 : 0.72); + final head = Offset(w * sx + p * dx, h * sy + p * dy); + final tail = head - Offset(dx * 0.38, dy * 0.38); + canvas.drawLine( + tail, + head, + Paint() + ..shader = LinearGradient( + colors: [ + const Color(0xFFFFF7D6).withValues(alpha: 0), + const Color(0xFFFFF7D6).withValues(alpha: alpha), + ], + ).createShader(Rect.fromPoints(tail, head)) + ..strokeWidth = 1.7 + ..strokeCap = StrokeCap.round, + ); + canvas.drawCircle( + head, + 2.1, + Paint()..color = const Color(0xFFFFFFFF).withValues(alpha: alpha), + ); + } + + drawMeteor(0.06, 0.22, 0.10, 0.12, 92, 38); + drawMeteor(0.56, 0.20, 0.36, 0.08, 78, 32); + } + + @override + bool shouldRepaint(covariant _CommunityAmbientPainter old) => + old.specId != specId || old.isDark != isDark; +} + +/// 56dp 悬浮底栏微缩动态插画装饰层(景物落于 5 项按钮缝隙与左右端头,不压图标文字)。 +class _CommunityTabDeco extends StatelessWidget { + const _CommunityTabDeco({required this.specId, required this.isDark}); + + final String specId; + final bool isDark; + + @override + Widget build(BuildContext context) => _AnimTabShell( + seconds: 8, + painterFor: (anim) => + _CommunityTabPainter(specId: specId, isDark: isDark, anim: anim), + ); +} + +class _CommunityTabPainter extends CustomPainter { + _CommunityTabPainter({ + required this.specId, + required this.isDark, + required this.anim, + }) : super(repaint: anim); + + final String specId; + final bool isDark; + final Animation anim; + + void _drawMiniStar4(Canvas canvas, Offset c, double r, Color color) { + final p = Path() + ..moveTo(c.dx, c.dy - r) + ..lineTo(c.dx + r * 0.26, c.dy - r * 0.26) + ..lineTo(c.dx + r, c.dy) + ..lineTo(c.dx + r * 0.26, c.dy + r * 0.26) + ..lineTo(c.dx, c.dy + r) + ..lineTo(c.dx - r * 0.26, c.dy + r * 0.26) + ..lineTo(c.dx - r, c.dy) + ..lineTo(c.dx - r * 0.26, c.dy - r * 0.26) + ..close(); + canvas.drawPath(p, Paint()..color = color); + } + + @override + void paint(Canvas canvas, Size size) { + if (size.isEmpty) return; + final w = size.width; + final h = size.height; + final t = anim.value; + final pulse = 0.5 + 0.5 * math.sin(t * math.pi * 2); + + if (specId == 'community_woodblock_lamp') { + final line = isDark ? const Color(0xFF7FD2CE) : const Color(0xFF2D6664); + final warm = isDark ? const Color(0xFFF9CC62) : const Color(0xFFD98B1E); + final wood = isDark ? const Color(0xFF6B4E38) : const Color(0xFF9C7656); + + // 实色木案底缘 + 木纹细线 + canvas.drawPath( + Path() + ..moveTo(0, h * 0.87) + ..quadraticBezierTo(w * 0.5, h * 0.83, w, h * 0.87) + ..lineTo(w, h) + ..lineTo(0, h) + ..close(), + Paint()..color = wood.withValues(alpha: isDark ? 0.42 : 0.24), + ); + canvas.drawLine( + Offset(w * 0.10, h * 0.93), + Offset(w * 0.88, h * 0.93), + Paint() + ..color = warm.withValues(alpha: isDark ? 0.16 : 0.18) + ..strokeWidth = 0.8, + ); + + // 左端迷你青瓷铜灯 + 呼吸暖光锥 + 上升微尘 + final beam = Path() + ..moveTo(w * 0.044, h * 0.50) + ..lineTo(w * 0.074, h * 0.50) + ..lineTo(w * 0.108, h * 0.92) + ..lineTo(w * 0.012, h * 0.92) + ..close(); + canvas.drawPath( + beam, + Paint() + ..shader = LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [ + warm.withValues(alpha: (isDark ? 0.34 : 0.24) + pulse * 0.10), + warm.withValues(alpha: 0), + ], + ).createShader(Rect.fromLTWH(0, h * 0.48, w * 0.12, h * 0.46)), + ); + canvas.drawPath( + Path() + ..moveTo(w * 0.032, h) + ..lineTo(w * 0.032, h * 0.58) + ..quadraticBezierTo(w * 0.032, h * 0.42, w * 0.058, h * 0.42), + Paint() + ..color = warm.withValues(alpha: 0.85) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.5, + ); + canvas.drawPath( + Path() + ..moveTo(w * 0.042, h * 0.51) + ..quadraticBezierTo(w * 0.058, h * 0.36, w * 0.076, h * 0.51) + ..close(), + Paint()..color = line.withValues(alpha: 0.95), + ); + // 迷你灯锥里升腾的两粒小金尘 + for (var i = 0; i < 2; i++) { + final mp = (t * 2 + i * 0.5) % 1.0; + final op = math.sin(math.pi * mp); + canvas.drawCircle( + Offset(w * (0.048 + i * 0.018), h * (0.86 - mp * 0.30)), + 1.2, + Paint()..color = const Color(0xFFFFF0B8).withValues(alpha: op * 0.9), + ); + } + + // 缝隙 1(0.20):卷曲刨花 + 轻飘木屑点 + final curl = Paint() + ..color = warm.withValues(alpha: 0.78) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.35 + ..strokeCap = StrokeCap.round; + canvas.drawArc( + Rect.fromCenter( + center: Offset(w * 0.20, h * 0.85), width: 7.5, height: 6.5), + 0.35, + math.pi * 1.5, + false, + curl, + ); + final chipP = (t + 0.2) % 1.0; + canvas.drawCircle( + Offset(w * 0.20 + math.sin(t * math.pi * 2) * 3, h * (0.76 - chipP * 0.35)), + 1.1, + Paint()..color = warm.withValues(alpha: math.sin(math.pi * chipP) * 0.72), + ); + + // 缝隙 2(0.40):木柄刻刀 + 刀锋闪光 + canvas.drawLine( + Offset(w * 0.388, h * 0.90), + Offset(w * 0.412, h * 0.72), + Paint() + ..color = wood.withValues(alpha: 0.88) + ..strokeWidth = 2.2 + ..strokeCap = StrokeCap.round, + ); + canvas.drawLine( + Offset(w * 0.412, h * 0.72), + Offset(w * 0.422, h * 0.63), + Paint() + ..color = line.withValues(alpha: 0.92) + ..strokeWidth = 1.6 + ..strokeCap = StrokeCap.round, + ); + final glint = math.pow(0.5 + 0.5 * math.sin(t * math.pi * 2 * 2), 3).toDouble(); + if (glint > 0.2) { + _drawMiniStar4( + canvas, + Offset(w * 0.422, h * 0.61), + 2.6 + glint * 2.2, + const Color(0xFFFFF4CC).withValues(alpha: glint * 0.9), + ); + } + + // 缝隙 3(0.60):朱红小木刻印章 + final chopRect = RRect.fromRectAndRadius( + Rect.fromCenter(center: Offset(w * 0.60, h * 0.83), width: 7.5, height: 7.5), + const Radius.circular(1.6), + ); + canvas.drawRRect( + chopRect, + Paint()..color = const Color(0xFFC44D42).withValues(alpha: isDark ? 0.32 : 0.20), + ); + canvas.drawRRect( + chopRect, + Paint() + ..color = const Color(0xFFC44D42).withValues(alpha: 0.82) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.1, + ); + + // 缝隙 4(0.80):袅袅摇曳小香烟丝 + final sWob = math.sin(t * math.pi * 2) * 3.2; + canvas.drawPath( + Path() + ..moveTo(w * 0.80, h * 0.88) + ..cubicTo( + w * 0.80 + sWob, + h * 0.68, + w * 0.80 - sWob, + h * 0.48, + w * 0.80 + sWob * 0.6, + h * 0.26, + ), + Paint() + ..color = line.withValues(alpha: (isDark ? 0.36 : 0.28) + pulse * 0.14) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.25 + ..strokeCap = StrokeCap.round, + ); + + // 右端靛墨碟 + 动态墨纹涟漪 + final dishC = Offset(w * 0.945, h * 0.87); + canvas.drawOval( + Rect.fromCenter(center: dishC, width: 18, height: 7), + Paint()..color = line.withValues(alpha: 0.78), + ); + canvas.drawOval( + Rect.fromCenter(center: dishC.translate(0, -0.5), width: 12, height: 4), + Paint() + ..color = (isDark ? const Color(0xFF3A588C) : const Color(0xFF213C54)) + .withValues(alpha: 0.92), + ); + final inkRip = (t * 2) % 1.0; + canvas.drawOval( + Rect.fromCenter( + center: dishC.translate(0, -0.5), + width: 4 + inkRip * 10, + height: 1.5 + inkRip * 3.0, + ), + Paint() + ..color = const Color(0xFF93C5FD).withValues(alpha: (1 - inkRip) * 0.55) + ..style = PaintingStyle.stroke + ..strokeWidth = 0.85, + ); + return; + } + + if (specId == 'community_honey_jar') { + final leaf = isDark ? const Color(0xFF83B88F) : const Color(0xFF426A4C); + final gold = isDark ? const Color(0xFFFAD05A) : const Color(0xFFD68414); + final petal = isDark ? const Color(0xFFFFF5E0) : Colors.white; + + // 底部暖蜜木底缘 + 流光高光 + canvas.drawPath( + Path() + ..moveTo(0, h * 0.88) + ..quadraticBezierTo(w * 0.5, h * 0.82, w, h * 0.88) + ..lineTo(w, h) + ..lineTo(0, h) + ..close(), + Paint()..color = gold.withValues(alpha: isDark ? 0.28 : 0.20), + ); + + // 左右两端随风轻摆的小白花枝 + final sway = math.sin(t * math.pi * 2) * 2.6; + void blossom(double sx, double ex, double ey, double dir) { + final tx = ex + sway * dir; + final ty = ey + math.cos(t * math.pi * 2) * 1.1; + canvas.drawPath( + Path() + ..moveTo(sx, h * 0.95) + ..quadraticBezierTo((sx + tx) / 2, h * 0.72, tx, ty), + Paint() + ..color = leaf.withValues(alpha: 0.86) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.5, + ); + // 5 瓣小白花 + for (var i = 0; i < 5; i++) { + final a = i * math.pi * 2 / 5 + t * 0.3; + canvas.drawCircle( + Offset(tx + math.cos(a) * 2.4, ty + math.sin(a) * 2.4), + 1.7, + Paint()..color = petal.withValues(alpha: 0.94), + ); + } + canvas.drawCircle(Offset(tx, ty), 1.5, Paint()..color = gold); + } + + blossom(w * 0.014, w * 0.062, h * 0.56, 1); + blossom(w * 0.986, w * 0.938, h * 0.56, -1); + + // 缝隙 1(0.20):缓慢下拉滴落的动态琥珀蜜滴 + 涟漪 + final dx = w * 0.20; + final dp = (t * 2) % 1.0; + if (dp < 0.75) { + final fp = dp / 0.75; + final y = h * (0.28 + fp * fp * 0.58); + canvas.drawPath( + Path() + ..moveTo(dx, y - 5.2) + ..cubicTo(dx + 3.2, y, dx + 3.2, y + 3.6, dx, y + 3.6) + ..cubicTo(dx - 3.2, y + 3.6, dx - 3.2, y, dx, y - 5.2) + ..close(), + Paint()..color = gold.withValues(alpha: 0.92), + ); + } else { + final rp = (dp - 0.75) / 0.25; + canvas.drawOval( + Rect.fromCenter( + center: Offset(dx, h * 0.88), + width: 5 + rp * 12, + height: 2 + rp * 3, + ), + Paint() + ..color = gold.withValues(alpha: (1 - rp) * 0.82) + ..style = PaintingStyle.stroke + ..strokeWidth = 1.1, + ); + } + + // 缝隙 2(0.40):随风轻飘的小白花瓣 + final pp = (t + 0.35) % 1.0; + final px = w * 0.38 + pp * 16 + math.sin(t * math.pi * 2 * 2) * 3; + final py = h * (0.20 + pp * 0.66); + canvas.save(); + canvas.translate(px, py); + canvas.rotate(t * math.pi * 2 * 2); + canvas.drawOval( + Rect.fromCenter(center: Offset.zero, width: 5.2, height: 2.8), + Paint()..color = petal.withValues(alpha: math.sin(math.pi * pp) * 0.88), + ); + canvas.restore(); + + // 缝隙 3(0.60):两片松绿嫩叶 + 闪光琥珀蜜珠 + canvas.save(); + canvas.translate(w * 0.595, h * 0.85); + canvas.rotate(-0.42 + math.sin(t * math.pi * 2) * 0.08); + canvas.drawOval( + Rect.fromCenter(center: Offset.zero, width: 9.5, height: 4.2), + Paint()..color = leaf.withValues(alpha: 0.82), + ); + canvas.restore(); + canvas.drawCircle( + Offset(w * 0.608, h * 0.76), + 2.3, + Paint()..color = gold.withValues(alpha: 0.75 + pulse * 0.22), + ); + + // 缝隙 4(0.80):高速振翅悬停飞舞的迷你小蜜蜂 + 虚线飞行轨 + final bx = w * 0.80 + math.sin(t * math.pi * 2 * 2) * 5.0; + final by = h * 0.62 + math.cos(t * math.pi * 2 * 3) * 4.5; + for (var d = 1; d <= 3; d++) { + final dt = (t - d * 0.025 + 1.0) % 1.0; + final tx = w * 0.80 + math.sin(dt * math.pi * 2 * 2) * 5.0; + final ty = h * 0.62 + math.cos(dt * math.pi * 2 * 3) * 4.5; + canvas.drawCircle( + Offset(tx, ty), + 1.1 - d * 0.15, + Paint()..color = gold.withValues(alpha: 0.45 - d * 0.10), + ); + } + final wingLift = math.sin(t * math.pi * 2 * 18) * 1.4; + canvas.drawOval( + Rect.fromCenter( + center: Offset(bx - 1.2, by - 3.3 + wingLift * 0.4), + width: 5.0, + height: 2.6, + ), + Paint()..color = petal.withValues(alpha: 0.88), + ); + canvas.drawOval( + Rect.fromCenter( + center: Offset(bx + 1.4, by - 3.1 - wingLift * 0.4), + width: 4.4, + height: 2.4, + ), + Paint()..color = petal.withValues(alpha: 0.72), + ); + canvas.drawOval( + Rect.fromCenter(center: Offset(bx, by), width: 7.8, height: 4.8), + Paint()..color = gold.withValues(alpha: 0.96), + ); + canvas.drawLine( + Offset(bx, by - 2.1), + Offset(bx, by + 2.1), + Paint() + ..color = const Color(0xFF42280B).withValues(alpha: 0.82) + ..strokeWidth = 1.2, + ); + return; + } + + // community_starlit_hive:顶部柔波极光丝带 + 青黛山脊 + 微摆松尖 + 发光小亭 + 萤火与迷你流星 + final ridge = isDark ? const Color(0xFF2B5269) : const Color(0xFF6B94A4); + final pine = isDark ? const Color(0xFF4E829A) : const Color(0xFF2B4A5E); + const light = Color(0xFFF6C453); + + // 1. 顶部流动极光丝带(避开按钮主体,紧贴顶沿柔光) + final aWob = math.sin(t * math.pi * 2) * 3.0; + canvas.drawPath( + Path() + ..moveTo(w * 0.04, h * 0.16 + aWob) + ..quadraticBezierTo(w * 0.28, h * 0.05 - aWob, w * 0.52, h * 0.18 + aWob) + ..quadraticBezierTo(w * 0.74, h * 0.28 - aWob, w * 0.94, h * 0.12 + aWob), + Paint() + ..shader = LinearGradient( + colors: [ + const Color(0xFF5EEAD4).withValues(alpha: 0), + const Color(0xFF6CE6D8).withValues(alpha: isDark ? 0.32 : 0.22), + const Color(0xFFFAD77C).withValues(alpha: isDark ? 0.24 : 0.16), + const Color(0xFF5EEAD4).withValues(alpha: 0), + ], + ).createShader(Rect.fromLTWH(0, 0, w, h * 0.34)) + ..style = PaintingStyle.stroke + ..strokeWidth = 4.2 + ..strokeCap = StrokeCap.round, + ); + + // 2. 青黛远山脊 + canvas.drawPath( + Path() + ..moveTo(0, h * 0.88) + ..quadraticBezierTo(w * 0.20, h * 0.71, w * 0.40, h * 0.84) + ..quadraticBezierTo(w * 0.68, h * 0.92, w * 0.84, h * 0.75) + ..quadraticBezierTo(w * 0.93, h * 0.71, w, h * 0.82) + ..lineTo(w, h) + ..lineTo(0, h) + ..close(), + Paint()..color = ridge.withValues(alpha: isDark ? 0.52 : 0.26), + ); + + // 3. 缝隙松尖 + 随风轻摆 + 升腾小萤火 + for (final (idx, fx, topY) in const [ + (0, 0.20, 0.68), + (1, 0.40, 0.73), + (2, 0.60, 0.70), + ]) { + final px = w * fx; + final tipSway = math.sin((t + idx * 0.3) * math.pi * 2) * 1.4; + canvas.drawPath( + Path() + ..moveTo(px - 3.6, h * 0.95) + ..lineTo(px + tipSway, h * topY) + ..lineTo(px + 3.6, h * 0.95) + ..close(), + Paint()..color = pine.withValues(alpha: 0.82), + ); + final fp = (t * 2 + idx * 0.33) % 1.0; + final fOp = math.sin(math.pi * fp); + final fy = h * (0.76 - fp * 0.46); + final fxPos = px + math.sin((t * 2 + idx) * math.pi * 2) * 4.0; + canvas.drawCircle( + Offset(fxPos, fy), + 3.2, + Paint()..color = light.withValues(alpha: fOp * 0.35), + ); + canvas.drawCircle( + Offset(fxPos, fy), + 1.2, + Paint()..color = const Color(0xFFFFF5CC).withValues(alpha: fOp * 0.92), + ); + } + + // 4. 缝隙 4(0.80):发光六角小亭 + 呼吸光晕 + final hx = w * 0.80; + canvas.drawCircle( + Offset(hx, h * 0.80), + 11.5, + Paint() + ..shader = RadialGradient( + colors: [ + light.withValues(alpha: (isDark ? 0.36 : 0.22) + pulse * 0.14), + light.withValues(alpha: 0), + ], + ).createShader(Rect.fromCircle(center: Offset(hx, h * 0.80), radius: 11.5)), + ); + canvas.drawPath( + Path() + ..moveTo(hx - 8.0, h * 0.72) + ..lineTo(hx, h * 0.58) + ..lineTo(hx + 8.0, h * 0.72) + ..close(), + Paint()..color = pine.withValues(alpha: 0.95), + ); + canvas.drawRect( + Rect.fromLTWH(hx - 5.2, h * 0.72, 10.4, h * 0.21), + Paint()..color = pine.withValues(alpha: 0.88), + ); + canvas.drawRect( + Rect.fromLTWH(hx - 2.4, h * 0.76, 4.8, h * 0.12), + Paint()..color = light.withValues(alpha: 0.86 + pulse * 0.14), + ); + + // 5. 端头与缝隙闪烁四角星芒 + for (final (fx, fy, phase) in const [ + (0.045, 0.28, 0.0), + (0.40, 0.22, 0.35), + (0.60, 0.24, 0.60), + (0.955, 0.30, 0.82), + ]) { + final starOp = + 0.32 + 0.68 * (0.5 + 0.5 * math.sin((t * 2 + phase) * math.pi * 2)); + _drawMiniStar4( + canvas, + Offset(w * fx, h * fy), + 2.2 + starOp * 1.4, + const Color(0xFFFFF5CC).withValues(alpha: starOp), + ); + } + + // 6. 顶沿迷你流星(每周期划过一次) + if (t < 0.26) { + final mp = t / 0.26; + final mAlpha = math.sin(math.pi * mp) * (isDark ? 0.88 : 0.70); + final head = Offset(w * 0.10 + mp * 44, h * 0.16 + mp * 12); + final tail = head - const Offset(18, 5); + canvas.drawLine( + tail, + head, + Paint() + ..shader = LinearGradient( + colors: [ + const Color(0xFFFFF7D6).withValues(alpha: 0), + const Color(0xFFFFF7D6).withValues(alpha: mAlpha), + ], + ).createShader(Rect.fromPoints(tail, head)) + ..strokeWidth = 1.4 + ..strokeCap = StrokeCap.round, + ); + } + } + + @override + bool shouldRepaint(covariant _CommunityTabPainter old) => + old.specId != specId || old.isDark != isDark; +} diff --git a/lib/styles/header_skins/page_composition.dart b/lib/styles/header_skins/page_composition.dart index 14b410a4d..1c46e0933 100644 --- a/lib/styles/header_skins/page_composition.dart +++ b/lib/styles/header_skins/page_composition.dart @@ -34,6 +34,12 @@ class HeaderSkinPageArtwork extends StatelessWidget { @override Widget build(BuildContext context) { + if (skin.pageBuilder != null) { + return KeyedSubtree( + key: ValueKey('page-art-${skin.id}'), + child: skin.pageBuilder!(skin.boundPrimary ?? primary, dark), + ); + } if (skin.isAnimated) { return KeyedSubtree( key: ValueKey('page-art-${skin.id}'), @@ -78,6 +84,10 @@ class HeaderSkinPageArtwork extends StatelessWidget { } List headerSkinPageColors(HeaderSkin skin, Color primary, bool dark) { + final communityColors = _communityPageColors(skin.id, dark); + if (communityColors != null) { + return communityColors; + } if (skin.id == 'aurora' && dark) { return _auroraNightColors(primary); } diff --git a/packages/beecount_business_ui/lib/src/app_profile/profile.dart b/packages/beecount_business_ui/lib/src/app_profile/profile.dart index ee245cac9..7fbf9c8ee 100644 --- a/packages/beecount_business_ui/lib/src/app_profile/profile.dart +++ b/packages/beecount_business_ui/lib/src/app_profile/profile.dart @@ -13,10 +13,14 @@ class BeeProfile extends StatelessWidget { required this.subtitle, required this.avatar, required this.onEdit, - required this.onTap}); + required this.onTap, + this.badge, + this.clipAvatar = true}); final String nickname, subtitle; final String? greeting, profileLabel, editLabel; final Widget avatar; + final Widget? badge; + final bool clipAvatar; final VoidCallback onEdit, onTap; @override @@ -34,11 +38,15 @@ class BeeProfile extends StatelessWidget { child: InkWell( onTap: onTap, customBorder: const CircleBorder(), - child: SizedBox( - key: const ValueKey('profile-avatar'), - width: 48, - height: 48, - child: ClipOval(child: avatar)))), + child: clipAvatar + ? SizedBox( + key: const ValueKey('profile-avatar'), + width: 48, + height: 48, + child: ClipOval(child: avatar)) + : KeyedSubtree( + key: const ValueKey('profile-avatar'), + child: avatar))), const SizedBox(width: 11), Expanded( child: Column( @@ -53,30 +61,41 @@ class BeeProfile extends StatelessWidget { fontSize: 10, height: 1.5, color: Theme.of(context).hintColor)), - Semantics( - container: true, - button: true, - label: editLabel, - child: InkWell( - onTap: onEdit, - child: ConstrainedBox( - constraints: const BoxConstraints(minHeight: 29), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - Flexible( - child: Text(nickname, - maxLines: 1, - overflow: TextOverflow.ellipsis, - style: const TextStyle( - fontSize: 19, - height: 1.2, - fontWeight: FontWeight.w600))), - const SizedBox(width: 5), - BeeLineIcon('PencilLine', - size: 12, - color: Theme.of(context).hintColor) - ])))), + Row(children: [ + Flexible( + child: Semantics( + container: true, + button: true, + label: editLabel, + child: InkWell( + onTap: onEdit, + child: ConstrainedBox( + constraints: + const BoxConstraints(minHeight: 29), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text(nickname, + maxLines: 1, + overflow: + TextOverflow.ellipsis, + style: const TextStyle( + fontSize: 19, + height: 1.2, + fontWeight: + FontWeight.w600))), + const SizedBox(width: 5), + BeeLineIcon('PencilLine', + size: 12, + color: + Theme.of(context).hintColor) + ]))))), + if (badge != null) ...[ + const SizedBox(width: 6), + badge!, + ], + ]), Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis, diff --git a/packages/beecount_business_ui/lib/src/sharing/annual_poster.dart b/packages/beecount_business_ui/lib/src/sharing/annual_poster.dart index 972bf5fcb..d0ad52353 100644 --- a/packages/beecount_business_ui/lib/src/sharing/annual_poster.dart +++ b/packages/beecount_business_ui/lib/src/sharing/annual_poster.dart @@ -51,8 +51,10 @@ class BeeAnnualReportPoster extends StatelessWidget { required this.expense, required this.summaryMetrics, required this.chapters, - required this.accent}); + required this.accent, + this.communityMark}); final Widget header, footer; + final Widget? communityMark; final String year, subtitle, expenseLabel, expense; final Color accent; final List summaryMetrics; @@ -118,7 +120,11 @@ class BeeAnnualReportPoster extends StatelessWidget { style: const TextStyle( fontSize: 23, height: 1.8, color: BeePaper.muted)), ]), - const SizedBox(height: 42), + if (communityMark != null) ...[ + const SizedBox(height: 24), + Align(alignment: Alignment.centerRight, child: communityMark!), + ], + const SizedBox(height: 34), footer, ])); } diff --git a/packages/beecount_business_ui/lib/src/sharing/share_poster_layouts.dart b/packages/beecount_business_ui/lib/src/sharing/share_poster_layouts.dart index d66cbc031..9129eca29 100644 --- a/packages/beecount_business_ui/lib/src/sharing/share_poster_layouts.dart +++ b/packages/beecount_business_ui/lib/src/sharing/share_poster_layouts.dart @@ -15,8 +15,10 @@ class BeeProfileSharePoster extends StatelessWidget { required this.daysCaption, required this.metrics, required this.journey, - required this.description}); + required this.description, + this.communityMark}); final Widget header, footer, avatar; + final Widget? communityMark; final Color accent; final String title, eyebrow, days, daysCaption, journey, description; final List metrics; @@ -77,12 +79,24 @@ class BeeProfileSharePoster extends StatelessWidget { const SizedBox(height: 31), const BeePaperRule(), const SizedBox(height: 32), - Text(journey, - style: const TextStyle(fontSize: 28, fontWeight: FontWeight.w600)), - const SizedBox(height: 14), - Text(description, - style: const TextStyle( - fontSize: 21, height: 1.85, color: BeePaper.muted)), + Row(crossAxisAlignment: CrossAxisAlignment.end, children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(journey, + style: const TextStyle( + fontSize: 28, fontWeight: FontWeight.w600)), + const SizedBox(height: 14), + Text(description, + style: const TextStyle( + fontSize: 21, height: 1.85, color: BeePaper.muted)), + ])), + if (communityMark != null) ...[ + const SizedBox(width: 20), + communityMark!, + ] + ]), const Spacer(), const SizedBox(height: 36), footer @@ -105,8 +119,10 @@ class BeeAppSharePoster extends StatelessWidget { required this.features, required this.qr, required this.invitation, - required this.tags}); + required this.tags, + this.communityMark}); final Widget header, footer, qr; + final Widget? communityMark; final String title, invitation; final Color accent; final List features; @@ -191,7 +207,11 @@ class BeeAppSharePoster extends StatelessWidget { ])) ])), const Spacer(), - const SizedBox(height: 42), + if (communityMark != null) ...[ + const SizedBox(height: 20), + Align(alignment: Alignment.centerRight, child: communityMark!), + ], + const SizedBox(height: 28), footer ]); } @@ -216,9 +236,10 @@ class BeeFinancialSharePoster extends StatelessWidget { this.description, this.period, this.titleIcon, - this.year = false}); + this.year = false, + this.communityMark}); final Widget header, footer; - final Widget? titleIcon; + final Widget? titleIcon, communityMark; final String title, subtitle, expenseLabel, @@ -294,11 +315,20 @@ class BeeFinancialSharePoster extends StatelessWidget { accent: accent, emptyLabel: emptyLabel)) ]), - if (description != null) ...[ + if (description != null || communityMark != null) ...[ const SizedBox(height: 18), - Text(description!, - style: const TextStyle( - fontSize: 20, height: 1.8, color: BeePaper.muted)) + Row(crossAxisAlignment: CrossAxisAlignment.end, children: [ + Expanded( + child: description != null + ? Text(description!, + style: const TextStyle( + fontSize: 20, height: 1.8, color: BeePaper.muted)) + : const SizedBox.shrink()), + if (communityMark != null) ...[ + const SizedBox(width: 20), + communityMark!, + ] + ]), ], const Spacer(), const SizedBox(height: 34), diff --git a/pubspec.yaml b/pubspec.yaml index a889485c3..4fc07fe1b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -145,6 +145,8 @@ flutter: - assets/icons/social/ - assets/images/ - assets/header_skins/ + - assets/community_skins/ + - docs/donate/supporters.json # 字体已移动到可选依赖,使用系统字体以减少应用体积 # fonts: # - family: Inter diff --git a/test/github_community_test.dart b/test/github_community_test.dart new file mode 100644 index 000000000..77850584a --- /dev/null +++ b/test/github_community_test.dart @@ -0,0 +1,565 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:beecount/l10n/app_localizations.dart'; +import 'package:beecount/pages/settings/github_community_page.dart'; +import 'package:beecount/pages/settings/support/bindings/support_platform.dart'; +import 'package:beecount/pages/shared/widgets/community_honor_widgets.dart'; +import 'package:beecount/providers/github_community_provider.dart'; +import 'package:beecount/providers/theme_providers.dart'; +import 'package:beecount/services/github/github_community_models.dart'; +import 'package:beecount/services/github/github_community_service.dart'; +import 'package:beecount/services/github/github_token_store.dart'; +import 'package:beecount/services/update/update_checker.dart'; +import 'package:beecount/styles/header_skins.dart'; +import 'package:beecount_business_ui/share_posters.dart'; +import 'package:dio/dio.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +class _FakeHttpAdapter implements HttpClientAdapter { + _FakeHttpAdapter(this.handler); + + final ResponseBody Function(RequestOptions options) handler; + final List requests = []; + + @override + Future fetch( + RequestOptions options, + Stream>? requestStream, + Future? cancelFuture, + ) async { + requests.add(options); + return handler(options); + } + + @override + void close({bool force = false}) {} +} + +class _FakeSupportPlatform extends SupportPlatform { + const _FakeSupportPlatform(); + + @override + bool get isIOS => false; + + @override + bool get isGooglePlay => false; + + @override + Future open(Uri url) async => true; +} + +ResponseBody _jsonBody( + Object data, { + int statusCode = 200, + Map>? headers, +}) { + return ResponseBody.fromString( + jsonEncode(data), + statusCode, + headers: { + Headers.contentTypeHeader: ['application/json; charset=utf-8'], + ...?headers, + }, + ); +} + +void main() { + setUp(() { + SharedPreferences.setMockInitialValues({}); + }); + + group('supporters.json & README fallback parsing', () { + test('parses real docs/donate/supporters.json with maintainer TNT-Likely', + () { + final raw = File('docs/donate/supporters.json').readAsStringSync(); + final registry = GitHubCommunityService.parseSupportersJson(raw); + + expect(registry.maintainers, contains('tnt-likely')); + expect(registry.thresholds.supporter, 1); + expect(registry.thresholds.goldPatron, 50); + expect(registry.thresholds.hiveGuardian, 150); + expect(registry.supportersByLogin['fishdivinity']?.amountCny, 150); + expect(registry.supportersByLogin['howcanoewang']?.amountCny, 98); + expect(registry.supportersByLogin['idedele']?.amountCny, 28.88); + }); + + test('parses real README.md supporters table as fallback', () { + final raw = File('README.md').readAsStringSync(); + final registry = GitHubCommunityService.parseReadmeSupporters(raw); + + expect(registry.supportersByLogin['fishdivinity']?.amountCny, 150); + expect(registry.supportersByLogin['howcanoewang']?.amountCny, 98); + expect(registry.supportersByLogin['zifengfanzhuo']?.amountCny, 5); + }); + }); + + group('honor tier & reward unlock rules', () { + test('maintainer TNT-Likely always receives highest Co-Creator tier & all 3 skins', + () { + final profile = GitHubCommunityProfile( + login: 'TNT-Likely', + isMaintainer: true, + fetchedAt: DateTime(2026, 11, 29), + ); + + expect(profile.isCoCreator, isTrue); + expect(profile.primaryTier, GitHubHonorTier.coCreator); + expect(profile.hasPosterChopHonor, isTrue); + expect(profile.unlockedCommunitySkinIds, equals(kAllCommunitySkinIds)); + for (final tier in GitHubHonorTier.values + .where((t) => t != GitHubHonorTier.none)) { + expect(profile.hasUnlockedTier(tier), isTrue); + } + }); + + test('filing issues alone does NOT grant code contributor honor', () { + final reporter = GitHubCommunityProfile( + login: 'issue_reporter', + starredMainRepo: true, + contributions: const [ + GitHubRepoContribution( + repo: 'BeeCount', commits: 0, mergedPrs: 0, issues: 12), + ], + fetchedAt: DateTime(2026, 11, 29), + ); + expect(reporter.hasCodeHonor, isFalse); + expect(reporter.codeTier, GitHubHonorTier.none); + expect(reporter.primaryTier, GitHubHonorTier.stargazer); + expect(reporter.unlockedCommunitySkinIds, isEmpty); + expect(reporter.hasPosterChopHonor, isFalse); + }); + + test('code-only contributor unlocks Woodblock Lamp skin only', () { + final builder = GitHubCommunityProfile( + login: 'dev_maple', + contributions: const [ + GitHubRepoContribution(repo: 'BeeCount', commits: 2, mergedPrs: 1), + ], + fetchedAt: DateTime(2026, 11, 29), + ); + expect(builder.primaryTier, GitHubHonorTier.builder); + expect( + builder.unlockedCommunitySkinIds, {kCommunitySkinWoodblockLamp}); + expect(builder.hasPosterChopHonor, isTrue); + + final core = GitHubCommunityProfile( + login: 'dev_core', + contributions: const [ + GitHubRepoContribution(repo: 'BeeCount', commits: 12, mergedPrs: 3), + GitHubRepoContribution( + repo: 'BeeCount-Cloud', commits: 4, mergedPrs: 2), + ], + fetchedAt: DateTime(2026, 11, 29), + ); + expect(core.primaryTier, GitHubHonorTier.coreContributor); + expect(core.unlockedCommunitySkinIds, {kCommunitySkinWoodblockLamp}); + }); + + test('donor-only unlocks Honey Jar skin only and scales tier by amount', + () { + GitHubCommunityProfile donor(double amount) => GitHubCommunityProfile( + login: 'patron', + donation: GitHubDonationInfo(amountCny: amount), + fetchedAt: DateTime(2026, 11, 29), + ); + + expect(donor(10).primaryTier, GitHubHonorTier.supporter); + expect(donor(50).primaryTier, GitHubHonorTier.goldPatron); + expect(donor(150).primaryTier, GitHubHonorTier.hiveGuardian); + expect(donor(10).unlockedCommunitySkinIds, {kCommunitySkinHoneyJar}); + expect(donor(10).hasPosterChopHonor, isTrue); + }); + + test('dual contributor + donor unlocks Co-Creator & all 3 skins', () { + final dual = GitHubCommunityProfile( + login: 'HowcanoeWang', + contributions: const [ + GitHubRepoContribution(repo: 'BeeCount', commits: 3, mergedPrs: 1), + ], + donation: const GitHubDonationInfo(amountCny: 98), + fetchedAt: DateTime(2026, 11, 29), + ); + expect(dual.primaryTier, GitHubHonorTier.coCreator); + expect(dual.unlockedCommunitySkinIds, equals(kAllCommunitySkinIds)); + }); + + test('stargazer only gets stargazer tier with no community skins or chop', + () { + final star = GitHubCommunityProfile( + login: 'fan', + starredMainRepo: true, + fetchedAt: DateTime(2026, 11, 29), + ); + expect(star.primaryTier, GitHubHonorTier.stargazer); + expect(star.unlockedCommunitySkinIds, isEmpty); + expect(star.hasPosterChopHonor, isFalse); + }); + }); + + group('GitHubCommunityService mocked API', () { + test('aggregates 6 repos, rate limit headers, star & supporters.json', + () async { + final supportersRaw = File('docs/donate/supporters.json').readAsStringSync(); + final supportersB64 = base64Encode(utf8.encode(supportersRaw)); + + final adapter = _FakeHttpAdapter((options) { + final path = options.uri.path; + expect(options.headers['Authorization'], 'Bearer ghp_test_token_1234'); + if (path == '/user') { + return _jsonBody( + {'login': 'HowcanoeWang', 'name': '浩瀚猫'}, + headers: { + 'x-ratelimit-limit': ['5000'], + 'x-ratelimit-remaining': ['4988'], + }, + ); + } + if (path == '/search/issues') { + final q = options.queryParameters['q']?.toString() ?? ''; + if (q.contains('type:pr')) { + return _jsonBody({ + 'total_count': 2, + 'items': [ + { + 'repository_url': + 'https://api.github.com/repos/TNT-Likely/BeeCount' + }, + { + 'repository_url': + 'https://api.github.com/repos/TNT-Likely/BeeCount-Cloud' + }, + ], + }); + } + return _jsonBody({ + 'total_count': 1, + 'items': [ + { + 'repository_url': + 'https://api.github.com/repos/TNT-Likely/BeeCount' + }, + ], + }); + } + if (path == '/repos/TNT-Likely/BeeCount/commits') { + return _jsonBody( + [ + {'sha': 'abc'} + ], + headers: { + 'link': [ + '; rel="last"' + ], + }, + ); + } + if (path.endsWith('/commits')) { + return _jsonBody([]); + } + if (path == '/user/starred/TNT-Likely/BeeCount') { + return ResponseBody.fromString('', 204); + } + if (path == + '/repos/TNT-Likely/BeeCount/contents/docs/donate/supporters.json') { + return _jsonBody({ + 'encoding': 'base64', + 'content': supportersB64, + }); + } + return _jsonBody({}, statusCode: 404); + }); + + final dio = Dio(BaseOptions(validateStatus: (s) => s != null && s < 500)) + ..httpClientAdapter = adapter; + final service = GitHubCommunityService(dio: dio); + + final profile = await service.verifyAndFetchProfile('ghp_test_token_1234'); + expect(profile.login, 'HowcanoeWang'); + expect(profile.rateLimit?.limit, 5000); + expect(profile.rateLimit?.remaining, 4988); + expect(profile.starredMainRepo, isTrue); + expect(profile.totalCommits, 14); + expect(profile.totalMergedPrs, 2); + expect(profile.totalIssues, 1); + expect(profile.donation?.amountCny, 98); + expect(profile.primaryTier, GitHubHonorTier.coCreator); + }); + + test('throws GitHubTokenInvalidException on HTTP 401', () async { + final adapter = _FakeHttpAdapter( + (_) => _jsonBody({'message': 'Bad credentials'}, statusCode: 401), + ); + final dio = Dio(BaseOptions(validateStatus: (s) => s != null && s < 500)) + ..httpClientAdapter = adapter; + final service = GitHubCommunityService(dio: dio); + + expect( + () => service.verifyAndFetchProfile('ghp_bad'), + throwsA(isA()), + ); + }); + + test('falls back to bundled supporters.json offline and dynamically updates cache when remote succeeds', + () async { + final bundledRaw = File('docs/donate/supporters.json').readAsStringSync(); + String? savedCache; + + // 1) Remote 404 -> falls back to bundled docs/donate/supporters.json + final offlineAdapter = _FakeHttpAdapter((options) { + final path = options.uri.path; + if (path == '/user') { + return _jsonBody({'login': 'fishdivinity', 'name': 'fishdivinity'}); + } + if (path == '/search/issues') return _jsonBody({'total_count': 0, 'items': []}); + if (path.endsWith('/commits')) return _jsonBody([]); + if (path == '/user/starred/TNT-Likely/BeeCount') { + return ResponseBody.fromString('', 404); + } + return _jsonBody({}, statusCode: 404); + }); + final offlineDio = Dio(BaseOptions(validateStatus: (s) => s != null && s < 500)) + ..httpClientAdapter = offlineAdapter; + final offlineService = GitHubCommunityService( + dio: offlineDio, + bundledSupportersLoader: () async => bundledRaw, + cachedSupportersLoader: () async => savedCache, + cachedSupportersSaver: (raw) async => savedCache = raw, + ); + + final offlineProfile = await offlineService.verifyAndFetchProfile('ghp_ok'); + expect(offlineProfile.donation?.amountCny, 150); + expect(offlineProfile.primaryTier, GitHubHonorTier.hiveGuardian); + + // 2) Remote returns dynamically updated supporters.json with a brand new donor + final updatedJson = jsonEncode({ + 'version': 1, + 'maintainers': ['TNT-Likely'], + 'tiers': {'supporter': 1, 'goldPatron': 50, 'hiveGuardian': 150}, + 'supporters': [ + {'github': 'brand_new_donor', 'name': 'New Patron', 'amountCny': 88}, + ], + }); + final onlineAdapter = _FakeHttpAdapter((options) { + final path = options.uri.path; + if (path == '/user') { + return _jsonBody({'login': 'brand_new_donor', 'name': 'New Patron'}); + } + if (path == '/search/issues') return _jsonBody({'total_count': 0, 'items': []}); + if (path.endsWith('/commits')) return _jsonBody([]); + if (path == '/user/starred/TNT-Likely/BeeCount') { + return ResponseBody.fromString('', 404); + } + if (path == '/repos/TNT-Likely/BeeCount/contents/docs/donate/supporters.json') { + return _jsonBody({ + 'encoding': 'base64', + 'content': base64Encode(utf8.encode(updatedJson)), + }); + } + return _jsonBody({}, statusCode: 404); + }); + final onlineDio = Dio(BaseOptions(validateStatus: (s) => s != null && s < 500)) + ..httpClientAdapter = onlineAdapter; + final onlineService = GitHubCommunityService( + dio: onlineDio, + bundledSupportersLoader: () async => bundledRaw, + cachedSupportersLoader: () async => savedCache, + cachedSupportersSaver: (raw) async => savedCache = raw, + ); + + final onlineProfile = await onlineService.verifyAndFetchProfile('ghp_ok'); + expect(onlineProfile.donation?.amountCny, 88); + expect(onlineProfile.primaryTier, GitHubHonorTier.goldPatron); + expect(savedCache, isNotNull); + }); + }); + + group('UpdateChecker with GitHub token & rate-limit handling', () { + test('sends Bearer token when configured and detects update', () async { + await GitHubTokenStore.saveToken('ghp_update_token_9999'); + final adapter = _FakeHttpAdapter((options) { + return _jsonBody( + { + 'tag_name': 'v9.9.9', + 'body': 'New release', + 'assets': [ + { + 'name': 'beecount-9.9.9.apk', + 'browser_download_url': 'https://example.com/beecount-9.9.9.apk', + }, + ], + }, + headers: { + 'x-ratelimit-limit': ['5000'], + 'x-ratelimit-remaining': ['4999'], + }, + ); + }); + final dio = Dio()..httpClientAdapter = adapter; + + final result = await UpdateChecker.checkUpdate( + dio: dio, + currentVersionOverride: () async => '4.0.0', + ); + expect(result.hasUpdate, isTrue); + expect(result.version, '9.9.9'); + expect( + adapter.requests.first.headers['Authorization'], + 'Bearer ghp_update_token_9999', + ); + }); + + test('falls back to anonymous on 401 and marks token invalid', () async { + await GitHubTokenStore.saveToken('ghp_expired_token_1111'); + var callCount = 0; + final adapter = _FakeHttpAdapter((options) { + callCount++; + if (callCount == 1) { + return _jsonBody({'message': 'Bad credentials'}, statusCode: 401); + } + return _jsonBody({ + 'tag_name': 'v4.0.0', + 'body': '', + 'assets': [], + }); + }); + final dio = Dio()..httpClientAdapter = adapter; + + final result = await UpdateChecker.checkUpdate( + dio: dio, + currentVersionOverride: () async => '4.0.0', + ); + expect(result.hasUpdate, isFalse); + expect(result.message, '__UPDATE_ALREADY_LATEST_SIMPLE__'); + expect(callCount, 2); + expect(adapter.requests[1].headers['Authorization'], isNull); + expect(await GitHubTokenStore.isTokenMarkedInvalid(), isTrue); + }); + + test('returns dedicated rate-limit marker on HTTP 403 remaining=0', + () async { + final adapter = _FakeHttpAdapter( + (_) => _jsonBody( + {'message': 'API rate limit exceeded'}, + statusCode: 403, + headers: { + 'x-ratelimit-limit': ['60'], + 'x-ratelimit-remaining': ['0'], + }, + ), + ); + final dio = Dio()..httpClientAdapter = adapter; + + final result = await UpdateChecker.checkUpdate( + dio: dio, + currentVersionOverride: () async => '4.0.0', + ); + expect(result.hasUpdate, isFalse); + expect(result.message, '__UPDATE_CHECK_RATE_LIMITED__'); + expect(adapter.requests.length, 1); + }); + }); + + group('UI widgets & state cleanup', () { + test('clearing token resets active community skin back to none', () async { + final container = ProviderContainer(); + addTearDown(container.dispose); + + applyHeaderSkinWith(container.read, kCommunitySkinStarlitHive); + expect(container.read(headerSkinProvider), kCommunitySkinStarlitHive); + + await container.read(githubCommunityProvider.notifier).clearToken(); + expect(container.read(headerSkinProvider), kHeaderSkinNone); + }); + + testWidgets('GitHubCommunityPage renders bound TNT-Likely Co-Creator passport & Scheme A chop', + (tester) async { + final profile = GitHubCommunityProfile( + login: 'TNT-Likely', + displayName: 'TNT-Likely', + isMaintainer: true, + starredMainRepo: true, + contributions: const [ + GitHubRepoContribution( + repo: 'BeeCount', commits: 120, mergedPrs: 45, issues: 18), + ], + rateLimit: const GitHubRateLimit(limit: 5000, remaining: 4990), + fetchedAt: DateTime.now(), + ); + await GitHubTokenStore.saveToken('ghp_owner_test_token_1234'); + await GitHubTokenStore.saveCachedProfile(profile); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + supportPlatformProvider + .overrideWithValue(const _FakeSupportPlatform()), + ], + child: MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: ThemeData.light(), + home: const GitHubCommunityPage(), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(const ValueKey('github-passport-card')), findsOneWidget); + expect(find.text('蜂巢共创者'), findsAtLeastNWidgets(1)); + expect(find.text('4990 / 5000'), findsOneWidget); + expect(find.text('CO-CREATOR'), findsOneWidget); + + // Tap honor tiers entry -> opens 7-tier honor ladder highlighting Co-Creator as highest + await tester.tap(find.byKey(const ValueKey('github-honor-tiers-btn'))); + await tester.pumpAndSettle(); + expect(find.text('社区荣誉等级体系'), findsOneWidget); + expect(find.text('当前 · 最高等级'), findsOneWidget); + expect(find.text('社区星友'), findsOneWidget); + expect(find.text('筑巢者'), findsOneWidget); + }); + + testWidgets('BeeProfileSharePoster renders CommunityPosterChop cleanly', + (tester) async { + final profile = GitHubCommunityProfile( + login: 'TNT-Likely', + isMaintainer: true, + fetchedAt: DateTime(2026, 11, 29), + ); + + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: FittedBox( + child: BeeProfileSharePoster( + header: const SizedBox(height: 40), + footer: const SizedBox(height: 60), + accent: const Color(0xFFF8C91C), + title: '日常账本', + eyebrow: '我的记账手记', + avatar: const Icon(Icons.person), + days: '326', + daysCaption: '坚持记账天数', + metrics: const [ + BeePosterMetric('累计记账笔数', '1,482'), + BeePosterMetric('账本数量', '3'), + ], + journey: '记账已成为日常习惯', + description: '始于 2025/12/08', + communityMark: CommunityPosterChop(profile: profile), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('CO-CREATOR'), findsOneWidget); + expect(find.text('@TNT-Likely'), findsOneWidget); + }); + }); +} diff --git a/test/styles/header_skins_test.dart b/test/styles/header_skins_test.dart index e46e03da5..4c0ee6b64 100644 --- a/test/styles/header_skins_test.dart +++ b/test/styles/header_skins_test.dart @@ -11,10 +11,15 @@ void main() { // The approved static catalogue is intentionally limited to these two. const newSkins = ['aurora', 'mountains']; - test('只保留两款静态皮肤与两款周年动态', () { + test('保留两款静态皮肤、两款周年动态与三款社区荣誉典藏', () { expect(kHeaderSkins.where((s) => !s.isAnimated).map((s) => s.id), newSkins); - expect(kHeaderSkins.where((s) => s.isAnimated).map((s) => s.id), - ['anniversary', 'anniv_cake']); + expect(kHeaderSkins.where((s) => s.isAnimated).map((s) => s.id), [ + 'anniversary', + 'anniv_cake', + 'community_woodblock_lamp', + 'community_honey_jar', + 'community_starlit_hive', + ]); }); testWidgets('保留的静态皮肤亮/暗两态可正常渲染', (tester) async { diff --git a/test/widgets/v4_skin_selector_page_test.dart b/test/widgets/v4_skin_selector_page_test.dart index 8606d9fcd..9f3c93957 100644 --- a/test/widgets/v4_skin_selector_page_test.dart +++ b/test/widgets/v4_skin_selector_page_test.dart @@ -255,7 +255,16 @@ void main() { expect(node.rect.width, t.getSize(none).width); semantics.dispose(); final ids = ['none', ...kVisibleHeaderSkins.map((s) => s.id)]; - expect(ids, ['none', 'anniversary', 'anniv_cake', 'aurora', 'mountains']); + expect(ids, [ + 'none', + 'anniversary', + 'anniv_cake', + 'community_woodblock_lamp', + 'community_honey_jar', + 'community_starlit_hive', + 'aurora', + 'mountains', + ]); for (final row in legacy.where((o) => ids.contains(o['id']))) { final id = row['id'] as String; final item = skinChoice(t.element(find.byType(HeaderSkinPage)), @@ -574,4 +583,23 @@ void main() { ((dark.preview as MediaQuery).child as ColoredBox).color, Colors.black); expect(t.takeException(), isNull); }); + + testWidgets('暗黑模式启用整页皮肤时,皮肤卡片标签底色保持深色可读而非纯白', (t) async { + applyHeaderSkinWith(container.read, 'community_starlit_hive'); + await mount(t, compact: true); + final loc = l(t); + final badgeText = find.descendant( + of: tile('anniversary'), + matching: find.text(loc.headerSkinAnimatedBadge), + ); + await t.ensureVisible(badgeText); + await t.pumpAndSettle(); + final box = t.widget( + find.ancestor(of: badgeText, matching: find.byType(DecoratedBox)).first, + ); + final color = (box.decoration as BoxDecoration).color!; + expect(color.a, 1.0); + expect(color.computeLuminance(), lessThan(0.25)); + expect(t.takeException(), isNull); + }); } diff --git a/test/widgets/v4_support_pages_test.dart b/test/widgets/v4_support_pages_test.dart index 713edfe4f..65b7f5730 100644 --- a/test/widgets/v4_support_pages_test.dart +++ b/test/widgets/v4_support_pages_test.dart @@ -90,7 +90,8 @@ class _Platform extends SupportPlatform { @override Future checkUpdate(BuildContext context, {required void Function(bool) setLoading, - required void Function(double, String) setProgress}) async { + required void Function(double, String) setProgress, + VoidCallback? onConfigureGitHubToken}) async { updates++; setLoading(true); setProgress(0, 'QA checking');