[ios] Add Parameters for Trending Queries feature

This will enable users to set the arms for this feature in
chrome://flags. The arm-specific checks are added to the model.

Bug: 1340123
Change-Id: Ib34f58e74347439011e95492f94f8c038b913c42
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3774084
Reviewed-by: Sebastien Seguin-Gagnon <sebsg@chromium.org>
Commit-Queue: Chris Lu <thegreenfrog@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1026269}
diff --git a/ios/chrome/browser/flags/about_flags.mm b/ios/chrome/browser/flags/about_flags.mm
index 311f998..5723f40b 100644
--- a/ios/chrome/browser/flags/about_flags.mm
+++ b/ios/chrome/browser/flags/about_flags.mm
@@ -397,6 +397,35 @@
      std::size(kFREDefaultBrowserPromoShortDelay), nullptr},
 };
 
+const FeatureEntry::FeatureParam kTrendingQueriesEnableAllUsers[] = {
+    {kTrendingQueriesHideShortcutsParam, "false"},
+    {kTrendingQueriesDisabledFeedParam, "false"},
+    {kTrendingQueriesSignedOutParam, "false"}};
+const FeatureEntry::FeatureParam kTrendingQueriesEnableAllUsersHideShortcuts[] =
+    {{kTrendingQueriesHideShortcutsParam, "true"},
+     {kTrendingQueriesDisabledFeedParam, "false"},
+     {kTrendingQueriesSignedOutParam, "false"}};
+const FeatureEntry::FeatureParam kTrendingQueriesEnableFeedDisabled[] = {
+    {kTrendingQueriesHideShortcutsParam, "false"},
+    {kTrendingQueriesDisabledFeedParam, "true"},
+    {kTrendingQueriesSignedOutParam, "false"}};
+const FeatureEntry::FeatureParam kTrendingQueriesEnableSignedOut[] = {
+    {kTrendingQueriesHideShortcutsParam, "true"},
+    {kTrendingQueriesDisabledFeedParam, "false"},
+    {kTrendingQueriesSignedOutParam, "true"}};
+
+const FeatureEntry::FeatureVariation kTrendingQueriesModuleVariations[] = {
+    {"Enabled All Users", kTrendingQueriesEnableAllUsers,
+     std::size(kTrendingQueriesEnableAllUsers), nullptr},
+    {"Enabled All Users Hide Shortcuts",
+     kTrendingQueriesEnableAllUsersHideShortcuts,
+     std::size(kTrendingQueriesEnableAllUsersHideShortcuts), nullptr},
+    {"Enabled Disabled Feed", kTrendingQueriesEnableFeedDisabled,
+     std::size(kTrendingQueriesEnableFeedDisabled), nullptr},
+    {"Enabled Signed Out", kTrendingQueriesEnableSignedOut,
+     std::size(kTrendingQueriesEnableSignedOut), nullptr},
+};
+
 const FeatureEntry::FeatureParam kNewMICEFREWithUMADialog[] = {
     {kNewMobileIdentityConsistencyFREParam,
      kNewMobileIdentityConsistencyFREParamUMADialog}};
@@ -1039,7 +1068,9 @@
      FEATURE_VALUE_TYPE(omnibox::kAdaptiveSuggestionsCount)},
     {"trending-queries-module", flag_descriptions::kTrendingQueriesModuleName,
      flag_descriptions::kTrendingQueriesModuleDescription, flags_ui::kOsIos,
-     FEATURE_VALUE_TYPE(kTrendingQueriesModule)},
+     FEATURE_WITH_PARAMS_VALUE_TYPE(kTrendingQueriesModule,
+                                    kTrendingQueriesModuleVariations,
+                                    "TrendingQueriesModule")},
     {"autofill-parse-iban-fields",
      flag_descriptions::kAutofillParseIbanFieldsName,
      flag_descriptions::kAutofillParseIbanFieldsDescription, flags_ui::kOsIos,
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h
index f6bd2c5..fe998d3 100644
--- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h
+++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h
@@ -31,6 +31,11 @@
 // Feature to show the Trending Queries module.
 extern const base::Feature kTrendingQueriesModule;
 
+// Feature params for kTrendingQueriesModule.
+extern const char kTrendingQueriesHideShortcutsParam[];
+extern const char kTrendingQueriesDisabledFeedParam[];
+extern const char kTrendingQueriesSignedOutParam[];
+
 // A parameter to indicate whether the native UI is enabled for the discover
 // feed.
 extern const char kDiscoverFeedIsNativeUIEnabled[];
@@ -54,4 +59,15 @@
 // Whether the Trending Queries module feature is enabled.
 bool IsTrendingQueriesModuleEnabled();
 
+// Whether the shorctus should be hidden while showing the Trending Queries
+// module.
+bool ShouldHideShortcutsForTrendingQueries();
+
+// Whether the Trending Queries module should only be shown to users who had the
+// feed disabled.
+bool ShouldOnlyShowTrendingQueriesForDisabledFeed();
+
+// Whether the Trending Queries module should only be shown to signed out users.
+bool ShouldOnlyShowTrendingQueriesForSignedOut();
+
 #endif  // IOS_CHROME_BROWSER_UI_CONTENT_SUGGESTIONS_CONTENT_SUGGESTIONS_FEATURE_H_
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm
index 138ea06..9e23868 100644
--- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm
+++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.mm
@@ -4,6 +4,8 @@
 
 #import "ios/chrome/browser/ui/content_suggestions/content_suggestions_feature.h"
 
+#import "base/metrics/field_trial_params.h"
+
 #if !defined(__has_feature) || !__has_feature(objc_arc)
 #error "This file requires ARC support."
 #endif
@@ -36,6 +38,9 @@
 const base::Feature kTrendingQueriesModule{"TrendingQueriesModule",
                                            base::FEATURE_DISABLED_BY_DEFAULT};
 
+const char kTrendingQueriesHideShortcutsParam[] = "hide_shortcuts";
+const char kTrendingQueriesDisabledFeedParam[] = "disabled_feed_only";
+const char kTrendingQueriesSignedOutParam[] = "signed_out_only";
 // A parameter to indicate whether the native UI is enabled for the discover
 // feed.
 const char kDiscoverFeedIsNativeUIEnabled[] = "DiscoverFeedIsNativeUIEnabled";
@@ -64,3 +69,18 @@
 bool IsTrendingQueriesModuleEnabled() {
   return base::FeatureList::IsEnabled(kTrendingQueriesModule);
 }
+
+bool ShouldHideShortcutsForTrendingQueries() {
+  return base::GetFieldTrialParamByFeatureAsBool(
+      kTrendingQueriesModule, kTrendingQueriesHideShortcutsParam, false);
+}
+
+bool ShouldOnlyShowTrendingQueriesForDisabledFeed() {
+  return base::GetFieldTrialParamByFeatureAsBool(
+      kTrendingQueriesModule, kTrendingQueriesDisabledFeedParam, false);
+}
+
+bool ShouldOnlyShowTrendingQueriesForSignedOut() {
+  return base::GetFieldTrialParamByFeatureAsBool(
+      kTrendingQueriesModule, kTrendingQueriesSignedOutParam, false);
+}
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm
index 89f01fe..6d015cf 100644
--- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm
+++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_mediator.mm
@@ -13,6 +13,7 @@
 #import "base/metrics/user_metrics_action.h"
 #import "base/strings/sys_string_conversions.h"
 #import "components/favicon/ios/web_favicon_driver.h"
+#import "components/feed/core/v2/public/ios/pref_names.h"
 #import "components/ntp_snippets/category.h"
 #import "components/ntp_snippets/category_info.h"
 #import "components/ntp_tiles/metrics.h"
@@ -30,6 +31,8 @@
 #import "ios/chrome/browser/ntp_tiles/most_visited_sites_observer_bridge.h"
 #import "ios/chrome/browser/policy/policy_util.h"
 #import "ios/chrome/browser/pref_names.h"
+#import "ios/chrome/browser/signin/authentication_service.h"
+#import "ios/chrome/browser/signin/authentication_service_factory.h"
 #import "ios/chrome/browser/ui/commands/application_commands.h"
 #import "ios/chrome/browser/ui/commands/browser_coordinator_commands.h"
 #import "ios/chrome/browser/ui/commands/open_new_tab_command.h"
@@ -264,19 +267,11 @@
     if ([self.mostVisitedItems count]) {
       [self.consumer setMostVisitedTilesWithConfigs:self.mostVisitedItems];
     }
-    if (!ShouldHideShortcutsForStartSurface()) {
+    if (!ShouldHideShortcutsForTrendingQueries()) {
       [self.consumer setShortcutTilesWithConfigs:self.actionButtonItems];
     }
     if (IsTrendingQueriesModuleEnabled()) {
-      // Fetch Trending Queries
-      TemplateURLRef::SearchTermsArgs args;
-      args.request_source = TemplateURLRef::NON_SEARCHBOX_NTP;
-      _startSuggestService->FetchSuggestions(
-          args,
-          base::BindOnce(
-              &StartSuggestServiceResponseBridge::OnSuggestionsReceived,
-              _startSuggestServiceResponseBridge->AsWeakPtr()),
-          self.showingStartSurface);
+      [self fetchTrendingQueriesIfApplicable];
     }
     return;
   }
@@ -811,6 +806,39 @@
   [self.dispatcher showSnackbarMessage:message];
 }
 
+- (void)fetchTrendingQueriesIfApplicable {
+  PrefService* pref_service =
+      ChromeBrowserState::FromBrowserState(self.browser->GetBrowserState())
+          ->GetPrefs();
+  BOOL isFeedVisible =
+      pref_service->GetBoolean(prefs::kArticlesForYouEnabled) &&
+      pref_service->GetBoolean(feed::prefs::kArticlesListVisible);
+  if (ShouldOnlyShowTrendingQueriesForDisabledFeed() && isFeedVisible) {
+    // Notify consumer with empty array so it knows to remove the module.
+    [self.consumer setTrendingQueriesWithConfigs:@[]];
+    return;
+  }
+  AuthenticationService* authService =
+      AuthenticationServiceFactory::GetForBrowserState(
+          self.browser->GetBrowserState());
+  BOOL isSignedIn =
+      authService->HasPrimaryIdentity(signin::ConsentLevel::kSignin);
+  if (ShouldOnlyShowTrendingQueriesForSignedOut() && isSignedIn) {
+    // Notify consumer with empty array so it knows to remove the module.
+    [self.consumer setTrendingQueriesWithConfigs:@[]];
+    return;
+  }
+
+  // Fetch Trending Queries
+  TemplateURLRef::SearchTermsArgs args;
+  args.request_source = TemplateURLRef::NON_SEARCHBOX_NTP;
+  _startSuggestService->FetchSuggestions(
+      args,
+      base::BindOnce(&StartSuggestServiceResponseBridge::OnSuggestionsReceived,
+                     _startSuggestServiceResponseBridge->AsWeakPtr()),
+      self.showingStartSurface);
+}
+
 #pragma mark - Properties
 
 - (NSArray<ContentSuggestionsMostVisitedActionItem*>*)actionButtonItems {
diff --git a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm
index fc278cfa..4f6aedb4 100644
--- a/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm
+++ b/ios/chrome/browser/ui/content_suggestions/content_suggestions_view_controller.mm
@@ -122,6 +122,8 @@
 // List of all UITapGestureRecognizers created for the Trending Queries.
 @property(nonatomic, strong)
     NSMutableArray<UITapGestureRecognizer*>* trendingQueryTapRecognizers;
+// Set to YES when the trending queries fetch has been received.
+@property(nonatomic, assign) BOOL trendingQueriesReceived;
 
 @end
 
@@ -260,7 +262,9 @@
     ]];
     [self populateMostVisitedModule];
   }
-  if (IsTrendingQueriesModuleEnabled()) {
+  BOOL noTrendingQueriesToShow =
+      self.trendingQueriesReceived && [self.trendingQueryViews count] == 0;
+  if (IsTrendingQueriesModuleEnabled() && !noTrendingQueriesToShow) {
     self.trendingQueriesContainingView = [[UIView alloc] init];
     self.trendingQueriesModuleContainer =
         [[ContentSuggestionsModuleContainer alloc]
@@ -522,6 +526,7 @@
 - (void)setTrendingQueriesWithConfigs:
     (NSArray<QuerySuggestionConfig*>*)configs {
   DCHECK(IsTrendingQueriesModuleEnabled());
+  self.trendingQueriesReceived = YES;
   if (!self.trendingQueriesContainingView) {
     self.trendingQueriesContainingView = [[UIView alloc] init];
   }
@@ -733,7 +738,6 @@
 
 - (void)populateTrendingQueriesModule {
   for (QuerySuggestionView* view in self.trendingQueryViews) {
-    //      view.menuProvider = self.menuProvider;
     UITapGestureRecognizer* tapRecognizer = [[UITapGestureRecognizer alloc]
         initWithTarget:self
                 action:@selector(contentSuggestionsElementTapped:)];