diff --git a/Sources/Montage/1 Components/3 Selection And Input/TextField.swift b/Sources/Montage/1 Components/3 Selection And Input/TextField.swift index 95a81312f..5e46c0bd2 100644 --- a/Sources/Montage/1 Components/3 Selection And Input/TextField.swift +++ b/Sources/Montage/1 Components/3 Selection And Input/TextField.swift @@ -396,6 +396,7 @@ public struct TextField: View { @Environment(\.isEnabled) private var isEnabled @Environment(\.colorScheme) private var colorScheme @State private var textFieldGlobalFrame: CGRect = .zero + @WindowSafeArea private var windowSafeAreaInsets @FocusState private var textFieldFocusState: Bool @State private var autoCompletionContentHeight: CGFloat = .zero @State private var fixAutocorrection = false @@ -485,6 +486,7 @@ private extension TextField { }, action: { textFieldGlobalFrame = $0 } ) + .readsWindowSafeArea($windowSafeAreaInsets) .background { fieldBackground } .overlay { RoundedRectangle(cornerRadius: size.cornerRadius) @@ -540,11 +542,9 @@ private extension TextField { } .scrollDisabled(autoCompletionContentHeight <= autoCompletionDataSource?.maxHeight ?? 0) .accessibilityIdentifier("autocomplete_container") - // safeAreaInsets 환경값은 기본값을 body 평가 중 UIKit에서 읽어 AttributeGraph 순환을 만들므로 - // (순환 이후 화면 업데이트가 멈춤, LIVE-1487) 팝업을 띄우는 시점에 직접 읽는다. .position( x: textFieldGlobalFrame.midX, - y: textFieldGlobalFrame.maxY - (UIApplication.keyWindow?.safeAreaInsets.top ?? 0) + y: textFieldGlobalFrame.maxY - windowSafeAreaInsets.top ) .offset( y: 8 + min(autoCompletionContentHeight, autoCompletionDataSource?.maxHeight ?? 0) / 2 diff --git a/Sources/Montage/1 Components/6 Navigations/TopNavigation.swift b/Sources/Montage/1 Components/6 Navigations/TopNavigation.swift index 3f067e6bb..a527b4c45 100644 --- a/Sources/Montage/1 Components/6 Navigations/TopNavigation.swift +++ b/Sources/Montage/1 Components/6 Navigations/TopNavigation.swift @@ -245,11 +245,12 @@ public struct TopNavigation: View { .ignoresSafeArea(.container, edges: .top) } } + .readsWindowSafeArea($windowSafeAreaInsets) } - + // MARK: - Computed properties - @Environment(\.safeAreaInsets) private var safeAreaInsets: EdgeInsets + @WindowSafeArea private var windowSafeAreaInsets /// ``ScreenScaffold``가 내려 주는 스크롤 오프셋. 스캐폴드 밖에서는 최상단(`0`)이다. @Environment(\.topNavigationScrollOffset) private var inheritedScrollOffset: CGFloat @@ -265,8 +266,8 @@ public struct TopNavigation: View { /// 스크롤하면 배경이 나와야 하므로 그때는 ``ModalNavigation``과 같은 32를 쓴다. private var backgroundOpacity: CGFloat { let threshold: CGFloat - if safeAreaInsets.top > 0 { - threshold = safeAreaInsets.top + if windowSafeAreaInsets.top > 0 { + threshold = windowSafeAreaInsets.top } else if variant.isFloating { threshold = 32 } else { diff --git a/Sources/Montage/1 Components/8 Presentation/BottomSheet.swift b/Sources/Montage/1 Components/8 Presentation/BottomSheet.swift index d2ff88b35..681f4a4f7 100644 --- a/Sources/Montage/1 Components/8 Presentation/BottomSheet.swift +++ b/Sources/Montage/1 Components/8 Presentation/BottomSheet.swift @@ -90,7 +90,8 @@ public struct BottomSheet: View { // MARK: - Body - @Environment(\.safeAreaInsets) private var safeAreaInsets + /// 시트가 놓인 window의 safe area. 받기 전에는 가장 최근에 읽은 window 값이고, 읽은 적이 없으면 `nil`이다. + @State private var windowSafeArea: WindowSafeAreaMetrics? = .lastRead @State private var navigationHeight: CGFloat = 0 @State private var contentHeight: CGFloat = 0 @State private var actionAreaHeight: CGFloat = 0 @@ -163,7 +164,7 @@ public struct BottomSheet: View { } } .environment(\.modalKind, modalKind) - .opacity(isContentMeasured ? 1 : 0) + .opacity(isContentMeasured && windowSafeArea != nil ? 1 : 0) .background( SwiftUI.Color.semantic(.backgroundNeutralPrimary) .opacity(.opacity88) @@ -195,6 +196,7 @@ public struct BottomSheet: View { .onChange(of: contentHeight) { newValue in if newValue > 0 { isContentMeasured = true } } + .onWindowSafeAreaChange { windowSafeArea = $0 } } // MARK: - Modifiers @@ -296,7 +298,9 @@ public struct BottomSheet: View { /// 콘텐츠가 시트 높이를 넘겨 스크롤이 생기는지 여부. private var isContentScrollable: Bool { - bottomSheetContentHeight > bottomSheetMaxHeight || + // window 값을 받기 전에는 최대 높이를 모르므로 분기를 바꾸지 않는다. 분기가 바뀌면 콘텐츠 상태가 초기화된다. + guard windowSafeArea != nil else { return false } + return bottomSheetContentHeight > bottomSheetMaxHeight || (resize.isFlexible && bottomSheetContentHeight > bottomSheetMaxHeight / 2) } @@ -351,10 +355,10 @@ public struct BottomSheet: View { /// detent가 가질 수 있는 최대 높이입니다. /// - /// 기준값은 키 윈도우에서 세이프 에어리어 상하를 제외한 높이라, 시트가 화면 최상단까지 + /// 기준값은 시트가 놓인 window에서 세이프 에어리어 상하를 제외한 높이라, 시트가 화면 최상단까지 /// 올라가지는 않는다. 상태 표시줄·홈 인디케이터 영역만큼 아래에서 시작한다. private var maxDetentHeight: CGFloat { - let safeAreaHeight = UIApplication.keyWindow?.safeAreaSize.height ?? 0 + let safeAreaHeight = windowSafeArea?.size.height ?? 0 if #available(iOS 26, *) { // iOS 26부터는 최대 높이에 도달해도 stacked sheet로 자동 전환되지 않으므로 보정하지 않는다. return safeAreaHeight @@ -395,13 +399,17 @@ public struct BottomSheet: View { } private var detents: Set { + guard let windowSafeArea else { + // window 크기를 받기 전에는 최대 높이를 모르므로 시스템 기본 높이로 둔다. 내용은 아직 가려져 있다. + return [.large] + } guard isContentMeasured else { return [.height(maxDetentHeight)] } switch resize { case .flexible: return [ - .height(min(bottomSheetContentHeight, maxDetentHeight / 2 + safeAreaInsets.bottom)), + .height(min(bottomSheetContentHeight, maxDetentHeight / 2 + windowSafeArea.insets.bottom)), .height(min(bottomSheetContentHeight, maxDetentHeight)) ] default: diff --git a/Sources/Montage/1 Components/9 Utilities/ScreenScaffold.swift b/Sources/Montage/1 Components/9 Utilities/ScreenScaffold.swift index 62f9bdacd..6c7e4f8fe 100644 --- a/Sources/Montage/1 Components/9 Utilities/ScreenScaffold.swift +++ b/Sources/Montage/1 Components/9 Utilities/ScreenScaffold.swift @@ -106,8 +106,6 @@ public struct ScreenScaffold: View { // MARK: - Body - @Environment(\.safeAreaInsets) private var safeAreaInsets: EdgeInsets - /// 스크롤 컨테이너가 preference로 올려 준 값. ``ScrollContainer/builtIn``은 스캐폴드의 /// ``ScrollView``가, ``ScrollContainer/custom``은 콘텐츠가 올린다. @State private var reportedScrollOffset: CGFloat? @@ -198,13 +196,14 @@ private extension ScreenScaffold { /// /// ``ScrollContainer/custom``인데 콘텐츠가 신호를 올리지 않으면 스크롤 위치를 알 수 없다. /// 이때 최상단(`0`)으로 두면 배경이 투명해져 콘텐츠가 내비게이션 글자와 겹치므로, - /// 배경이 완전히 짙어지는 값을 넣어 불투명으로 고정한다. + /// 배경이 완전히 짙어지는 값을 넣어 불투명으로 고정한다. ``TopNavigation``이 불투명도를 0~1로 자르므로 + /// 문턱값(safe area 높이)과 무관하게 불투명해지도록 음의 무한대를 쓴다. var effectiveScrollOffset: CGFloat { switch scrollContainer { case .builtIn: reportedScrollOffset ?? 0 case .custom: - reportedScrollOffset ?? -safeAreaInsets.top + reportedScrollOffset ?? -.infinity } } diff --git a/Sources/Montage/2 Utilities/Extension/SwiftUI/EnvironmentValues+.swift b/Sources/Montage/2 Utilities/Extension/SwiftUI/EnvironmentValues+.swift deleted file mode 100644 index f1dddabc6..000000000 --- a/Sources/Montage/2 Utilities/Extension/SwiftUI/EnvironmentValues+.swift +++ /dev/null @@ -1,20 +0,0 @@ -// -// EnvironmentValues+.swift -// Montage -// -// Created by Ahn Sang Hoon on 7/12/24. -// - -import SwiftUI - -extension EnvironmentValues { - var safeAreaInsets: EdgeInsets { - self[SafeAreaInsetsKey.self] - } -} - -struct SafeAreaInsetsKey: EnvironmentKey { - static var defaultValue: EdgeInsets { - (UIApplication.keyWindow?.safeAreaInsets ?? .zero).insets - } -} diff --git a/Sources/Montage/2 Utilities/Modifiers/WindowSafeAreaModifier.swift b/Sources/Montage/2 Utilities/Modifiers/WindowSafeAreaModifier.swift new file mode 100644 index 000000000..718075f2b --- /dev/null +++ b/Sources/Montage/2 Utilities/Modifiers/WindowSafeAreaModifier.swift @@ -0,0 +1,137 @@ +// +// WindowSafeAreaModifier.swift +// Montage +// +// Created by 김삼열 on 10/28/26. +// Copyright © 2026 WantedLab Inc. All rights reserved. +// + +import SwiftUI +import UIKit + +/// 뷰가 놓인 window의 safe area 인셋과 크기. +public struct WindowSafeAreaMetrics: Equatable { + /// window의 safe area 인셋. + public var insets: EdgeInsets + /// window 크기에서 safe area 인셋을 뺀 크기. + public var size: CGSize + + /// - Parameters: + /// - insets: window의 safe area 인셋 + /// - size: window 크기에서 safe area 인셋을 뺀 크기 + public init(insets: EdgeInsets, size: CGSize) { + self.insets = insets + self.size = size + } + + /// 가장 최근에 읽은 window 값. 값을 받기 전 첫 프레임에 쓴다. + static var lastRead: WindowSafeAreaMetrics? { + WindowSafeAreaReader.lastMetrics + } +} + +/// 뷰가 놓인 window의 safe area 인셋을 담는 상태. +/// +/// body 평가 중에 `UIWindow`의 safe area를 읽으면 AttributeGraph 순환이 생겨 화면 갱신이 멈출 수 있습니다. +/// 이 상태는 ``SwiftUI/View/readsWindowSafeArea(_:)``가 window에 붙은 UIKit 뷰의 콜백에서 읽은 값으로 갱신되므로 +/// 렌더 중에 UIKit을 읽지 않습니다. 회전·창 크기 변경에 다시 갱신되고, 여러 window(멀티씬)에서는 각자 자기 window 값을 받습니다. +/// +/// 값을 받기 전 첫 프레임에는 가장 최근에 읽은 window 값을 씁니다. 앱이 처음 그리는 화면만 0에서 시작합니다. +/// +/// ```swift +/// @WindowSafeArea private var safeAreaInsets +/// +/// var body: some View { +/// content +/// .padding(.bottom, safeAreaInsets.bottom) +/// .readsWindowSafeArea($safeAreaInsets) +/// } +/// ``` +@propertyWrapper +public struct WindowSafeArea: DynamicProperty { + @State private var insets: EdgeInsets + + /// 가장 최근에 읽은 window 값으로 시작합니다. 읽은 적이 없으면 0입니다. + public init() { + _insets = State(initialValue: WindowSafeAreaMetrics.lastRead?.insets ?? EdgeInsets()) + } + + /// window의 safe area 인셋. + public var wrappedValue: EdgeInsets { + get { insets } + nonmutating set { insets = newValue } + } + + /// ``SwiftUI/View/readsWindowSafeArea(_:)``에 넘길 바인딩. + public var projectedValue: Binding { + $insets + } +} + +extension View { + /// 이 뷰가 놓인 window의 safe area 인셋을 ``WindowSafeArea`` 상태에 넣습니다. + /// + /// - Parameter insets: ``WindowSafeArea``의 projected value(`$`) + public func readsWindowSafeArea(_ insets: Binding) -> some View { + onWindowSafeAreaChange { insets.wrappedValue = $0.insets } + } + + /// 이 뷰가 놓인 window의 safe area를 처음 한 번, 그리고 바뀔 때마다 알려 줍니다. + /// + /// 인셋만 필요하면 ``WindowSafeArea``와 ``readsWindowSafeArea(_:)``를 씁니다. 이 modifier는 safe area 크기까지 + /// 필요할 때 씁니다. window에 붙기 전에는 호출되지 않으므로 받기 전에 쓸 값을 정해 둡니다. + /// + /// - Parameter action: 바뀐 safe area를 받는 클로저 + public func onWindowSafeAreaChange(perform action: @escaping (WindowSafeAreaMetrics) -> Void) -> some View { + background(WindowSafeAreaReader(action: action)) + } +} + +private struct WindowSafeAreaReader: UIViewRepresentable { + nonisolated(unsafe) static var lastMetrics: WindowSafeAreaMetrics? + + let action: (WindowSafeAreaMetrics) -> Void + + func makeUIView(context: Context) -> ReaderView { + let view = ReaderView() + view.isUserInteractionEnabled = false + view.action = action + return view + } + + func updateUIView(_ uiView: ReaderView, context: Context) { + uiView.action = action + } + + final class ReaderView: UIView { + var action: ((WindowSafeAreaMetrics) -> Void)? + private var reportedValue: WindowSafeAreaMetrics? + + override func didMoveToWindow() { + super.didMoveToWindow() + reportIfChanged() + } + + override func layoutSubviews() { + super.layoutSubviews() + reportIfChanged() + } + + override func safeAreaInsetsDidChange() { + super.safeAreaInsetsDidChange() + reportIfChanged() + } + + /// 레이아웃 콜백 안에서 SwiftUI 상태를 바로 바꾸지 않도록 다음 런루프에 넘긴다. + private func reportIfChanged() { + guard let window else { return } + let value = WindowSafeAreaMetrics(insets: window.safeAreaInsets.insets, size: window.safeAreaSize) + WindowSafeAreaReader.lastMetrics = value + guard value != reportedValue else { return } + reportedValue = value + DispatchQueue.main.async { [weak self] in + self?.action?(value) + } + } + } +} diff --git a/documentation/utilities/ios-extensions/swiftuicore.md b/documentation/utilities/ios-extensions/swiftuicore.md index 1e997df3c..ca2fa11a7 100644 --- a/documentation/utilities/ios-extensions/swiftuicore.md +++ b/documentation/utilities/ios-extensions/swiftuicore.md @@ -433,6 +433,23 @@ View의 지오메트리 변경정보를 디바운스시켜서 받습니다.
+``func onWindowSafeAreaChange(perform: (WindowSafeAreaMetrics) -> Void) -> some View`` + + +이 뷰가 놓인 window의 safe area를 처음 한 번, 그리고 바뀔 때마다 알려 줍니다. + +- **Parameters** + + | Parameter | Description | + | --- | --- | + | `action` | 바뀐 safe area를 받는 클로저 | + +- **Discussion** + + 인셋만 필요하면 [WindowSafeArea](/documentation/montage/windowsafearea.md)와 [readsWindowSafeArea(_:)](/documentation/montage/swiftuicore/view/readswindowsafearea(_:).md)를 씁니다. 이 modifier는 safe area 크기까지 필요할 때 씁니다. window에 붙기 전에는 호출되지 않으므로 받기 전에 쓸 값을 정해 둡니다. +
+
+ ``func popoverCustom(isPresented: Binding, content: () -> V) -> some View`` @@ -640,6 +657,20 @@ View의 지오메트리 변경정보를 디바운스시켜서 받습니다.
+``func readsWindowSafeArea(Binding) -> some View`` + + +이 뷰가 놓인 window의 safe area 인셋을 [WindowSafeArea](/documentation/montage/windowsafearea.md) 상태에 넣습니다. + +- **Parameters** + + | Parameter | Description | + | --- | --- | + | `insets` | [WindowSafeArea](/documentation/montage/windowsafearea.md)의 projected value(`$`) | + +
+
+ ``func recognizeView(SwiftUI.Color, fill: Bool, drawOnPreviewOnly: Bool) -> some View`` diff --git a/documentation/utilities/modifiers/ios-utility-components/windowsafearea.md b/documentation/utilities/modifiers/ios-utility-components/windowsafearea.md new file mode 100644 index 000000000..37f3475c5 --- /dev/null +++ b/documentation/utilities/modifiers/ios-utility-components/windowsafearea.md @@ -0,0 +1,62 @@ +--- +title: WindowSafeArea +description: 뷰가 놓인 window의 safe area 인셋을 담는 상태. +--- + +```swift +@propertyWrapper struct WindowSafeArea +``` + +## Overview + +Body 평가 중에 `UIWindow`의 safe area를 읽으면 AttributeGraph 순환이 생겨 화면 갱신이 멈출 수 있습니다. 이 상태는 `SwiftUI/View/readsWindowSafeArea(_:)`가 window에 붙은 UIKit 뷰의 콜백에서 읽은 값으로 갱신되므로 렌더 중에 UIKit을 읽지 않습니다. 회전·창 크기 변경에 다시 갱신되고, 여러 window(멀티씬)에서는 각자 자기 window 값을 받습니다. + +값을 받기 전 첫 프레임에는 가장 최근에 읽은 window 값을 씁니다. 앱이 처음 그리는 화면만 0에서 시작합니다. + +```swift +@WindowSafeArea private var safeAreaInsets + +var body: some View { + content + .padding(.bottom, safeAreaInsets.bottom) + .readsWindowSafeArea($safeAreaInsets) +} +``` + +## Topics + +### Initializers + +
+ +``init()`` + + +가장 최근에 읽은 window 값으로 시작합니다. 읽은 적이 없으면 0입니다. +
+ +### Instance Properties + +
+ +``var projectedValue: Binding`` + + +`SwiftUI/View/readsWindowSafeArea(_:)`에 넘길 바인딩. +
+
+ +``var wrappedValue: EdgeInsets`` + + +window의 safe area 인셋. +
+ +## Relationships + +Conforms To + +`SwiftUICore.DynamicProperty` + + + diff --git a/documentation/utilities/modifiers/ios-utility-components/windowsafeareametrics.md b/documentation/utilities/modifiers/ios-utility-components/windowsafeareametrics.md new file mode 100644 index 000000000..205e80a62 --- /dev/null +++ b/documentation/utilities/modifiers/ios-utility-components/windowsafeareametrics.md @@ -0,0 +1,52 @@ +--- +title: WindowSafeAreaMetrics +description: 뷰가 놓인 window의 safe area 인셋과 크기. +--- + +```swift +struct WindowSafeAreaMetrics +``` + +## Topics + +### Initializers + +
+ +``init(insets: EdgeInsets, size: CGSize)`` + + +- **Parameters** + + | Parameter | Description | + | --- | --- | + | `insets` | window의 safe area 인셋 | + | `size` | Window 크기에서 safe area 인셋을 뺀 크기 | + +
+ +### Instance Properties + +
+ +``var insets: EdgeInsets`` + + +window의 safe area 인셋. +
+
+ +``var size: CGSize`` + + +window 크기에서 safe area 인셋을 뺀 크기. +
+ +## Relationships + +Conforms To + +`Swift.Equatable` + + + diff --git a/packages/montage-mcp/data/components.json b/packages/montage-mcp/data/components.json index 4057b220e..98ca646ff 100644 --- a/packages/montage-mcp/data/components.json +++ b/packages/montage-mcp/data/components.json @@ -3944,6 +3944,38 @@ ] } ] + }, + { + "slug": "windowsafearea", + "name": "WindowSafeArea", + "category": "uncategorized", + "kind": "struct", + "declaration": "struct WindowSafeArea", + "summary": "뷰가 놓인 window의 safe area 인셋을 담는 상태.", + "initializers": [ + { + "signature": "init()" + } + ], + "modifiers": [], + "staticMembers": [], + "nestedTypes": [] + }, + { + "slug": "windowsafeareametrics", + "name": "WindowSafeAreaMetrics", + "category": "uncategorized", + "kind": "struct", + "declaration": "struct WindowSafeAreaMetrics", + "summary": "뷰가 놓인 window의 safe area 인셋과 크기.", + "initializers": [ + { + "signature": "init(insets:size:)" + } + ], + "modifiers": [], + "staticMembers": [], + "nestedTypes": [] } ] }