Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 38 additions & 23 deletions Modules/Sources/JetpackStats/Cards/TopListCard.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ struct TopListCard: View {
.environment(\.context, context)
.environment(\.router, router)

router.navigate(to: screen, title: viewModel.selection.item.localizedTitle)
router.navigate(to: screen, title: viewModel.selection.localizedScreenTitle)
}

private var itemTypePicker: some View {
Expand All @@ -203,7 +203,8 @@ struct TopListCard: View {
selection.item = item
let supportedMetric = getSupportedMetrics(for: item)
if !supportedMetric.contains(selection.metric),
let metric = supportedMetric.first {
let metric = supportedMetric.first
{
selection.metric = metric
}
viewModel.selection = selection
Expand Down Expand Up @@ -262,10 +263,14 @@ struct TopListCard: View {
viewModel.selection.options.locationLevel = level

// Track location level change
viewModel.tracker?.send(.locationLevelChanged, properties: [
"from_level": previousLevel.analyticsName,
"to_level": level.analyticsName
])
viewModel.tracker?
.send(
.locationLevelChanged,
properties: [
"from_level": previousLevel.analyticsName,
"to_level": level.analyticsName
]
)
} label: {
Label(level.localizedTitle, systemImage: level.systemImage)
}
Expand All @@ -280,10 +285,14 @@ struct TopListCard: View {
viewModel.selection.options.deviceBreakdown = breakdown

// Track device breakdown change
viewModel.tracker?.send(.deviceBreakdownChanged, properties: [
"from_breakdown": previousBreakdown.analyticsName,
"to_breakdown": breakdown.analyticsName
])
viewModel.tracker?
.send(
.deviceBreakdownChanged,
properties: [
"from_breakdown": previousBreakdown.analyticsName,
"to_breakdown": breakdown.analyticsName
]
)
} label: {
Label(breakdown.localizedTitle, systemImage: breakdown.systemImage)
}
Expand All @@ -300,10 +309,14 @@ struct TopListCard: View {
viewModel.selection.options.utmParamGrouping = grouping

// Track UTM parameter grouping change
viewModel.tracker?.send(.utmParamGroupingChanged, properties: [
"from_grouping": previousGrouping.analyticsName,
"to_grouping": grouping.analyticsName
])
viewModel.tracker?
.send(
.utmParamGroupingChanged,
properties: [
"from_grouping": previousGrouping.analyticsName,
"to_grouping": grouping.analyticsName
]
)
} label: {
Text(grouping.localizedTitle)
}
Expand Down Expand Up @@ -449,15 +462,17 @@ private struct TopListCardPreview: View {

init(item: TopListItemType) {
self.item = item
self._viewModel = StateObject(wrappedValue: TopListViewModel(
configuration: TopListCardConfiguration(
item: item,
metric: item == .fileDownloads ? .downloads : .views
),
dateRange: Calendar.demo.makeDateRange(for: .last28Days),
service: MockStatsService(),
tracker: MockStatsTracker.shared
))
self._viewModel = StateObject(
wrappedValue: TopListViewModel(
configuration: TopListCardConfiguration(
item: item,
metric: item == .fileDownloads ? .downloads : .views
),
dateRange: Calendar.demo.makeDateRange(for: .last28Days),
service: MockStatsService(),
tracker: MockStatsTracker.shared
)
)
}

var body: some View {
Expand Down
50 changes: 37 additions & 13 deletions Modules/Sources/JetpackStats/Cards/TopListViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {
private let service: any StatsServiceProtocol
let tracker: (any StatsTracker)?
private let fetchLimit: Int?
private let loadsMapData: Bool

private var loadingTask: Task<Void, Never>?
private var loadRequestCount = 0
Expand All @@ -54,6 +55,15 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {
var item: TopListItemType
var metric: SiteMetric
var options = TopListItemOptions()

/// Title of the screen listing every item in this selection.
var localizedScreenTitle: String {
if item == .locations {
options.locationLevel.localizedTitle
} else {
item.localizedTitle
}
}
}

enum Filter: Equatable {
Expand All @@ -65,23 +75,29 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {

private var isFirstAppear = true

/// - parameter loadsMapData: Whether to load `countriesMapData`. For the
/// Regions and Cities levels this is a separate request, and the whole
/// load fails if it fails. Pass `false` when nothing draws the map.
init(
configuration: TopListCardConfiguration,
options: TopListItemOptions = TopListItemOptions(),
dateRange: StatsDateRange,
service: any StatsServiceProtocol,
tracker: (any StatsTracker)? = nil,
items: [TopListItemType]? = nil,
fetchLimit: Int? = 100,
loadsMapData: Bool = true,
filter: Filter? = nil,
initialData: TopListData? = nil
) {
self.configuration = configuration
self.selection = Selection(item: configuration.item, metric: configuration.metric)
self.selection = Selection(item: configuration.item, metric: configuration.metric, options: options)
self.items = items ?? service.supportedItems
self.dateRange = StatsDateRangeSelection(range: dateRange)
self.service = service
self.tracker = tracker
self.fetchLimit = fetchLimit
self.loadsMapData = loadsMapData
self.filter = filter
self.data = initialData
self.isLoading = initialData == nil
Expand All @@ -91,9 +107,11 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {
TopListItemType.contentItems,
TopListItemType.trafficSourceItems,
TopListItemType.audienceEngagementItems
].map {
]
.map {
$0.filter(supportedItems.contains)
}.filter {
}
.filter {
!$0.isEmpty
}
}
Expand All @@ -111,12 +129,16 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {
isFirstAppear = false

// Track card shown event
tracker?.send(.cardShown, properties: [
"card_type": CardType.topList.rawValue,
"configuration": "\(selection.item.analyticsName)_\(selection.metric.analyticsName)",
"item_type": selection.item.analyticsName,
"metric": selection.metric.analyticsName
])
tracker?
.send(
.cardShown,
properties: [
"card_type": CardType.topList.rawValue,
"configuration": "\(selection.item.analyticsName)_\(selection.metric.analyticsName)",
"item_type": selection.item.analyticsName,
"metric": selection.metric.analyticsName
]
)

loadData()
}
Expand Down Expand Up @@ -175,7 +197,7 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {

// Fetch country-level data for map if viewing regions or cities
var mapData: CountriesMapData?
if selection.item == .locations {
if loadsMapData && selection.item == .locations {
if selection.options.locationLevel == .countries {
// Use the main data for countries
mapData = createCountriesMapData(from: data)
Expand Down Expand Up @@ -291,14 +313,16 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {
case .author(let userId):
let authors = items.lazy.compactMap { $0 as? TopListItem.Author }
if let author = authors.first(where: { $0.userId == userId }),
let posts = author.posts {
let posts = author.posts
{
return posts
}
return []
case .utmMetric(let values):
let utmMetrics = items.lazy.compactMap { $0 as? TopListItem.UTMMetric }
if let metric = utmMetrics.first(where: { $0.values == values }),
let posts = metric.posts {
let posts = metric.posts
{
return posts
}
return []
Expand All @@ -315,4 +339,4 @@ final class TopListViewModel: ObservableObject, TrafficCardViewModel {
previousLocations: previousLocations
)
}
}
}
39 changes: 26 additions & 13 deletions Modules/Sources/JetpackStats/Screens/TopListScreenView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,19 @@ struct TopListScreenView: View {
item: selection.item,
metric: selection.metric
)
self._viewModel = StateObject(wrappedValue: TopListViewModel(
configuration: configuration,
dateRange: dateRange,
service: service,
tracker: context.tracker,
fetchLimit: nil, // Get all items
filter: filter,
initialData: initialData
))
self._viewModel = StateObject(
wrappedValue: TopListViewModel(
configuration: configuration,
options: selection.options,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Finding from Claude:

With Regions or Cities selected, the Show All screen can show an error even though the list it needs loaded fine.

What happens

  • Now that Show All keeps the card's level, the view model also requests every country to build map data (TopListViewModel.swift:180-186).
  • Only the card draws that map (countriesMapData is read only at TopListCard.swift:110), so on Show All this request is never needed. It also has no size limit there (fetchLimit: nil).
  • If that request fails, the catch sets data = nil, and the regions list that did load is thrown away.
  • Before this PR, Show All always used Countries, so this extra request never happened there.

Who is affected
Anyone who opens Show All for Regions or Cities on a slow or flaky connection. Everyone else pays for an extra request with no size limit each time the screen loads (two with a comparison period).

What they see
The error state under a "Regions" title.

Show All titled Regions showing ‘The operation couldn’t be completed. (NSURLErrorDomain error -1001.)’

Steps to reproduce

  1. Open Stats → Traffic on a site with visitors from several regions (mobile.blog was used).
  2. On the Locations card, switch the level to Regions and wait for it to load.
  3. Tap Show All.
  4. Make the all-countries request fail. For the screenshot, a temporary local change in StatsService.getTopListData threw URLError(.timedOut) for .locations + .countries + limit == nil. Only the Show All screen sends that combination, and the regions request was left untouched.

Suggested fix
Only fetch map data when the view model drives a card. For example, skip it when fetchLimit == nil, or pass an explicit flag. Making a failed map request leave data alone would also avoid the error state. Once that's in, the new test could assert the full request list ([.regions] on Show All) instead of .first, so a change to the map request gets caught.

How this was checked

  • Jetpack Debug build of 3a67b951bf on an iOS 27.2 simulator, signed in to WordPress.com. Without the temporary change, Show All for Regions loads correctly (title "Regions", region rows).
  • With the temporary change: the screenshot above.
  • A unit test against the same commit, using a fake service whose countries request throws: the requests were [regions, countries] with limits [nil, nil], then data == nil and loadingError was set. The test is below and was not committed.
Unit test used
@Test("A failed map fetch hides the loaded regions list on Show All")
func mapFetchFailureHidesList() async throws {
    let service = RecordingStatsService(failCountries: true) // throws URLError(.timedOut) for .countries
    let calendar = Calendar.mock()
    let dateRange = StatsDateRange(
        interval: calendar.makeDateInterval(for: .today),
        component: .day,
        comparison: .off,
        calendar: calendar
    )
    let viewModel = TopListViewModel(
        configuration: TopListCardConfiguration(item: .locations, metric: .views),
        options: TopListItemOptions(locationLevel: .regions),
        dateRange: dateRange,
        service: service,
        fetchLimit: nil // as TopListScreenView passes it
    )
    viewModel.onAppear()
    try await waitUntil { !viewModel.isLoading }

    #expect(await service.requestedLocationLevels == [.regions, .countries]) // passes
    #expect(viewModel.data == nil)          // passes: the loaded regions list is discarded
    #expect(viewModel.loadingError != nil)  // passes
}

Output: levels=[regions, countries] limits=[nil, nil] data=nil error=NSURLErrorDomain Code=-1001

dateRange: dateRange,
service: service,
tracker: context.tracker,
fetchLimit: nil, // Get all items
loadsMapData: false,
filter: filter,
initialData: initialData
)
)
self._postThumbnailStore = StateObject(wrappedValue: PostThumbnailStore(service: service))
}

Expand Down Expand Up @@ -67,7 +71,9 @@ struct TopListScreenView: View {
.environment(\.postThumbnailStore, thumbnailStore)
}
} else {
makeEmptyStateView(message: viewModel.loadingError?.localizedDescription ?? Strings.Errors.generic)
makeEmptyStateView(
message: viewModel.loadingError?.localizedDescription ?? Strings.Errors.generic
)
}
}
.padding(.horizontal, Constants.cardHorizontalInset(for: horizontalSizeClass))
Expand All @@ -79,7 +85,7 @@ struct TopListScreenView: View {
.animation(.default, value: viewModel.data.map(ObjectIdentifier.init))
.listStyle(.plain)
.environment(\.defaultMinListRowHeight, 1)
.navigationTitle(viewModel.selection.item.localizedTitle)
.navigationTitle(viewModel.selection.localizedScreenTitle)
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItemGroup(placement: .navigationBarTrailing) {
Expand Down Expand Up @@ -223,7 +229,14 @@ struct TopListScreenView: View {
.padding(.horizontal, Constants.step1)
} else {
listHeaderView(title: section.title)
.padding(EdgeInsets(top: Constants.step3, leading: Constants.step1, bottom: Constants.step0_5, trailing: Constants.step1))
.padding(
EdgeInsets(
top: Constants.step3,
leading: Constants.step1,
bottom: Constants.step0_5,
trailing: Constants.step1
)
)
.dynamicTypeSize(...DynamicTypeSize.xLarge)
}
listForEach(for: section, data: data)
Expand Down Expand Up @@ -329,7 +342,7 @@ struct TopListScreenView: View {
dateFormatter.dateFormat = "yyyy-MM-dd"
let dateString = dateFormatter.string(from: Date())

let itemName = viewModel.selection.item.localizedTitle
let itemName = viewModel.selection.localizedScreenTitle
.replacingOccurrences(of: " ", with: "_")
.replacingOccurrences(of: "&", with: "and")

Expand Down
Loading