diff --git a/Primuse/Views/Components/AlbumCardView.swift b/Primuse/Views/Components/AlbumCardView.swift index e8050201e..89a50b467 100644 --- a/Primuse/Views/Components/AlbumCardView.swift +++ b/Primuse/Views/Components/AlbumCardView.swift @@ -6,12 +6,19 @@ struct AlbumCardView: View { var showsSongCount = false var isIntelligentRecommendation = false var subtitle: String? = nil + var usesCoverZoomSource = false var body: some View { VStack(alignment: .leading, spacing: 6) { AlbumArtworkView(album: album, cornerRadius: 10) .aspectRatio(1, contentMode: .fit) .searchRecommendationOverlay(isRecommended: isIntelligentRecommendation) + #if os(macOS) + .macFluentCoverSource(id: album.id) + #endif + .if(usesCoverZoomSource) { + $0.mediaZoomSource(.album, id: album.id, shape: .roundedRect(10)) + } VStack(alignment: .leading, spacing: 2) { Text(album.title) diff --git a/Primuse/Views/Components/CollectionCoverWallHeader.swift b/Primuse/Views/Components/CollectionCoverWallHeader.swift index 82fd725c4..6d62a337e 100644 --- a/Primuse/Views/Components/CollectionCoverWallHeader.swift +++ b/Primuse/Views/Components/CollectionCoverWallHeader.swift @@ -93,6 +93,7 @@ struct CollectionCoverWallHeader: View { .mask { LinearGradient(stops: maskStops, startPoint: .top, endPoint: .bottom) } + .if(topInset > 0) { $0.pmHeroOverscrollStretch() } .accessibilityHidden(true) titleBlock diff --git a/Primuse/Views/Components/PMMotion.swift b/Primuse/Views/Components/PMMotion.swift index ec792883f..68196bc34 100644 --- a/Primuse/Views/Components/PMMotion.swift +++ b/Primuse/Views/Components/PMMotion.swift @@ -48,6 +48,10 @@ enum PMMotion: Sendable { case entrance /// 红心点亮时向外散开的那圈光点:从心形飞出、减速、淡掉。 case burst + /// Fluent 钻入详情页:封面沿弧线放大飞入、正文轻度上浮到位。 + case drillIn + /// Fluent 退回总览页:正文先让位、封面逆向缩回原格位,节奏较钻入略干脆。 + case drillOut var animation: Animation { switch self { @@ -57,7 +61,7 @@ enum PMMotion: Sendable { case .pageSwitch: return .easeOut(duration: 0.18) case .contentAppear: return .easeOut(duration: 0.2) case .list: return .snappy(duration: 0.22) - case .panel: return .easeInOut(duration: 0.25) + case .panel: return .spring(duration: 0.28, bounce: 0) case .selection: return .spring(response: 0.3, dampingFraction: 0.86) case .trackChange: return .easeInOut(duration: 0.28) case .ambient: return .easeInOut(duration: 0.5) @@ -67,6 +71,8 @@ enum PMMotion: Sendable { case .trackSwapGentle: return .spring(response: 0.7, dampingFraction: 0.92) case .entrance: return .spring(response: 0.5, dampingFraction: 0.86) case .burst: return .easeOut(duration: 0.62) + case .drillIn: return .timingCurve(0.10, 0.90, 0.20, 1.0, duration: FluentDrillTransitionPolicy.enterDuration) + case .drillOut: return .timingCurve(0.16, 0.88, 0.26, 1.0, duration: FluentDrillTransitionPolicy.exitDuration) } } @@ -77,7 +83,7 @@ enum PMMotion: Sendable { case .control, .pageSwitch: return 0.18 case .contentAppear: return 0.2 case .list: return 0.22 - case .panel: return 0.25 + case .panel: return 0.3 case .selection: return 0.3 case .trackChange: return 0.28 case .ambient: return 0.5 @@ -87,6 +93,8 @@ enum PMMotion: Sendable { case .trackSwapGentle: return 0.75 case .entrance: return 0.55 case .burst: return 0.62 + case .drillIn: return FluentDrillTransitionPolicy.enterDuration + 0.05 + case .drillOut: return FluentDrillTransitionPolicy.exitDuration + 0.04 } } @@ -94,7 +102,7 @@ enum PMMotion: Sendable { var involvesMovement: Bool { switch self { case .press, .list, .panel, .selection, - .pop, .toast, .trackSwap, .trackSwapGentle, .entrance, .burst: + .pop, .toast, .trackSwap, .trackSwapGentle, .entrance, .burst, .drillIn, .drillOut: return true case .hover, .control, .pageSwitch, .contentAppear, .trackChange, .ambient: return false @@ -457,18 +465,19 @@ private struct PMPageEnterModifier: ViewModifier { content .environment(\.pmPageEntering, entering) .opacity(visible ? 1 : 0) - .offset(y: risen ? 0 : 8) + .offset(y: (risen || reduceMotion) ? 0 : 10) .onAppear { - withAnimation(PMMotion.pageSwitch.animation) { visible = true } - if let rise = PMMotion.list.resolved(reduceMotion: reduceMotion) { - withAnimation(rise) { risen = true } - } else { + let anim: Animation = reduceMotion + ? .easeOut(duration: 0.16) + : .timingCurve(0.12, 0.90, 0.24, 1.0, duration: 0.22) + withAnimation(anim) { + visible = true risen = true } } .task { // 入场的时长之后, 再出现的内容各自淡入。 - try? await Task.sleep(for: .milliseconds(260)) + try? await Task.sleep(for: .milliseconds(240)) entering = false } } @@ -773,3 +782,31 @@ extension View { } } #endif + +#if os(iOS) +extension View { + /// 详情页顶部全铺封面在下拉过卷时随阻力弹性拉伸,顶边贴齐屏顶不露缝(120Hz 纯图层变换)。 + func pmHeroOverscrollStretch() -> some View { + modifier(PMHeroOverscrollStretchModifier()) + } +} + +private struct PMHeroOverscrollStretchModifier: ViewModifier { + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + func body(content: Content) -> some View { + let reduceMotion = reduceMotion + content.visualEffect { view, proxy in + let minY = proxy.frame(in: .scrollView(axis: .vertical)).minY + let frame = FluentDrillTransitionPolicy.heroOverscrollFrame( + pullOffset: Double(minY), + heroHeight: Double(proxy.size.height), + reduceMotion: reduceMotion + ) + return view + .scaleEffect(frame.scale, anchor: .top) + .offset(y: frame.offsetY) + } + } +} +#endif diff --git a/Primuse/Views/Components/SongRowView.swift b/Primuse/Views/Components/SongRowView.swift index 984d66066..90b4e6b59 100644 --- a/Primuse/Views/Components/SongRowView.swift +++ b/Primuse/Views/Components/SongRowView.swift @@ -1753,7 +1753,7 @@ private extension View { /// 正在播那一行的波形。单独一个视图:播放、暂停只重画这一个图标;只有正在播的那一行会建它, /// 别的行不观察播放状态。播放时律动,暂停时停在完整的静止波形。 -private struct SongRowPlayingWaveform: View { +struct SongRowPlayingWaveform: View { @Environment(AudioPlayerService.self) private var player let tint: Color diff --git a/Primuse/Views/ContentView.swift b/Primuse/Views/ContentView.swift index 6835966f8..d77a8c8a8 100644 --- a/Primuse/Views/ContentView.swift +++ b/Primuse/Views/ContentView.swift @@ -395,19 +395,29 @@ extension EnvironmentValues { // MARK: - 详情页 zoom 展开 -/// 列表卡片与详情页之间的转场标识。专辑 / 艺术家 / 歌单共用一层导航栈的 -/// 命名空间,靠 kind 区分,免得不同类型撞上同一个 ID 时互相匹配。 +/// 列表卡片与详情页之间的转场标识。专辑 / 艺术家 / 歌单 / 流派 / 智能歌单 / 有声书共用一层 +/// 导航栈的命名空间,靠 kind 区分,免得不同类型撞上同一个 ID 时互相匹配。 struct MediaZoomTransitionID: Hashable { enum Kind: String { case album case artist case playlist + case genre + case smartPlaylist + case spokenWordBook } let kind: Kind let id: String } +/// 列表页缩放转场源的裁剪形状:纯封面或圆形头像直接按自身形状飞出与缩回,避免拉扯标题文字。 +enum MediaZoomSourceShape: Equatable { + case automatic + case roundedRect(CGFloat) + case circle +} + /// 用可选值:绝大多数视图不在这套转场里,取不到命名空间时两个修饰符都原样 /// 返回内容,页面照常 push,只是没有放大动画。 private struct MediaZoomNamespaceEnvironmentKey: EnvironmentKey { @@ -423,6 +433,7 @@ extension EnvironmentValues { private struct MediaZoomSourceModifier: ViewModifier { let transitionID: MediaZoomTransitionID + let shape: MediaZoomSourceShape @Environment(\.mediaZoomNamespace) private var namespace @Environment(\.accessibilityReduceMotion) private var reduceMotion @@ -430,10 +441,18 @@ private struct MediaZoomSourceModifier: ViewModifier { func body(content: Content) -> some View { #if os(iOS) if let namespace, !reduceMotion { - // 不自定义裁剪形状:卡片是"封面 + 标题"的组合,拿一个矩形去裁本来 - // 就对不上,而圆形头像想要的超大圆角会让 continuous 圆角路径退化, - // 整张卡片被裁成空白。交给系统按视图自身形状取转场源。 - content.matchedTransitionSource(id: transitionID, in: namespace) + switch shape { + case .automatic: + content.matchedTransitionSource(id: transitionID, in: namespace) + case .roundedRect(let radius): + content.matchedTransitionSource(id: transitionID, in: namespace) { source in + source.clipShape(RoundedRectangle(cornerRadius: radius, style: .continuous)) + } + case .circle: + content.matchedTransitionSource(id: transitionID, in: namespace) { source in + source.clipShape(RoundedRectangle(cornerRadius: 999, style: .circular)) + } + } } else { content } @@ -468,11 +487,16 @@ extension View { environment(\.mediaZoomNamespace, namespace) } - /// 挂在列表卡片上:详情页从这张卡片放大出来,返回时缩回原位。 - func mediaZoomSource(_ kind: MediaZoomTransitionID.Kind, id: String) -> some View { + /// 挂在列表卡片或封面容器上:详情页从源形状放大出来,返回时缩回原位。 + func mediaZoomSource( + _ kind: MediaZoomTransitionID.Kind, + id: String, + shape: MediaZoomSourceShape = .automatic + ) -> some View { modifier( MediaZoomSourceModifier( - transitionID: MediaZoomTransitionID(kind: kind, id: id) + transitionID: MediaZoomTransitionID(kind: kind, id: id), + shape: shape ) ) } diff --git a/Primuse/Views/Home/HomeForYouSection.swift b/Primuse/Views/Home/HomeForYouSection.swift index 4391ba6c3..38390567f 100644 --- a/Primuse/Views/Home/HomeForYouSection.swift +++ b/Primuse/Views/Home/HomeForYouSection.swift @@ -989,7 +989,7 @@ struct MacHomeForYouSection: View { ) return HStack(spacing: 12) { MacHomeDetailLink(album: album) { - AlbumArtworkView(album: album, size: 78, cornerRadius: PMRadius.m) + AlbumArtworkView(album: album, size: 78, cornerRadius: PMRadius.m).macFluentCoverSource(id: album.id) } .pmScrollingHelp(Text("go_to_album")) diff --git a/Primuse/Views/Home/HomeHeroRecommendations.swift b/Primuse/Views/Home/HomeHeroRecommendations.swift index cfd943c9a..1f618d6ba 100644 --- a/Primuse/Views/Home/HomeHeroRecommendations.swift +++ b/Primuse/Views/Home/HomeHeroRecommendations.swift @@ -935,9 +935,8 @@ struct HomeHeroRecommendationDetail: View { if content == .albums, !model.albums.isEmpty { LazyVGrid(columns: [GridItem(.adaptive(minimum: 145), spacing: 16)], spacing: 20) { ForEach(model.albums) { album in - NavigationLink(value: album) { AlbumCardView(album: album, showsSongCount: true) } + NavigationLink(value: album) { AlbumCardView(album: album, showsSongCount: true, usesCoverZoomSource: true) } .buttonStyle(.plain) - .mediaZoomSource(.album, id: album.id) .accessibilityIdentifier("home.hero.recommendation.albumDetail.\(album.id)") } } diff --git a/Primuse/Views/Home/HomeView.swift b/Primuse/Views/Home/HomeView.swift index 018754732..8aecd2b78 100644 --- a/Primuse/Views/Home/HomeView.swift +++ b/Primuse/Views/Home/HomeView.swift @@ -134,10 +134,9 @@ private struct RecentlyAddedAlbumsView: View { // 走首页导航栈上的 Album 目的地,和资料库的专辑网格一样从卡片放大展开。 ForEach(filteredAlbums) { album in NavigationLink(value: album) { - AlbumCardView(album: album, showsSongCount: true) + AlbumCardView(album: album, showsSongCount: true, usesCoverZoomSource: true) } .buttonStyle(.pmPressable) - .mediaZoomSource(.album, id: album.id) .contextMenu { Toggle("home_show_preview_albums", isOn: $showsExternalAlbums) } } } @@ -2197,6 +2196,7 @@ struct HomeView: View { } .navigationDestination(for: SmartPlaylist.self) { SmartPlaylistDetailView(smartPlaylistID: $0.id) + .mediaZoomDestination(.smartPlaylist, id: $0.id) } .navigationDestination(for: HomeLibraryPage.self) { page in switch page { @@ -5555,11 +5555,10 @@ struct HomeView: View { LazyHGrid(rows: carouselRows(.recentlyAdded, height: Self.coverCardHeight(width: cardWidth), itemCount: shownAlbums.count), spacing: 14) { ForEach(shownAlbums) { tile in NavigationLink(value: HomeLibraryPage.recentAlbum(tile.id)) { - AlbumCardView(album: tile.album, showsSongCount: true) + AlbumCardView(album: tile.album, showsSongCount: true, usesCoverZoomSource: true) .frame(width: cardWidth) } .buttonStyle(.pmPressable) - .mediaZoomSource(.album, id: tile.album.id) .contextMenu { Toggle("home_show_preview_albums", isOn: $showsExternalAlbums) } } } @@ -5587,10 +5586,9 @@ struct HomeView: View { LazyVGrid(columns: recentlyAddedGridColumns, spacing: 20) { ForEach(albums.prefix(sectionItemCount(.recentlyAdded, usesPadMetrics ? 12 : 6))) { tile in NavigationLink(value: HomeLibraryPage.recentAlbum(tile.id)) { - AlbumCardView(album: tile.album, showsSongCount: true) + AlbumCardView(album: tile.album, showsSongCount: true, usesCoverZoomSource: true) } .buttonStyle(.pmPressable) - .mediaZoomSource(.album, id: tile.album.id) .contextMenu { Toggle("home_show_preview_albums", isOn: $showsExternalAlbums) } } } diff --git a/Primuse/Views/Library/AlbumDetailView.swift b/Primuse/Views/Library/AlbumDetailView.swift index c34151604..de0b330c7 100644 --- a/Primuse/Views/Library/AlbumDetailView.swift +++ b/Primuse/Views/Library/AlbumDetailView.swift @@ -626,6 +626,7 @@ struct AlbumDetailView: View { .allowsHitTesting(false) .accessibilityHidden(true) } + .pmHeroOverscrollStretch() VStack(spacing: 18) { heroIdentityText(centered: true) @@ -1021,7 +1022,7 @@ struct AlbumDetailView: View { } } .padding(.horizontal, PMSpace.xxxl) - .padding(.top, PMSpace.l) + .padding(.top, PMSpace.l).macFluentContinuumContent() } .padding(.bottom, 112) } @@ -1425,9 +1426,7 @@ struct AlbumDetailView: View { HStack(spacing: PMSpace.s10) { ZStack { if isCurrent { - Image(systemName: "play.fill") - .font(.system(size: 11, weight: .semibold)) - .foregroundStyle(PMColor.brand) + SongRowPlayingWaveform(tint: PMColor.brand) .pmFadeTransition() } else if showsRowNumbers { Text(verbatim: trackNumber.formatted(.number.locale(locale))) @@ -1594,6 +1593,7 @@ private struct AlbumHeroActionRow: View { PMHaptics.likeToggled(isLiked: !favorite.isLiked) favorite.toggle() } + .pmLikeBurst(isLiked: favorite.isLiked, tint: .red) .accessibilityAddTraits(favorite.isLiked ? .isSelected : []) .accessibilityIdentifier("libraryDetail.favorite") } diff --git a/Primuse/Views/Library/AlbumGridView.swift b/Primuse/Views/Library/AlbumGridView.swift index e117b212b..a7fe5bac6 100644 --- a/Primuse/Views/Library/AlbumGridView.swift +++ b/Primuse/Views/Library/AlbumGridView.swift @@ -210,12 +210,6 @@ struct AlbumGridView: View { } else { #if os(macOS) macGrid - .onReceive(NotificationCenter.default.publisher(for: .primuseDetailOpenAlbum)) { note in - guard let album = note.object as? Album, - library.visibleAlbum(id: album.id) != nil else { return } - albumFilter = "" - openAlbum(album) - } .task(id: offlineFilterTaskKey) { await refreshOfflineAlbumIDs() } @@ -390,20 +384,21 @@ struct AlbumGridView: View { private func albumCell(_ album: Album) -> some View { NavigationLink(value: album) { - AlbumCardView(album: album) + AlbumCardView(album: album, usesCoverZoomSource: true) } .buttonStyle(.pmPressable) .contextMenu { albumMenu(album) } .accessibilityAction(named: Text(favorites.isLiked(album) ? "library_favorite_unlike" : "library_favorite_like")) { favorites.toggle(album) } - .mediaZoomSource(.album, id: album.id) } #endif #if os(macOS) + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @Environment(\.macFluentAlbumDrill) private var fluentDrill @State private var albumViewMode: AlbumViewMode = .grid - @State private var selectedAlbumID: String? + @Namespace private var viewModeNamespace private enum AlbumViewMode: String, CaseIterable, Hashable { case grid, list @@ -420,36 +415,13 @@ struct AlbumGridView: View { } } - /// 设计稿 LIB-02: 不再用带大封面的 hero header (那是全部歌曲/歌单的样式), - /// 而是左上角专辑标题 + 右上排序, 下面五列封面网格。 - @ViewBuilder - private var macGrid: some View { - ZStack { - // Keep the overview mounted: replacing its branch destroys the - // scroll view and returns both grid and list modes to the top. - macAlbumOverview - .opacity(selectedAlbum == nil ? 1 : 0) - .disabled(selectedAlbum != nil) - .allowsHitTesting(selectedAlbum == nil) - .accessibilityHidden(selectedAlbum != nil) - - if let selectedAlbum { - AlbumDetailView( - album: selectedAlbum, - onMacInlineBack: closeAlbum - ) - // 淡入挂在 .id 里面: 换一张专辑时身份跟着重建, 修饰符的状态才会跟着重置。 - .pmAppearFade() - .id(selectedAlbum.id) - .pmFadeTransition() - .zIndex(1) - } - } + private var activeSourceCornerRadius: Double { + albumViewMode == .grid ? Double(PMRadius.m) : 6 } - private var selectedAlbum: Album? { - guard let selectedAlbumID else { return nil } - return library.visibleAlbum(id: selectedAlbumID) + /// 设计稿 LIB-02: 左上角专辑标题 + 右上排序,下面封面网格。 + private var macGrid: some View { + macAlbumOverview } private var macAlbumOverview: some View { @@ -531,13 +503,13 @@ struct AlbumGridView: View { } private func macAlbumGridButton(_ album: Album, artworkSize: CGFloat) -> some View { - PMScrollingButton { + PMScrollingButton(style: .pressable) { openAlbum(album) } label: { macAlbumTile(album, artworkSize: artworkSize) } .contextMenu { albumMenu(album) } - .pmHoverLift() + .pmHoverLift(scale: 1.022) } private func macAlbumListButton(_ album: Album) -> some View { @@ -592,14 +564,15 @@ struct AlbumGridView: View { } private func openAlbum(_ album: Album) { - pmWithAnimation(.list) { - selectedAlbumID = album.id - } - } - - private func closeAlbum() { - pmWithAnimation(.list) { - selectedAlbumID = nil + if let fluentDrill { + fluentDrill.open( + album, + sourceCornerRadius: activeSourceCornerRadius, + reduceMotion: reduceMotion, + library: library + ) + } else { + NotificationCenter.default.post(name: .primuseDetailOpenAlbum, object: album) } } @@ -648,10 +621,10 @@ struct AlbumGridView: View { HStack(spacing: 2) { ForEach(AlbumViewMode.allCases, id: \.self) { mode in Button { - albumViewMode = mode + pmWithAnimation(.selection) { albumViewMode = mode } } label: { Image(systemName: mode.icon) - .macSegment(selected: albumViewMode == mode, iconOnly: true) + .macSegment(selected: albumViewMode == mode, iconOnly: true, namespace: viewModeNamespace) } .buttonStyle(.plain) .help(Text(mode.label)) @@ -723,7 +696,8 @@ struct AlbumGridView: View { private func macAlbumTile(_ album: Album, artworkSize: CGFloat) -> some View { return VStack(alignment: .leading, spacing: 0) { AlbumArtworkView(album: album, size: artworkSize, cornerRadius: PMRadius.m) - .shadow(color: .black.opacity(0.22), radius: 8, y: 4) + .shadow(color: .black.opacity(0.22), radius: 8, y: 4) + .macFluentCoverSource(id: album.id) Text(album.title) .font(.system(size: 12.5, weight: .semibold)) @@ -752,6 +726,7 @@ struct AlbumGridView: View { private func macAlbumListRow(_ album: Album) -> some View { return HStack(spacing: 12) { AlbumArtworkView(album: album, size: 44, cornerRadius: 6) + .macFluentCoverSource(id: album.id) VStack(alignment: .leading, spacing: 2) { Text(album.title) .font(.system(size: 12.5, weight: .semibold)) diff --git a/Primuse/Views/Library/ArtistDetailView.swift b/Primuse/Views/Library/ArtistDetailView.swift index 70852a996..672b961aa 100644 --- a/Primuse/Views/Library/ArtistDetailView.swift +++ b/Primuse/Views/Library/ArtistDetailView.swift @@ -613,6 +613,7 @@ struct ArtistDetailView: View { } .accessibilityHidden(true) } + .pmHeroOverscrollStretch() ArtistHeroTitleBlock( name: displayArtistName, @@ -978,11 +979,10 @@ struct ArtistDetailView: View { spacing: 22 ) { ForEach(albums) { album in - NavigationLink(value: album) { + MacFluentAlbumLink(album: album, cornerRadius: Double(PMRadius.s)) { macAlbumTile(album, showsPlayCount: showsPlayCount) } - .buttonStyle(.plain) - .pmHoverLift() + .pmHoverLift(scale: 1.022) .contextMenu { AlbumReleaseCategoryMenu(album: album) } } } @@ -1143,6 +1143,7 @@ struct ArtistDetailView: View { AlbumArtworkView(album: album, cornerRadius: PMRadius.s) .aspectRatio(1, contentMode: .fit) .shadow(color: .black.opacity(0.20), radius: 8, y: 4) + .macFluentCoverSource(id: album.id) Text(verbatim: album.title) .font(.system(size: 12.5, weight: .semibold)) @@ -1329,9 +1330,8 @@ struct ArtistAlbumsGrid: View { var body: some View { LazyVGrid(columns: [GridItem(.adaptive(minimum: dynamicTypeSize.isAccessibilitySize ? 240 : 104), spacing: 10)], spacing: 14) { ForEach(albums) { album in - NavigationLink(value: album) { AlbumCardView(album: album, subtitle: Self.subtitle(for: album)) } + NavigationLink(value: album) { AlbumCardView(album: album, subtitle: Self.subtitle(for: album), usesCoverZoomSource: true) } .buttonStyle(.pmPressable) - .mediaZoomSource(.album, id: album.id) .accessibilityIdentifier("artist.album.\(album.id)") .contextMenu { AlbumReleaseCategoryMenu(album: album) diff --git a/Primuse/Views/Library/ArtistListView.swift b/Primuse/Views/Library/ArtistListView.swift index 32595e97f..6db8e8db6 100644 --- a/Primuse/Views/Library/ArtistListView.swift +++ b/Primuse/Views/Library/ArtistListView.swift @@ -522,7 +522,6 @@ struct ArtistListView: View { .accessibilityAction(named: Text(favorites.isLiked(artist) ? "library_favorite_unlike" : "library_favorite_like")) { favorites.toggle(artistNamed: artist.name) } - .mediaZoomSource(.artist, id: artist.id) } private func artistGridCell(_ artist: Artist) -> some View { @@ -534,6 +533,7 @@ struct ArtistListView: View { Circle().strokeBorder(Color.primary.opacity(0.06), lineWidth: 0.5) } .searchRecommendationOverlay(isRecommended: intelligentRecommendationIDs.contains(artist.id), iconOnly: true) + .mediaZoomSource(.artist, id: artist.id, shape: .circle) Text(displayName(for: artist)) .font(.subheadline.weight(.medium)) @@ -589,6 +589,7 @@ struct ArtistListView: View { cornerRadius: 22 ) .searchRecommendationOverlay(isRecommended: intelligentRecommendationIDs.contains(artist.id), iconOnly: true, inset: 3) + .mediaZoomSource(.artist, id: artist.id, shape: .circle) VStack(alignment: .leading, spacing: 2) { Text(displayName(for: artist)) @@ -624,7 +625,6 @@ struct ArtistListView: View { .accessibilityAction(named: Text(favorites.isLiked(artist) ? "library_favorite_unlike" : "library_favorite_like")) { favorites.toggle(artistNamed: artist.name) } - .mediaZoomSource(.artist, id: artist.id) } #endif @@ -708,7 +708,7 @@ struct ArtistListView: View { // 只在重建后淡入: 详情页一次 body 要过滤整库专辑, // 不能把它拉进交叉淡入的事务里。 ArtistDetailView(artist: artist) - .pmAppearFade() + .pmPageEnter() .id(artist.id) } else if !showsCatalogArtistList && (!library.isReady || macCatalogKey != nil || library.catalogHost != nil) { ProgressView() diff --git a/Primuse/Views/Library/GenreLibraryView.swift b/Primuse/Views/Library/GenreLibraryView.swift index 37465f3be..3c4c50af3 100644 --- a/Primuse/Views/Library/GenreLibraryView.swift +++ b/Primuse/Views/Library/GenreLibraryView.swift @@ -56,6 +56,7 @@ struct GenreLibraryView: View { iosBody .navigationDestination(for: LibraryGenre.self) { genre in GenreDetailView(genre: genre) + .mediaZoomDestination(.genre, id: genre.id) } } #endif @@ -99,6 +100,7 @@ struct GenreLibraryView: View { ForEach(genres) { genre in NavigationLink(value: genre) { LibraryGenreCard(genre: genre, height: cardHeight) + .mediaZoomSource(.genre, id: genre.id, shape: .roundedRect(18)) } .buttonStyle(.pmPressable) } @@ -212,7 +214,7 @@ struct GenreLibraryView: View { if let selectedGenre { // 淡入挂在 .id 里面: 换流派时身份重建, 修饰符的状态才会跟着重置。 GenreDetailView(genre: selectedGenre) - .pmAppearFade() + .pmPageEnter() .id(selectedGenre.id) .frame(maxWidth: .infinity, maxHeight: .infinity) } else { @@ -759,11 +761,17 @@ struct GenreDetailView: View { ScrollView(.horizontal, showsIndicators: false) { LazyHStack(alignment: .top, spacing: 14) { ForEach(albums) { album in - NavigationLink(value: album) { + #if os(macOS) + MacFluentAlbumLink(album: album, cornerRadius: 10) { AlbumCardView(album: album).frame(width: 142) } + .pmHoverLift(scale: 1.022) + #else + NavigationLink(value: album) { + AlbumCardView(album: album, usesCoverZoomSource: true).frame(width: 142) + } .buttonStyle(.plain) - .mediaZoomSource(.album, id: album.id) + #endif } } .padding(.horizontal, sectionInset) diff --git a/Primuse/Views/Library/LibraryView.swift b/Primuse/Views/Library/LibraryView.swift index 93e90b3a2..452dd0135 100644 --- a/Primuse/Views/Library/LibraryView.swift +++ b/Primuse/Views/Library/LibraryView.swift @@ -959,10 +959,10 @@ struct LibraryView: View { // `libraryStackRegistersCollectionDetails`)。登记在分类页里面时,极简模式下点流派 // 卡片没有反应,经典模式下能进;专辑、艺人、歌单一直登记在这里,两种模式都正常。 .navigationDestination(for: LibraryGenre.self) { genre in - GenreDetailView(genre: genre) + GenreDetailView(genre: genre).mediaZoomDestination(.genre, id: genre.id) } .navigationDestination(for: SmartPlaylist.self) { smart in - SmartPlaylistDetailView(smartPlaylistID: smart.id) + SmartPlaylistDetailView(smartPlaylistID: smart.id).mediaZoomDestination(.smartPlaylist, id: smart.id) } .onAppear { if deepLink == nil, rootSection == nil { diff --git a/Primuse/Views/Library/PlaylistListView.swift b/Primuse/Views/Library/PlaylistListView.swift index 6a264424e..2ab1d35c3 100644 --- a/Primuse/Views/Library/PlaylistListView.swift +++ b/Primuse/Views/Library/PlaylistListView.swift @@ -420,7 +420,7 @@ struct PlaylistListView: View { } private func smartPlaylistLink(_ smart: SmartPlaylist) -> some View { - NavigationLink(value: smart) { smartPlaylistRow(smart) } + NavigationLink(value: smart) { smartPlaylistRow(smart) }.mediaZoomSource(.smartPlaylist, id: smart.id) .disabled(isOrderingPlaylists) .swipeActions(edge: .trailing, allowsFullSwipe: false) { if !isOrderingPlaylists { @@ -1707,7 +1707,7 @@ private struct SmartPlaylistDestinationModifier: ViewModifier { content } else { content.navigationDestination(for: SmartPlaylist.self) { smart in - SmartPlaylistDetailView(smartPlaylistID: smart.id) + SmartPlaylistDetailView(smartPlaylistID: smart.id).mediaZoomDestination(.smartPlaylist, id: smart.id) } } } diff --git a/Primuse/Views/Library/ReleaseDateLibraryView+Catalog.swift b/Primuse/Views/Library/ReleaseDateLibraryView+Catalog.swift index 5a994ab6f..f56396a3e 100644 --- a/Primuse/Views/Library/ReleaseDateLibraryView+Catalog.swift +++ b/Primuse/Views/Library/ReleaseDateLibraryView+Catalog.swift @@ -286,18 +286,16 @@ struct ReleaseDateCatalogPage: View { private func albumCell(_ album: Album) -> some View { #if os(iOS) NavigationLink(value: album) { - AlbumCardView(album: album) + AlbumCardView(album: album, usesCoverZoomSource: true) } .buttonStyle(.pmPressable) .contextMenu { albumMenu(album) } - .mediaZoomSource(.album, id: album.id) #else - NavigationLink(value: album) { + MacFluentAlbumLink(album: album, cornerRadius: 10) { AlbumCardView(album: album) } - .buttonStyle(.plain) .contextMenu { albumMenu(album) } - .pmHoverLift() + .pmHoverLift(scale: 1.022) #endif } diff --git a/Primuse/Views/Library/ReleaseDateLibraryView.swift b/Primuse/Views/Library/ReleaseDateLibraryView.swift index 087ad01f2..e6f4b9e11 100644 --- a/Primuse/Views/Library/ReleaseDateLibraryView.swift +++ b/Primuse/Views/Library/ReleaseDateLibraryView.swift @@ -196,18 +196,16 @@ struct ReleaseDateLibraryView: View { private func albumCell(_ album: Album) -> some View { #if os(iOS) NavigationLink(value: album) { - AlbumCardView(album: album) + AlbumCardView(album: album, usesCoverZoomSource: true) } .buttonStyle(.pmPressable) .contextMenu { albumMenu(album) } - .mediaZoomSource(.album, id: album.id) #else - NavigationLink(value: album) { + MacFluentAlbumLink(album: album, cornerRadius: 10) { AlbumCardView(album: album) } - .buttonStyle(.plain) .contextMenu { albumMenu(album) } - .pmHoverLift() + .pmHoverLift(scale: 1.022) #endif } diff --git a/Primuse/Views/Library/SpokenWordLibraryView.swift b/Primuse/Views/Library/SpokenWordLibraryView.swift index 5d5ee2374..6c117fb23 100644 --- a/Primuse/Views/Library/SpokenWordLibraryView.swift +++ b/Primuse/Views/Library/SpokenWordLibraryView.swift @@ -1434,9 +1434,9 @@ struct SpokenWordBookLink: View { NavigationLink(value: MacSpokenWordBookDestination(bookID: bookID), label: label) #else NavigationLink { - SpokenWordBookDetailView(bookID: bookID) + SpokenWordBookDetailView(bookID: bookID).mediaZoomDestination(.spokenWordBook, id: bookID) } label: { - label() + label().mediaZoomSource(.spokenWordBook, id: bookID) } #endif } diff --git a/Primuse/Views/Mac/MacContentView.swift b/Primuse/Views/Mac/MacContentView.swift index 7d30a3445..845cc30d0 100644 --- a/Primuse/Views/Mac/MacContentView.swift +++ b/Primuse/Views/Mac/MacContentView.swift @@ -577,11 +577,11 @@ struct MacContentView: View { } .onReceive(NotificationCenter.default.publisher(for: .primuseDetailOpenAlbum)) { note in guard note.object is Album else { return } - nowPlayingPresented = false + pmWithAnimation(.panel) { nowPlayingPresented = false } } .onReceive(NotificationCenter.default.publisher(for: .primuseDetailOpenArtist)) { note in guard note.object is Artist else { return } - nowPlayingPresented = false + pmWithAnimation(.panel) { nowPlayingPresented = false } } // 在 Spotlight 里点开的一项:歌直接放,专辑、艺人、歌单打开详情;「在 Primuse 中搜索」带着字进搜索页。 // 收到的时候记在路由上(见 `MacSystemActivityRouter`),主界面这时一定已经挂上。 diff --git a/Primuse/Views/Mac/MacDetailContainer.swift b/Primuse/Views/Mac/MacDetailContainer.swift index 8887f67dc..98740b5f6 100644 --- a/Primuse/Views/Mac/MacDetailContainer.swift +++ b/Primuse/Views/Mac/MacDetailContainer.swift @@ -1,4 +1,5 @@ #if os(macOS) +import AppKit import SwiftUI import PrimuseKit @@ -17,101 +18,123 @@ struct MacDetailContainer: View { var onOpenSources: (() -> Void)? = nil @Environment(MusicLibrary.self) private var library @Environment(SourcesStore.self) private var sourcesStore + @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var path = NavigationPath() + @State private var albumDrill = MacFluentAlbumDrillCoordinator() + @State private var isPoppingDetail = false + @State private var rootRevealToken = 0 + @State private var popTask: Task? var body: some View { - NavigationStack(path: $path) { - content - // 这一项还读整库数组时:歌曲模型不在内存里就显示加载、替它占用模型(6c 单元 4 U2b)。 - .macLibraryPage(route.pageKind) - #if DEBUG - .onAppear { - MacRouteTiming.mark("appear") - } - #endif - .navigationBarBackButtonHidden(true) - .transaction { transaction in - transaction.animation = nil - } - // push/pop 本身仍然是无动画的(见 pushAlbum/pushArtist), 详情页 - // 自己淡入一下, 免得点进去像换了张截图。 - .navigationDestination(for: Album.self) { album in - AlbumDetailView(album: album, onMacInlineBack: popDetail) - .macLibraryPage(.albumDetail) - .navigationBarBackButtonHidden(true) - .pmAppearFade() - } - .navigationDestination(for: Artist.self) { artist in - ArtistDetailView(artist: artist, onMacInlineBack: popDetail) - .macLibraryPage(.artistDetail) - .navigationBarBackButtonHidden(true) - .pmAppearFade() - } - .navigationDestination(for: Playlist.self) { playlist in - PlaylistDetailView(playlist: playlist, onMacInlineBack: popDetail) - .macLibraryPage(.playlistDetail) - .navigationBarBackButtonHidden(true) - .pmAppearFade() - } - .navigationDestination(for: MacSearchCollectionDestination.self) { destination in - SearchCollectionDetailView(result: destination.result, onMacInlineBack: popDetail) - .macLibraryPage(.searchCollection) - .navigationBarBackButtonHidden(true) - .pmAppearFade() - } - .navigationDestination(for: AppleMusicCatalogArtistHit.self) { artist in - AppleMusicCatalogArtistView(artist: artist, onMacInlineBack: popDetail) - .macLibraryPage(.appleMusicArtist) - .navigationBarBackButtonHidden(true) - .pmAppearFade() - } - .navigationDestination(for: MacSpokenWordBookDestination.self) { destination in - SpokenWordBookDetailView(bookID: destination.bookID, onMacInlineBack: popDetail) - .macLibraryPage(.spokenWordBook) - .navigationBarBackButtonHidden(true) - .pmAppearFade() - } - .navigationDestination(for: SmartPlaylist.self) { smart in - SmartPlaylistDetailView( - smartPlaylistID: smart.id, - onMacInlineBack: popDetail - ) - .macLibraryPage(.smartPlaylistDetail) + MacFluentAlbumDrillHost( + coordinator: albumDrill, + onEscapeBack: closeFluentAlbum + ) { + NavigationStack(path: $path) { + content + // 这一项还读整库数组时:歌曲模型不在内存里就显示加载、替它占用模型(6c 单元 4 U2b)。 + .macLibraryPage(route.pageKind) + .modifier(MacFluentRootRevealModifier(trigger: rootRevealToken)) + #if DEBUG + .onAppear { + MacRouteTiming.mark("appear") + } + #endif .navigationBarBackButtonHidden(true) - .pmAppearFade() - } + // 压栈与退栈统一走 Fluent 钻取过渡,不再对整棵 content 子树抹除事务动画。 + .navigationDestination(for: Album.self) { album in + fluentStackDestination { + AlbumDetailView(album: album, onMacInlineBack: popDetail) + .macLibraryPage(.albumDetail) + } + } + .navigationDestination(for: Artist.self) { artist in + fluentStackDestination { + ArtistDetailView(artist: artist, onMacInlineBack: popDetail) + .macLibraryPage(.artistDetail) + } + } + .navigationDestination(for: Playlist.self) { playlist in + fluentStackDestination { + PlaylistDetailView(playlist: playlist, onMacInlineBack: popDetail) + .macLibraryPage(.playlistDetail) + } + } + .navigationDestination(for: MacSearchCollectionDestination.self) { destination in + fluentStackDestination { + SearchCollectionDetailView(result: destination.result, onMacInlineBack: popDetail) + .macLibraryPage(.searchCollection) + } + } + .navigationDestination(for: AppleMusicCatalogArtistHit.self) { artist in + fluentStackDestination { + AppleMusicCatalogArtistView(artist: artist, onMacInlineBack: popDetail) + .macLibraryPage(.appleMusicArtist) + } + } + .navigationDestination(for: MacSpokenWordBookDestination.self) { destination in + fluentStackDestination { + SpokenWordBookDetailView(bookID: destination.bookID, onMacInlineBack: popDetail) + .macLibraryPage(.spokenWordBook) + } + } + .navigationDestination(for: SmartPlaylist.self) { smart in + fluentStackDestination { + SmartPlaylistDetailView( + smartPlaylistID: smart.id, + onMacInlineBack: popDetail + ) + .macLibraryPage(.smartPlaylistDetail) + } + } + } + .environment(\.macFluentAlbumDrill, albumDrill) + } detail: { album in + AlbumDetailView(album: album, onMacInlineBack: closeFluentAlbum) + .macLibraryPage(.albumDetail) } .environment(\.macFolderShowInLibrary) { song in onShowSongInLibrary(song) } .onAppear { consumeSpokenWordBookRequest() } + .onDisappear { + popTask?.cancel() + albumDrill.cancelTasks() + } .onChange(of: spokenWordBookRequest) { _, _ in consumeSpokenWordBookRequest() } + .onChange(of: library.visibleSongCollectionRevision) { _, _ in + guard let id = albumDrill.activeAlbum?.id else { return } + albumDrill.syncResolvedAlbum(library.visibleAlbum(id: id)) + } .onReceive(NotificationCenter.default.publisher(for: .primuseRevealSearchResults)) { _ in // 标题栏里接着搜: 从结果点进去的专辑 / 艺人 / 歌单还压着时退回结果页。 guard case .search = route else { return } + albumDrill.resetImmediately() clearDetailPath() } .onReceive(NotificationCenter.default.publisher(for: .primuseSelectPlaylists)) { _ in // 删除当前歌单后跳「歌单」总览。若这张歌单是 push 进来的 (从总览点入), // 详情栈里可能还压着它的空详情 — 这里主动清栈。 - guard !path.isEmpty else { return } - var transaction = Transaction() - transaction.disablesAnimations = true - withTransaction(transaction) { - path = NavigationPath() - } + albumDrill.resetImmediately() + clearDetailPath() } .onReceive(NotificationCenter.default.publisher(for: .primuseDetailOpenAlbum)) { note in guard let album = note.object as? Album else { return } - // 专辑分区由网格自己打开;目录现拼的专辑网格里没有,照常推进详情栈。 - if case .section(.albums) = route, !AppleMusicCatalogAlbumIdentity.isCatalogAlbum(album.id) { - clearDetailPath() + if !AppleMusicCatalogAlbumIdentity.isCatalogAlbum(album.id) { + albumDrill.open( + album, + sourceCornerRadius: Double(PMRadius.m), + reduceMotion: reduceMotion, + library: library + ) return } + albumDrill.resetImmediately() pushAlbum(album) } .onReceive(NotificationCenter.default.publisher(for: .primuseDetailOpenArtist)) { note in guard let artist = note.object as? Artist else { return } + albumDrill.resetImmediately() if case .section(.artists) = route { clearDetailPath() return @@ -119,6 +142,9 @@ struct MacDetailContainer: View { pushArtist(artist) } .onReceive(NotificationCenter.default.publisher(for: .primuseDetailOpenPlaylist)) { note in + albumDrill.resetImmediately() + popTask?.cancel() + isPoppingDetail = false var transaction = Transaction() transaction.disablesAnimations = true if let playlist = note.object as? Playlist { @@ -129,6 +155,20 @@ struct MacDetailContainer: View { } } + private func closeFluentAlbum() { + albumDrill.close(reduceMotion: reduceMotion, library: library) + } + + @ViewBuilder + private func fluentStackDestination( + @ViewBuilder _ destination: () -> Destination + ) -> some View { + destination() + .navigationBarBackButtonHidden(true) + .modifier(MacFluentStackDetailModifier(isExiting: isPoppingDetail)) + .onExitCommand { popDetail() } + } + @ViewBuilder private var content: some View { // 这一栏的页面都不设 navigationTitle: 它会变成窗口标题, 每换一页 AppKit 就重排一次 @@ -193,6 +233,8 @@ struct MacDetailContainer: View { } private func pushAlbum(_ album: Album) { + popTask?.cancel() + isPoppingDetail = false var transaction = Transaction() transaction.disablesAnimations = true withTransaction(transaction) { @@ -201,6 +243,8 @@ struct MacDetailContainer: View { } private func pushArtist(_ artist: Artist) { + popTask?.cancel() + isPoppingDetail = false var transaction = Transaction() transaction.disablesAnimations = true withTransaction(transaction) { @@ -209,8 +253,26 @@ struct MacDetailContainer: View { } private func popDetail() { - guard !path.isEmpty else { return } - path.removeLast() + guard !path.isEmpty, !isPoppingDetail else { return } + popTask?.cancel() + isPoppingDetail = true + let exitDelayMS = reduceMotion ? 130 : 170 + popTask = Task { @MainActor in + try? await Task.sleep(for: .milliseconds(exitDelayMS)) + guard !Task.isCancelled, !path.isEmpty else { + isPoppingDetail = false + return + } + var transaction = Transaction() + transaction.disablesAnimations = true + withTransaction(transaction) { + path.removeLast() + isPoppingDetail = false + } + if path.isEmpty { + rootRevealToken &+= 1 + } + } } /// 播放页「转到这本书」: 只在「有声」一栏取走请求, 书压在书架上面。 @@ -218,6 +280,8 @@ struct MacDetailContainer: View { guard let bookID = spokenWordBookRequest, case .section(.spokenWord) = route else { return } spokenWordBookRequest = nil + popTask?.cancel() + isPoppingDetail = false var transaction = Transaction() transaction.disablesAnimations = true withTransaction(transaction) { @@ -227,6 +291,8 @@ struct MacDetailContainer: View { } private func clearDetailPath() { + popTask?.cancel() + isPoppingDetail = false guard !path.isEmpty else { return } var transaction = Transaction() transaction.disablesAnimations = true @@ -348,4 +414,423 @@ struct MacSearchCollectionDestination: Hashable { hasher.combine(result.id) } } + +// MARK: - Windows Fluent 2 连贯封面飞行与钻取协调器(120Hz 实时时钟驱动) + +/// 任意专辑入口 ↔ 专辑详情的 Fluent 2 连贯封面飞行状态协调器。 +@MainActor +@Observable +final class MacFluentAlbumDrillCoordinator { + var state = FluentDrillTransitionPolicy.State() + var activeAlbum: Album? + var flyingImage: NSImage? + var transitionStartedAt: TimeInterval = 0 + var transitionDuration: TimeInterval = 0 + var transitionReduceMotion = false + var viewportSize = FluentDrillTransitionPolicy.Size(width: 0, height: 0) + @ObservationIgnored var completionTask: Task? + @ObservationIgnored let registry = MacFluentCoverRegistry() + + init() {} +} + +extension MacFluentAlbumDrillCoordinator { + var isShowingDetail: Bool { + activeAlbum != nil && state.isShowingDetail + } + + func isCoverFlightActive(reduceMotion: Bool) -> Bool { + guard activeAlbum != nil, state.isTransitioning else { return false } + return FluentDrillTransitionPolicy.shouldFlyCover( + source: state.activeFlightFromRect, + destination: state.activeFlightToRect, + viewport: viewportSize, + reduceMotion: reduceMotion + ) + } + + func hiddenCoverID(reduceMotion: Bool) -> String? { + guard let id = state.flightID, + state.shouldHideArtwork(id: id, viewport: viewportSize, reduceMotion: reduceMotion) else { + return nil + } + return id + } + + func rawProgress(at timestamp: TimeInterval) -> Double { + guard state.isTransitioning else { + return state.phase == .presented ? 1 : 0 + } + guard transitionDuration > 0 else { return 1 } + return min(max((timestamp - transitionStartedAt) / transitionDuration, 0), 1) + } + + func coverFrame(at timestamp: TimeInterval) -> FluentDrillTransitionPolicy.CoverFrame? { + guard state.isTransitioning, + let fromRect = state.activeFlightFromRect, + let toRect = state.activeFlightToRect else { return nil } + let raw = rawProgress(at: timestamp) + let eased = state.phase == .entering + ? FluentDrillTransitionPolicy.enterEase(raw) + : FluentDrillTransitionPolicy.exitEase(raw) + return FluentDrillTransitionPolicy.coverFrame( + from: fromRect, + to: toRect, + fromCornerRadius: state.activeFlightFromRadius, + toCornerRadius: state.activeFlightToRadius, + progress: eased + ) + } + + func open( + _ album: Album, + sourceCornerRadius: Double = Double(PMRadius.m), + reduceMotion: Bool, + library: MusicLibrary + ) { + cancelTasks() + let sourceRect = registry.rect(forSource: album.id) + let now = Date().timeIntervalSinceReferenceDate + let duration = reduceMotion + ? FluentDrillTransitionPolicy.reducedMotionDuration + : FluentDrillTransitionPolicy.enterDuration + + viewportSize = registry.viewportSize() + flyingImage = MacFluentCoverSnapshot.resolve(album: album, library: library) + activeAlbum = album + transitionReduceMotion = reduceMotion + transitionDuration = duration + transitionStartedAt = now + + let generation = state.beginEnter( + id: album.id, + sourceRect: sourceRect, + destinationRect: Self.predictedAlbumHeaderRect, + sourceCornerRadius: sourceCornerRadius, + destinationCornerRadius: Double(PMRadius.l) + ) + + registry.onDestinationLayout = { [weak self] id in + guard let self, id == album.id, self.state.generation == generation else { return } + DispatchQueue.main.async { + guard self.state.generation == generation, + let measured = self.registry.rect(forDestination: id) else { return } + self.viewportSize = self.registry.viewportSize() + self.state.updateDestinationRect(measured, for: id) + } + } + + completionTask = Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(duration + 0.02)) + guard let self, !Task.isCancelled else { return } + self.registry.onDestinationLayout = nil + self.state.completeEnter(generation: generation) + } + } + + func close( + sourceCornerRadius: Double? = nil, + reduceMotion: Bool, + library: MusicLibrary + ) { + guard let album = activeAlbum else { return } + let now = Date().timeIntervalSinceReferenceDate + let wasEntering = state.phase == .entering + let liveCover = wasEntering ? coverFrame(at: now) : nil + let priorProgress = wasEntering ? rawProgress(at: now) : 1 + + cancelTasks() + viewportSize = registry.viewportSize() + let invalidRect = FluentDrillTransitionPolicy.Rect(x: 0, y: 0, width: 0, height: 0) + let liveSource = wasEntering ? nil : (registry.rect(forSource: album.id) ?? invalidRect) + let liveDestination = wasEntering ? nil : (registry.rect(forDestination: album.id) ?? invalidRect) + + guard let exit = state.beginExit( + fromCurrentCoverRect: liveCover?.rect, + fromCurrentCornerRadius: liveCover?.cornerRadius, + sourceRect: liveSource, + destinationRect: liveDestination, + sourceCornerRadius: sourceCornerRadius, + destinationCornerRadius: Double(PMRadius.l) + ) else { return } + + if flyingImage == nil { + flyingImage = MacFluentCoverSnapshot.resolve(album: album, library: library) + } + let baseDuration = reduceMotion + ? FluentDrillTransitionPolicy.reducedMotionDuration + : FluentDrillTransitionPolicy.exitDuration + let duration = wasEntering + ? max(0.16, baseDuration * max(0.40, priorProgress)) + : baseDuration + + transitionReduceMotion = reduceMotion + transitionDuration = duration + transitionStartedAt = now + + completionTask = Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(duration + 0.02)) + guard let self, !Task.isCancelled else { return } + if self.state.completeExit(generation: exit.generation) { + self.activeAlbum = nil + self.flyingImage = nil + } + } + } + + func syncResolvedAlbum(_ resolved: Album?) { + guard activeAlbum != nil else { return } + if let resolved { + if resolved != activeAlbum { activeAlbum = resolved } + } else if state.phase != .exiting { + resetImmediately() + } + } + + func resetImmediately() { + cancelTasks() + state.reset() + activeAlbum = nil + flyingImage = nil + } + + func cancelTasks() { + registry.onDestinationLayout = nil + completionTask?.cancel() + completionTask = nil + } + + /// MacLibraryHeader(`artworkBackdrop == true`)默认首屏封面落点预估;布局就绪后由实测坐标平滑校准。 + private static let predictedAlbumHeaderRect = FluentDrillTransitionPolicy.Rect( + x: 36, y: 20, width: 196, height: 196 + ) +} + +/// 专辑总览与详情的 Fluent 2 钻取宿主:TimelineView 120Hz 同步时钟驱动,零跳延迟起飞、零过冲落位。 +struct MacFluentAlbumDrillHost: View { + let coordinator: MacFluentAlbumDrillCoordinator + let onEscapeBack: () -> Void + @ViewBuilder let overview: () -> Overview + @ViewBuilder let detail: (Album) -> Detail + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + var body: some View { + TimelineView(.animation(paused: !coordinator.state.isTransitioning)) { context in + content(at: context.date.timeIntervalSinceReferenceDate) + } + } + + @ViewBuilder + private func content(at timestamp: TimeInterval) -> some View { + let phase = coordinator.state.phase + let isShowing = coordinator.isShowingDetail + let hasFlight = coordinator.isCoverFlightActive(reduceMotion: reduceMotion) + let raw = coordinator.rawProgress(at: timestamp) + let layer = resolvedLayerFrame(phase: phase, rawProgress: raw, hasCoverFlight: hasFlight) + let anchor = FluentDrillTransitionPolicy.overviewAnchor( + source: coordinator.state.sourceRect, + viewport: coordinator.viewportSize + ) + let continuum = MacFluentContinuumState( + headerOpacity: layer.detailHeaderOpacity, + headerOffsetX: layer.detailHeaderOffsetX, + contentOpacity: layer.detailContentOpacity, + contentOffsetY: layer.detailContentOffsetY + ) + + ZStack { + overview() + .scaleEffect(layer.overviewScale, anchor: UnitPoint(x: anchor.x, y: anchor.y)) + .opacity(layer.overviewOpacity) + .clipped() + .disabled(isShowing) + .allowsHitTesting(!isShowing) + .accessibilityHidden(isShowing) + + if let album = coordinator.activeAlbum { + detail(album) + .id(album.id) + .environment(\.macFluentContinuum, continuum) + .opacity(layer.detailBackdropOpacity) + .allowsHitTesting(phase == .presented) + .onExitCommand(perform: onEscapeBack) + .zIndex(1) + } + + if hasFlight, + let album = coordinator.activeAlbum, + let frame = coordinator.coverFrame(at: timestamp) { + MacFluentFlyingCoverView( + album: album, + image: coordinator.flyingImage, + frame: frame + ) + .allowsHitTesting(false) + .accessibilityHidden(true) + .zIndex(2) + } + } + .background { + MacFluentCanvasProbe(registry: coordinator.registry) + .allowsHitTesting(false) + .accessibilityHidden(true) + } + .environment(\.macFluentCoverRegistry, coordinator.registry) + .environment(\.macFluentHiddenCoverID, coordinator.hiddenCoverID(reduceMotion: reduceMotion)) + } + + private func resolvedLayerFrame( + phase: FluentDrillTransitionPolicy.Phase, + rawProgress: Double, + hasCoverFlight: Bool + ) -> FluentDrillTransitionPolicy.LayerFrame { + switch phase { + case .idle: + return FluentDrillTransitionPolicy.layerFrame( + direction: .drillOut, progress: 1, hasCoverFlight: false, reduceMotion: true + ) + case .presented: + return FluentDrillTransitionPolicy.layerFrame( + direction: .drillIn, progress: 1, hasCoverFlight: false, reduceMotion: true + ) + case .entering: + return FluentDrillTransitionPolicy.layerFrame( + direction: .drillIn, progress: rawProgress, + hasCoverFlight: hasCoverFlight, reduceMotion: reduceMotion + ) + case .exiting: + return FluentDrillTransitionPolicy.layerFrame( + direction: .drillOut, progress: rawProgress, + hasCoverFlight: hasCoverFlight, reduceMotion: reduceMotion + ) + } + } +} + +private struct MacFluentFlyingCoverView: View { + let album: Album + let image: NSImage? + let frame: FluentDrillTransitionPolicy.CoverFrame + + var body: some View { + let width = CGFloat(frame.rect.width) + let height = CGFloat(frame.rect.height) + let radius = CGFloat(frame.cornerRadius) + let shape = RoundedRectangle(cornerRadius: radius, style: .continuous) + + Group { + if let image { + Image(nsImage: image) + .resizable() + .aspectRatio(contentMode: .fill) + .frame(width: width, height: height) + .clipShape(shape) + } else { + let side = max(width, height, 1) + AlbumArtworkView( + album: album, + size: side, + cornerRadius: radius, + presentationRole: .staticFirstFrame, + isAnimationVisible: false + ) + .frame(width: width, height: height) + .clipShape(shape) + } + } + .overlay { + if frame.borderHighlightOpacity > 0.005 { + shape.strokeBorder(.white.opacity(frame.borderHighlightOpacity), lineWidth: 1) + } + } + .shadow( + color: .black.opacity(frame.shadowOpacity), + radius: CGFloat(frame.shadowRadius), + y: CGFloat(frame.shadowRadius * 0.42) + ) + .position(x: CGFloat(frame.rect.midX), y: CGFloat(frame.rect.midY)) + } +} + +/// 任意专辑卡片统一入口:优先触发 Fluent 2 共享封面飞行钻取,目录现拼专辑或无宿主时自动回落详情栈。 +struct MacFluentAlbumLink: View { + let album: Album + var cornerRadius: Double = Double(PMRadius.m) + @ViewBuilder let label: () -> Label + @Environment(MusicLibrary.self) private var library + @Environment(\.macFluentAlbumDrill) private var fluentDrill + @Environment(\.accessibilityReduceMotion) private var reduceMotion + + var body: some View { + if let fluentDrill, !AppleMusicCatalogAlbumIdentity.isCatalogAlbum(album.id) { + Button { + fluentDrill.open( + album, + sourceCornerRadius: cornerRadius, + reduceMotion: reduceMotion, + library: library + ) + } label: { + label() + } + .buttonStyle(.pmPressable) + } else { + NavigationLink(value: album, label: label) + .buttonStyle(.plain) + } + } +} + +/// 详情栈(非专辑页或目录现拼专辑推入)的 Fluent 2 钻入 / 钻出修饰符。 +private struct MacFluentStackDetailModifier: ViewModifier { + let isExiting: Bool + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var entered = false + + func body(content: Content) -> some View { + let shown = entered && !isExiting + let offsetY: CGFloat = reduceMotion ? 0 : ( + isExiting ? CGFloat(FluentDrillTransitionPolicy.detailExitOffsetY) : + (entered ? 0 : 14) + ) + content + .offset(y: offsetY) + .opacity(shown ? 1 : 0) + .onAppear { + guard !entered else { return } + let anim: Animation = reduceMotion + ? .easeOut(duration: FluentDrillTransitionPolicy.reducedMotionDuration) + : .timingCurve(0.10, 0.90, 0.20, 1.0, duration: 0.28) + withAnimation(anim) { entered = true } + } + .animation( + reduceMotion + ? .easeOut(duration: 0.14) + : .timingCurve(0.16, 0.88, 0.26, 1.0, duration: 0.20), + value: isExiting + ) + } +} + +/// 详情栈退回根页时的 Fluent 前移复原,替代退栈一瞬间的生硬硬切。 +private struct MacFluentRootRevealModifier: ViewModifier { + let trigger: Int + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var isRevealed = true + + func body(content: Content) -> some View { + content + .scaleEffect(isRevealed || reduceMotion ? 1 : 1.02) + .opacity(isRevealed ? 1 : 0.35) + .onChange(of: trigger) { _, _ in + var reset = Transaction(animation: nil) + reset.disablesAnimations = true + withTransaction(reset) { isRevealed = false } + let anim: Animation = reduceMotion + ? .easeOut(duration: 0.14) + : .timingCurve(0.16, 0.88, 0.26, 1.0, duration: 0.24) + withAnimation(anim) { isRevealed = true } + } + } +} #endif diff --git a/Primuse/Views/Mac/MacHomeAlbumPickHero.swift b/Primuse/Views/Mac/MacHomeAlbumPickHero.swift index fd7961298..f23965cc3 100644 --- a/Primuse/Views/Mac/MacHomeAlbumPickHero.swift +++ b/Primuse/Views/Mac/MacHomeAlbumPickHero.swift @@ -74,6 +74,7 @@ struct MacHomeAlbumPickHero: View { MacHomeDetailLink(album: album) { AlbumArtworkView(album: album, size: 240, cornerRadius: PMRadius.l) .shadow(color: .black.opacity(0.32), radius: 18, y: 8) + .macFluentCoverSource(id: album.id) } .pmScrollingHelp(Text("go_to_album")) .contextMenu { menu } diff --git a/Primuse/Views/Mac/MacHomeRecentlyAddedPage.swift b/Primuse/Views/Mac/MacHomeRecentlyAddedPage.swift index 150031b05..a62a90147 100644 --- a/Primuse/Views/Mac/MacHomeRecentlyAddedPage.swift +++ b/Primuse/Views/Mac/MacHomeRecentlyAddedPage.swift @@ -89,6 +89,7 @@ struct MacHomeAlbumCard: View { AlbumArtworkView(album: album, cornerRadius: PMRadius.m) .aspectRatio(1, contentMode: .fit) .shadow(color: .black.opacity(0.22), radius: 8, y: 4) + .macFluentCoverSource(id: album.id) Text(album.title) .font(.system(size: 12.5, weight: .medium)) diff --git a/Primuse/Views/Mac/MacHomeView.swift b/Primuse/Views/Mac/MacHomeView.swift index 4fb12bb2a..2976dfa21 100644 --- a/Primuse/Views/Mac/MacHomeView.swift +++ b/Primuse/Views/Mac/MacHomeView.swift @@ -42,6 +42,9 @@ struct MacHomeDetailLink: View { private let target: Target private let label: Label + @Environment(MusicLibrary.self) private var library + @Environment(\.macFluentAlbumDrill) private var fluentDrill + @Environment(\.accessibilityReduceMotion) private var reduceMotion init(album: Album, @ViewBuilder label: () -> Label) { target = .album(album) @@ -67,8 +70,22 @@ struct MacHomeDetailLink: View { if PMScrollingControls.usesButtons { switch target { case .album(let album): - NavigationLink(value: album) { label } - .buttonStyle(.plain) + if let fluentDrill, !AppleMusicCatalogAlbumIdentity.isCatalogAlbum(album.id) { + Button { + fluentDrill.open( + album, + sourceCornerRadius: Double(PMRadius.m), + reduceMotion: reduceMotion, + library: library + ) + } label: { + label + } + .buttonStyle(.pmPressable) + } else { + NavigationLink(value: album) { label } + .buttonStyle(.plain) + } case .artist(let artist): NavigationLink(value: artist) { label } .buttonStyle(.plain) @@ -87,7 +104,16 @@ struct MacHomeDetailLink: View { private func open() { switch target { case .album(let album): - NotificationCenter.default.post(name: .primuseDetailOpenAlbum, object: album) + if let fluentDrill, !AppleMusicCatalogAlbumIdentity.isCatalogAlbum(album.id) { + fluentDrill.open( + album, + sourceCornerRadius: Double(PMRadius.m), + reduceMotion: reduceMotion, + library: library + ) + } else { + NotificationCenter.default.post(name: .primuseDetailOpenAlbum, object: album) + } case .artist(let artist): NotificationCenter.default.post(name: .primuseDetailOpenArtist, object: artist) case .playlist(let playlist): diff --git a/Primuse/Views/Mac/MacLibraryHeader.swift b/Primuse/Views/Mac/MacLibraryHeader.swift index 56172ee5c..43940b637 100644 --- a/Primuse/Views/Mac/MacLibraryHeader.swift +++ b/Primuse/Views/Mac/MacLibraryHeader.swift @@ -1,4 +1,5 @@ #if os(macOS) +import AppKit import SwiftUI import PrimuseKit @@ -137,7 +138,13 @@ struct MacLibraryHeader: View { Button(action: favorite.toggle) { Image(systemName: favorite.isLiked ? "heart.fill" : "heart") .font(.system(size: 14, weight: .semibold)) - .foregroundStyle(.white) + .foregroundStyle(favorite.isLiked ? Color.red : Color.white) + .contentTransition(.symbolEffect(.replace)) + .pmLikeBurst( + isLiked: favorite.isLiked, + identity: coverAlbum?.id ?? coverArtist?.id ?? coverPlaylist?.id, + tint: .red + ) .frame(width: 32, height: 32) .background(Color.white.opacity(0.16), in: .rect(cornerRadius: 8)) .overlay { RoundedRectangle(cornerRadius: 8).strokeBorder(.white.opacity(0.22), lineWidth: 0.5) } @@ -182,6 +189,7 @@ struct MacLibraryHeader: View { } .padding(.top, 8) } + .macFluentContinuumHeader() Spacer(minLength: 0) } .padding(.horizontal, 36) @@ -297,6 +305,7 @@ struct MacLibraryHeader: View { presentationRole: .animatedHero ) .shadow(color: .black.opacity(0.35), radius: 18, y: 8) + .macFluentCoverDestination(id: album.id) } else if let artist = coverArtist { ArtistArtworkView( artist: artist, @@ -467,8 +476,10 @@ private struct MacControlChrome: ViewModifier { private struct MacSegmentChrome: ViewModifier { let selected: Bool let iconOnly: Bool + let namespace: Namespace.ID? @Environment(\.macControlTier) private var tier @Environment(\.colorScheme) private var colorScheme + @Environment(\.accessibilityReduceMotion) private var reduceMotion func body(content: Content) -> some View { let inner = tier.height - 4 @@ -481,13 +492,18 @@ private struct MacSegmentChrome: ViewModifier { .frame(width: iconOnly ? tier.height - 2 : nil, height: inner) .background { if selected { - RoundedRectangle(cornerRadius: tier.cornerRadius - 2, style: .continuous) + let pill = RoundedRectangle(cornerRadius: tier.cornerRadius - 2, style: .continuous) .fill(colorScheme == .dark ? Color.white.opacity(0.16) : Color.white) .shadow(color: .black.opacity(colorScheme == .dark ? 0.25 : 0.10), radius: 1.5, y: 0.5) + if let namespace, !reduceMotion { + pill.matchedGeometryEffect(id: "macSegmentHighlight", in: namespace) + } else { + pill + } } } .contentShape(Rectangle()) - .pmAnimation(.hover, value: selected) + .pmAnimation(namespace == nil ? .hover : .selection, value: selected) } } @@ -533,8 +549,8 @@ extension View { modifier(MacSegmentedContainerChrome()) } - func macSegment(selected: Bool, iconOnly: Bool = false) -> some View { - modifier(MacSegmentChrome(selected: selected, iconOnly: iconOnly)) + func macSegment(selected: Bool, iconOnly: Bool = false, namespace: Namespace.ID? = nil) -> some View { + modifier(MacSegmentChrome(selected: selected, iconOnly: iconOnly, namespace: namespace)) } } @@ -697,4 +713,285 @@ struct MacHeaderMoreMenu: View { .opacity(item.enabled ? 1 : 0.4) } } + +// MARK: - Fluent 封面锚点、同步位图快照与 Continuum 错峰编排 + +/// 详情页 Fluent Continuum 三层错峰实时数值(仅过渡期间更新,静止态保持 `.resting`)。 +struct MacFluentContinuumState: Equatable, Sendable { + var headerOpacity: Double = 1 + var headerOffsetX: Double = 0 + var contentOpacity: Double = 1 + var contentOffsetY: Double = 0 + + static let resting = MacFluentContinuumState() +} + +/// 记录可见源封面与详情头图封面的弱引用;不做 `@Observable`,滚动期间零回调、零重算。 +@MainActor +final class MacFluentCoverRegistry { + enum Role: Equatable { + case source(String) + case destination(String) + } + + private struct WeakEntry { + let id: String + weak var view: NSView? + } + + weak var canvasView: NSView? + var onDestinationLayout: ((String) -> Void)? + + private var sourceEntries: [WeakEntry] = [] + private var destinationEntries: [WeakEntry] = [] + private static let maxMountedSources = 128 + + func register(_ view: NSView, role: Role) { + switch role { + case .source(let id): + sourceEntries.removeAll { $0.view == nil || ($0.id == id && $0.view === view) } + sourceEntries.append(WeakEntry(id: id, view: view)) + if sourceEntries.count > Self.maxMountedSources { + sourceEntries.removeFirst(sourceEntries.count - Self.maxMountedSources) + } + case .destination(let id): + destinationEntries.removeAll { $0.view == nil || $0.id == id } + destinationEntries.append(WeakEntry(id: id, view: view)) + } + } + + func unregister(_ view: NSView, role: Role) { + switch role { + case .source(let id): + sourceEntries.removeAll { $0.view == nil || ($0.id == id && $0.view === view) } + case .destination(let id): + destinationEntries.removeAll { $0.view == nil || ($0.id == id && $0.view === view) } + } + } + + func notifyDestinationLayout(id: String) { + onDestinationLayout?(id) + } + + func rect(forSource id: String) -> FluentDrillTransitionPolicy.Rect? { + guard let view = sourceEntries.last(where: { $0.id == id && $0.view?.window != nil })?.view else { return nil } + return rect(of: view) + } + + func rect(forDestination id: String) -> FluentDrillTransitionPolicy.Rect? { + guard let view = destinationEntries.last(where: { $0.id == id && $0.view?.window != nil })?.view else { return nil } + return rect(of: view) + } + + func viewportSize() -> FluentDrillTransitionPolicy.Size { + guard let canvasView else { return .init(width: 0, height: 0) } + return .init(width: Double(canvasView.bounds.width), height: Double(canvasView.bounds.height)) + } + + private func rect(of view: NSView) -> FluentDrillTransitionPolicy.Rect? { + guard let canvas = canvasView, view.window != nil, view.window === canvas.window else { return nil } + let frame = view.convert(view.bounds, to: canvas) + let rect = FluentDrillTransitionPolicy.Rect( + x: Double(frame.origin.x), y: Double(frame.origin.y), + width: Double(frame.size.width), height: Double(frame.size.height) + ) + return rect.isValid ? rect : nil + } +} + +/// 同步解析已解码封面位图,确保飞行层第 0 帧即显真图,不闪占位符也不走异步 `.task`。 +@MainActor +enum MacFluentCoverSnapshot { + private static let cache: NSCache = { + let store = NSCache() + store.countLimit = 24 + return store + }() + + static func resolve(album: Album, library: MusicLibrary) -> NSImage? { + let key = "\(album.id)#\(library.artworkOverrideRevision)" as NSString + if let cached = cache.object(forKey: key) { return cached } + + let owner = LibraryArtworkOwner(kind: .album, id: album.id) + let presentation = library.artworkPresentation(for: owner) + if let contentID = presentation.uploadedContentID, + let data = MetadataAssetStore.shared.customArtworkData(contentID: contentID), + let image = NSImage(data: data) { + cache.setObject(image, forKey: key) + return image + } + + let candidateSong: Song? = presentation.selectedSong + ?? ArtworkSongCatalogMemo.shared.cachedSongID(for: .album(album.id), library: library) + .flatMap { library.unobservedVisibleSong(id: $0) } + if let song = candidateSong { + for side: CGFloat in [196, 160, 112, 44] { + if let mem = CachedArtworkView.memoryCachedSongArtwork( + coverRef: song.coverArtFileName, songID: song.id, size: side, + sourceID: song.sourceID, filePath: song.filePath, fileFormat: song.fileFormat + ) { + cache.setObject(mem, forKey: key) + return mem + } + } + if let fileName = song.coverArtFileName, + let data = MetadataAssetStore.shared.readCoverData(named: fileName), + let image = NSImage(data: data) { + cache.setObject(image, forKey: key) + return image + } + } + if let path = album.coverArtPath, + let data = MetadataAssetStore.shared.readCoverData(named: path), + let image = NSImage(data: data) { + cache.setObject(image, forKey: key) + return image + } + return nil + } +} + +extension EnvironmentValues { + @Entry var macFluentCoverRegistry: MacFluentCoverRegistry? = nil + @Entry var macFluentHiddenCoverID: String? = nil + @Entry var macFluentContinuum = MacFluentContinuumState.resting + @Entry var macFluentAlbumDrill: MacFluentAlbumDrillCoordinator? = nil +} + +extension View { + func macFluentCoverSource(id: String) -> some View { + modifier(MacFluentCoverAnchorModifier(role: .source(id), coverID: id)) + } + + func macFluentCoverDestination(id: String) -> some View { + modifier(MacFluentCoverAnchorModifier(role: .destination(id), coverID: id)) + } + + func macFluentContinuumHeader() -> some View { + modifier(MacFluentContinuumHeaderModifier()) + } + + func macFluentContinuumContent() -> some View { + modifier(MacFluentContinuumContentModifier()) + } +} + +private struct MacFluentContinuumHeaderModifier: ViewModifier { + @Environment(\.macFluentContinuum) private var continuum + + func body(content: Content) -> some View { + content + .offset(x: continuum.headerOffsetX) + .opacity(continuum.headerOpacity) + } +} + +private struct MacFluentContinuumContentModifier: ViewModifier { + @Environment(\.macFluentContinuum) private var continuum + + func body(content: Content) -> some View { + content + .offset(y: continuum.contentOffsetY) + .opacity(continuum.contentOpacity) + } +} + +private struct MacFluentCoverAnchorModifier: ViewModifier { + let role: MacFluentCoverRegistry.Role + let coverID: String + @Environment(\.macFluentCoverRegistry) private var registry + @Environment(\.macFluentHiddenCoverID) private var hiddenCoverID + + func body(content: Content) -> some View { + if let registry { + content + .opacity(hiddenCoverID == coverID ? 0 : 1) + .background { + MacFluentCoverAnchorProbe(role: role, registry: registry) + .allowsHitTesting(false) + .accessibilityHidden(true) + } + } else { + content + } + } +} + +struct MacFluentCanvasProbe: NSViewRepresentable { + let registry: MacFluentCoverRegistry + + func makeNSView(context: Context) -> MacFluentCanvasNSView { + let view = MacFluentCanvasNSView(frame: .zero) + registry.canvasView = view + return view + } + + func updateNSView(_ nsView: MacFluentCanvasNSView, context: Context) { + registry.canvasView = nsView + } +} + +final class MacFluentCanvasNSView: NSView { + override var isFlipped: Bool { true } + override func hitTest(_ point: NSPoint) -> NSView? { nil } +} + +private struct MacFluentCoverAnchorProbe: NSViewRepresentable { + let role: MacFluentCoverRegistry.Role + let registry: MacFluentCoverRegistry + + func makeNSView(context: Context) -> MacFluentCoverAnchorNSView { + let view = MacFluentCoverAnchorNSView(frame: .zero) + view.configure(role: role, registry: registry) + return view + } + + func updateNSView(_ nsView: MacFluentCoverAnchorNSView, context: Context) { + nsView.configure(role: role, registry: registry) + } + + static func dismantleNSView(_ nsView: MacFluentCoverAnchorNSView, coordinator: ()) { + nsView.unregister() + } +} + +private final class MacFluentCoverAnchorNSView: NSView { + private var role: MacFluentCoverRegistry.Role? + private weak var registry: MacFluentCoverRegistry? + + override func hitTest(_ point: NSPoint) -> NSView? { nil } + + func configure(role: MacFluentCoverRegistry.Role, registry: MacFluentCoverRegistry) { + if let previous = self.role, previous != role { + self.registry?.unregister(self, role: previous) + } + self.role = role + self.registry = registry + registry.register(self, role: role) + notifyIfDestination() + } + + func unregister() { + if let role { registry?.unregister(self, role: role) } + role = nil + registry = nil + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + if let role { registry?.register(self, role: role) } + notifyIfDestination() + } + + override func layout() { + super.layout() + notifyIfDestination() + } + + private func notifyIfDestination() { + guard case .destination(let id) = role, window != nil, + bounds.width > 1, bounds.height > 1 else { return } + registry?.notifyDestinationLayout(id: id) + } +} #endif diff --git a/Primuse/Views/Mac/MacSidebar.swift b/Primuse/Views/Mac/MacSidebar.swift index 32aa18766..e0eeb7a7b 100644 --- a/Primuse/Views/Mac/MacSidebar.swift +++ b/Primuse/Views/Mac/MacSidebar.swift @@ -72,6 +72,7 @@ struct MacSidebar: View { } /// 这次启动没装过歌曲模型时,书架的本数从曲库目录数(U8a,`spokenWordCatalogShelfCounts`)。 @State private var catalogShelfCounts: SpokenWordShelfCounts? + @Namespace private var selectionNamespace var body: some View { ScrollView(.vertical, showsIndicators: false) { @@ -105,6 +106,7 @@ struct MacSidebar: View { } .onChange(of: counts, initial: true) { _, counts in shownCounts = counts } .spokenWordCatalogShelfCounts($catalogShelfCounts) + .environment(\.macSidebarSelectionNamespace, selectionNamespace) .frame(maxHeight: .infinity) // 底色接到窗口顶: 播放页开着时标题栏褪透明, 侧栏的封面色从红绿灯那一角就开始。 .background(MacSidebarBackdrop().macExtendsUnderTitleBar().ignoresSafeArea()) @@ -894,6 +896,10 @@ private struct MacSidebarManageSourcesButton: View { } } +private extension EnvironmentValues { + @Entry var macSidebarSelectionNamespace: Namespace.ID? = nil +} + /// 侧栏里能点进某一页的一行。选没选中在这一行自己的 body 里读(`MacRouteRowHighlight`): 换页时 /// 重画的只有新旧两行, 侧栏其余部分 —— 各行的计数、歌单列表、每行的右键菜单 —— 不跟着再求一遍。 private struct MacSidebarRow: View { @@ -901,6 +907,9 @@ private struct MacSidebarRow: View { let highlight: MacRouteRowHighlight let onSelectRoute: (MacRoute) -> Void @ViewBuilder let label: (_ selected: Bool) -> Label + @Environment(\.macSidebarSelectionNamespace) private var selectionNamespace + @Environment(\.accessibilityReduceMotion) private var reduceMotion + @State private var hover = false var body: some View { let selected = highlight.isSelected @@ -910,7 +919,35 @@ private struct MacSidebarRow: View { label(selected) .padding(.horizontal, 10) .padding(.vertical, 6) - .pmRowBackground(selected: selected) + .background { + ZStack(alignment: .leading) { + if hover && !selected { + RoundedRectangle(cornerRadius: PMRadius.s, style: .continuous) + .fill(PMColor.rowHover) + } + if selected { + let pill = ZStack(alignment: .leading) { + RoundedRectangle(cornerRadius: PMRadius.s, style: .continuous) + .fill(PMColor.brand.opacity(0.22)) + Capsule() + .fill(PMColor.brand) + .frame(width: 3, height: 14) + .padding(.leading, 2) + } + if let selectionNamespace, !reduceMotion { + pill.matchedGeometryEffect(id: "macSidebarSelection", in: selectionNamespace) + } else { + pill + } + } + } + } + .onHover { hover = $0 } + .pmAnimation(.hover, value: hover) + .animation( + reduceMotion ? .easeOut(duration: 0.14) : .spring(duration: 0.28, bounce: 0.06), + value: selected + ) .contentShape(Rectangle()) } .buttonStyle(.plain) diff --git a/Primuse/Views/Mac/PMTitleBar.swift b/Primuse/Views/Mac/PMTitleBar.swift index bab1ae98a..c493afa95 100644 --- a/Primuse/Views/Mac/PMTitleBar.swift +++ b/Primuse/Views/Mac/PMTitleBar.swift @@ -321,6 +321,7 @@ private struct MacTitleBarBackdrop: View { Rectangle().fill(PMColor.divider).frame(height: 0.5) } .opacity(followsPlayer ? 0 : 1) + .pmAnimation(.ambient, value: followsPlayer) .contentShape(Rectangle()) } } diff --git a/Primuse/Views/Search/SearchView.swift b/Primuse/Views/Search/SearchView.swift index da55c6a3e..80c2162c8 100644 --- a/Primuse/Views/Search/SearchView.swift +++ b/Primuse/Views/Search/SearchView.swift @@ -400,10 +400,10 @@ private struct SearchAlbumResultsGrid: View { VStack(alignment: .leading, spacing: 2) { NavigationLink(value: album) { AlbumCardView(album: album, showsSongCount: true, - isIntelligentRecommendation: intelligentRecommendationIDs.contains(album.id)) + isIntelligentRecommendation: intelligentRecommendationIDs.contains(album.id), + usesCoverZoomSource: true) } .buttonStyle(.plain) - .mediaZoomSource(.album, id: album.id) actions(album) } } @@ -2310,8 +2310,7 @@ struct SearchView: View { NavigationLink(value: artist) { macHeroCardBody(match) } .buttonStyle(.plain) case .album(let album): - NavigationLink(value: album) { macHeroCardBody(match) } - .buttonStyle(.plain) + MacFluentAlbumLink(album: album, cornerRadius: 10) { macHeroCardBody(match) } case .song(let result): Button { playSong(result.song, lyricsHint: result.lyricSnippet, matchKind: result.matchKind) @@ -2410,7 +2409,7 @@ struct SearchView: View { ArtistArtworkView(artist: artist, size: 112, cornerRadius: 56) .searchRecommendationOverlay(isRecommended: intelligentArtistIDs.contains(artist.id), iconOnly: true) case .album(let album): - AlbumArtworkView(album: album, size: 112, cornerRadius: 10) + AlbumArtworkView(album: album, size: 112, cornerRadius: 10).macFluentCoverSource(id: album.id) .searchRecommendationOverlay(isRecommended: intelligentAlbumIDs.contains(album.id)) case .song(let result): CachedArtworkView( @@ -2442,7 +2441,7 @@ struct SearchView: View { } .buttonStyle(.plain) case .album(let album): - NavigationLink(value: album) { + MacFluentAlbumLink(album: album, cornerRadius: 10) { macTopCard( title: album.title, subtitle: [album.artistName ?? "", String(localized: "tab_albums")] @@ -2452,7 +2451,6 @@ struct SearchView: View { album: album ) } - .buttonStyle(.plain) case .song(let result): Button { playSong(result.song, lyricsHint: result.lyricSnippet, matchKind: result.matchKind) @@ -3196,9 +3194,9 @@ struct SearchView: View { private func macAlbumCard(_ album: PrimuseKit.Album) -> some View { VStack(alignment: .leading, spacing: 2) { - NavigationLink(value: album) { + MacFluentAlbumLink(album: album, cornerRadius: 10) { VStack(alignment: .leading, spacing: 7) { - AlbumArtworkView(album: album, cornerRadius: 10) + AlbumArtworkView(album: album, cornerRadius: 10).macFluentCoverSource(id: album.id) .aspectRatio(1, contentMode: .fit) .searchRecommendationOverlay(isRecommended: intelligentAlbumIDs.contains(album.id)) Text(album.title) @@ -3218,8 +3216,7 @@ struct SearchView: View { .lineLimit(1) } } - .buttonStyle(.plain) - .pmHoverLift() + .pmHoverLift(scale: 1.022) resultActions(.album(album.id)) } } @@ -3325,7 +3322,7 @@ struct SearchView: View { filePath: song.filePath, fileFormat: song.fileFormat) } else if let album { - AlbumArtworkView(album: album, size: 80, cornerRadius: 10) + AlbumArtworkView(album: album, size: 80, cornerRadius: 10).macFluentCoverSource(id: album.id) .searchRecommendationOverlay(isRecommended: intelligentAlbumIDs.contains(album.id)) } else { Circle() @@ -4168,11 +4165,11 @@ struct SearchView: View { VStack(alignment: .leading, spacing: 2) { NavigationLink(value: album) { AlbumCardView(album: album, showsSongCount: true, - isIntelligentRecommendation: intelligentAlbumIDs.contains(album.id)) + isIntelligentRecommendation: intelligentAlbumIDs.contains(album.id), + usesCoverZoomSource: true) .frame(width: albumCardWidth) } .buttonStyle(.plain) - .mediaZoomSource(.album, id: album.id) resultActions(.album(album.id)) } } diff --git a/PrimuseKit/Sources/PrimuseKit/Interface/ScreenChangeTransitionPolicy.swift b/PrimuseKit/Sources/PrimuseKit/Interface/ScreenChangeTransitionPolicy.swift index 8bbacf55e..b8ab57d0b 100644 --- a/PrimuseKit/Sources/PrimuseKit/Interface/ScreenChangeTransitionPolicy.swift +++ b/PrimuseKit/Sources/PrimuseKit/Interface/ScreenChangeTransitionPolicy.swift @@ -306,3 +306,488 @@ extension ScreenChangeTransitionPolicy { } } } + + +// MARK: - Fluent 封面飞行与钻取过渡 + +/// Windows Fluent 2 风格的连贯封面飞行与钻取(Drill-In / Drill-Out / Continuum)过渡规则。 +/// +/// 桌面端(macOS 各专辑入口 ↔ 专辑详情页)与移动端(iOS 封面缩放与头图下拉弹性)共用这份纯数值规则: +/// - 进入详情时:底层总览以被点击封面为锚点轻度放大潜入淡出(始终 >= 1.0 不露边缘黑框),封面按 Fluent 2 +/// 指数缓出曲线零过冲飞向详情头图,详情氛围底满幅柔和浮现,标题/按钮从封面右侧顺势横滑展开,曲目表错峰上浮; +/// - 返回总览时:详情文字与曲目表在前 1/3 内迅速清场,单张封面逆向飞回原卡片格位,底层总览由潜入态平滑收拢复原; +/// - 进场中途按返回时从封面此刻的空中实时坐标无缝折返,源/目标离屏或减弱动态效果时自动退化。 +public enum FluentDrillTransitionPolicy { + public struct Rect: Equatable, Sendable { + public var x: Double + public var y: Double + public var width: Double + public var height: Double + + public init(x: Double, y: Double, width: Double, height: Double) { + self.x = x + self.y = y + self.width = width + self.height = height + } + + public var minX: Double { x } + public var minY: Double { y } + public var maxX: Double { x + width } + public var maxY: Double { y + height } + public var midX: Double { x + width / 2 } + public var midY: Double { y + height / 2 } + + public var isValid: Bool { + x.isFinite && y.isFinite && width.isFinite && height.isFinite + && width > 1 && height > 1 + } + } + + public struct Size: Equatable, Sendable { + public var width: Double + public var height: Double + + public init(width: Double, height: Double) { + self.width = width + self.height = height + } + + public var isValid: Bool { + width.isFinite && height.isFinite && width > 1 && height > 1 + } + } + + public struct Anchor: Equatable, Sendable { + public var x: Double + public var y: Double + + public init(x: Double, y: Double) { + self.x = x + self.y = y + } + + public static let center = Anchor(x: 0.5, y: 0.5) + } + + public enum Phase: Equatable, Sendable { + case idle + case entering + case presented + case exiting + } + + public enum Direction: Equatable, Sendable { + case drillIn + case drillOut + } + + public struct CoverFrame: Equatable, Sendable { + public var rect: Rect + public var cornerRadius: Double + public var shadowRadius: Double + public var shadowOpacity: Double + public var borderHighlightOpacity: Double + } + + public struct LayerFrame: Equatable, Sendable { + public var overviewScale: Double + public var overviewOpacity: Double + public var detailBackdropOpacity: Double + public var detailHeaderOpacity: Double + public var detailHeaderOffsetX: Double + public var detailContentOpacity: Double + public var detailContentOffsetY: Double + public var hidesSourceArtwork: Bool + public var hidesDestinationArtwork: Bool + } + + public struct HeroOverscrollFrame: Equatable, Sendable { + public var scale: Double + public var offsetY: Double + } + + // MARK: - Fluent 2 档位参数 + + /// 钻入时长(秒):Fluent 2 Connected Animation 指数缓出,首帧高速离地、后段丝绒落位零过冲。 + public static let enterDuration: Double = 0.40 + /// 返回时长(秒):较钻入干脆约 25%,退场利落不拖泥带水。 + public static let exitDuration: Double = 0.30 + /// 减弱动态效果时的纯交叉淡入时长(秒)。 + public static let reducedMotionDuration: Double = 0.18 + + /// 总览页潜入时的放大比例(始终 >= 1.0,不露画布外边框)。 + public static let overviewZoomInScale: Double = 1.032 + /// 详情页页头(标题与操作按钮)从封面右侧滑入的起始偏移(点)。 + public static let detailHeaderEnterOffsetX: Double = -16 + /// 详情页页头退场时的轻微左收偏移(点)。 + public static let detailHeaderExitOffsetX: Double = -8 + /// 详情页曲目表进场时轻度上浮的起点距离(点)。 + public static let detailEnterOffsetY: Double = 22 + /// 详情页曲目表退场时轻度下沉的终点距离(点)。 + public static let detailExitOffsetY: Double = 10 + + /// 封面飞行中点的最大向上重力弧线抬升量(点)。 + public static let maxGravityArcLift: Double = 16 + /// 飞行距离折算成弧线抬升量的比例。 + public static let gravityArcRatio: Double = 0.06 + + public static let restingShadowRadius: Double = 10 + public static let restingShadowOpacity: Double = 0.22 + public static let flightShadowRadius: Double = 26 + public static let flightShadowOpacity: Double = 0.38 + /// 飞行中段的 Fluent Elevation 细高光描边透明度。 + public static let flightBorderHighlightOpacity: Double = 0.24 + + /// iOS 详情页下拉过卷时的最大头图拉伸比例。 + public static let heroOverscrollMaxStretch: Double = 0.24 + + // MARK: - Fluent 2 三次贝塞尔曲线 + + /// 求值标准 CSS/Fluent 三次贝塞尔 `cubic-bezier(x1, y1, x2, y2)` 在归一化时间 `t ∈ [0, 1]` 处的输出。 + public static func cubicBezier( + x1: Double, y1: Double, x2: Double, y2: Double, t: Double + ) -> Double { + guard t.isFinite else { return 0 } + if t <= 0 { return 0 } + if t >= 1 { return 1 } + + let ax = 3 * x1 - 3 * x2 + 1 + let bx = 3 * x2 - 6 * x1 + let cx = 3 * x1 + let ay = 3 * y1 - 3 * y2 + 1 + let by = 3 * y2 - 6 * y1 + let cy = 3 * y1 + + func sampleX(_ u: Double) -> Double { ((ax * u + bx) * u + cx) * u } + func sampleY(_ u: Double) -> Double { ((ay * u + by) * u + cy) * u } + func derivativeX(_ u: Double) -> Double { (3 * ax * u + 2 * bx) * u + cx } + + var u = t + for _ in 0..<6 { + let err = sampleX(u) - t + if abs(err) < 1e-6 { return sampleY(u) } + let d = derivativeX(u) + if abs(d) < 1e-6 { break } + u = min(max(u - err / d, 0), 1) + } + var lo = 0.0 + var hi = 1.0 + u = t + for _ in 0..<12 { + let x = sampleX(u) + if abs(x - t) < 1e-6 { break } + if x < t { lo = u } else { hi = u } + u = 0.5 * (lo + hi) + } + return sampleY(u) + } + + /// Fluent 2 钻入缓动:极快起速 + 长尾平滑减速,零过冲。 + public static func enterEase(_ rawProgress: Double) -> Double { + cubicBezier(x1: 0.10, y1: 0.90, x2: 0.20, y2: 1.0, t: rawProgress) + } + + /// Fluent 2 钻出缓动:迅捷离位 + 干脆回落原格位,零过冲。 + public static func exitEase(_ rawProgress: Double) -> Double { + cubicBezier(x1: 0.16, y1: 0.88, x2: 0.26, y2: 1.0, t: rawProgress) + } + + /// 详情页内容柔和缓出曲线。 + private static func contentEase(_ rawProgress: Double) -> Double { + cubicBezier(x1: 0.15, y1: 0.85, x2: 0.30, y2: 1.0, t: rawProgress) + } + + private static func remap(_ value: Double, start: Double, end: Double) -> Double { + guard end > start else { return value >= end ? 1 : 0 } + return min(max((value - start) / (end - start), 0), 1) + } + + // MARK: - 几何判定与插值 + + /// 封面区域是否仍在可见视口内(允许略微超出边缘 `margin`)。 + public static func isRectVisible( + _ rect: Rect, + in viewport: Size, + margin: Double = 24 + ) -> Bool { + guard rect.isValid, viewport.isValid else { return false } + let safeMargin = max(0, margin) + return rect.maxX > -safeMargin + && rect.minX < viewport.width + safeMargin + && rect.maxY > -safeMargin + && rect.minY < viewport.height + safeMargin + } + + /// 这次钻取是否具备执行共享封面飞行的条件;否则无缝退化为纯钻取淡入淡出。 + public static func shouldFlyCover( + source: Rect?, + destination: Rect?, + viewport: Size, + reduceMotion: Bool + ) -> Bool { + guard !reduceMotion, let source, let destination else { return false } + return isRectVisible(source, in: viewport) + && isRectVisible(destination, in: viewport) + } + + /// 计算底层总览潜入/收拢的缩放锚点:锁定在被点击封面的中心,边缘夹在 [0.15, 0.85] 避免极端偏心。 + public static func overviewAnchor(source: Rect?, viewport: Size) -> Anchor { + guard let source, source.isValid, viewport.isValid else { return .center } + let x = min(max(source.midX / viewport.width, 0.15), 0.85) + let y = min(max(source.midY / viewport.height, 0.15), 0.85) + return Anchor(x: x, y: y) + } + + /// 飞行封面在已缓动进度 `progress`(0 = 起点,1 = 终点)处的几何、圆角、阴影与高光描边。 + public static func coverFrame( + from: Rect, + to: Rect, + fromCornerRadius: Double, + toCornerRadius: Double, + progress: Double + ) -> CoverFrame { + let clamped = progress.isFinite ? min(max(progress, 0), 1) : 0 + let width = max(1, from.width + (to.width - from.width) * clamped) + let height = max(1, from.height + (to.height - from.height) * clamped) + let x = from.x + (to.x - from.x) * clamped + let linearY = from.y + (to.y - from.y) * clamped + + let distance = hypot(to.midX - from.midX, to.midY - from.midY) + let arcWave = (clamped <= 0 || clamped >= 1) ? 0 : sin(Double.pi * clamped) + let arcLift = min(maxGravityArcLift, distance * gravityArcRatio) * arcWave + + let radius = max(0, fromCornerRadius + (toCornerRadius - fromCornerRadius) * clamped) + let shadowRadius = restingShadowRadius + (flightShadowRadius - restingShadowRadius) * arcWave + let shadowOpacity = restingShadowOpacity + (flightShadowOpacity - restingShadowOpacity) * arcWave + let borderOpacity = flightBorderHighlightOpacity * arcWave + + return CoverFrame( + rect: Rect(x: x, y: linearY - arcLift, width: width, height: height), + cornerRadius: radius, + shadowRadius: shadowRadius, + shadowOpacity: shadowOpacity, + borderHighlightOpacity: borderOpacity + ) + } + + /// 总览层与详情三层(氛围底图、页头信息、曲目内容)在归一化时间 `rawProgress ∈ [0, 1]` 时的变换。 + public static func layerFrame( + direction: Direction, + progress rawProgress: Double, + hasCoverFlight: Bool, + reduceMotion: Bool + ) -> LayerFrame { + let t = rawProgress.isFinite ? min(max(rawProgress, 0), 1) : 0 + if reduceMotion { + let fade = direction == .drillIn ? t : (1 - t) + return LayerFrame( + overviewScale: 1, + overviewOpacity: 1 - fade, + detailBackdropOpacity: fade, + detailHeaderOpacity: fade, + detailHeaderOffsetX: 0, + detailContentOpacity: fade, + detailContentOffsetY: 0, + hidesSourceArtwork: false, + hidesDestinationArtwork: false + ) + } + + let inFlight = hasCoverFlight && t < 1 + switch direction { + case .drillIn: + let eased = enterEase(t) + let overviewScale = 1 + (overviewZoomInScale - 1) * eased + let overviewOpacity = 1 - remap(t, start: 0.0, end: 0.48) + + let backdropOpacity = contentEase(remap(t, start: 0.0, end: 0.56)) + let headerT = contentEase(remap(t, start: 0.14, end: 0.78)) + let contentT = contentEase(remap(t, start: 0.22, end: 0.96)) + return LayerFrame( + overviewScale: overviewScale, + overviewOpacity: overviewOpacity, + detailBackdropOpacity: backdropOpacity, + detailHeaderOpacity: headerT, + detailHeaderOffsetX: detailHeaderEnterOffsetX * (1 - headerT), + detailContentOpacity: contentT, + detailContentOffsetY: detailEnterOffsetY * (1 - contentT), + hidesSourceArtwork: inFlight, + hidesDestinationArtwork: inFlight + ) + + case .drillOut: + let eased = exitEase(t) + let overviewScale = overviewZoomInScale - (overviewZoomInScale - 1) * eased + let overviewOpacity = contentEase(remap(t, start: 0.10, end: 0.70)) + + let backdropOpacity = 1 - remap(t, start: 0.0, end: 0.44) + let headerOut = remap(t, start: 0.0, end: 0.30) + let contentOut = remap(t, start: 0.0, end: 0.34) + return LayerFrame( + overviewScale: overviewScale, + overviewOpacity: overviewOpacity, + detailBackdropOpacity: backdropOpacity, + detailHeaderOpacity: 1 - headerOut, + detailHeaderOffsetX: detailHeaderExitOffsetX * headerOut, + detailContentOpacity: 1 - contentOut, + detailContentOffsetY: detailExitOffsetY * contentOut, + hidesSourceArtwork: inFlight, + hidesDestinationArtwork: inFlight + ) + } + } + + /// iOS 详情页下拉过卷时的弹性头图变换:顶部紧贴屏顶不露缝,封面随下拉阻力放大延伸。 + public static func heroOverscrollFrame( + pullOffset: Double, + heroHeight: Double, + reduceMotion: Bool + ) -> HeroOverscrollFrame { + guard !reduceMotion, + pullOffset.isFinite, heroHeight.isFinite, + pullOffset > 0, heroHeight > 1 else { + return HeroOverscrollFrame(scale: 1, offsetY: 0) + } + let maxExtra = heroHeight * heroOverscrollMaxStretch + // 阻尼曲线:前段跟手 1:1,继续拉时柔和趋近上限。 + let dampedExtra = maxExtra * (1 - exp(-pullOffset / maxExtra)) + let scale = 1 + dampedExtra / heroHeight + return HeroOverscrollFrame(scale: scale, offsetY: -pullOffset) + } + + /// 静止、入场、退场状态机:支持进场中途按实时空中坐标无缝折返,并防止过期完成回调串台。 + public struct State: Equatable, Sendable { + public private(set) var presentedID: String? + public private(set) var phase: Phase = .idle + public private(set) var flightID: String? + public private(set) var sourceRect: Rect? + public private(set) var destinationRect: Rect? + public private(set) var exitStartRect: Rect? + public private(set) var sourceCornerRadius: Double = 8 + public private(set) var destinationCornerRadius: Double = 12 + public private(set) var exitStartCornerRadius: Double = 12 + public private(set) var generation: UInt64 = 0 + + public init() {} + + public var isShowingDetail: Bool { + presentedID != nil && phase != .idle + } + + public var isTransitioning: Bool { + phase == .entering || phase == .exiting + } + + /// 当前阶段实际用于飞行插值的起点矩形。 + public var activeFlightFromRect: Rect? { + phase == .entering ? sourceRect : (exitStartRect ?? destinationRect) + } + + /// 当前阶段实际用于飞行插值的终点矩形。 + public var activeFlightToRect: Rect? { + phase == .entering ? destinationRect : sourceRect + } + + public var activeFlightFromRadius: Double { + phase == .entering ? sourceCornerRadius : exitStartCornerRadius + } + + public var activeFlightToRadius: Double { + phase == .entering ? destinationCornerRadius : sourceCornerRadius + } + + @discardableResult + public mutating func beginEnter( + id: String, + sourceRect: Rect?, + destinationRect: Rect? = nil, + sourceCornerRadius: Double = 8, + destinationCornerRadius: Double = 12 + ) -> UInt64 { + generation &+= 1 + presentedID = id + flightID = id + phase = .entering + self.sourceRect = sourceRect + self.destinationRect = destinationRect + self.exitStartRect = nil + self.sourceCornerRadius = sourceCornerRadius + self.destinationCornerRadius = destinationCornerRadius + self.exitStartCornerRadius = destinationCornerRadius + return generation + } + + public mutating func updateDestinationRect(_ rect: Rect, for id: String) { + guard flightID == id || presentedID == id, rect.isValid else { return } + destinationRect = rect + } + + @discardableResult + public mutating func completeEnter(generation: UInt64) -> Bool { + guard self.generation == generation, phase == .entering else { return false } + phase = .presented + flightID = nil + return true + } + + @discardableResult + public mutating func beginExit( + fromCurrentCoverRect: Rect? = nil, + fromCurrentCornerRadius: Double? = nil, + sourceRect: Rect?, + destinationRect: Rect?, + sourceCornerRadius: Double? = nil, + destinationCornerRadius: Double? = nil + ) -> (id: String, generation: UInt64)? { + guard let id = presentedID, phase == .presented || phase == .entering else { return nil } + let wasEntering = phase == .entering + generation &+= 1 + phase = .exiting + flightID = id + if let sourceRect { self.sourceRect = sourceRect } + if let destinationRect { self.destinationRect = destinationRect } + if let sourceCornerRadius { self.sourceCornerRadius = sourceCornerRadius } + if let destinationCornerRadius { self.destinationCornerRadius = destinationCornerRadius } + if wasEntering, let liveRect = fromCurrentCoverRect, liveRect.isValid { + self.exitStartRect = liveRect + self.exitStartCornerRadius = fromCurrentCornerRadius ?? self.destinationCornerRadius + } else { + self.exitStartRect = self.destinationRect + self.exitStartCornerRadius = self.destinationCornerRadius + } + return (id, generation) + } + + @discardableResult + public mutating func completeExit(generation: UInt64) -> Bool { + guard self.generation == generation, phase == .exiting else { return false } + reset() + return true + } + + public mutating func reset() { + generation &+= 1 + presentedID = nil + phase = .idle + flightID = nil + sourceRect = nil + destinationRect = nil + exitStartRect = nil + } + + public func shouldHideArtwork( + id: String, + viewport: Size, + reduceMotion: Bool + ) -> Bool { + guard isTransitioning, flightID == id else { return false } + return FluentDrillTransitionPolicy.shouldFlyCover( + source: activeFlightFromRect, + destination: activeFlightToRect, + viewport: viewport, + reduceMotion: reduceMotion + ) + } + } +} diff --git a/PrimuseKit/Tests/PrimuseKitTests/Interface/FluentDrillTransitionPolicyTests.swift b/PrimuseKit/Tests/PrimuseKitTests/Interface/FluentDrillTransitionPolicyTests.swift new file mode 100644 index 000000000..36a3bc6e6 --- /dev/null +++ b/PrimuseKit/Tests/PrimuseKitTests/Interface/FluentDrillTransitionPolicyTests.swift @@ -0,0 +1,208 @@ +import Testing +import PrimuseKit + +@Suite("FluentDrillTransitionPolicy") +struct FluentDrillTransitionPolicyTests { + private let viewport = FluentDrillTransitionPolicy.Size(width: 1200, height: 800) + private let source = FluentDrillTransitionPolicy.Rect(x: 420, y: 340, width: 170, height: 170) + private let destination = FluentDrillTransitionPolicy.Rect(x: 36, y: 20, width: 196, height: 196) + + @Test("Fluent 2 cubic-bezier curves launch fast, remain monotonic, and land with zero overshoot") + func fluentCurvesLaunchFastWithZeroOvershoot() { + #expect(FluentDrillTransitionPolicy.enterEase(0) == 0) + #expect(FluentDrillTransitionPolicy.enterEase(1) == 1) + #expect(FluentDrillTransitionPolicy.exitEase(0) == 0) + #expect(FluentDrillTransitionPolicy.exitEase(1) == 1) + + // Fast initial takeoff: at 35% elapsed time, Fluent 2 has already crossed 70% of travel. + #expect(FluentDrillTransitionPolicy.enterEase(0.35) > 0.70) + #expect(FluentDrillTransitionPolicy.exitEase(0.35) > 0.65) + + var prevEnter = -1.0 + var prevExit = -1.0 + for step in 0...40 { + let t = Double(step) / 40.0 + let eIn = FluentDrillTransitionPolicy.enterEase(t) + let eOut = FluentDrillTransitionPolicy.exitEase(t) + #expect(eIn >= prevEnter && eIn <= 1.0) + #expect(eOut >= prevExit && eOut <= 1.0) + prevEnter = eIn + prevExit = eOut + } + } + + @Test("Cover flight interpolates exact endpoints, lifts along a gravity arc, and shows specular rim mid-flight") + func coverFlightInterpolatesEndpointsArcAndSpecularRim() { + let start = FluentDrillTransitionPolicy.coverFrame( + from: source, to: destination, fromCornerRadius: 8, toCornerRadius: 12, progress: 0 + ) + let mid = FluentDrillTransitionPolicy.coverFrame( + from: source, to: destination, fromCornerRadius: 8, toCornerRadius: 12, progress: 0.5 + ) + let end = FluentDrillTransitionPolicy.coverFrame( + from: source, to: destination, fromCornerRadius: 8, toCornerRadius: 12, progress: 1 + ) + + #expect(start.rect == source) + #expect(start.cornerRadius == 8) + #expect(start.borderHighlightOpacity == 0) + #expect(end.rect == destination) + #expect(end.cornerRadius == 12) + #expect(end.borderHighlightOpacity == 0) + + let linearMidY = (source.y + destination.y) / 2 + #expect(mid.rect.y < linearMidY) + #expect(mid.shadowRadius > start.shadowRadius) + #expect(mid.shadowOpacity > start.shadowOpacity) + #expect(mid.borderHighlightOpacity > 0.2) + } + + @Test("Cover flight degrades cleanly when reduce motion is on or a rect scrolled off-screen") + func coverFlightVisibilityAndReduceMotionGuard() { + #expect(FluentDrillTransitionPolicy.shouldFlyCover( + source: source, destination: destination, viewport: viewport, reduceMotion: false + )) + #expect(!FluentDrillTransitionPolicy.shouldFlyCover( + source: source, destination: destination, viewport: viewport, reduceMotion: true + )) + + let scrolledOffTop = FluentDrillTransitionPolicy.Rect(x: 36, y: -260, width: 196, height: 196) + #expect(!FluentDrillTransitionPolicy.shouldFlyCover( + source: source, destination: scrolledOffTop, viewport: viewport, reduceMotion: false + )) + #expect(!FluentDrillTransitionPolicy.shouldFlyCover( + source: nil, destination: destination, viewport: viewport, reduceMotion: false + )) + } + + @Test("Overview anchor tracks clicked tile center and clamps safely inside viewport") + func overviewAnchorClampsToSafeBounds() { + let centered = FluentDrillTransitionPolicy.overviewAnchor(source: source, viewport: viewport) + #expect(abs(centered.x - source.midX / viewport.width) < 0.001) + #expect(abs(centered.y - source.midY / viewport.height) < 0.001) + + let corner = FluentDrillTransitionPolicy.Rect(x: 4, y: 4, width: 40, height: 40) + let clamped = FluentDrillTransitionPolicy.overviewAnchor(source: corner, viewport: viewport) + #expect(clamped.x == 0.15) + #expect(clamped.y == 0.15) + } + + @Test("Drill-in dives overview outward without edge gaps and staggers Fluent Continuum detail layers") + func drillInAndDrillOutContinuumChoreography() { + let enterStart = FluentDrillTransitionPolicy.layerFrame( + direction: .drillIn, progress: 0, hasCoverFlight: true, reduceMotion: false + ) + let enterMid = FluentDrillTransitionPolicy.layerFrame( + direction: .drillIn, progress: 0.35, hasCoverFlight: true, reduceMotion: false + ) + let enterEnd = FluentDrillTransitionPolicy.layerFrame( + direction: .drillIn, progress: 1, hasCoverFlight: true, reduceMotion: false + ) + + #expect(enterStart.overviewScale == 1) + #expect(enterStart.overviewOpacity == 1) + #expect(enterStart.detailBackdropOpacity == 0) + #expect(enterStart.detailHeaderOffsetX < 0) + #expect(enterStart.detailContentOffsetY > 0) + #expect(enterStart.hidesSourceArtwork) + #expect(enterStart.hidesDestinationArtwork) + + // Dive-in overview scales >= 1.0 (never shrinks inside viewport borders). + #expect(enterMid.overviewScale > 1.0) + // Continuum stagger: backdrop leads header, header leads tracklist content. + #expect(enterMid.detailBackdropOpacity > enterMid.detailHeaderOpacity) + #expect(enterMid.detailHeaderOpacity > enterMid.detailContentOpacity) + + #expect(enterEnd.overviewOpacity == 0) + #expect(enterEnd.detailBackdropOpacity == 1) + #expect(enterEnd.detailHeaderOpacity == 1) + #expect(enterEnd.detailHeaderOffsetX == 0) + #expect(enterEnd.detailContentOpacity == 1) + #expect(enterEnd.detailContentOffsetY == 0) + #expect(!enterEnd.hidesSourceArtwork) + #expect(!enterEnd.hidesDestinationArtwork) + + // Drill-out clears header & content rapidly in the first third so solo cover owns the stage. + let exitQuickClear = FluentDrillTransitionPolicy.layerFrame( + direction: .drillOut, progress: 0.35, hasCoverFlight: true, reduceMotion: false + ) + #expect(exitQuickClear.detailHeaderOpacity == 0) + #expect(exitQuickClear.detailContentOpacity == 0) + #expect(exitQuickClear.overviewScale >= 1.0) + #expect(exitQuickClear.overviewOpacity > 0.3) + + let exitEnd = FluentDrillTransitionPolicy.layerFrame( + direction: .drillOut, progress: 1, hasCoverFlight: true, reduceMotion: false + ) + #expect(exitEnd.overviewScale == 1) + #expect(exitEnd.overviewOpacity == 1) + #expect(exitEnd.detailBackdropOpacity == 0) + } + + @Test("Reduce motion falls back to pure crossfade without scaling, offsets, or hiding artwork") + func reduceMotionPureCrossfade() { + let mid = FluentDrillTransitionPolicy.layerFrame( + direction: .drillIn, progress: 0.5, hasCoverFlight: true, reduceMotion: true + ) + #expect(mid.overviewScale == 1) + #expect(mid.detailHeaderOffsetX == 0) + #expect(mid.detailContentOffsetY == 0) + #expect(mid.overviewOpacity == 0.5) + #expect(mid.detailBackdropOpacity == 0.5) + #expect(mid.detailHeaderOpacity == 0.5) + #expect(mid.detailContentOpacity == 0.5) + #expect(!mid.hidesSourceArtwork) + #expect(!mid.hidesDestinationArtwork) + } + + @Test("State machine handles mid-enter live mid-air interruption and ignores stale generations") + func stateMachineMidAirInterruptionAndGenerationGuard() { + var state = FluentDrillTransitionPolicy.State() + let enterGen = state.beginEnter(id: "album-1", sourceRect: source, destinationRect: destination) + #expect(state.phase == .entering) + #expect(state.isShowingDetail) + #expect(state.activeFlightFromRect == source) + #expect(state.activeFlightToRect == destination) + + let midAir = FluentDrillTransitionPolicy.Rect(x: 210, y: 170, width: 184, height: 184) + let exit = state.beginExit( + fromCurrentCoverRect: midAir, + fromCurrentCornerRadius: 10, + sourceRect: nil, + destinationRect: nil + ) + #expect(exit != nil) + #expect(state.phase == .exiting) + #expect(state.activeFlightFromRect == midAir) + #expect(state.activeFlightToRect == source) + #expect(state.activeFlightFromRadius == 10) + + let staleEnterCompleted = state.completeEnter(generation: enterGen) + #expect(!staleEnterCompleted) + #expect(state.phase == .exiting) + + let exitCompleted = state.completeExit(generation: exit!.generation) + #expect(exitCompleted) + #expect(state.phase == .idle) + #expect(!state.isShowingDetail) + } + + @Test("Hero overscroll stretch scales smoothly with damping and stays identity when not pulling down") + func heroOverscrollStretchBehavior() { + let idle = FluentDrillTransitionPolicy.heroOverscrollFrame(pullOffset: 0, heroHeight: 400, reduceMotion: false) + let scrolledUp = FluentDrillTransitionPolicy.heroOverscrollFrame(pullOffset: -120, heroHeight: 400, reduceMotion: false) + #expect(idle.scale == 1 && idle.offsetY == 0) + #expect(scrolledUp.scale == 1 && scrolledUp.offsetY == 0) + + let pulledSmall = FluentDrillTransitionPolicy.heroOverscrollFrame(pullOffset: 40, heroHeight: 400, reduceMotion: false) + let pulledLarge = FluentDrillTransitionPolicy.heroOverscrollFrame(pullOffset: 300, heroHeight: 400, reduceMotion: false) + #expect(pulledSmall.scale > 1.05 && pulledSmall.scale < 1.12) + #expect(pulledLarge.scale > pulledSmall.scale) + #expect(pulledLarge.scale < 1 + FluentDrillTransitionPolicy.heroOverscrollMaxStretch) + #expect(pulledSmall.offsetY == -40) + #expect(pulledLarge.offsetY == -300) + + let reduced = FluentDrillTransitionPolicy.heroOverscrollFrame(pullOffset: 100, heroHeight: 400, reduceMotion: true) + #expect(reduced.scale == 1 && reduced.offsetY == 0) + } +}