mycode/myApp/HaruDanim/Widgets/ActionRunWidget.swift
songyc macbook ed8b52792a feat(widgets): 홈/잠금화면 위젯 6종 + Interactive Widgets (CLAUDE.md §8)
- 행동 실행(A): 소형1/중형3/대형4칸, Button(intent:)로 앱 없이 즉시 실행,
  측정 중 실시간 타이머 + 노란 테두리, 표시 기간(오늘/이번 주/이번 달) 옵션
- 목표 진행률(B): 하루/주간/월간 가로 진행바, 소형1/중형2/대형4
- 다짐 진행률(C): 원형 링 + 기간 옵션, 단일 행동 다짐은 눌러서 실행,
  '이하 유지'는 한도 지킴/초과로 표현
- 다짐 현황(D): 목표명 + 원형 링 그리드 (소형 2x2 / 중형 최대 8 / 대형 목표 2개)
- 통계: 행동 최대 3개 꺾은선 그래프, 앱 통계 탭과 동일 산식·색,
  소형은 '한 달 일별' 제외 (스펙 §8.3)
- 잠금화면: circular/rectangular/inline, 표시 방식 3종(게이지/숫자/다짐 점)
- 전 위젯 프리미엄 게이트 (미결제 시 잠금 안내)
- DEBUG 미리보기 화면: -widgetPreview YES|lock, -widgetPreviewScroll B|C|D|S

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013yKDMhuF39GVYy3FMcGHh7
2026-07-10 08:59:47 +09:00

203 lines
7.4 KiB
Swift

//
// ActionRunWidget.swift
// Haru_DanimWidgets
//
// (CLAUDE.md §8.2 A / A / A)
// Interactive Widgets: ( / +1)
//
import SwiftUI
import WidgetKit
import AppIntents
// MARK: -
struct ActionRunConfigIntent: WidgetConfigurationIntent {
static let title: LocalizedStringResource = "행동 실행 위젯"
static let description = IntentDescription("표시할 행동과 누적 기간을 선택하세요.")
@Parameter(title: "표시 기간", default: .day)
var period: SpanOption
@Parameter(title: "행동 1")
var action1: ActionEntity?
@Parameter(title: "행동 2")
var action2: ActionEntity?
@Parameter(title: "행동 3")
var action3: ActionEntity?
@Parameter(title: "행동 4")
var action4: ActionEntity?
}
// MARK: -
struct ActionRunEntry: TimelineEntry {
let date: Date
let locked: Bool
let periodLabel: String
let cells: [ActionCellSnapshot]
}
struct ActionRunProvider: AppIntentTimelineProvider {
@MainActor
static func makeEntry(_ configuration: ActionRunConfigIntent) -> ActionRunEntry {
guard WidgetStore.isUnlocked else {
return ActionRunEntry(date: .now, locked: true, periodLabel: "", cells: [])
}
let span = configuration.period.statSpan
let chosen = [configuration.action1, configuration.action2, configuration.action3, configuration.action4]
.compactMap { $0 }
.compactMap { WidgetStore.action($0.id) }
let actions = chosen.isEmpty ? WidgetStore.defaultActions(4) : chosen
return ActionRunEntry(
date: .now,
locked: false,
periodLabel: configuration.period.label,
cells: actions.map { ActionCellSnapshot.make(action: $0, span: span) }
)
}
func placeholder(in context: Context) -> ActionRunEntry {
ActionRunEntry(date: .now, locked: false, periodLabel: "오늘", cells: [])
}
@MainActor
func snapshot(for configuration: ActionRunConfigIntent, in context: Context) async -> ActionRunEntry {
Self.makeEntry(configuration)
}
@MainActor
func timeline(for configuration: ActionRunConfigIntent, in context: Context) async -> Timeline<ActionRunEntry> {
// / reloadAllTimelines ,
// 15
Timeline(entries: [Self.makeEntry(configuration)], policy: .after(.now.addingTimeInterval(15 * 60)))
}
}
// MARK: -
struct ActionRunCellView: View {
let cell: ActionCellSnapshot
let periodLabel: String
var compact = false
var body: some View {
Button(intent: RunActionIntent(action: cell.entity)) {
VStack(alignment: .leading, spacing: compact ? 2 : 4) {
HStack {
Image(systemName: cell.symbolName)
.font(.system(size: compact ? 14 : 18, weight: .semibold))
Spacer()
if cell.isRunning {
Image(systemName: "record.circle")
.font(.system(size: compact ? 10 : 12, weight: .bold))
.foregroundStyle(AppTheme.yellow)
}
}
Spacer(minLength: 0)
Text(cell.name)
.font(compact ? .caption2.weight(.semibold) : .caption.weight(.semibold))
.lineLimit(1)
Group {
if cell.isCount {
Text("\(periodLabel) \(Int(cell.value))")
} else if let base = cell.tickingBase {
// :
Text(base, style: .timer)
} else {
Text("\(periodLabel) \(Format.durationShort(cell.value))")
}
}
.font(compact ? .caption2.monospacedDigit() : .caption.monospacedDigit())
.opacity(0.85)
.lineLimit(1)
}
.foregroundStyle(.white)
.padding(compact ? 8 : 12)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
.background(
RoundedRectangle(cornerRadius: 14, style: .continuous)
.fill(cell.color)
)
.overlay {
if cell.isRunning {
RoundedRectangle(cornerRadius: 14, style: .continuous)
.strokeBorder(AppTheme.yellow, lineWidth: 2)
}
}
}
.buttonStyle(.plain)
}
}
struct ActionRunWidgetView: View {
@Environment(\.widgetFamily) private var envFamily
/// DEBUG
var previewFamily: WidgetFamily? = nil
private var family: WidgetFamily { previewFamily ?? envFamily }
let entry: ActionRunEntry
var body: some View {
Group {
if entry.locked {
WidgetLockedView()
} else if entry.cells.isEmpty {
Text("앱에서 행동을 만들면 여기서 실행할 수 있어요.")
.font(.caption2)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
} else {
switch family {
case .systemMedium:
HStack(spacing: 8) {
ForEach(entry.cells.prefix(3)) { cell in
ActionRunCellView(cell: cell, periodLabel: entry.periodLabel, compact: true)
}
}
case .systemLarge:
let cells = Array(entry.cells.prefix(4))
VStack(spacing: 8) {
HStack(spacing: 8) {
ForEach(cells.prefix(2)) { cell in
ActionRunCellView(cell: cell, periodLabel: entry.periodLabel)
}
}
if cells.count > 2 {
HStack(spacing: 8) {
ForEach(cells.dropFirst(2)) { cell in
ActionRunCellView(cell: cell, periodLabel: entry.periodLabel)
}
}
}
}
default:
if let cell = entry.cells.first {
ActionRunCellView(cell: cell, periodLabel: entry.periodLabel)
}
}
}
}
.containerBackground(AppTheme.background, for: .widget)
}
}
// MARK: -
struct ActionRunWidget: Widget {
var body: some WidgetConfiguration {
AppIntentConfiguration(
kind: "HaruActionRunWidget",
intent: ActionRunConfigIntent.self,
provider: ActionRunProvider()
) { entry in
ActionRunWidgetView(entry: entry)
}
.configurationDisplayName("행동 실행")
.description("행동을 위젯에서 바로 실행하고 누적값을 확인해요. (프리미엄)")
.supportedFamilies([.systemSmall, .systemMedium, .systemLarge])
}
}