Mobile widgets

From j4flmao/agent-skills · View interactive version

Mobile widgets is an AI agent skill from the GitHub repository j4flmao/agent-skills. Use when the user asks about home screen widgets, WidgetKit, timelines, Live Activities, Dynamic Island, App Intents widgets, Android App Widgets or Jetpack Glance. Produces widget extensions, refresh strategy and deep links into the app. Not for in-app UI components (use ios or android).

How to use this skill

Skill file

Mobile Widgets Skill

Purpose

Build glanceable, performant widget experiences across iOS and Android with proper timeline management, refresh strategies, and platform-specific best practices.

Agent Protocol

Trigger

User mentions widgets, iOS WidgetKit, Android App Widgets, Live Activities, complications, watchOS complications, Wear OS tiles, widget timeline, widget families, widget configuration, widget deep linking, widget refresh, or widget testing.

Input Context

Output Artifact

SKILL.md adherence document plus implemented widget extensions, timeline providers, configuration UI, deep link handling, and refresh logic.

Response Format

No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output — why use many token when few do trick.

Completion Criteria

Max Response Length

4096 tokens

Workflow

  1. iOS WidgetKit Timeline Provider: Define how your widget provides content over time.
import WidgetKit
import SwiftUI

struct TaskProvider: TimelineProvider {
  typealias Entry = TaskEntry

  func placeholder(in context: Context) -> TaskEntry {
    TaskEntry(date: Date(), items: TaskItem.previewData)
  }

  func getSnapshot(in context: Context, completion: @escaping (TaskEntry) -> Void) {
    let entry = TaskEntry(date: Date(), items: loadCurrentItems())
    completion(entry)
  }

  func getTimeline(in context: Context, completion: @escaping (Timeline<TaskEntry>) -> Void) {
    let entries: [TaskEntry] = generateEntries()
    let nextUpdate = Calendar.current.date(byAdding: .minute, value: 15, to: Date())!
    let timeline = Timeline(entries: entries, policy: .after(nextUpdate))
    completion(timeline)
  }

  private func generateEntries() -> [TaskEntry] {
    let now = Date()
    let items = loadCurrentItems()
    var entries: [TaskEntry] = []

    for minuteOffset in stride(from: 0, to: 60, by: 15) {
      let entryDate = Calendar.current.date(byAdding: .minute, value: minuteOffset, to: now)!
      entries.append(TaskEntry(date: entryDate, items: items))
    }

    return entries
  }
}
  1. Widget View & Entry: SwiftUI views adapted to widget families.
struct TaskEntry: TimelineEntry {
  let date: Date
  let items: [TaskItem]
}

struct TaskWidgetEntryView: View {
  var entry: TaskProvider.Entry
  @Environment(\.widgetFamily) var family

  var body: some View {
    switch family {
    case .systemSmall:
      SmallTaskView(items: entry.items)
    case .systemMedium:
      MediumTaskView(items: entry.items)
    case .systemLarge:
      LargeTaskView(items: entry.items)
    default:
      MediumTaskView(items: entry.items)
    }
  }
}

struct SmallTaskView: View {
  let items: [TaskItem]

  var body: some View {
    VStack(alignment: .leading, spacing: 4) {
      Text("To-Do").font(.headline).foregroundColor(.secondary)
      ForEach(items.prefix(3)) { item in
        HStack(spacing: 4) {
          Image(systemName: item.isCompleted ? "checkmark.circle.fill" : "circle")
            .foregroundColor(item.isCompleted ? .green : .gray)
            .font(.caption)
          Text(item.title).font(.caption).lineLimit(1)
        }
      }
      if items.count > 3 {
        Text("+\(items.count - 3) more").font(.caption2).foregroundColor(.secondary)
      }
    }
    .padding()
    .widgetURL(URL(string: "myapp://tasks"))
  }
}
  1. Widget Configuration with App Intents: User-configurable widgets via AppIntentConfiguration and WidgetConfigurationIntent (iOS 17+; the older SiriKit .intentdefinition path is legacy).
import AppIntents

struct SelectListIntent: WidgetConfigurationIntent {
  static let title: LocalizedStringResource = "Select List"
  static let description = IntentDescription("Choose which to-do list to display.")

  @Parameter(title: "List")
  var list: ListEntity?

  static var parameterSummary: some ParameterSummary {
    Summary("Show items from \(\.$list)")
  }
}

struct ListEntity: AppEntity {
  let id: String
  let name: String

  static var typeDisplayRepresentation: TypeDisplayRepresentation = "List"
  static var defaultQuery = ListQuery()

  var displayRepresentation: DisplayRepresentation {
    DisplayRepresentation(title: "\(name)")
  }
}

struct ListQuery: EntityStringQuery {
  func entities(matching string: String) async throws -> [ListEntity] {
    return await ListStore.shared.lists.filter { $0.name.contains(string) }
  }

  func suggestedEntities() async throws -> [ListEntity] {
    return await ListStore.shared.lists
  }

  func defaultResult() async -> ListEntity? {
    return await ListStore.shared.lists.first
  }
}
  1. Live Activities (iOS 16.1+): Dynamic, real-time updates on Lock Screen and Dynamic Island.
import ActivityKit

struct DeliveryActivityAttributes: ActivityAttributes {
  public struct ContentState: Codable, Hashable {
    var driverName: String
    var estimatedMinutes: Int
    var status: DeliveryStatus
    var lastUpdate: Date
  }

  var orderId: String
  var restaurantName: String
}

enum DeliveryStatus: String, Codable, Hashable {
  case preparing
  case pickedUp
  case inTransit
  case delivered
}

func startDeliveryActivity(orderId: String, restaurantName: String) {
  let attributes = DeliveryActivityAttributes(orderId: orderId, restaurantName: restaurantName)
  let state = DeliveryActivityAttributes.ContentState(
    driverName: "",
    estimatedMinutes: 0,
    status: .preparing,
    lastUpdate: Date()
  )

  do {
    let activity = try Activity<DeliveryActivityAttributes>.request(
      attributes: attributes,
      content: ActivityContent(state: state, staleDate: nil),
      pushType: .token
    )
    print("Started Live Activity: \(activity.id)")
  } catch {
    print("Failed to start Live Activity: \(error)")
  }
}

func updateDeliveryActivity(activityId: String, state: DeliveryActivityAttributes.ContentState) {
  Task {
    let activity = Activity<DeliveryActivityAttributes>.activities.first { $0.id == activityId }
    await activity?.update(
      ActivityContent(state: state, staleDate: Date().addingTimeInterval(30 * 60))
    )
  }
}

// Live Activity SwiftUI view
struct DeliveryLiveActivityView: View {
  let context: ActivityViewContext<DeliveryActivityAttributes>

  var body: some View {
    HStack {
      VStack(alignment: .leading) {
        Text(context.attributes.restaurantName).font(.headline)
        Text(context.state.driverName).font(.caption).foregroundColor(.secondary)
      }
      Spacer()
      VStack(alignment: .trailing) {
        Text("\(context.state.estimatedMinutes) min").font(.title2).bold()
        Text(context.state.status.rawValue).font(.caption).foregroundColor(.blue)
      }
    }
    .padding()
    .activitySystemActionForegroundColor(.indigo)
  }
}
  1. Android App Widgets: RemoteViews with configuration activity.
// TaskWidgetProvider.kt
class TaskWidgetProvider : AppWidgetProvider() {
  override fun onUpdate(
    context: Context,
    appWidgetManager: AppWidgetManager,
    appWidgetIds: IntArray
  ) {
    for (appWidgetId in appWidgetIds) {
      updateAppWidget(context, appWidgetManager, appWidgetId)
    }
  }

  override fun onDeleted(context: Context, appWidgetIds: IntArray) {
    for (appWidgetId in appWidgetIds) {
      TaskWidgetConfig.removeWidget(context, appWidgetId)
    }
  }

  override fun onEnabled(context: Context) {
    // Prepare for first widget instance
  }

  override fun onDisabled(context: Context) {
    // Clean up when last widget removed
  }

  companion object {
    internal fun updateAppWidget(
      context: Context,
      appWidgetManager: AppWidgetManager,
      appWidgetId: Int
    ) {
      val listId = TaskWidgetConfig.loadListPref(context, appWidgetId)
      val items = TaskRepository.getItems(listId)

      val views = RemoteViews(context.packageName, R.layout.task_widget)
      views.setTextViewText(R.id.widget_title, getListName(listId))

      val rv = RemoteViews(context.packageName, R.layout.task_widget_item)
      views.removeAllViews(R.id.widget_list_container)

      items.take(5).forEach { item ->
        val itemView = RemoteViews(context.packageName, R.layout.task_widget_item)
        itemView.setTextViewText(R.id.item_text, item.title)
        itemView.setInt(R.id.item_checkbox, "setChecked", if (item.isCompleted) 1 else 0)

        val fillInIntent = Intent(context, MainActivity::class.java).apply {
          action = Intent.ACTION_VIEW
          data = Uri.parse("myapp://task/${item.id}")
        }
        val pendingIntent = PendingIntent.getActivity(
          context, item.id.toInt(), fillInIntent,
          PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        itemView.setOnClickPendingIntent(R.id.item_container, pendingIntent)
        views.addView(R.id.widget_list_container, itemView)
      }

      val configIntent = Intent(context, TaskWidgetConfigureActivity::class.java).apply {
        putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
      }
      val configPendingIntent = PendingIntent.getActivity(
        context, appWidgetId, configIntent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
      )
      views.setOnClickPendingIntent(R.id.widget_settings, configPendingIntent)

      appWidgetManager.updateAppWidget(appWidgetId, views)
    }
  }
}

// Widget layout: res/layout/task_widget.xml
// <LinearLayout
//   xmlns:android="http://schemas.android.com/apk/res/android"
//   android:layout_width="match_parent"
//   android:layout_height="match_parent"
//   android:orientation="vertical"
//   android:padding="@dimen/widget_margin">
//   <LinearLayout android:orientation="horizontal" android:layout_width="match_parent">
//     <TextView android:id="@+id/widget_title" .../>
//     <ImageButton android:id="@+id/widget_settings" .../>
//   </LinearLayout>
//   <LinearLayout android:id="@+id/widget_list_container" android:orientation="vertical" .../>
// </LinearLayout>
  1. Widget Refresh Strategies: Balance freshness with battery life.
// iOS: TimelineReloadPolicy (WidgetKit) — returned with each Timeline
// .after(date)  request the next timeline at or after a date (system may delay)
// .atEnd        request a new timeline after the last entry
// .never        reload only when the app calls WidgetCenter.reloadTimelines

// iOS Background refresh via push
func handleWidgetPush(token: String, data: [String: Any]) {
  let newEntry = TaskEntry(date: Date(), items: parseItems(from: data))
  WidgetCenter.shared.reloadTimelines(ofKind: "TaskWidget")
}

// Android periodic refresh
class TaskWidgetProvider : AppWidgetProvider() {
  override fun onUpdate(...) {
    // Scheduled via AlarmManager or WorkManager
    val workRequest = PeriodicWorkRequestBuilder<WidgetRefreshWorker>(
      15, TimeUnit.MINUTES
    ).build()
    WorkManager.getInstance(context).enqueueUniquePeriodicWork(
      "widget_refresh",
      ExistingPeriodicWorkPolicy.KEEP,
      workRequest
    )
  }
}
  1. Widget Deep Linking: Navigate to specific app screens on tap.
// iOS: widgetURL for the entire widget
// widgetUrl(URL(string: "myapp://dashboard"))

// iOS: Link for specific areas within widget
Link(destination: URL(string: "myapp://task/\(item.id)")!) {
  Text(item.title)
}

// Android: PendingIntent with custom URI
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("myapp://task/$itemId"))
val pendingIntent = PendingIntent.getActivity(context, requestCode, intent, flags)
views.setOnClickPendingIntent(R.id.item_container, pendingIntent)
  1. Widget Testing: Preview with different data states.
// iOS widget previews
struct TaskWidget_Previews: PreviewProvider {
  static var previews: some View {
    Group {
      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: TaskItem.previewData))
        .previewContext(WidgetPreviewContext(family: .systemSmall))

      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: TaskItem.previewData))
        .previewContext(WidgetPreviewContext(family: .systemMedium))

      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: []))
        .previewContext(WidgetPreviewContext(family: .systemSmall))

      TaskWidgetEntryView(entry: TaskEntry(date: Date(), items: TaskItem.previewErrorData))
        .previewContext(WidgetPreviewContext(family: .systemLarge))
    }
  }
}

Rules

  1. Never perform network calls in widget views — fetch in the timeline provider (iOS getTimeline/timeline(for:in:)) or a background worker (Android), then render cached data.
  2. Always provide a placeholder view for loading states.
  3. Keep the widget extension small: extensions run under a tight memory limit (tens of MB), so downsample images and keep assets minimal.
  4. Support only the widget families whose layout fits your content (supportedFamilies), and design each one deliberately.
  5. Never use infinite timelines — always provide a finite set of entries.
  6. Always test widgets with system Dark Mode and Accent Color.
  7. Never use custom fonts not bundled in widget extension target.
  8. Always provide snapshot data for widget gallery preview.
  9. Never hardcode refresh intervals — respect user's battery settings.
  10. Always implement tap targets with minimum 44pt touch area.
  11. Never use UIWebView/WKWebView inside widgets (not supported).
  12. Always provide accessibility labels for VoiceOver/TalkBack.
  13. Never store large datasets in UserDefaults for widget access — use shared container.
  14. Always handle empty state gracefully (no data view, not blank).
  15. Keep widget animations to the system-provided content transitions; widgets do not run custom animation loops.
  16. Always implement configurable widgets when user personalization is needed.
  17. Never use UIKit/AppKit inside iOS widgets — SwiftUI only.
  18. Always test widgets with different Dynamic Type sizes.
  19. Respect the iOS reload budget (the system allows a limited number of reloads per day, typically every 15–60 minutes for a frequently viewed widget); use app-triggered reloadTimelines after real data changes instead of short timers. Android updatePeriodMillis is clamped to a 30-minute minimum.
  20. Always remove widget data when all widget instances are deleted.

References

Handoff

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.