mycode/myApp/HaruDanim/Widgets/LockScreenWidgets.swift
songyc macbook 1dea41b472 feat(ux): 잠금화면 다짐 점 링 방식 + 즐겨찾기 순서 변경 시트 (실기기 피드백 2건)
첫 출시 전 반영 요청된 사용성 개선 — 둘 다 표시 계층·기기 로컬 설정만
건드리는 안전 범주.

① 잠금화면 위젯 다짐 점: '아래에서 차오르는 물높이' 채움은 5~6pt에서
   90%↔100% 차이(위쪽 1px)가 배경에 따라 사실상 안 보임 —
   **미완료 = 링(호) 진행(시작 최소 10%, 완료 직전에도 틈이 보이게
   최대 88%까지만 감김) / 완료 = 꽉 찬 원반**으로 교체. 링 끝의 틈은
   둘레에 생겨 눈에 띄고, 완료는 면적(빈 링 vs 원반) 자체가 달라
   어떤 배경에서도 구분된다. ratio 그대로라 '이하 유지'는
   한도 안=원반/초과=빈 트랙으로 의미 유지 (§10 문서화)

② 즐겨찾기 순서 변경: 행동 탭 ⋯ 메뉴에 '즐겨찾기 순서 변경' 시트
   추가(2개 이상일 때, 꼬리표 순서 시트와 동일 패턴 — 닫힐 때 1회
   커밋). LocalPrefs.reorderFavorites는 전역 배치에서 즐겨찾기가
   차지한 자리들만 재배열해 나머지 행동·위젯 기본 슬롯 무영향.
   모음 탭 즐겨찾기 섹션·애플워치 즐겨찾기가 같은 순서를 읽으므로
   세 표면이 자동 일관 (§6.2·§6.1·§11 문서화).
   move(fromOffsets:)는 SwiftUI 확장이라 Foundation 계층에 동일
   의미로 직접 구현

- 도움말 '즐겨찾기 모아 보기' 본문에 순서 변경 경로·워치 적용 추가
- 신규 문구 4키 en/ja 완역, 옛 본문 stale 정리 (missing/stale 0)
- §14에 -actionShowFavoriteOrder 검증 인자 추가
- 검증: Debug/Store 빌드, 잠금 위젯 프리뷰·순서 시트 스크린샷

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-22 21:38:16 +09:00

265 lines
10 KiB
Swift

//
// LockScreenWidgets.swift
// Haru_DanimWidgets
//
// (CLAUDE.md §8.4) 1 /
// : / /
//
import SwiftUI
import WidgetKit
import AppIntents
// MARK: -
enum LockStyleOption: String, AppEnum {
case gauge
case number
case dots
static let typeDisplayRepresentation = TypeDisplayRepresentation(name: "표시 방식")
static let caseDisplayRepresentations: [LockStyleOption: DisplayRepresentation] = [
.gauge: "원형 게이지",
.number: "숫자만",
.dots: "다짐 점 표시",
]
}
struct LockGoalConfigIntent: WidgetConfigurationIntent {
static let title: LocalizedStringResource = "잠금화면 목표 위젯"
static let description = IntentDescription("잠금화면에 표시할 목표와 기간, 표시 방식을 선택하세요.")
@Parameter(title: "목표")
var goal: GoalEntity?
@Parameter(title: "달성률 기간", default: .day)
var span: SpanOption
@Parameter(title: "표시 방식", default: .gauge)
var style: LockStyleOption
static var parameterSummary: some ParameterSummary {
Summary("목표 달성률을 \(\.$span) 기준 \(\.$style)(으)로 표시") {
\.$goal
}
}
}
// MARK: -
struct LockGoalEntry: TimelineEntry {
let date: Date
let locked: Bool
let spanLabel: String
let style: LockStyleOption
let goal: GoalSnapshot?
let ratio: Double
var isLive: Bool { goal?.quests.contains { $0.isRunning } ?? false }
}
struct LockGoalProvider: AppIntentTimelineProvider {
@MainActor
static func makeEntry(_ configuration: LockGoalConfigIntent, now: Date = .now) -> LockGoalEntry {
IntentStore.refresh()
guard PremiumGate.isUnlocked(.lockScreenWidgets) else {
return LockGoalEntry(date: now, locked: true, spanLabel: "", style: .gauge, goal: nil, ratio: 0)
}
let span = configuration.span.statSpan
let model = WidgetStore.goal(configuration.goal?.id) ?? WidgetStore.defaultGoals(1).first
let snapshot = model.map { GoalSnapshot.make(goal: $0, span: span, now: now) }
return LockGoalEntry(
date: now,
locked: false,
spanLabel: configuration.span.label,
style: configuration.style,
goal: snapshot,
ratio: snapshot?.ratio(for: span) ?? 0
)
}
func placeholder(in context: Context) -> LockGoalEntry {
let goal = GoalSnapshot.sample
return LockGoalEntry(date: .now, locked: false, spanLabel: String(localized: "오늘"), style: .gauge, goal: goal, ratio: goal.dayRatio)
}
@MainActor
func snapshot(for configuration: LockGoalConfigIntent, in context: Context) async -> LockGoalEntry {
Self.makeEntry(configuration)
}
@MainActor
func timeline(for configuration: LockGoalConfigIntent, in context: Context) async -> Timeline<LockGoalEntry> {
let first = Self.makeEntry(configuration)
return WidgetRefresh.timeline(first: first, live: first.isLive) { date in
Self.makeEntry(configuration, now: date)
}
}
}
// MARK: -
struct LockGoalWidgetView: View {
@Environment(\.widgetFamily) private var envFamily
/// DEBUG
var previewFamily: WidgetFamily? = nil
private var family: WidgetFamily { previewFamily ?? envFamily }
let entry: LockGoalEntry
var body: some View {
Group {
if entry.locked {
switch family {
case .accessoryInline:
Text("하루 다님 · 프리미엄 기능")
default:
VStack(spacing: 2) {
Image(systemName: "crown.fill")
.widgetAccentable()
Text("프리미엄")
.font(.caption2)
}
}
} else if let goal = entry.goal {
switch family {
case .accessoryInline:
// : + + %
Text("\(goal.title) \(Format.percent(entry.ratio))")
case .accessoryRectangular:
rectangularView(goal)
default:
circularView(goal)
}
} else {
switch family {
case .accessoryInline:
Text("하루 다님 · 목표 없음")
default:
VStack(spacing: 2) {
Image(systemName: "flag.checkered")
Text("목표 없음")
.font(.caption2)
}
}
}
}
.containerBackground(.clear, for: .widget)
}
/// (/ )
/// (AccessoryWidgetBackground) ,
/// .primary + .widgetAccentable()
@ViewBuilder
private func circularView(_ goal: GoalSnapshot) -> some View {
switch entry.style {
case .gauge:
Gauge(value: min(max(entry.ratio, 0), 1)) {
Image(systemName: goal.symbolName)
.widgetAccentable()
} currentValueLabel: {
Text("\(Int((entry.ratio * 100).rounded()))")
.font(.system(size: 14, weight: .bold).monospacedDigit())
.foregroundStyle(.primary)
}
.gaugeStyle(.accessoryCircular)
case .number:
ZStack {
AccessoryWidgetBackground()
VStack(spacing: 0) {
Text("\(Int((entry.ratio * 100).rounded()))%")
.font(.system(size: 16, weight: .bold).monospacedDigit())
.foregroundStyle(.primary)
.widgetAccentable()
Text(entry.spanLabel)
.font(.system(size: 9))
.foregroundStyle(.secondary)
}
}
case .dots:
// ( 6)
ZStack {
AccessoryWidgetBackground()
VStack(spacing: 3) {
Image(systemName: goal.symbolName)
.font(.system(size: 12, weight: .semibold))
.widgetAccentable()
questDots(goal, size: 6)
}
}
}
}
private func rectangularView(_ goal: GoalSnapshot) -> some View {
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 4) {
Image(systemName: goal.symbolName)
.font(.system(size: 11, weight: .semibold))
Text(goal.title)
.font(.caption.weight(.semibold))
.lineLimit(1)
}
.foregroundStyle(.primary)
.widgetAccentable()
Gauge(value: min(max(entry.ratio, 0), 1)) { EmptyView() }
.gaugeStyle(.accessoryLinearCapacity)
HStack {
Text("\(entry.spanLabel) \(Format.percent(entry.ratio))")
.font(.caption2)
.foregroundStyle(.secondary)
Spacer()
if !goal.quests.isEmpty {
questDots(goal, size: 5)
}
}
}
}
/// () , .
/// ' ' 5~6pt 90% 100% ( 1px )
/// '' (
/// 88% ), ( vs )
/// . ratio ' ' = / = .
private func questDots(_ goal: GoalSnapshot, size: CGFloat) -> some View {
HStack(spacing: 3) {
ForEach(goal.quests.prefix(6)) { quest in
let ratio = min(max(quest.ratio, 0), 1)
let lineWidth = max(size * 0.3, 1.4)
ZStack {
if ratio >= 0.999 {
Circle()
.fill(.primary)
} else {
Circle()
.inset(by: lineWidth / 2)
.stroke(.primary.opacity(0.35), lineWidth: lineWidth)
Circle()
.inset(by: lineWidth / 2)
// 10%, 88%
.trim(from: 0, to: ratio > 0 ? min(max(ratio, 0.1), 0.88) : 0)
.stroke(.primary, style: StrokeStyle(lineWidth: lineWidth, lineCap: .round))
.rotationEffect(.degrees(-90))
}
}
.frame(width: size, height: size)
}
}
}
}
// MARK: -
struct LockGoalWidget: Widget {
var body: some WidgetConfiguration {
AppIntentConfiguration(
kind: "HaruLockGoalWidget",
intent: LockGoalConfigIntent.self,
provider: LockGoalProvider()
) { entry in
LockGoalWidgetView(entry: entry)
}
.configurationDisplayName("목표 달성률 (잠금화면)")
.description("잠금화면에서 목표 달성률과 다짐 현황을 확인해요. (프리미엄)")
.supportedFamilies([.accessoryCircular, .accessoryRectangular, .accessoryInline])
}
}