From ab108cb728e0c9ce81158c2878254948a92f084b Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:29:40 +0900 Subject: [PATCH 01/25] =?UTF-8?q?[Feat]=20#283=20-=20=EC=A0=84=EC=B2=B4=20?= =?UTF-8?q?=EA=B3=B5=EA=B0=9C=20=EC=BB=AC=EB=A0=89=EC=85=98=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=20=EC=A1=B0=ED=9A=8C=20UseCase=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 작성자(owner)를 함께 보여줘야 해서 CollectionCard에 얹지 않고 PublicCollectionCard를 따로 둔다. 서버(GET /collections)가 전체 개수를 주지 않아 다른 목록과 달리 커서 페이지만 돌려준다. Co-Authored-By: Claude Opus 5.5 --- Projects/Domain/CollectionDomain/CLAUDE.md | 3 + .../Sources/Entity/PublicCollectionCard.swift | 48 +++++++++ .../Repository/CollectionRepository.swift | 10 ++ .../LoadPublicCollectionsUseCase.swift | 31 ++++++ .../Mock/MockCollectionRepository.swift | 10 ++ .../LoadPublicCollectionsUseCaseTests.swift | 100 ++++++++++++++++++ 6 files changed, 202 insertions(+) create mode 100644 Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift create mode 100644 Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift create mode 100644 Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift diff --git a/Projects/Domain/CollectionDomain/CLAUDE.md b/Projects/Domain/CollectionDomain/CLAUDE.md index 25a76bd27..425bfcb81 100644 --- a/Projects/Domain/CollectionDomain/CLAUDE.md +++ b/Projects/Domain/CollectionDomain/CLAUDE.md @@ -59,3 +59,6 @@ 상한은 `addNovel`과 같은 `novelOverLimit` throw(선택 화면이 UI에서 이미 100개로 막아두므로 실사용 경로는 아니지만, "사용자 입력은 거부"라는 `updateName` 방침과 일관되게 clamp 대신 throw를 골랐다). 대표 작품이 새 목록에서 빠지면 `removeNovel`과 동일하게 대표 지정도 함께 풀린다. +- **공개 컬렉션 목록(홈 섹션·전체 컬렉션뷰, #283)은 `PublicCollectionCard`를 따로 쓴다** — 작성자(`owner: Author`)가 필요한데 + 위 권고대로 `CollectionCard`에 얹지 않았다. 공개 목록만 오므로 `isPrivate`이 없고, 서버(`GET /collections`)가 전체 개수를 + 주지 않아 `fetchPublicCollections`는 다른 목록과 달리 `(페이지, 개수)` 튜플이 아니라 페이지만 돌려준다. diff --git a/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift b/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift new file mode 100644 index 000000000..cd04108c1 --- /dev/null +++ b/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift @@ -0,0 +1,48 @@ +// +// PublicCollectionCard.swift +// CollectionDomain +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation + +import BaseDomain + +/// 홈 컬렉션 섹션·전체 컬렉션뷰의 카드. 모든 사용자의 공개 컬렉션을 작성자 프로필과 함께 보여준다. +/// +/// `CollectionCard`에 `owner`를 옵셔널로 얹지 않고 따로 둔 이유: 사용자별·좋아요 목록은 작성자를 쓰지 않아 +/// 두 목록이 같은 카드를 공유하는 구조가 깨진다. 공개 목록만 공개 컬렉션이 오므로 `isPrivate`도 없다. +public struct PublicCollectionCard: Sendable { + + public let id: CollectionID + public let name: String + + /// 없으면 nil. + public let description: String? + + /// 컬렉션에 든 **전체** 작품 수. `recentNovels.count`가 아니다(미리보기는 최대 5개뿐). + public let novelCount: Int + + /// 저장된 표시 순서 앞에서부터 최대 5개. 홈 섹션은 앞 4개만 쓴다. + public let recentNovels: [CollectionNovel] + + public let owner: Author + + public init( + id: CollectionID, + name: String, + description: String?, + novelCount: Int, + recentNovels: [CollectionNovel], + owner: Author + ) { + self.id = id + self.name = name + self.description = description + self.novelCount = novelCount + self.recentNovels = recentNovels + self.owner = owner + } +} diff --git a/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift b/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift index 0bc2405df..fbb948d63 100644 --- a/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift +++ b/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift @@ -41,6 +41,16 @@ public protocol CollectionRepository: Sendable { size: Int ) async throws(RepositoryError) -> (CursorPaginated, Int) + /// 모든 사용자의 공개 컬렉션 목록. 최초 생성 시점 최신순(수정·좋아요로 순서가 바뀌지 않는다). + /// + /// 조회자 본인의 비공개 컬렉션은 오지 않고, 로그인 상태면 차단 관계 작성자의 컬렉션이 빠진다. + /// 서버가 전체 개수를 주지 않아 다른 목록과 달리 커서 페이지만 돌려준다. + /// - Parameter cursor: 직전 응답의 `nextCursor`. 첫 페이지는 nil. + func fetchPublicCollections( + cursor: String?, + size: Int + ) async throws(RepositoryError) -> CursorPaginated + /// 컬렉션 상세. 작품은 페이지네이션 없이 전부 내려온다. /// - Parameter sortType: 작품 정렬. `.recent`는 저장된 표시 순서 그대로, `.old`는 그 역순. func fetchCollectionDetail( diff --git a/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift new file mode 100644 index 000000000..9b036bfcd --- /dev/null +++ b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift @@ -0,0 +1,31 @@ +// +// LoadPublicCollectionsUseCase.swift +// CollectionDomain +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation + +import BaseDomain + +public protocol LoadPublicCollectionsUseCase: Sendable { + /// 모든 사용자의 공개 컬렉션을 최신순으로 가져온다. + /// 홈 섹션은 첫 페이지만(`size` 10), 전체 컬렉션뷰는 커서로 이어서 부른다. + /// - Parameter cursor: 직전 응답의 `nextCursor`. 첫 페이지는 nil. + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated +} + +public final class DefaultLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { + + private let collectionRepository: CollectionRepository + + public init(collectionRepository: CollectionRepository) { + self.collectionRepository = collectionRepository + } + + public func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + try await collectionRepository.fetchPublicCollections(cursor: cursor, size: size) + } +} diff --git a/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift b/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift index 2f28fc6b3..8e5e3bf87 100644 --- a/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift +++ b/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift @@ -18,6 +18,7 @@ public final class MockCollectionRepository: CollectionRepository { public var fetchCollectionPreviewsResult: Result<([CollectionPreview], Int), RepositoryError>! public var fetchCollectionsResult: Result<(CursorPaginated, Int), RepositoryError>! public var fetchLikedCollectionsResult: Result<(CursorPaginated, Int), RepositoryError>! + public var fetchPublicCollectionsResult: Result, RepositoryError>! public var fetchCollectionDetailResult: Result! public var createCollectionResult: Result! public var updateCollectionResult: Result = .success(()) @@ -30,6 +31,7 @@ public final class MockCollectionRepository: CollectionRepository { public private(set) var fetchedPreviewRequests: [(userID: UserID, size: Int)] = [] public private(set) var fetchedCollectionRequests: [(userID: UserID, cursor: String?, size: Int)] = [] public private(set) var fetchedLikedRequests: [(cursor: String?, size: Int)] = [] + public private(set) var fetchedPublicRequests: [(cursor: String?, size: Int)] = [] public private(set) var fetchedDetailRequests: [(id: CollectionID, sortType: SortType)] = [] public private(set) var createdDrafts: [CollectionDraft] = [] public private(set) var updatedRequests: [(id: CollectionID, draft: CollectionDraft)] = [] @@ -66,6 +68,14 @@ public final class MockCollectionRepository: CollectionRepository { return try fetchLikedCollectionsResult.get() } + public func fetchPublicCollections( + cursor: String?, + size: Int + ) async throws(RepositoryError) -> CursorPaginated { + fetchedPublicRequests.append((cursor, size)) + return try fetchPublicCollectionsResult.get() + } + public func fetchCollectionDetail( id: CollectionID, sortType: SortType diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift new file mode 100644 index 000000000..e1d42bf41 --- /dev/null +++ b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift @@ -0,0 +1,100 @@ +// +// LoadPublicCollectionsUseCaseTests.swift +// CollectionDomainTests +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Testing +import Foundation + +@testable import CollectionDomain +import CollectionDomainTesting +import BaseDomain + +@Suite("LoadPublicCollectionsUseCase") +struct LoadPublicCollectionsUseCaseTests { + + @Test("공개 컬렉션 목록을 작성자와 함께 불러온다") + func loadSuccess() async throws { + let mock = MockCollectionRepository() + mock.fetchPublicCollectionsResult = .success(makePage(cardCount: 3)) + let useCase = DefaultLoadPublicCollectionsUseCase(collectionRepository: mock) + + let page = try await useCase.execute(cursor: nil, size: 10) + + #expect(page.items.count == 3) + #expect(page.items.first?.owner.nickname == "작성자") + } + + @Test("서버가 준 순서를 바꾸지 않고 그대로 돌려준다") + func preservesServerOrder() async throws { + let mock = MockCollectionRepository() + mock.fetchPublicCollectionsResult = .success(makePage(cardCount: 3)) + let useCase = DefaultLoadPublicCollectionsUseCase(collectionRepository: mock) + + let page = try await useCase.execute(cursor: nil, size: 10) + + #expect(page.items.map(\.id) == [CollectionID(0), CollectionID(1), CollectionID(2)]) + } + + @Test("커서와 개수를 그대로 넘겨 다음 페이지를 잇는다") + func passesCursorAndSizeAsIs() async throws { + let mock = MockCollectionRepository() + mock.fetchPublicCollectionsResult = .success(makePage()) + let useCase = DefaultLoadPublicCollectionsUseCase(collectionRepository: mock) + + _ = try await useCase.execute(cursor: "server-issued-cursor", size: 20) + + #expect(mock.fetchedPublicRequests.count == 1) + #expect(mock.fetchedPublicRequests.last?.cursor == "server-issued-cursor") + #expect(mock.fetchedPublicRequests.last?.size == 20) + } + + @Test("다음 페이지 여부와 커서를 그대로 전달한다") + func passesPagingInfo() async throws { + let mock = MockCollectionRepository() + mock.fetchPublicCollectionsResult = .success(makePage(hasNext: true, nextCursor: "next")) + let useCase = DefaultLoadPublicCollectionsUseCase(collectionRepository: mock) + + let page = try await useCase.execute(cursor: nil, size: 10) + + #expect(page.hasNext) + #expect(page.nextCursor == "next") + } + + @Test("조회에 실패하면 에러를 그대로 전달한다") + func loadFailure() async { + let mock = MockCollectionRepository() + mock.fetchPublicCollectionsResult = .failure(.networkUnavailable) + let useCase = DefaultLoadPublicCollectionsUseCase(collectionRepository: mock) + + await #expect(throws: RepositoryError.networkUnavailable) { + try await useCase.execute(cursor: nil, size: 10) + } + } +} + +private extension LoadPublicCollectionsUseCaseTests { + func makePage( + cardCount: Int = 1, + hasNext: Bool = false, + nextCursor: String? = nil + ) -> CursorPaginated { + CursorPaginated( + items: (0.. Date: Mon, 12 Oct 2026 14:29:46 +0900 Subject: [PATCH 02/25] =?UTF-8?q?[Network]=20#283=20-=20=EC=A0=84=EC=B2=B4?= =?UTF-8?q?=20=EA=B3=B5=EA=B0=9C=20=EC=BB=AC=EB=A0=89=EC=85=98=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=20API=20=EC=97=B0=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET /collections는 비로그인도 조회할 수 있고 토큰이 있으면 차단 작성자를 빼므로 usesTokenIfAvailable로 둔다. 응답에 collectionsCount·isPublic·대표 작품이 없고 owner가 있어 CollectionsResponse를 재사용하지 않고 DTO를 분리했다. Co-Authored-By: Claude Opus 5.5 --- Projects/Data/CollectionData/CLAUDE.md | 6 +++- .../Response/PublicCollectionsResponse.swift | 36 +++++++++++++++++++ .../Sources/Endpoint/CollectionEndpoint.swift | 11 ++++-- .../Sources/Logger/CollectionAction.swift | 2 ++ .../Sources/Mapper/CollectionMapper.swift | 34 +++++++++++++++--- .../DefaultCollectionRepository.swift | 25 +++++++++++++ .../Sources/Service/CollectionService.swift | 1 + .../Service/DefaultCollectionService.swift | 7 ++++ docs/PENDING_DECISIONS.md | 3 +- 9 files changed, 115 insertions(+), 10 deletions(-) create mode 100644 Projects/Data/CollectionData/Sources/DTO/Response/PublicCollectionsResponse.swift diff --git a/Projects/Data/CollectionData/CLAUDE.md b/Projects/Data/CollectionData/CLAUDE.md index 62866236c..7c2c6b12e 100644 --- a/Projects/Data/CollectionData/CLAUDE.md +++ b/Projects/Data/CollectionData/CLAUDE.md @@ -33,5 +33,9 @@ Mapper만 갈린다(`collectionPreviews` / `collectionCards`). 엔드포인트를 추가하기 전에 Mapper로 해결되는지 먼저 볼 것. - **Demo 앱은 `TEST_API_KEY`(`Config_Debug.xcconfig`)로 인증한다.** 만료되면 모든 호출이 `AUTH-000`으로 실패한다 — Demo가 안 될 때 코드부터 의심하지 말고 토큰부터 확인할 것. 갱신 방법은 `/api-spec` 스킬 문서에 있다. -- 컬렉션 상세만 `usesTokenIfAvailable`이다(공유 링크로 들어온 비로그인 조회자에게도 내려간다). 나머지는 `requireToken` — +- 컬렉션 상세와 전체 공개 목록(`GET /collections`)만 `usesTokenIfAvailable`이다(비로그인도 조회 가능 — 공개 목록은 토큰이 + 있으면 차단 관계 작성자를 빼므로 있으면 붙인다). 나머지는 `requireToken` — 목록 API의 비로그인 허용 여부는 서버 명세에 명시가 없어 보수적으로 잡아뒀다. 비로그인 진입 경로가 생기면 그때 확인해 바꾼다. +- **전체 공개 목록은 `CollectionsResponse`를 재사용하지 않고 `PublicCollectionsResponse`를 따로 둔다** — 같은 `nextCursor`·`hasNext` + 구조지만 `collectionsCount`·`isPublic`·`representativeNovel`이 없고 `owner`가 있어, 공용 DTO에 optional을 늘리면 기존 + 두 목록의 필수값 디코딩 검증이 약해진다. 커서는 목록마다 서버가 따로 발급한다(다른 목록 커서를 넣으면 `COLLECTION-007`). diff --git a/Projects/Data/CollectionData/Sources/DTO/Response/PublicCollectionsResponse.swift b/Projects/Data/CollectionData/Sources/DTO/Response/PublicCollectionsResponse.swift new file mode 100644 index 000000000..918efa00e --- /dev/null +++ b/Projects/Data/CollectionData/Sources/DTO/Response/PublicCollectionsResponse.swift @@ -0,0 +1,36 @@ +// +// PublicCollectionsResponse.swift +// CollectionData +// +// Created by Guryss on 10/12/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation + +/// 전체 공개 컬렉션 목록(`GET /collections`) 응답. +/// +/// 사용자별·좋아요 목록(`CollectionsResponse`)과 달리 `collectionsCount`·`isPublic`·`representativeNovel`이 없고 +/// `owner`가 있어 DTO를 따로 둔다. +struct PublicCollectionsResponse: Decodable { + public let collections: [PublicCollectionCardResponse] + public let hasNext: Bool + + /// hasNext가 false면 null이다. + public let nextCursor: String? +} + +struct PublicCollectionCardResponse: Decodable { + public let collectionId: Int + public let collectionName: String + public let collectionDescription: String? + + /// 컬렉션에 든 전체 작품 수. `recentNovels`의 개수가 아니다. + public let novelCount: Int + + /// 저장된 표시 순서 앞에서부터 최대 5개. 실제 작품만 담아 5개보다 적을 수 있다. + public let recentNovels: [CollectionNovelResponse] + + /// 컬렉션 상세의 owner와 같은 구조. 탈퇴한 사용자는 알 수 없는 사용자 프로필로 온다. + public let owner: CollectionOwnerResponse +} diff --git a/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift b/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift index b83fc70df..4a262134c 100644 --- a/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift +++ b/Projects/Data/CollectionData/Sources/Endpoint/CollectionEndpoint.swift @@ -20,6 +20,7 @@ enum CollectionEndpoint: Endpoint { case deleteCollectionLike(collectionID: Int) case getUserCollections(userID: Int, CollectionsQuery) case getLikedCollections(CollectionsQuery) + case getPublicCollections(CollectionsQuery) var baseURL: URL { URL(string: NetworkingConfig.baseURL) ?? URL(string: "")! @@ -27,7 +28,7 @@ enum CollectionEndpoint: Endpoint { var path: String { switch self { - case .postCollection: + case .postCollection, .getPublicCollections: return "/collections" case .getCollectionDetail(let collectionID, _), .putCollection(let collectionID, _), @@ -47,7 +48,7 @@ enum CollectionEndpoint: Endpoint { switch self { case .postCollection: return .post - case .getCollectionDetail, .getUserCollections, .getLikedCollections: + case .getCollectionDetail, .getUserCollections, .getLikedCollections, .getPublicCollections: return .get case .putCollection, .putCollectionLike: return .put @@ -62,7 +63,8 @@ enum CollectionEndpoint: Endpoint { return .convertible(query) case .getUserCollections(_, let query): return .convertible(query) - case .getLikedCollections(let query): + case .getLikedCollections(let query), + .getPublicCollections(let query): return .convertible(query) default: return .none @@ -85,6 +87,9 @@ enum CollectionEndpoint: Endpoint { // 토큰이 있으면 isMyCollection·isLiked가 채워지므로 있으면 붙인다. case .getCollectionDetail: return .usesTokenIfAvailable + // 비로그인도 조회할 수 있고, 토큰이 있으면 차단 관계 작성자의 컬렉션이 빠진다. + case .getPublicCollections: + return .usesTokenIfAvailable default: return .requireToken } diff --git a/Projects/Data/CollectionData/Sources/Logger/CollectionAction.swift b/Projects/Data/CollectionData/Sources/Logger/CollectionAction.swift index 196e8718e..1c6b69bbc 100644 --- a/Projects/Data/CollectionData/Sources/Logger/CollectionAction.swift +++ b/Projects/Data/CollectionData/Sources/Logger/CollectionAction.swift @@ -14,6 +14,7 @@ enum CollectionAction { case fetchCollectionPreviews(userID: Int) case fetchCollections(userID: Int) case fetchLikedCollections + case fetchPublicCollections case fetchCollectionDetail(collectionID: Int) case createCollection case updateCollection(collectionID: Int) @@ -26,6 +27,7 @@ enum CollectionAction { case .fetchCollectionPreviews(let userID): "마이페이지 컬렉션 미리보기 조회: \(userID)" case .fetchCollections(let userID): "컬렉션 목록 조회: \(userID)" case .fetchLikedCollections: "좋아요한 컬렉션 목록 조회" + case .fetchPublicCollections: "전체 공개 컬렉션 목록 조회" case .fetchCollectionDetail(let collectionID): "컬렉션 상세 조회: \(collectionID)" case .createCollection: "컬렉션 생성" case .updateCollection(let collectionID): "컬렉션 수정: \(collectionID)" diff --git a/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift b/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift index 8ad38b29a..22ae27c8f 100644 --- a/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift +++ b/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift @@ -52,6 +52,26 @@ enum CollectionMapper { ) } + /// 홈 컬렉션 섹션·전체 컬렉션뷰용. + public static func publicCollectionCards( + from dto: PublicCollectionsResponse + ) -> CursorPaginated { + CursorPaginated( + items: dto.collections.map { + PublicCollectionCard( + id: CollectionID($0.collectionId), + name: $0.collectionName, + description: $0.collectionDescription, + novelCount: $0.novelCount, + recentNovels: $0.recentNovels.map(collectionNovel(from:)), + owner: author(from: $0.owner) + ) + }, + hasNext: dto.hasNext, + nextCursor: dto.nextCursor + ) + } + // MARK: - 상세 public static func collectionDetail(from dto: CollectionDetailResponse) -> CollectionDetail { @@ -59,11 +79,7 @@ enum CollectionMapper { id: CollectionID(dto.collectionId), name: dto.collectionName, description: dto.collectionDescription, - owner: Author( - userId: UserID(dto.owner.userId), - nickname: dto.owner.nickname, - profileImage: dto.owner.avatarImage.flatMap { ImageURLResolver.resolve(from: $0) } - ), + owner: author(from: dto.owner), isMine: dto.isMyCollection, isPrivate: dto.isPublic == false, representativeNovelID: NovelID(dto.representativeNovelId), @@ -97,6 +113,14 @@ enum CollectionMapper { // MARK: - 공통 + private static func author(from dto: CollectionOwnerResponse) -> Author { + Author( + userId: UserID(dto.userId), + nickname: dto.nickname, + profileImage: dto.avatarImage.flatMap { ImageURLResolver.resolve(from: $0) } + ) + } + private static func collectionNovel(from dto: CollectionNovelResponse) -> CollectionNovel { CollectionNovel( id: NovelID(dto.novelId), diff --git a/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift b/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift index d1c77727f..299ffa6ff 100644 --- a/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift +++ b/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift @@ -106,6 +106,31 @@ struct DefaultCollectionRepository: CollectionRepository { } } + public func fetchPublicCollections( + cursor: String?, + size: Int + ) async throws(RepositoryError) -> CursorPaginated { + let action = CollectionAction.fetchPublicCollections + + do { + let response = try await service.getPublicCollections( + query: CollectionsQuery(cursor: cursor, size: size) + ) + let result = CollectionMapper.publicCollectionCards(from: response) + logger?.logSuccess(action: action.name) + return result + } catch let error as NetworkingError { + logger?.logNetworkError(action: action.name, error: error) + throw error.toRepositoryError() + } catch let error as MappingError { + logger?.logMappingError(action: action.name, error: error) + throw .invalidData + } catch { + logger?.logUnknownError(action: action.name, error: error) + throw .unknown + } + } + // MARK: - 상세 public func fetchCollectionDetail( diff --git a/Projects/Data/CollectionData/Sources/Service/CollectionService.swift b/Projects/Data/CollectionData/Sources/Service/CollectionService.swift index 2ef957e7e..3677dee71 100644 --- a/Projects/Data/CollectionData/Sources/Service/CollectionService.swift +++ b/Projects/Data/CollectionData/Sources/Service/CollectionService.swift @@ -11,6 +11,7 @@ import Foundation protocol CollectionService: Sendable { func getUserCollections(userID: Int, query: CollectionsQuery) async throws -> CollectionsResponse func getLikedCollections(query: CollectionsQuery) async throws -> CollectionsResponse + func getPublicCollections(query: CollectionsQuery) async throws -> PublicCollectionsResponse func getCollectionDetail(collectionID: Int, query: CollectionDetailQuery) async throws -> CollectionDetailResponse func postCollection(request: SubmitCollectionRequest) async throws -> CreateCollectionResponse func putCollection(collectionID: Int, request: SubmitCollectionRequest) async throws diff --git a/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift b/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift index cb908f6bf..e9f1a6419 100644 --- a/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift +++ b/Projects/Data/CollectionData/Sources/Service/DefaultCollectionService.swift @@ -32,6 +32,13 @@ struct DefaultCollectionService: CollectionService { ) } + public func getPublicCollections(query: CollectionsQuery) async throws -> PublicCollectionsResponse { + try await network.request( + CollectionEndpoint.getPublicCollections(query), + decodeTo: PublicCollectionsResponse.self + ) + } + public func getCollectionDetail( collectionID: Int, query: CollectionDetailQuery diff --git a/docs/PENDING_DECISIONS.md b/docs/PENDING_DECISIONS.md index 6997160a8..479eb524d 100644 --- a/docs/PENDING_DECISIONS.md +++ b/docs/PENDING_DECISIONS.md @@ -23,7 +23,7 @@ ## A. 백엔드 확인 필요 -(현재 열린 항목 없음 — 8번은 닫힘 이력 참조) +(현재 열린 항목 없음 — 8·9번은 닫힘 이력 참조) --- @@ -66,3 +66,4 @@ - **5** 감상평 첫 진입 온보딩 힌트 — **되살린다(사용자 확정 2026-08-28)** → 구현은 TODO 12절. 반영: NovelDetail 계약 6.4·0절 4. - **6** 비로그인/온보딩 분석 계측 — **닫음(사용자 2026-08-28)**: 비로그인 경로가 없고, Amplitude 등 애널리틱스는 나중에 횡단으로 도입(TODO 12절) — 별도 항목 불필요. 반영: Onboarding 계약 0절 5(➡️ 흡수). - **8** `feedId`·`novelId` 없는 비공지 알림 — **실존하지 않음으로 확정(사용자 2026-08-29)** → 닫는 조건 (a): V2 현행(`.unknown` → 읽음 처리만, 전환 없음)을 방어 코드로 유지, 🔧 확정. 반영: Notification 계약 0절 4·1.3·부록 A.2. +- **9** 전체 공개 컬렉션 목록 API — **서버 명세 등록(2026-10-12)**: `GET /collections`(커서 페이지네이션, 카드에 `owner` 포함). 범위는 모든 사용자의 공개 컬렉션(본인 공개분 포함·본인 비공개 제외), 로그인 시 양방향 차단 작성자 제외. 홈 섹션은 같은 API의 첫 페이지로 구성. 반영: `CollectionData` 연결(#283). From e21aed317cebf2c4eb728b98482c223fa38253fc Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:30:10 +0900 Subject: [PATCH 03/25] =?UTF-8?q?[Refactor]=20#283=20-=20=EC=BB=AC?= =?UTF-8?q?=EB=A0=89=EC=85=98=20=ED=91=9C=EC=A7=80=20=EC=8A=A4=ED=83=9D?= =?UTF-8?q?=EC=9D=84=20WSSComponent=EB=A1=9C=20=EC=8A=B9=EA=B2=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 홈 컬렉션 섹션(4칸)이 컬렉션 목록(5칸)과 같은 표지 겹침 스택을 써야 해서 슬롯 수를 인자로 받게 옮겼다. WSSComponent는 BaseDomain까지만 알아 CollectionNovel 대신 표지 URL 배열을 받는다. Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/CollectionFeature/CLAUDE.md | 3 +- .../CollectionCoverStackView.swift | 69 ------------------ .../CollectionList/CollectionListView.swift | 2 +- Projects/Feature/UserPageFeature/CLAUDE.md | 2 +- Projects/UI/WSSComponent/CLAUDE.md | 5 ++ .../Collection/WSSCollectionCoverStack.swift | 70 +++++++++++++++++++ 6 files changed, 79 insertions(+), 72 deletions(-) delete mode 100644 Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCoverStackView.swift create mode 100644 Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift diff --git a/Projects/Feature/CollectionFeature/CLAUDE.md b/Projects/Feature/CollectionFeature/CLAUDE.md index fda39d0a3..3f42ecebd 100644 --- a/Projects/Feature/CollectionFeature/CLAUDE.md +++ b/Projects/Feature/CollectionFeature/CLAUDE.md @@ -88,7 +88,8 @@ dismiss만) **이 화면은 복귀를 "성공/취소"로 구분하지 않고** `hasAppearedOnce` 플래그로 감지한다(이 화면의 App 경로엔 자식이 이 화면 하나뿐이라, 최초 `onAppear` 이후의 재발화는 정의상 "그 자식에서 돌아옴"이다) — 복귀 시 무조건 `.reloadAfterReturn(selectedTab)`으로 그 탭을 다시 로드한다. 카드 - 표지 스택은 `CollectionCoverStackView`(로컬) — 마이페이지 미리보기(`UserPageFeature.CollectionSection`, + 표지 스택은 `WSSComponent.WSSCollectionCoverStack(slotCount: 5)`(#283에 이 모듈 로컬 `CollectionCoverStackView`에서 + 승격 — 홈 컬렉션 섹션이 4칸으로 함께 쓴다) — 마이페이지 미리보기(`UserPageFeature.CollectionSection`, 대표 표지 1장)와는 시각 패턴이 달라 별개 컴포넌트다. **표지 슬롯은 실제 작품 수(1~5)와 무관하게 항상 5칸**이다(사용자 확정, 2026-08-21) — `recentNovels`가 5개 미만이면 남는 슬롯을 `WSSNovelCoverImage(url: nil)`의 기본 표지 폴백으로 채운다("몇 개 들었나"를 표지 개수로 세지 않게 diff --git a/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCoverStackView.swift b/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCoverStackView.swift deleted file mode 100644 index ac7d6b107..000000000 --- a/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCoverStackView.swift +++ /dev/null @@ -1,69 +0,0 @@ -// -// CollectionCoverStackView.swift -// CollectionFeature -// -// Created by Guryss on 8/21/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import SwiftUI - -import CollectionDomain -import DesignSystem -import WSSComponent - -/// 컬렉션 목록 카드의 표지 스택 — `CollectionCard.recentNovels`(최대 5개)를 가로로 겹쳐 그린다. -/// 마이페이지 미리보기(대표 표지 1장, `UserPageFeature.CollectionSection`)와는 시각 패턴이 달라 -/// 별개 컴포넌트다 — 각자 자기 모듈에 1곳씩만 쓰여 승격 근거가 없다(`CollectionFeature/CLAUDE.md`). -struct CollectionCoverStackView: View { - - private let recentNovels: [CollectionNovel] - - init(recentNovels: [CollectionNovel]) { - self.recentNovels = recentNovels - } - - private enum Metric { - static let coverWidth: CGFloat = 74 - static let coverHeight: CGFloat = 108 - static let cornerRadius: CGFloat = 8 - /// `CollectionCard.recentNovels`는 최대 5개까지만 온다(문서 참고) — 실제 작품이 그보다 - /// 적어도 슬롯 자체는 항상 5개로 고정한다(사용자 확정, 2026-08-21). 모자란 슬롯은 - /// `WSSNovelCoverImage(url: nil)`의 기본 표지 폴백으로 채운다 — "몇 개 들었나"를 표지 개수로 - /// 세지 않게 하려는 디자인 의도. 작품 수는 카드 부제(`작품 N`)로만 알린다. - static let slotCount = 5 - } - - var body: some View { - GeometryReader { proxy in - HStack(spacing: spacing(for: proxy.size.width)) { - ForEach(0.. CGFloat { - let step = (availableWidth - Metric.coverWidth) / CGFloat(Metric.slotCount - 1) - return -(Metric.coverWidth - step) - } - - // 크기 고정 자리라 aspectRatio 파라미터 없이 .frame으로 직접 크기를 준다(WSSNovelSelectRow와 - // 동일 패턴 — `WSSComponent/CLAUDE.md` 정본, 열 너비를 따라가는 그리드 셀과는 다른 경우다). - private func cover(url: URL?) -> some View { - WSSNovelCoverImage(url: url) - .frame(width: Metric.coverWidth, height: Metric.coverHeight) - .clipShape(RoundedRectangle(cornerRadius: Metric.cornerRadius)) - .shadow(color: Color.black.opacity(0.1), radius: 7.5, x: 0, y: 2) - } -} diff --git a/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift b/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift index d5396b46a..e247e0ffc 100644 --- a/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift +++ b/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift @@ -210,7 +210,7 @@ private extension CollectionListView { cardSubtitle(card) } - CollectionCoverStackView(recentNovels: card.recentNovels) + WSSCollectionCoverStack(coverURLs: card.recentNovels.map(\.thumbnailImage), slotCount: 5) if card.isPrivate { privateTag diff --git a/Projects/Feature/UserPageFeature/CLAUDE.md b/Projects/Feature/UserPageFeature/CLAUDE.md index b5565e123..b9584fd20 100644 --- a/Projects/Feature/UserPageFeature/CLAUDE.md +++ b/Projects/Feature/UserPageFeature/CLAUDE.md @@ -133,7 +133,7 @@ **SwiftUI `Layout` 프로토콜**(`placeSubviews`가 실제 레이아웃 계산 단계 안에서 동기적으로 각 서브뷰 폭을 확정)을 써서, "일단 그리고 → 측정값을 읽어 → state로 반영해 다시 그리는" 2단계 지연 자체가 없다 — 폭 기준 정밀 대칭이 꼭 필요한 자리가 아니면 여전히 - `CollectionCoverStackView`처럼 역산하지 말고 고정값+정렬로 단순하게 가는 게 기본이지만, 이 + `WSSCollectionCoverStack`처럼 역산하지 말고 고정값+정렬로 단순하게 가는 게 기본이지만, 이 화면처럼 **화면 폭에 따라 실제로 늘고 줄어야 하는 요구가 명확할 땐 `Layout` 프로토콜을 우선 검토할 것** — `GeometryReader` 기반 후측정으로 되돌리지 말 것. - ⚠️ **"왼쪽이 더 밀려 보인다"는 리포트를 받아 `GeometryReader`로 좌우 여백을 실측했더니 39pt로 diff --git a/Projects/UI/WSSComponent/CLAUDE.md b/Projects/UI/WSSComponent/CLAUDE.md index afcf208c1..648216760 100644 --- a/Projects/UI/WSSComponent/CLAUDE.md +++ b/Projects/UI/WSSComponent/CLAUDE.md @@ -23,6 +23,11 @@ - 여기 모인 함정 3개를 화면마다 다시 만들지 말 것: ① `icNavigateLeft`는 원색이 연회색(#C7C7D0)이라 `renderingMode(.template)` + `wssBlack`으로 색을 입혀야 하고, ② 아이콘 24를 44 히트 영역 가운데 두며, ③ 타이틀은 `ZStack` 중앙에 둔다(`HStack`에 넣으면 뒤로가기 폭만큼 오른쪽으로 밀린다). - ⚠️ **타이틀이 길어지면 양쪽 버튼 영역을 넘어서던 버그(2026-09-12)** — `Text(title)`에 `lineLimit`도, 버튼 영역을 피하는 여백도 없어 자연 폭 그대로 렌더돼 뒤로가기/우측 액션과 겹쳤다. `lineLimit(1)` + `truncationMode(.tail)` + 좌우 동일한 `sidePadding`(뒤로가기 쪽 고정폭 50과 `trailing` 실측 폭 중 큰 값, `PreferenceKey`로 갱신)을 타이틀에 걸어 해결 — SwiftUI `padding`은 자식에게 줄어든 proposed width를 내려보내므로 이 안에서 말줄임이 실제로 동작한다. 좌우를 동일한 값으로 줘야 `ZStack` 중앙 정렬이 깨지지 않는다. - **스크롤 반응형 네비 배경(히어로 이미지 위 투명→흰색 전환 등)을 쓰는 화면**(`UserPageView`·`MypageView`·`CollectionDetailView`)은 `WSSNavigationBar`(back+title 고정형)가 아니라 **`NovelDetailView`식 커스텀 오버레이 바**로 각자 만들었다(#244, 사용자 확정). 세 화면 다 시스템 툴바(+`.toolbarBackground`)를 걷어내고, 스크롤 측정(`isScrolledFromTop`)으로 **배경·타이틀·아이콘 색을 opacity/색 전환**하는 커스텀 바를 그렸다 — 커스텀 오버레이라 시스템 `.principal`의 UIKit 브리지 함정(아래 항목)이 없어 `.opacity`/색 전환이 그대로 반영된다(`if` 구조 토글이 필요 없다). ⚠️ **스크롤 전환 애니메이션은 사용자 선호로 전부 걷어내 즉시 전환한다**(#244 후속 — `isScrolledFromTop`/`showNavTitle`에 걸었던 `.animation(.easeInOut …)`을 이 세 화면 + `NovelDetailView`에서 제거, 되살리지 말 것). MypageView(흰 배경, 뒤로가기 없는 탭 루트)·UserPageView(primary20 히어로)는 `safeAreaInset`으로 바를 고정하고, CollectionDetailView(히어로 이미지 위 투명 바)만 `ZStack` 오버레이 + `.ignoresSafeArea(edges:.top)` 배경 확장 + 아이콘 색 흰↔검정 적응을 쓴다(진짜 몰입형). 배경 색이 항상 콘텐츠와 이어지므로 리퀴드 글래스가 애초에 안 뜬다. +- **컬렉션 카드 조각(`Sources/Collection/`, #283)** — `WSSCollectionCoverStack(coverURLs:slotCount:)`(표지 겹침 스택, + `CollectionFeature` 목록 5칸·`HomeFeature` 홈 섹션 4칸). + **카드 전체는 승격하지 않았다** — 홈 카드(폭 284·패딩 16·헤더↔표지 12)와 목록 카드(폭 가득·패딩 17/16·16)가 + 수치부터 달라 한 컴포넌트로 묶으면 파라미터만 늘어난다. 스택은 도메인 타입 대신 URL만 받는다(이 모듈은 BaseDomain까지만 안다). + 슬롯 수와 무관하게 **스택 전체가 카드 폭을 꽉 채우도록 간격을 역산**한다(원래 `CollectionFeature`에서 실기기 리포트로 고친 동작). - **`WSSEmptyView`의 CTA는 선택이다** — `action`을 생략(nil)하거나 `type.buttonTitle`이 nil이면 **버튼과 그 위 간격(36)이 함께 사라진다**. 유도할 행동이 없는 빈 상태(`.notification` — 알림 목록)를 화면마다 다시 그리지 않으려고 #181에서 열었다. `action`에 기본값이 있어 기존 호출부는 그대로 동작한다. - ⚠️ **`LibraryFeature`의 `noMatchSection`(필터 0건)은 아직 이 컴포넌트로 옮기지 않았다** — 그쪽은 이미지를 39×48로 줄이고 상단 여백 120을 직접 잡는 등 **렌더가 달라서**, 옮기면 서재 화면 재검증이 필요하다. 옮길 거면 크기 파라미터를 열지 말고 **왜 두 빈 상태의 이미지 크기가 다른지부터** 디자인과 정할 것. - **`NetworkErrorView`는 로드 실패 전면 뷰(재시도 버튼 내장)다** — `init(error: RepositoryError = .unknown, action:)`(#244). 잡은 `RepositoryError`를 받아 title/description을 **3분류로 가른다**: `serverUnavailable`("서버에 문제가\n생겼어요" / "잠시 후 다시 시도해 주세요"), `networkUnavailable`("네트워크 연결에\n실패했어요" / "연결 상태를 확인한 후\n다시 시도해 보세요"), 그 외 `default`("일시적인 오류가\n발생했어요" / "다시 시도해 주세요"). 일러스트(`imgEmptyCatQuestionmark`)·"페이지 다시 불러오기" 버튼·레이아웃은 케이스 불문 **동일** — 문구만 분기. diff --git a/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift new file mode 100644 index 000000000..c928ad2e3 --- /dev/null +++ b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift @@ -0,0 +1,70 @@ +// +// WSSCollectionCoverStack.swift +// WSSComponent +// +// Created by Guryss on 8/21/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import SwiftUI + +import DesignSystem + +/// 컬렉션 카드의 표지 스택 — 작품 표지를 가로로 겹쳐 그린다. 컬렉션 목록(`CollectionFeature`, 5칸)과 +/// 홈 컬렉션 섹션(`HomeFeature`, 4칸)이 함께 쓴다(#283에 `CollectionFeature`에서 승격). +/// +/// 도메인 타입(`CollectionNovel`)을 모르도록 표지 URL만 받는다. +public struct WSSCollectionCoverStack: View { + + private let coverURLs: [URL?] + private let slotCount: Int + + /// - Parameters: + /// - coverURLs: 표시 순서대로의 표지. `slotCount`를 넘는 뒤쪽은 버린다. + /// - slotCount: 슬롯 수. 작품이 모자라도 슬롯은 항상 이 개수로 고정하고, 남는 칸은 + /// `WSSNovelCoverImage(url: nil)`의 기본 표지로 채운다 — "몇 개 들었나"를 표지 개수로 세지 않게 하려는 + /// 디자인 의도(사용자 확정, 2026-08-21). 작품 수는 카드 부제(`작품 N`)로만 알린다. + public init(coverURLs: [URL?], slotCount: Int) { + self.coverURLs = coverURLs + self.slotCount = max(slotCount, 1) + } + + private enum Metric { + static let coverWidth: CGFloat = 74 + static let coverHeight: CGFloat = 108 + static let cornerRadius: CGFloat = 8 + } + + public var body: some View { + GeometryReader { proxy in + HStack(spacing: spacing(for: proxy.size.width)) { + ForEach(0.. CGFloat { + guard slotCount > 1 else { return 0 } + let step = (availableWidth - Metric.coverWidth) / CGFloat(slotCount - 1) + return -(Metric.coverWidth - step) + } + + // 크기 고정 자리라 aspectRatio 파라미터 없이 .frame으로 직접 크기를 준다(WSSNovelSelectRow와 + // 동일 패턴 — 열 너비를 따라가는 그리드 셀과는 다른 경우다). + private func cover(url: URL?) -> some View { + WSSNovelCoverImage(url: url) + .frame(width: Metric.coverWidth, height: Metric.coverHeight) + .clipShape(RoundedRectangle(cornerRadius: Metric.cornerRadius)) + .shadow(color: Color.black.opacity(0.1), radius: 7.5, x: 0, y: 2) + } +} From 7a6bae5f195bb4081073c8f457fc9f65119a75c0 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:30:15 +0900 Subject: [PATCH 04/25] =?UTF-8?q?[Add]=20#283=20-=20=EC=BB=AC=EB=A0=89?= =?UTF-8?q?=EC=85=98=20=EC=9E=91=EC=84=B1=EC=9E=90=20=EB=9D=BC=EB=B2=A8=20?= =?UTF-8?q?=EC=BB=B4=ED=8F=AC=EB=84=8C=ED=8A=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Projects/UI/WSSComponent/CLAUDE.md | 2 +- .../Collection/WSSCollectionOwnerLabel.swift | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 Projects/UI/WSSComponent/Sources/Collection/WSSCollectionOwnerLabel.swift diff --git a/Projects/UI/WSSComponent/CLAUDE.md b/Projects/UI/WSSComponent/CLAUDE.md index 648216760..b6ecfc782 100644 --- a/Projects/UI/WSSComponent/CLAUDE.md +++ b/Projects/UI/WSSComponent/CLAUDE.md @@ -24,7 +24,7 @@ - ⚠️ **타이틀이 길어지면 양쪽 버튼 영역을 넘어서던 버그(2026-09-12)** — `Text(title)`에 `lineLimit`도, 버튼 영역을 피하는 여백도 없어 자연 폭 그대로 렌더돼 뒤로가기/우측 액션과 겹쳤다. `lineLimit(1)` + `truncationMode(.tail)` + 좌우 동일한 `sidePadding`(뒤로가기 쪽 고정폭 50과 `trailing` 실측 폭 중 큰 값, `PreferenceKey`로 갱신)을 타이틀에 걸어 해결 — SwiftUI `padding`은 자식에게 줄어든 proposed width를 내려보내므로 이 안에서 말줄임이 실제로 동작한다. 좌우를 동일한 값으로 줘야 `ZStack` 중앙 정렬이 깨지지 않는다. - **스크롤 반응형 네비 배경(히어로 이미지 위 투명→흰색 전환 등)을 쓰는 화면**(`UserPageView`·`MypageView`·`CollectionDetailView`)은 `WSSNavigationBar`(back+title 고정형)가 아니라 **`NovelDetailView`식 커스텀 오버레이 바**로 각자 만들었다(#244, 사용자 확정). 세 화면 다 시스템 툴바(+`.toolbarBackground`)를 걷어내고, 스크롤 측정(`isScrolledFromTop`)으로 **배경·타이틀·아이콘 색을 opacity/색 전환**하는 커스텀 바를 그렸다 — 커스텀 오버레이라 시스템 `.principal`의 UIKit 브리지 함정(아래 항목)이 없어 `.opacity`/색 전환이 그대로 반영된다(`if` 구조 토글이 필요 없다). ⚠️ **스크롤 전환 애니메이션은 사용자 선호로 전부 걷어내 즉시 전환한다**(#244 후속 — `isScrolledFromTop`/`showNavTitle`에 걸었던 `.animation(.easeInOut …)`을 이 세 화면 + `NovelDetailView`에서 제거, 되살리지 말 것). MypageView(흰 배경, 뒤로가기 없는 탭 루트)·UserPageView(primary20 히어로)는 `safeAreaInset`으로 바를 고정하고, CollectionDetailView(히어로 이미지 위 투명 바)만 `ZStack` 오버레이 + `.ignoresSafeArea(edges:.top)` 배경 확장 + 아이콘 색 흰↔검정 적응을 쓴다(진짜 몰입형). 배경 색이 항상 콘텐츠와 이어지므로 리퀴드 글래스가 애초에 안 뜬다. - **컬렉션 카드 조각(`Sources/Collection/`, #283)** — `WSSCollectionCoverStack(coverURLs:slotCount:)`(표지 겹침 스택, - `CollectionFeature` 목록 5칸·`HomeFeature` 홈 섹션 4칸). + `CollectionFeature` 목록 5칸·`HomeFeature` 홈 섹션 4칸)과 `WSSCollectionOwnerLabel`("{닉네임}님의 컬렉션"). **카드 전체는 승격하지 않았다** — 홈 카드(폭 284·패딩 16·헤더↔표지 12)와 목록 카드(폭 가득·패딩 17/16·16)가 수치부터 달라 한 컴포넌트로 묶으면 파라미터만 늘어난다. 스택은 도메인 타입 대신 URL만 받는다(이 모듈은 BaseDomain까지만 안다). 슬롯 수와 무관하게 **스택 전체가 카드 폭을 꽉 채우도록 간격을 역산**한다(원래 `CollectionFeature`에서 실기기 리포트로 고친 동작). diff --git a/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionOwnerLabel.swift b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionOwnerLabel.swift new file mode 100644 index 000000000..13bad79fa --- /dev/null +++ b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionOwnerLabel.swift @@ -0,0 +1,44 @@ +// +// WSSCollectionOwnerLabel.swift +// WSSComponent +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import SwiftUI + +import DesignSystem + +/// 컬렉션 카드 하단의 작성자 표시 — "{닉네임}님의 컬렉션". 홈 컬렉션 섹션과 전체 컬렉션뷰(#283)가 함께 쓴다. +/// 탭 동작은 없다(사용자 확정 2026-09-28 — 카드 전체가 컬렉션 상세로 가는 버튼이다). +public struct WSSCollectionOwnerLabel: View { + + private let nickname: String + private let profileImage: URL? + + public init(nickname: String, profileImage: URL?) { + self.nickname = nickname + self.profileImage = profileImage + } + + private enum Metric { + static let imageSize: CGFloat = 16 + static let imageCornerRadius: CGFloat = 4 + static let spacing: CGFloat = 4 + } + + public var body: some View { + HStack(spacing: 0) { + WSSProfileImage(url: profileImage) + .frame(width: Metric.imageSize, height: Metric.imageSize) + .clipShape(RoundedRectangle(cornerRadius: Metric.imageCornerRadius)) + + Spacer().frame(width: Metric.spacing) + + Text("\(nickname)님의 컬렉션") + .applyWSSFont(.label2, color: .wssGray200) + .lineLimit(1) + } + } +} From c26f5ad91c3c90e7a3ea73819056b344e4a18013 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:30:21 +0900 Subject: [PATCH 05/25] =?UTF-8?q?[Refactor]=20#283=20-=20=EC=BB=AC?= =?UTF-8?q?=EB=A0=89=EC=85=98=20=EC=B9=B4=EB=93=9C=20=ED=97=A4=EB=8D=94?= =?UTF-8?q?=EB=A5=BC=20=EA=B3=B5=EC=9A=A9=20=EB=B7=B0=EB=A1=9C=20=EC=B6=94?= =?UTF-8?q?=EC=B6=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 전체 컬렉션뷰 카드가 컬렉션 목록 카드와 같은 제목·"설명 · 작품 N" 헤더를 쓴다. Co-Authored-By: Claude Opus 5.5 --- .../CollectionList/CollectionCardHeader.swift | 69 +++++++++++++++++++ .../CollectionList/CollectionListView.swift | 46 +------------ 2 files changed, 70 insertions(+), 45 deletions(-) create mode 100644 Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCardHeader.swift diff --git a/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCardHeader.swift b/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCardHeader.swift new file mode 100644 index 000000000..364f1742b --- /dev/null +++ b/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionCardHeader.swift @@ -0,0 +1,69 @@ +// +// CollectionCardHeader.swift +// CollectionFeature +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import SwiftUI + +import DesignSystem +import WSSComponent + +/// 컬렉션 카드 상단 — 제목(+ 우측 화살표)과 "설명 · 작품 N" 부제. 컬렉션 목록(`CollectionListView`)과 +/// 전체 컬렉션뷰(`PublicCollectionListView`, #283)의 카드가 같은 헤더를 쓴다. +struct CollectionCardHeader: View { + + let name: String + let description: String? + let novelCount: Int + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 0) { + Text(name) + .applyWSSFont(.title2, color: .wssGray300) + .lineLimit(1) + + Spacer() + + WSSImage.icNavigateRight.swiftUIImage + .renderingMode(.template) + .resizable() + .scaledToFit() + .foregroundStyle(Color.wssGray300) + .frame(width: 24, height: 24) + } + + subtitle + } + } + + private var subtitle: some View { + HStack(spacing: 0) { + if let description { + Text(description) + .applyWSSFont(.label1, color: .wssGray300) + .lineLimit(1) + + Spacer().frame(width: 4) + + Circle() + .fill(Color.wssGray300) + .frame(width: 2, height: 2) + + Spacer().frame(width: 4) + } + + HStack(spacing: 0) { + Text("작품 ") + .applyWSSFont(.label1, color: .wssGray300) + Text("\(novelCount)") + .applyWSSFont(.label1, color: .wssPrimary100) + } + + Spacer().frame(width: 80) + } + } +} diff --git a/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift b/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift index e247e0ffc..b88656c1f 100644 --- a/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift +++ b/Projects/Feature/CollectionFeature/Sources/CollectionList/CollectionListView.swift @@ -191,24 +191,7 @@ private extension CollectionListView { func collectionCardContent(_ card: CollectionCard) -> some View { VStack(alignment: .leading, spacing: 16) { - VStack(alignment: .leading, spacing: 4) { - HStack(spacing: 0) { - Text(card.name) - .applyWSSFont(.title2, color: .wssGray300) - .lineLimit(1) - - Spacer() - - WSSImage.icNavigateRight.swiftUIImage - .renderingMode(.template) - .resizable() - .scaledToFit() - .foregroundStyle(Color.wssGray300) - .frame(width: 24, height: 24) - } - - cardSubtitle(card) - } + CollectionCardHeader(name: card.name, description: card.description, novelCount: card.novelCount) WSSCollectionCoverStack(coverURLs: card.recentNovels.map(\.thumbnailImage), slotCount: 5) @@ -223,33 +206,6 @@ private extension CollectionListView { .contentShape(Rectangle()) } - func cardSubtitle(_ card: CollectionCard) -> some View { - HStack(spacing: 0) { - if let description = card.description { - Text(description) - .applyWSSFont(.label1, color: .wssGray300) - .lineLimit(1) - - Spacer().frame(width: 4) - - Circle() - .fill(Color.wssGray300) - .frame(width: 2, height: 2) - - Spacer().frame(width: 4) - } - - HStack(spacing: 0) { - Text("작품 ") - .applyWSSFont(.label1, color: .wssGray300) - Text("\(card.novelCount)") - .applyWSSFont(.label1, color: .wssPrimary100) - } - - Spacer().frame(width: 80) - } - } - var privateTag: some View { HStack(spacing: 6) { WSSImage.icLock.swiftUIImage From e9bc202061b4dd77d845ada3e3136f52fbcc842e Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:30:27 +0900 Subject: [PATCH 06/25] =?UTF-8?q?[Feat]=20#283=20-=20=EC=A0=84=EC=B2=B4=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=EB=B7=B0=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 모든 사용자의 공개 컬렉션을 최신순 무한 스크롤로 보여주고, 당겨서 새로고침에 햅틱을 건다. 실패는 첫 페이지·더보기·새로고침 모두 NetworkErrorView로 표현한다(Feature 로드 실패 표현 계약). Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/CollectionFeature/CLAUDE.md | 11 ++ .../Demo/CollectionFeatureDemoApp.swift | 62 ++++++ .../Factory/CollectionFeatureFactory.swift | 21 +++ .../Sources/Navigation/CollectionRoutes.swift | 6 + .../PublicCollectionListView.swift | 163 ++++++++++++++++ .../PublicCollectionListViewModel.swift | 176 ++++++++++++++++++ 6 files changed, 439 insertions(+) create mode 100644 Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift create mode 100644 Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift diff --git a/Projects/Feature/CollectionFeature/CLAUDE.md b/Projects/Feature/CollectionFeature/CLAUDE.md index 3f42ecebd..b5cd3a2e1 100644 --- a/Projects/Feature/CollectionFeature/CLAUDE.md +++ b/Projects/Feature/CollectionFeature/CLAUDE.md @@ -228,6 +228,17 @@ - "공유" 아이콘(`icShare`, Figma `humbleicons:share`)은 이 작업에서 `DesignSystem`에 신규 추가한 에셋이다(기존엔 없었음, 사용자 승인). +### 전체 컬렉션뷰(`PublicCollectionListView`, #283 — 사용자 확정 2026-09-28) + +- 홈 "컬렉션 모음.zip" 섹션 제목 탭에서만 진입한다. 모든 사용자의 **공개** 컬렉션을 최신순(위가 최신)으로 20개씩 무한 스크롤. +- 카드는 컬렉션 목록 카드와 같은 틀(`CollectionCardHeader` + 표지 5칸)에 비공개 태그 대신 **작성자 라벨** + (`WSSCollectionOwnerLabel`, 탭 없음)을 단다 — 표지와 라벨 사이 8(목록 카드의 비공개 태그는 16). 카드 탭 → 컬렉션 상세. +- **당겨서 새로고침 + 햅틱(`HapticManager.impact(.light)`)** — 목록을 비우지 않고 첫 페이지로 교체한다. +- **실패는 첫 페이지·더보기·새로고침 모두 `NetworkErrorView`로 목록을 대체한다**(Feature 로드 실패 표현 계약 — + 같은 모듈 `CollectionListView`의 더보기 실패 토스트와 다르다, 그쪽이 계약 이전 코드다). +- 상세에 다녀와도 재로드하지 않는다(이 목록엔 상세에서 바뀔 값이 없다). 0건 빈 상태는 명세에 없어 따로 그리지 않는다. +- 이벤트 트래킹은 명세에 없어 걸지 않았다(이벤트 이름을 지어내지 않는다). + ## 주의사항 (작업 중 발견 시 누적) - `CollectionAnalyticsEvent`(`collection_list`/`collection_write`/`collection_save`/`collection_detail`/ diff --git a/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift b/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift index 98c32edba..9249f02aa 100644 --- a/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift +++ b/Projects/Feature/CollectionFeature/Demo/CollectionFeatureDemoApp.swift @@ -60,6 +60,7 @@ private struct DemoRootView: View { case create case edit(CollectionID) case list(isEmpty: Bool) + case publicList case detail(CollectionID) /// 진입 시점의 선택 스냅샷을 path payload로 직접 태운다 — 별도 `@State` 스크래치 변수에 먼저 /// 써두고 그 값을 읽어 destination을 만드는 방식은 **레이스가 있다**(실측, 2026-08-28): 같은 @@ -104,6 +105,11 @@ private struct DemoRootView: View { } .buttonStyle(.bordered) + Button("전체 컬렉션뷰 열기") { + path.append(Destination.publicList) + } + .buttonStyle(.bordered) + // Mock 전용 — 실서버는 실제 계정 데이터를 그대로 조회하므로 빈 상태를 강제할 수 없다. // 두 탭(내 컬렉션/좋아요한 컬렉션) 모두 첫 페이지부터 빈 배열을 반환해, 세그먼트를 // 오가며 두 탭의 빈 상태(CTA 유무 차이 포함)를 한 화면에서 확인할 수 있다. @@ -148,6 +154,8 @@ private struct DemoRootView: View { editView(id: id) case .list(let isEmpty): listView(isEmpty: isEmpty) + case .publicList: + publicListView case .detail(let id): detailView(id: id) case .searchNovel(let initialSelection): @@ -223,6 +231,31 @@ private struct DemoRootView: View { } } + @ViewBuilder + private var publicListView: some View { + let useCase: LoadPublicCollectionsUseCase = switch dataSource { + case .mock: + DemoLoadPublicCollectionsUseCase() + case .live: + DefaultLoadPublicCollectionsUseCase( + collectionRepository: CollectionDataFactory.makeRepository( + network: makeLiveClient(), + logger: DataLogger(moduleName: "CollectionData", underlying: consoleLogger) + ) + ) + } + CollectionFeatureFactory.makePublicCollectionListView( + loadPublicCollectionsUseCase: useCase, + logger: consoleLogger, + onAuthenticationRequired: handleAuthenticationRequired, + onRoute: { route in + switch route { + case .collectionDetail(let id): path.append(Destination.detail(id)) + } + } + ) + } + /// Mock 전용(실서버는 목록 화면에서 카드를 탭해 진입하는 경로만 유효 — 위 바로가기 주석 참고). private func detailView(id: CollectionID) -> some View { CollectionFeatureFactory.makeCollectionDetailView( @@ -689,3 +722,32 @@ private enum DemoCollectionCardPage { ) } } + +/// 전체 컬렉션뷰 데모 — 25개를 20개씩 끊어 무한 스크롤까지 확인한다. 작품 수를 0~7개로 돌려 빈 표지 슬롯도 함께 본다. +private struct DemoLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + try? await Task.sleep(nanoseconds: 300_000_000) + let total = 25 + let start = cursor.flatMap(Int.init) ?? 0 + let end = min(start + size, total) + let cards = (start.. Void, + onRoute: @escaping (PublicCollectionListRoute) -> Void + ) -> some View { + PublicCollectionListView( + viewModel: PublicCollectionListViewModel( + loadPublicCollectionsUseCase: loadPublicCollectionsUseCase, + logger: logger + ), + onAuthenticationRequired: onAuthenticationRequired, + onRoute: onRoute + ) + } + /// - Parameters: /// - id: 조회할 컬렉션. `CollectionListView`의 카드 탭에서 넘어온다. /// - deleteCollectionUseCase: 우상단 더보기(소유자에게만 노출)의 "컬렉션 삭제". diff --git a/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift b/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift index 7d61ec55a..403be603b 100644 --- a/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift +++ b/Projects/Feature/CollectionFeature/Sources/Navigation/CollectionRoutes.swift @@ -42,3 +42,9 @@ public enum CollectionDetailRoute { /// 더보기 "컬렉션 수정" 탭 — 수정 화면이 `id`로 대상을 스스로 다시 불러오므로 payload가 없다. case editCollection } + +/// 전체 컬렉션뷰(`PublicCollectionListView`, #283). +public enum PublicCollectionListRoute { + /// 카드 탭 → 컬렉션 상세. 작성자 프로필은 탭 동작이 없다(사용자 확정 2026-09-28). + case collectionDetail(CollectionID) +} diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift new file mode 100644 index 000000000..8e8905876 --- /dev/null +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift @@ -0,0 +1,163 @@ +// +// PublicCollectionListView.swift +// CollectionFeature +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import SwiftUI + +import BaseDomain +import CollectionDomain +import DesignSystem +import WSSComponent + +/// 전체 컬렉션뷰("컬렉션 모음.zip") — 모든 사용자의 공개 컬렉션. 홈 컬렉션 섹션 제목 탭에서 진입한다(#283). +/// 화면 동작 계약은 `CollectionFeature/CLAUDE.md` 참고. +struct PublicCollectionListView: View { + + @State private var viewModel: PublicCollectionListViewModel + @Environment(\.dismiss) private var dismiss + + private let onAuthenticationRequired: () -> Void + /// 화면 전환 의도 콜백 — 계약은 `PublicCollectionListRoute`(Navigation/)가 정본. + private let onRoute: (PublicCollectionListRoute) -> Void + + private enum Metric { + static let listPadding: CGFloat = 16 + static let cardSpacing: CGFloat = 16 + static let coverSlotCount = 5 + } + + init( + viewModel: PublicCollectionListViewModel, + onAuthenticationRequired: @escaping () -> Void, + onRoute: @escaping (PublicCollectionListRoute) -> Void + ) { + self._viewModel = State(initialValue: viewModel) + self.onAuthenticationRequired = onAuthenticationRequired + self.onRoute = onRoute + } + + var body: some View { + VStack(spacing: 0) { + WSSNavigationBar(title: "컬렉션 모음.zip") { dismiss() } + + content + } + .background(Color.wssWhite) + .wssCustomNavigationBar() + // 카드 탭으로 상세에 다녀와도 다시 부르지 않는다 — 이 목록에 상세에서 바뀔 값(좋아요 수 등)이 없다. + .onAppear { viewModel.handle(.load) } + // 인증 만료 신호 — 실제 로그인 화면 전환은 호출자(App)가 콜백 안에서 수행한다. + .onChange(of: viewModel.state.requiresAuthentication) { _, needsAuth in + if needsAuth { onAuthenticationRequired() } + } + } + + @ViewBuilder + private var content: some View { + if let error = viewModel.state.loadFailed { + NetworkErrorView(error: error) { viewModel.handle(.retry) } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if viewModel.state.isLoading { + LoadingView() + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + collectionList + } + } +} + +// MARK: - Sections + +private extension PublicCollectionListView { + + var collectionList: some View { + ScrollView { + VStack(spacing: 0) { + LazyVStack(spacing: Metric.cardSpacing) { + ForEach(viewModel.state.items, id: \.id) { card in + collectionCard(card) + .onAppear { + if card.id == viewModel.state.items.last?.id { + viewModel.handle(.loadMore) + } + } + } + } + + if viewModel.state.isLoadingMore { + ProgressView() + .padding(.vertical, 16) + } + } + .padding(Metric.listPadding) + } + .refreshable { + HapticManager.impact(.light) + viewModel.handle(.refresh) + // `handle`은 동기 반환이라 그대로 두면 인디케이터가 즉시 사라진다 — 진행 중 로드의 종료를 기다린다. + await viewModel.awaitLoad() + } + .scrollIndicators(.hidden) + } + + func collectionCard(_ card: PublicCollectionCard) -> some View { + Button { + onRoute(.collectionDetail(card.id)) + } label: { + VStack(alignment: .leading, spacing: 0) { + CollectionCardHeader(name: card.name, description: card.description, novelCount: card.novelCount) + + Spacer().frame(height: 16) + + WSSCollectionCoverStack( + coverURLs: card.recentNovels.map(\.thumbnailImage), + slotCount: Metric.coverSlotCount + ) + + Spacer().frame(height: 8) + + WSSCollectionOwnerLabel(nickname: card.owner.nickname, profileImage: card.owner.profileImage) + } + .padding(.horizontal, 17) + .padding(.vertical, 16) + .background(Color.wssPrimary20) + .clipShape(RoundedRectangle(cornerRadius: 14)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } +} + +// MARK: - Preview + +#Preview { + NavigationStack { + PublicCollectionListView( + viewModel: PublicCollectionListViewModel( + loadPublicCollectionsUseCase: PreviewLoadPublicCollectionsUseCase() + ), + onAuthenticationRequired: {}, + onRoute: { print("화면 전환 요청: \($0)") } + ) + } +} + +private struct PreviewLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + let cards = (0..<5).map { index in + PublicCollectionCard( + id: CollectionID(index), + name: "일이삼사오육칠팔구십일이삼사오육칠팔구십", + description: "존잼 수준이 정도를 넘음", + novelCount: index + 1, + recentNovels: [], + owner: Author(userId: UserID(index), nickname: "코띠", profileImage: nil) + ) + } + return CursorPaginated(items: cards, hasNext: false, nextCursor: nil) + } +} diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift new file mode 100644 index 000000000..6ea1fb38d --- /dev/null +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift @@ -0,0 +1,176 @@ +// +// PublicCollectionListViewModel.swift +// CollectionFeature +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import Foundation +import Observation + +import BaseDomain +import CollectionDomain +import Logger + +/// 전체 컬렉션뷰 — 모든 사용자의 공개 컬렉션을 최신순 무한 스크롤로 본다. 홈 "컬렉션 모음.zip" 섹션 +/// 제목 탭에서 진입한다(#283). 화면 동작 계약은 `CollectionFeature/CLAUDE.md` 참고. +@MainActor +@Observable +final class PublicCollectionListViewModel { + + // MARK: - State + + struct State { + var items: [PublicCollectionCard] = [] + /// 초기값 true — onAppear의 `.load`보다 첫 body 평가가 먼저라, false로 시작하면 로드 시작 전 + /// 한 프레임 빈 상태가 스친다(`CollectionListViewModel`과 동일 이유). + var isLoading = true + var isLoadingMore = false + var loadFailed: RepositoryError? + var requiresAuthentication = false + } + + // MARK: - Action + + enum Action { + case load + case loadMore + /// 당겨서 새로고침 — 목록을 비우지 않고 첫 페이지로 교체한다(비우면 인디케이터 아래가 깜빡인다). + case refresh + /// 실패 뷰(`NetworkErrorView`)의 재시도 — 처음부터 다시 세운다. + case retry + } + + // MARK: - Output + + private(set) var state = State() + + // MARK: - Property + + /// 커서+generation 부기(View가 안 보는 값) — 진행 중이던 로드의 늦은 응답이 새 목록을 덮지 않게 한다. + @ObservationIgnored private var nextCursor: String? + @ObservationIgnored private var hasNext = true + @ObservationIgnored private var generation = 0 + @ObservationIgnored private var loadTask: Task? + + /// 서버 권장 페이지 크기가 따로 없어 화면이 정한다(`CollectionListViewModel`과 같은 값). + private static let pageSize = 20 + + // MARK: - Dependency + + private let logger: Logger? + + // CollectionDomain + private let loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase + + // MARK: - Init + + init( + loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase, + logger: Logger? = nil + ) { + self.loadPublicCollectionsUseCase = loadPublicCollectionsUseCase + self.logger = logger + } + + // MARK: - handle + + func handle(_ action: Action) { + switch action { + case .load: + guard loadTask == nil, state.items.isEmpty else { return } + reload(clearingItems: true) + case .loadMore: + loadMore() + case .refresh: + reload(clearingItems: false) + case .retry: + reload(clearingItems: true) + } + } + + /// `.refreshable`이 인디케이터를 로드가 끝날 때까지 붙잡도록 진행 중 로드를 기다린다 + /// (`handle`은 동기 반환 — `SosoFeedViewModel.awaitFeedsLoad`와 같은 이유). + func awaitLoad() async { + await loadTask?.value + } +} + +// MARK: - Action Handling + +private extension PublicCollectionListViewModel { + + func reload(clearingItems: Bool) { + generation += 1 + loadTask?.cancel() + nextCursor = nil + hasNext = true + + if clearingItems { + state.items = [] + state.isLoading = true + } + state.isLoadingMore = false + state.loadFailed = nil + + let generation = generation + loadTask = Task { await loadPage(cursor: nil, generation: generation) } + } + + /// 다음 페이지. 커서는 직전 응답의 `nextCursor`를 그대로 왕복한다. + func loadMore() { + guard hasNext, loadTask == nil, !state.isLoading, state.loadFailed == nil, + let cursor = nextCursor else { return } + state.isLoadingMore = true + let generation = generation + loadTask = Task { await loadPage(cursor: cursor, generation: generation) } + } +} + +// MARK: - UseCase Handling + +private extension PublicCollectionListViewModel { + + /// `cursor == nil`이면 첫 페이지(목록 교체), 아니면 다음 페이지(append). + func loadPage(cursor: String?, generation: Int) async { + defer { + if self.generation == generation { + loadTask = nil + state.isLoading = false + state.isLoadingMore = false + } + } + do { + let page = try await loadPublicCollectionsUseCase.execute(cursor: cursor, size: Self.pageSize) + guard self.generation == generation, !Task.isCancelled else { return } + if cursor == nil { + state.items = page.items + } else { + state.items.append(contentsOf: page.items) + } + nextCursor = page.nextCursor + hasNext = page.hasNext + } catch { + guard self.generation == generation, !Task.isCancelled else { return } + presentLoadFailure(error, cursor: cursor) + } + } +} + +// MARK: - Error Mapping + +private extension PublicCollectionListViewModel { + + /// 첫 페이지·더보기·새로고침 모두 실패 뷰로 표현한다 — 목록이 남아 있어도 걷어낸다 + /// (Feature 레이어 "로드 실패 표현 계약": 토스트는 사라지면 재시도 수단이 없다). + func presentLoadFailure(_ error: Error, cursor: String?) { + // 인증 만료는 실패 뷰 대신 로그인 유도로 일원화 — 실패 플래그보다 먼저 거른다. + guard (error as? RepositoryError) != .authenticationRequired else { + state.requiresAuthentication = true + return + } + logger?.error("PublicCollectionList 실패(\(cursor == nil ? "load" : "loadMore")): \(String(describing: error))") + state.loadFailed = (error as? RepositoryError) ?? .unknown + } +} From ffe448c236eeee615abfe9002ada1544f8634ee8 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:30:31 +0900 Subject: [PATCH 07/25] =?UTF-8?q?[Feat]=20#283=20-=20=ED=99=88=20=EC=BB=AC?= =?UTF-8?q?=EB=A0=89=EC=85=98=20=EB=AA=A8=EC=9D=8C.zip=20=EC=84=B9?= =?UTF-8?q?=EC=85=98=20=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 공개 컬렉션 첫 페이지(size 10)를 가로 스크롤 카드로 보여주고, 0건이면 제목까지 숨긴다. 배지와 같은 부수 콘텐츠라 실패해도 홈을 실패 뷰로 덮지 않고 로그만 남긴다. Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/HomeFeature/CLAUDE.md | 27 ++-- .../HomeFeature/Demo/HomeFeatureDemoApp.swift | 48 +++++- Projects/Feature/HomeFeature/Project.swift | 3 + .../Sources/Factory/HomeFeatureFactory.swift | 3 + .../HomeFeature/Sources/Home/HomeView.swift | 38 ++++- .../Sources/Home/HomeViewModel.swift | 39 ++++- .../Home/PublicCollectionSection.swift | 146 ++++++++++++++++++ .../Sources/Navigation/HomeRoute.swift | 5 + 8 files changed, 294 insertions(+), 15 deletions(-) create mode 100644 Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift diff --git a/Projects/Feature/HomeFeature/CLAUDE.md b/Projects/Feature/HomeFeature/CLAUDE.md index d063ae18b..0fdbbfd02 100644 --- a/Projects/Feature/HomeFeature/CLAUDE.md +++ b/Projects/Feature/HomeFeature/CLAUDE.md @@ -6,19 +6,21 @@ - 식별자: `ModuleType.feature(.home)` / 의존: `BaseDomain`, **`RecommendationDomain`**(홈의 Domain 코드가 별도 `HomeDomain`이 아니라 여기 있음 — `LoadHomeDataUseCase`·`HomeData`·`TodayDiscovery`·`TrendingFeed`· - `PreferenceGenreNovelState`), **`NotificationDomain`**(알림 벨 배지), `DesignSystem`, `WSSComponent`, `Logger`, + `PreferenceGenreNovelState`), **`NotificationDomain`**(알림 벨 배지), **`CollectionDomain`**(컬렉션 모음.zip 섹션, #283), + `DesignSystem`, `WSSComponent`, `Logger`, `PushAuthorization`(#193 — 알림 벨 탭 시 시스템 권한 확인용) - 진입점: `HomeFeatureFactory.makeView(loadHomeDataUseCase:loadUnreadNotificationStatusUseCase: - pushAuthorizationChecker:logger:onRoute:onAuthenticationRequired:)` — + loadPublicCollectionsUseCase:pushAuthorizationChecker:logger:onRoute:onAuthenticationRequired:)` — **탭 콘텐츠만** 반환(탭바·화면 전환은 App 몫). 화면 전환 의도는 `onRoute: (HomeRoute) -> Void` 하나 - (#253 — `.novelDetail`/`.feedDetail`/`.search`/`.detailSearch`/`.notification`/`.preferenceGenreSetting`, + (#253 — `.novelDetail`/`.feedDetail`/`.search`/`.detailSearch`/`.notification`/`.preferenceGenreSetting`/ + `.publicCollectionList`/`.collectionDetail`, 정본 `Sources/Navigation/HomeRoute.swift`) ## 핵심 시나리오 -- **로드**: `onAppear`마다 `.load` → `LoadHomeDataUseCase`(추천 3종)와 `LoadUnreadNotificationStatusUseCase` - (알림 배지)를 **`async let`으로 동시에** 부른다. - 추천 3종도 UseCase 안에서 동시 호출이라, 홈 진입 시 **총 4건이 한꺼번에 나간다**(순차로 펴지 말 것 → +- **로드**: `onAppear`마다 `.load` → `LoadHomeDataUseCase`(추천 3종)·`LoadUnreadNotificationStatusUseCase` + (알림 배지)·`LoadPublicCollectionsUseCase`(컬렉션 섹션, #283)를 **`async let`으로 동시에** 부른다. + 추천 3종도 UseCase 안에서 동시 호출이라, 홈 진입 시 **총 5건이 한꺼번에 나간다**(순차로 펴지 말 것 → [RecommendationDomain](../../Domain/RecommendationDomain/CLAUDE.md)에 퇴행 이력과 컴파일 함정이 있다). - **수확은 콘텐츠·배지 따로다(2026-08-31)** — 콘텐츠(추천 3종)는 성공 즉시 그리고, 배지는 도착하는 대로 따로 반영한다. 한 do/catch로 묶으면 프리페치로 즉시 끝나는 콘텐츠가 배지 네트워크 왕복까지 기다렸다가 @@ -28,8 +30,8 @@ 일부러 안 쓴다: 배지는 실패해도 "보이는 고장"이 없어 멀쩡한 홈 위의 에러 토스트가 설명이 안 되고, 탭 복귀 갱신마다 반복 노출만 된다(다음 탭 복귀가 자동 재시도 = self-healing). 인증 만료만은 배지 경로에서도 로그인 라우팅을 태운다(idempotent 계약이라 안전). -- **섹션 4개**: 검색바·상세검색 배너 / 오늘의 발견(가로 캐러셀) / {닉네임}님을 위한 추천글(2개씩 3페이지) / - 이 웹소설은 어때요?(2열 그리드, 선호장르 미설정이면 설정 유도 CTA). +- **섹션 5개**: 검색바·상세검색 배너 / 오늘의 발견(가로 캐러셀) / {닉네임}님을 위한 추천글(2개씩 3페이지) / + 컬렉션 모음.zip(공개 컬렉션 가로 스크롤, #283) / 이 웹소설은 어때요?(2열 그리드, 선호장르 미설정이면 설정 유도 CTA). - 선택 결과는 전부 콜백으로 상위에 위임한다 — 이 화면은 스스로 화면을 전환하지 않는다. - **홈 진입마다 시스템 푸시 권한을 확인, notDetermined면 그 자리에서 시스템 프롬프트(#193)**: `onAppear`의 `.load`와 별도로 `.checkPushAuthorizationOnEntry`를 함께 보낸다. 회원가입 직후 첫 홈 @@ -80,6 +82,13 @@ 한 장은 `hidden="true"`이고, 모양이 아래 그리드 셀(거긴 `/novels/taste`가 실제로 내려줌)과 동일해 **복사 잔재로 확인**했다. **시안에 있다는 이유로 되살리지 말 것.** - **오늘의 발견 카드 탭 → 작품 상세**(유저 한마디 카드도 마찬가지, 유저 프로필로 가지 않는다). +- **"컬렉션 모음.zip" 섹션(#283, 사용자 확정 2026-09-28)** — 모든 사용자의 공개 컬렉션을 최신순(왼쪽이 최신)으로 + 최대 10개(`size=10` 첫 페이지만, 더보기 없음). 제목 줄(`>` 포함) 탭 → 전체 컬렉션뷰(`.publicCollectionList`), + 카드 탭 → 컬렉션 상세(`.collectionDetail`), 작성자 라벨은 탭 없음. 카드는 표지 **4칸 고정**(모자라면 기본 표지). + - **부수 콘텐츠라 실패해도 홈을 실패 뷰로 덮지 않는다** — 배지와 같은 lane: 로그만, 토스트 없음, 직전 카드 유지, + 첫 로드 실패면 빈 채라 섹션이 숨는다. 추천 3종과 같은 `async let` 묶음이지만 수확은 따로다. + - 섹션이 숨으면 추천글↔선호장르 간격은 원래 값(38)으로 돌아가고, 보이면 위아래 32(Figma 실측)를 쓴다. + - Figma 카드 헤더의 빈 24pt 프레임(`bookmark-outline`)은 에셋 없는 빈 자리라 그리지 않는다. ### 실서버가 주는 개수 (시안과 일치 — #179 실측) @@ -102,7 +111,7 @@ 최초 1회로 좁혔다 — 이 둘을 같은 가드로 착각해 트래킹까지 매번 걸리게 되돌리지 말 것. - 홈 Domain을 찾을 때 `HomeDomain`을 만들지 말 것 — 정본은 `RecommendationDomain/Sources/`다 (`LibraryFeature`↔`NovelDomain`과 같은 형태의 이름 불일치). -- **홈은 앱에서 손꼽히는 "동시 요청 4건" 지점**이다 → access token이 만료된 채 진입하면 **401도 4건이 동시에** +- **홈은 앱에서 손꼽히는 "동시 요청 5건" 지점**이다(#283 컬렉션 섹션으로 4→5) → access token이 만료된 채 진입하면 **401도 5건이 동시에** 난다. 이걸 안전하게 만드는 건 `Networking`의 재발급 직렬화(`SessionRefreshCoordinator`)다 — 그게 없으면 재발급이 4번 나가 refresh token 회전 때문에 3건이 실패하고 로그아웃된다(#184). - ⚠️ **`.load`에 "최초 1회" 가드를 넣지 말 것** — 홈은 밖(피드 작성·선호장르 설정·알림 확인)에서 바뀐 값을 diff --git a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift index de0f5d48b..85d083640 100644 --- a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift +++ b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift @@ -12,9 +12,11 @@ import HomeFeature import BaseDomain import RecommendationDomain import NotificationDomain +import CollectionDomain import BaseData import RecommendationData import NotificationData +import CollectionData import Logger import Networking import PushAuthorization @@ -136,7 +138,8 @@ private struct DemoRootView: View { case .mock: makeHomeView( loadHomeDataUseCase: DemoLoadHomeDataUseCase(scenario: scenario), - loadUnreadNotificationStatusUseCase: DemoLoadUnreadNotificationStatusUseCase(scenario: scenario) + loadUnreadNotificationStatusUseCase: DemoLoadUnreadNotificationStatusUseCase(scenario: scenario), + loadPublicCollectionsUseCase: DemoLoadPublicCollectionsUseCase(scenario: scenario) ) case .live: makeLiveView() @@ -148,11 +151,13 @@ private struct DemoRootView: View { @MainActor private func makeHomeView( loadHomeDataUseCase: LoadHomeDataUseCase, - loadUnreadNotificationStatusUseCase: LoadUnreadNotificationStatusUseCase + loadUnreadNotificationStatusUseCase: LoadUnreadNotificationStatusUseCase, + loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase ) -> some View { HomeFeatureFactory.makeView( loadHomeDataUseCase: loadHomeDataUseCase, loadUnreadNotificationStatusUseCase: loadUnreadNotificationStatusUseCase, + loadPublicCollectionsUseCase: loadPublicCollectionsUseCase, pushAuthorizationChecker: DemoPushAuthorizationChecker(status: pushAuthorizationScenario.status), logger: consoleLogger, onRoute: { route in @@ -163,6 +168,8 @@ private struct DemoRootView: View { case .detailSearch: consoleLogger.info("상세 검색 진입 요청") case .notification: consoleLogger.info("알림 진입 요청") case .preferenceGenreSetting: consoleLogger.info("선호장르 설정 진입 요청") + case .publicCollectionList: consoleLogger.info("전체 컬렉션뷰 진입 요청") + case .collectionDetail(let id): consoleLogger.info("컬렉션 상세 진입 요청: \(id)") } }, onAuthenticationRequired: { consoleLogger.info("인증 만료 → 로그인 진입 요청") } @@ -190,6 +197,12 @@ private struct DemoRootView: View { loadHomeDataUseCase: DefaultLoadHomeDataUseCase(repository: recommendationRepository), loadUnreadNotificationStatusUseCase: DefaultLoadUnreadNotificationStatusUseCase( repository: notificationRepository + ), + loadPublicCollectionsUseCase: DefaultLoadPublicCollectionsUseCase( + collectionRepository: CollectionDataFactory.makeRepository( + network: client, + logger: DataLogger(moduleName: "CollectionData", underlying: consoleLogger) + ) ) ) } @@ -343,3 +356,34 @@ private enum DemoHomeData { ) } } + +/// "컬렉션 모음.zip" 섹션 — 정상 시나리오는 10개(작품 수 0~7개로 빈 표지 슬롯 확인), 빈 데이터 시나리오는 0개로 +/// 섹션이 통째로 숨는 레이아웃을 본다. 나머지 실패 시나리오는 홈 전체가 실패 뷰라 무관하다. +private struct DemoLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { + let scenario: DemoHomeScenario + + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + guard scenario != .empty else { + return CursorPaginated(items: [], hasNext: false, nextCursor: nil) + } + let cards = (0.. CursorPaginated { + let cards = (0..<3).map { index in + PublicCollectionCard( + id: CollectionID(index), + name: "개존잼 소설 🤩", + description: "존잼 수준이 정도를 넘음", + novelCount: index + 1, + recentNovels: [], + owner: Author(userId: UserID(index), nickname: "코띠", profileImage: nil) + ) + } + return CursorPaginated(items: cards, hasNext: false, nextCursor: nil) + } +} + private struct PreviewPushAuthorizationChecker: PushAuthorizationChecker { func authorizationStatus() async -> PushAuthorizationStatus { .authorized } func requestAuthorization() async -> Bool { true } diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift index c935ffaa2..47c3a6ad1 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift @@ -12,6 +12,7 @@ import Observation import BaseDomain import RecommendationDomain import NotificationDomain +import CollectionDomain import Logger import PushAuthorization import Analytics @@ -30,6 +31,8 @@ final class HomeViewModel { /// nil = 아직 로드 전. `.noGenreSettings`(미설정)와 구분해야 로딩 중 설정 유도 CTA가 번쩍이지 않는다. var preferenceGenreNovelState: PreferenceGenreNovelState? var hasUnreadNotifications = false + /// "컬렉션 모음.zip" 섹션. 비면 섹션을 제목까지 숨긴다(첫 로드 실패도 빈 채라 숨는다). + var publicCollections: [PublicCollectionCard] = [] /// ⚠️ 초깃값 `true` — `onAppear`의 `.load`보다 첫 body 평가가 먼저라, false면 한 프레임 동안 /// "검색바·배너만 있는 빈 홈"이 스친다(Library·NovelDetail과 같은 이유). @@ -93,20 +96,28 @@ final class HomeViewModel { // NotificationDomain private let loadUnreadNotificationStatusUseCase: LoadUnreadNotificationStatusUseCase + // CollectionDomain + private let loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase + // PushAuthorization private let pushAuthorizationChecker: PushAuthorizationChecker + /// 홈 섹션은 최대 10개(기획) — 가로 스크롤 첫 페이지만 쓰고 더 불러오지 않는다. + private static let publicCollectionCount = 10 + // MARK: - Init init( loadHomeDataUseCase: LoadHomeDataUseCase, loadUnreadNotificationStatusUseCase: LoadUnreadNotificationStatusUseCase, + loadPublicCollectionsUseCase: LoadPublicCollectionsUseCase, pushAuthorizationChecker: PushAuthorizationChecker, logger: Logger? = nil, analyticsTracker: AnalyticsTracker? = nil ) { self.loadHomeDataUseCase = loadHomeDataUseCase self.loadUnreadNotificationStatusUseCase = loadUnreadNotificationStatusUseCase + self.loadPublicCollectionsUseCase = loadPublicCollectionsUseCase self.pushAuthorizationChecker = pushAuthorizationChecker self.logger = logger self.analyticsTracker = analyticsTracker @@ -170,10 +181,10 @@ private extension HomeViewModel { private extension HomeViewModel { - /// 추천 3종(콘텐츠)과 알림 배지를 **따로** 수확한다 — 한 do/catch로 묶으면 프리페치로 즉시 + /// 추천 3종(콘텐츠)·알림 배지·컬렉션 섹션을 **따로** 수확한다 — 한 do/catch로 묶으면 프리페치로 즉시 /// 끝나는 콘텐츠가 배지 네트워크 왕복까지 기다렸다가 그려진다(첫 런치의 프리페치 이득이 죽는다). - /// 실패도 분리다: 콘텐츠 실패만 전면 실패 뷰, 배지 실패는 조용히 무시(로그만 — 이유는 아래 - /// `presentBadgeFailure` 주석). + /// 실패도 분리다: 콘텐츠 실패만 전면 실패 뷰, 배지·컬렉션 실패는 조용히 무시(로그만 — 이유는 아래 + /// `presentBadgeFailure`·`presentPublicCollectionsFailure` 주석). func loadHome() async { state.isLoading = true // 재시도·재진입 시작 시점에 함께 내린다 — 성공할 때만 내리면 "페이지 다시 불러오기"를 눌러도 @@ -185,6 +196,10 @@ private extension HomeViewModel { // 홈은 탭 복귀마다 갱신하는 화면이라 그 비용을 매번 낸다. async let homeData = loadHomeDataUseCase.execute() async let notificationStatus = loadUnreadNotificationStatusUseCase.execute() + async let publicCollections = loadPublicCollectionsUseCase.execute( + cursor: nil, + size: Self.publicCollectionCount + ) // 1) 콘텐츠 — 성공하는 즉시 그린다(배지를 기다리지 않는다). do { @@ -216,6 +231,15 @@ private extension HomeViewModel { } catch { presentBadgeFailure(.unknown) } + + // 3) 컬렉션 섹션 — 배지와 같은 이유로 콘텐츠 성패와 무관하게 수확한다. + do { + state.publicCollections = try await publicCollections.items + } catch let error as RepositoryError { + presentPublicCollectionsFailure(error) + } catch { + presentPublicCollectionsFailure(.unknown) + } } } @@ -247,6 +271,15 @@ private extension HomeViewModel { logger?.error("알림 배지 로드 실패: \(error)") } + /// 컬렉션 섹션도 부수 콘텐츠라 실패해도 홈을 실패 뷰로 덮지 않는다 — **직전에 그린 카드는 그대로 두고** + /// 로그만 남긴다(첫 로드 실패면 빈 채라 섹션이 숨는다). 배지와 같은 이유로 토스트도 안 띄운다: 탭 복귀 + /// 갱신마다 반복 노출만 되고, 다음 탭 복귀가 자동 재시도한다. + func presentPublicCollectionsFailure(_ error: RepositoryError) { + guard !routeToLoginIfAuthenticationRequired(error) else { return } + + logger?.error("컬렉션 섹션 로드 실패: \(error)") + } + func routeToLoginIfAuthenticationRequired(_ error: RepositoryError) -> Bool { guard error == .authenticationRequired else { return false } diff --git a/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift b/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift new file mode 100644 index 000000000..fc3a0f678 --- /dev/null +++ b/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift @@ -0,0 +1,146 @@ +// +// PublicCollectionSection.swift +// HomeFeature +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import SwiftUI + +import BaseDomain +import CollectionDomain +import DesignSystem +import WSSComponent + +/// "컬렉션 모음.zip" — 모든 사용자의 공개 컬렉션을 최신순(왼쪽이 최신) 가로 스크롤로 최대 10개 보여준다(#283). +/// 제목 줄 탭은 전체 컬렉션뷰, 카드 탭은 컬렉션 상세로 간다. +struct PublicCollectionSection: View { + + let collections: [PublicCollectionCard] + let onTitleTapped: () -> Void + let onCollectionSelected: (CollectionID) -> Void + + private enum Metric { + static let horizontalPadding: CGFloat = 20 + static let titleToCards: CGFloat = 14 + static let cardSpacing: CGFloat = 12 + + static let cardWidth: CGFloat = 284 + static let cardPadding: CGFloat = 16 + static let cardCornerRadius: CGFloat = 14 + static let headerToCovers: CGFloat = 12 + static let coversToOwner: CGFloat = 8 + static let subtitleSpacing: CGFloat = 4 + static let coverSlotCount = 4 + } + + var body: some View { + VStack(spacing: 0) { + sectionTitle + Spacer().frame(height: Metric.titleToCards) + cards + } + } +} + +// MARK: - Sections + +private extension PublicCollectionSection { + + var sectionTitle: some View { + Button(action: onTitleTapped) { + HStack(spacing: 0) { + Text("컬렉션 모음.zip") + .applyWSSFont(.headline1, color: .wssBlack, alignment: .leading) + .lineLimit(1) + + Spacer() + + WSSImage.icNavigateRight.swiftUIImage + .renderingMode(.template) + .resizable() + .scaledToFit() + .foregroundStyle(Color.wssBlack) + .frame(width: 24, height: 24) + } + .padding(.horizontal, Metric.horizontalPadding) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + var cards: some View { + ScrollView(.horizontal, showsIndicators: false) { + LazyHStack(spacing: Metric.cardSpacing) { + ForEach(collections, id: \.id) { collection in + card(collection) + } + } + .padding(.horizontal, Metric.horizontalPadding) + } + } + + func card(_ collection: PublicCollectionCard) -> some View { + Button { + onCollectionSelected(collection.id) + } label: { + VStack(alignment: .leading, spacing: 0) { + Text(collection.name) + .applyWSSFont(.title2, color: .wssGray300, alignment: .leading) + .lineLimit(1) + + Spacer().frame(height: Metric.subtitleSpacing) + + subtitle(collection) + + Spacer().frame(height: Metric.headerToCovers) + + WSSCollectionCoverStack( + coverURLs: collection.recentNovels.map(\.thumbnailImage), + slotCount: Metric.coverSlotCount + ) + + Spacer().frame(height: Metric.coversToOwner) + + WSSCollectionOwnerLabel( + nickname: collection.owner.nickname, + profileImage: collection.owner.profileImage + ) + } + .padding(Metric.cardPadding) + .frame(width: Metric.cardWidth, alignment: .leading) + .background(Color.wssPrimary20) + .clipShape(RoundedRectangle(cornerRadius: Metric.cardCornerRadius)) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + } + + /// "설명 · 작품 N". 설명이 없으면 "작품 N"만 남는다. 설명이 길면 설명만 말줄임되고 작품 수는 지킨다. + func subtitle(_ collection: PublicCollectionCard) -> some View { + HStack(spacing: 0) { + if let description = collection.description { + Text(description) + .applyWSSFont(.label1, color: .wssGray300) + .lineLimit(1) + + Spacer().frame(width: 4) + + Circle() + .fill(Color.wssGray300) + .frame(width: 2, height: 2) + + Spacer().frame(width: 4) + } + + HStack(spacing: 0) { + Text("작품 ") + .applyWSSFont(.label1, color: .wssGray300) + Text("\(collection.novelCount)") + .applyWSSFont(.label1, color: .wssPrimary100) + } + .fixedSize() + } + } +} diff --git a/Projects/Feature/HomeFeature/Sources/Navigation/HomeRoute.swift b/Projects/Feature/HomeFeature/Sources/Navigation/HomeRoute.swift index 545279098..3990b622e 100644 --- a/Projects/Feature/HomeFeature/Sources/Navigation/HomeRoute.swift +++ b/Projects/Feature/HomeFeature/Sources/Navigation/HomeRoute.swift @@ -7,6 +7,7 @@ // import BaseDomain +import CollectionDomain /// 홈(탭 콘텐츠) 화면이 밖(App 조정 계층)으로 요청하는 화면 전환의 전부 — #253. public enum HomeRoute { @@ -22,4 +23,8 @@ public enum HomeRoute { case notification /// 선호장르 설정 — 미설정 유도 CTA 탭(전용 화면이 없어 App은 마이페이지 편집으로 보낸다, 사용자 확정). case preferenceGenreSetting + /// 전체 컬렉션뷰 — "컬렉션 모음.zip" 섹션 제목 탭(#283). + case publicCollectionList + /// 컬렉션 상세 — "컬렉션 모음.zip" 섹션 카드 탭(#283). + case collectionDetail(CollectionID) } From b8e4b89af27cb91b97730011ea804d515917cfa9 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:30:34 +0900 Subject: [PATCH 08/25] =?UTF-8?q?[Feat]=20#283=20-=20=ED=99=88=EC=97=90?= =?UTF-8?q?=EC=84=9C=20=EC=A0=84=EC=B2=B4=20=EC=BB=AC=EB=A0=89=EC=85=98?= =?UTF-8?q?=EB=B7=B0=EC=99=80=20=EC=BB=AC=EB=A0=89=EC=85=98=20=EC=83=81?= =?UTF-8?q?=EC=84=B8=EB=A1=9C=20=EC=9D=B4=EB=8F=99=20=EC=97=B0=EA=B2=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../PublicCollectionListAssembly.swift | 32 +++++++++++++++++++ Projects/App/Sources/Home/HomeRootView.swift | 23 ++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 Projects/App/Sources/Collection/PublicCollectionListAssembly.swift diff --git a/Projects/App/Sources/Collection/PublicCollectionListAssembly.swift b/Projects/App/Sources/Collection/PublicCollectionListAssembly.swift new file mode 100644 index 000000000..78d2fc1dd --- /dev/null +++ b/Projects/App/Sources/Collection/PublicCollectionListAssembly.swift @@ -0,0 +1,32 @@ +// +// PublicCollectionListAssembly.swift +// WSS-iOS +// +// Created by Guryss on 9/28/26. +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import SwiftUI + +import CollectionDomain +import CollectionFeature + +/// 전체 컬렉션뷰("컬렉션 모음.zip", `CollectionFeatureFactory.makePublicCollectionListView`) 조립 — +/// 지금 진입점은 홈 컬렉션 섹션 제목 하나뿐이다(#283). +@MainActor +enum PublicCollectionListAssembly { + static func makeView( + dependencies: AppDependencies, + onAuthenticationRequired: @escaping () -> Void, + onRoute: @escaping (PublicCollectionListRoute) -> Void + ) -> some View { + CollectionFeatureFactory.makePublicCollectionListView( + loadPublicCollectionsUseCase: DefaultLoadPublicCollectionsUseCase( + collectionRepository: dependencies.collectionRepository + ), + logger: dependencies.logger, + onAuthenticationRequired: onAuthenticationRequired, + onRoute: onRoute + ) + } +} diff --git a/Projects/App/Sources/Home/HomeRootView.swift b/Projects/App/Sources/Home/HomeRootView.swift index 5a2dde058..4fc01c43f 100644 --- a/Projects/App/Sources/Home/HomeRootView.swift +++ b/Projects/App/Sources/Home/HomeRootView.swift @@ -44,8 +44,11 @@ struct HomeRootView: View { case userLibrary(UserID) /// 타유저 프로필의 "활동기록 더보기" → 전체 피드 목록(#201, `UserPageAssembly.makeFeedListView`). case userFeedList(userID: UserID, nickname: String, profileImage: URL?) - /// 타유저 프로필의 컬렉션 미리보기 항목 탭 → 그 컬렉션 상세(`CollectionDetailAssembly`). + /// 타유저 프로필의 컬렉션 미리보기 항목 탭·홈 "컬렉션 모음.zip" 카드 탭·전체 컬렉션뷰 카드 탭(#283) + /// → 그 컬렉션 상세(`CollectionDetailAssembly`). case collectionDetail(CollectionID) + /// 홈 "컬렉션 모음.zip" 섹션 제목 탭 → 전체 컬렉션뷰(#283, `PublicCollectionListAssembly`). + case publicCollectionList /// 타유저 프로필의 컬렉션 섹션 헤더 탭 → 그 유저의 컬렉션 목록(`CollectionListAssembly`, /// "내 컬렉션" 탭만 보이는 모드). case collectionList(UserID) @@ -114,6 +117,9 @@ struct HomeRootView: View { loadUnreadNotificationStatusUseCase: DefaultLoadUnreadNotificationStatusUseCase( repository: dependencies.notificationRepository ), + loadPublicCollectionsUseCase: DefaultLoadPublicCollectionsUseCase( + collectionRepository: dependencies.collectionRepository + ), pushAuthorizationChecker: DefaultPushAuthorizationChecker(), logger: dependencies.logger, analyticsTracker: dependencies.analyticsTracker, @@ -136,6 +142,10 @@ struct HomeRootView: View { } case .preferenceGenreSetting: path.append(Destination.preferenceGenreSetting) + case .publicCollectionList: + path.append(Destination.publicCollectionList) + case .collectionDetail(let id): + path.append(Destination.collectionDetail(id)) } }, onAuthenticationRequired: onAuthenticationRequired @@ -218,6 +228,17 @@ struct HomeRootView: View { } } ) + case .publicCollectionList: + PublicCollectionListAssembly.makeView( + dependencies: dependencies, + onAuthenticationRequired: onAuthenticationRequired, + onRoute: { route in + switch route { + case .collectionDetail(let collectionID): + path.append(Destination.collectionDetail(collectionID)) + } + } + ) case .editCollection(let id): editCollectionView(id: id) case .searchNovelForCollection(let initialSelection): From f753dc597fce0848bf5c36d57ff32232a185639b Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 14:49:54 +0900 Subject: [PATCH 09/25] =?UTF-8?q?[Fix]=20#283=20-=20=EC=BB=AC=EB=A0=89?= =?UTF-8?q?=EC=85=98=20=ED=91=9C=EC=A7=80=20=EC=8A=A4=ED=83=9D=EC=9D=B4=20?= =?UTF-8?q?=EB=84=93=EC=9D=80=20=EA=B8=B0=EA=B8=B0=EC=97=90=EC=84=9C=20?= =?UTF-8?q?=EB=B2=8C=EC=96=B4=EC=A7=80=EB=8A=94=20=EB=AC=B8=EC=A0=9C=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 표지 크기를 74×108로 고정한 채 간격만 역산해, 카드가 넓은 기기(17 Pro Max 5칸)에서 간격이 양수가 돼 표지가 떨어졌다. Figma 겹침 비율(58/74)을 고정하고 표지 크기를 카드 폭에 비례시키는 Layout으로 바꿔 기기와 무관하게 같은 모양으로 겹친다. Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/UserPageFeature/CLAUDE.md | 4 +- Projects/UI/WSSComponent/CLAUDE.md | 6 +- .../Collection/WSSCollectionCoverStack.swift | 80 +++++++++++++------ 3 files changed, 63 insertions(+), 27 deletions(-) diff --git a/Projects/Feature/UserPageFeature/CLAUDE.md b/Projects/Feature/UserPageFeature/CLAUDE.md index b9584fd20..3bfdc2533 100644 --- a/Projects/Feature/UserPageFeature/CLAUDE.md +++ b/Projects/Feature/UserPageFeature/CLAUDE.md @@ -133,8 +133,8 @@ **SwiftUI `Layout` 프로토콜**(`placeSubviews`가 실제 레이아웃 계산 단계 안에서 동기적으로 각 서브뷰 폭을 확정)을 써서, "일단 그리고 → 측정값을 읽어 → state로 반영해 다시 그리는" 2단계 지연 자체가 없다 — 폭 기준 정밀 대칭이 꼭 필요한 자리가 아니면 여전히 - `WSSCollectionCoverStack`처럼 역산하지 말고 고정값+정렬로 단순하게 가는 게 기본이지만, 이 - 화면처럼 **화면 폭에 따라 실제로 늘고 줄어야 하는 요구가 명확할 땐 `Layout` 프로토콜을 + 역산하지 말고 고정값+정렬로 단순하게 가는 게 기본이지만, 이 화면이나 `WSSCollectionCoverStack`(#283)처럼 + **화면 폭에 따라 실제로 늘고 줄어야 하는 요구가 명확할 땐 `Layout` 프로토콜을 우선 검토할 것** — `GeometryReader` 기반 후측정으로 되돌리지 말 것. - ⚠️ **"왼쪽이 더 밀려 보인다"는 리포트를 받아 `GeometryReader`로 좌우 여백을 실측했더니 39pt로 완전히 대칭이었다**(레이아웃 버그 아님, 2026-08-21) — 원인은 각 항목 표지 뒤 장식 사각형 diff --git a/Projects/UI/WSSComponent/CLAUDE.md b/Projects/UI/WSSComponent/CLAUDE.md index b6ecfc782..a30677e7a 100644 --- a/Projects/UI/WSSComponent/CLAUDE.md +++ b/Projects/UI/WSSComponent/CLAUDE.md @@ -27,7 +27,11 @@ `CollectionFeature` 목록 5칸·`HomeFeature` 홈 섹션 4칸)과 `WSSCollectionOwnerLabel`("{닉네임}님의 컬렉션"). **카드 전체는 승격하지 않았다** — 홈 카드(폭 284·패딩 16·헤더↔표지 12)와 목록 카드(폭 가득·패딩 17/16·16)가 수치부터 달라 한 컴포넌트로 묶으면 파라미터만 늘어난다. 스택은 도메인 타입 대신 URL만 받는다(이 모듈은 BaseDomain까지만 안다). - 슬롯 수와 무관하게 **스택 전체가 카드 폭을 꽉 채우도록 간격을 역산**한다(원래 `CollectionFeature`에서 실기기 리포트로 고친 동작). + 슬롯 수와 무관하게 **스택 전체가 카드 폭을 꽉 채운다**(원래 `CollectionFeature`에서 실기기 리포트로 고친 동작). + ⚠️ **표지 크기를 고정(74×108)한 채 간격만 역산하지 말 것** — 카드가 넓은 기기(17 Pro Max의 5칸 목록 카드)에서 간격이 + 양수가 돼 표지가 서로 떨어졌다(#283 실측). 지금은 Figma 겹침 비율(등차 58 ÷ 표지 74)을 고정하고 **표지 크기를 카드 폭에 + 비례해 키우고 줄이는** `Layout`(`CoverStackLayout`)이다 — 높이도 폭을 따라 바뀌므로 호출부에서 높이를 고정하지 말 것. + 폭 제안이 nil·무한대면 Figma 원본 크기로 답한다(무한대 그대로 쓰면 높이까지 무한대가 된다). - **`WSSEmptyView`의 CTA는 선택이다** — `action`을 생략(nil)하거나 `type.buttonTitle`이 nil이면 **버튼과 그 위 간격(36)이 함께 사라진다**. 유도할 행동이 없는 빈 상태(`.notification` — 알림 목록)를 화면마다 다시 그리지 않으려고 #181에서 열었다. `action`에 기본값이 있어 기존 호출부는 그대로 동작한다. - ⚠️ **`LibraryFeature`의 `noMatchSection`(필터 0건)은 아직 이 컴포넌트로 옮기지 않았다** — 그쪽은 이미지를 39×48로 줄이고 상단 여백 120을 직접 잡는 등 **렌더가 달라서**, 옮기면 서재 화면 재검증이 필요하다. 옮길 거면 크기 파라미터를 열지 말고 **왜 두 빈 상태의 이미지 크기가 다른지부터** 디자인과 정할 것. - **`NetworkErrorView`는 로드 실패 전면 뷰(재시도 버튼 내장)다** — `init(error: RepositoryError = .unknown, action:)`(#244). 잡은 `RepositoryError`를 받아 title/description을 **3분류로 가른다**: `serverUnavailable`("서버에 문제가\n생겼어요" / "잠시 후 다시 시도해 주세요"), `networkUnavailable`("네트워크 연결에\n실패했어요" / "연결 상태를 확인한 후\n다시 시도해 보세요"), 그 외 `default`("일시적인 오류가\n발생했어요" / "다시 시도해 주세요"). 일러스트(`imgEmptyCatQuestionmark`)·"페이지 다시 불러오기" 버튼·레이아웃은 케이스 불문 **동일** — 문구만 분기. diff --git a/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift index c928ad2e3..dd1dff456 100644 --- a/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift +++ b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift @@ -30,41 +30,73 @@ public struct WSSCollectionCoverStack: View { } private enum Metric { - static let coverWidth: CGFloat = 74 - static let coverHeight: CGFloat = 108 static let cornerRadius: CGFloat = 8 } public var body: some View { - GeometryReader { proxy in - HStack(spacing: spacing(for: proxy.size.width)) { - ForEach(0.. CGFloat { - guard slotCount > 1 else { return 0 } - let step = (availableWidth - Metric.coverWidth) / CGFloat(slotCount - 1) - return -(Metric.coverWidth - step) - } - - // 크기 고정 자리라 aspectRatio 파라미터 없이 .frame으로 직접 크기를 준다(WSSNovelSelectRow와 - // 동일 패턴 — 열 너비를 따라가는 그리드 셀과는 다른 경우다). + // 크기는 CoverStackLayout이 제안한 값을 그대로 받는다 — scaledToFill 표지가 넘치지 않도록 + // 프레임으로 그 크기에 묶은 뒤 자른다. private func cover(url: URL?) -> some View { WSSNovelCoverImage(url: url) - .frame(width: Metric.coverWidth, height: Metric.coverHeight) + .frame(maxWidth: .infinity, maxHeight: .infinity) .clipShape(RoundedRectangle(cornerRadius: Metric.cornerRadius)) .shadow(color: Color.black.opacity(0.1), radius: 7.5, x: 0, y: 2) } } + +/// 표지를 **카드 폭에 비례해 키우고 줄여** 어느 기기에서든 같은 비율로 겹치게 배치한다. +/// +/// Figma(375pt) 실측은 표지 74×108에 등차 58 — 겹침 비율 58/74를 고정하고, 슬롯들이 받은 폭을 정확히 +/// 채우도록 표지 크기를 역산한다. 표지 크기를 74로 고정한 채 간격만 역산하던 예전 방식은 넓은 기기 +/// (17 Pro Max의 5칸 카드)에서 간격이 양수가 돼 표지가 서로 떨어졌다(#283 실측). +/// 높이도 폭을 따라 바뀌어야 해서 `GeometryReader`(높이 고정 필요) 대신 `Layout`으로 크기를 보고한다. +private struct CoverStackLayout: Layout { + + private enum Metric { + static let coverAspectRatio: CGFloat = 108.0 / 74.0 + /// 다음 표지까지의 거리 ÷ 표지 폭(Figma 58/74). 1보다 작아야 겹친다. + static let stepRatio: CGFloat = 58.0 / 74.0 + /// 폭 제안이 없거나 무한대일 때 쓰는 Figma 원본 표지 폭. + static let idealCoverWidth: CGFloat = 74 + } + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + // 폭 제안이 없거나 무한대(가로 ScrollView 등)면 높이도 무한대가 되므로 Figma 원본 크기로 답한다. + let width = proposal.width.flatMap { $0.isFinite ? $0 : nil } + ?? totalWidth(coverWidth: Metric.idealCoverWidth, count: subviews.count) + let coverWidth = coverWidth(for: width, count: subviews.count) + return CGSize(width: width, height: coverWidth * Metric.coverAspectRatio) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + let coverWidth = coverWidth(for: bounds.width, count: subviews.count) + let coverSize = ProposedViewSize(width: coverWidth, height: coverWidth * Metric.coverAspectRatio) + + for (index, subview) in subviews.enumerated() { + let x = bounds.minX + CGFloat(index) * coverWidth * Metric.stepRatio + subview.place(at: CGPoint(x: x, y: bounds.minY), anchor: .topLeading, proposal: coverSize) + } + } + + /// 첫 표지 한 장 + 나머지마다 등차 한 칸 = 전체 폭. + private func coverWidth(for totalWidth: CGFloat, count: Int) -> CGFloat { + guard count > 0 else { return 0 } + return totalWidth / (1 + CGFloat(count - 1) * Metric.stepRatio) + } + + private func totalWidth(coverWidth: CGFloat, count: Int) -> CGFloat { + guard count > 0 else { return 0 } + return coverWidth * (1 + CGFloat(count - 1) * Metric.stepRatio) + } +} From 4bf1fc8fd25036f97bac1136a53f828d16f50b29 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:02:13 +0900 Subject: [PATCH 10/25] =?UTF-8?q?[Fix]=20#283=20-=20=EC=A0=84=EC=B2=B4=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=EB=B7=B0=EA=B0=80=20=EC=83=81?= =?UTF-8?q?=EC=84=B8=EC=97=90=EC=84=9C=20=EB=B3=B5=EA=B7=80=ED=95=98?= =?UTF-8?q?=EB=A9=B4=20=EB=AA=A9=EB=A1=9D=EC=9D=84=20=EB=8B=A4=EC=8B=9C=20?= =?UTF-8?q?=EB=B0=9B=EB=8F=84=EB=A1=9D=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 공개 목록에 본인 공개 컬렉션도 섞여, 상세에서 수정·삭제·비공개 전환한 카드가 복귀 후에도 남았다. CollectionListView와 같이 hasAppearedOnce로 복귀를 감지해 목록을 비우지 않고 첫 페이지로 교체한다. Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/CollectionFeature/CLAUDE.md | 4 +++- .../PublicCollectionListView.swift | 15 +++++++++++++-- .../PublicCollectionListViewModel.swift | 4 +++- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/Projects/Feature/CollectionFeature/CLAUDE.md b/Projects/Feature/CollectionFeature/CLAUDE.md index b5cd3a2e1..7b9553a69 100644 --- a/Projects/Feature/CollectionFeature/CLAUDE.md +++ b/Projects/Feature/CollectionFeature/CLAUDE.md @@ -236,7 +236,9 @@ - **당겨서 새로고침 + 햅틱(`HapticManager.impact(.light)`)** — 목록을 비우지 않고 첫 페이지로 교체한다. - **실패는 첫 페이지·더보기·새로고침 모두 `NetworkErrorView`로 목록을 대체한다**(Feature 로드 실패 표현 계약 — 같은 모듈 `CollectionListView`의 더보기 실패 토스트와 다르다, 그쪽이 계약 이전 코드다). -- 상세에 다녀와도 재로드하지 않는다(이 목록엔 상세에서 바뀔 값이 없다). 0건 빈 상태는 명세에 없어 따로 그리지 않는다. +- **상세에서 돌아오면 `.refresh`로 첫 페이지를 다시 받는다**(`hasAppearedOnce`, `CollectionListView`와 같은 패턴) — + 목록에 **본인 공개 컬렉션도 섞이므로** 상세에서 수정·삭제·비공개 전환된 카드가 남지 않게 하려는 것. 목록은 비우지 않고 교체한다. + ("이 목록엔 상세에서 바뀔 값이 없다"며 재로드를 뺐다가 리뷰에서 잡혔다 — 되돌리지 말 것.) 0건 빈 상태는 명세에 없어 따로 그리지 않는다. - 이벤트 트래킹은 명세에 없어 걸지 않았다(이벤트 이름을 지어내지 않는다). ## 주의사항 (작업 중 발견 시 누적) diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift index 8e8905876..cbddc5968 100644 --- a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift @@ -18,6 +18,10 @@ import WSSComponent struct PublicCollectionListView: View { @State private var viewModel: PublicCollectionListViewModel + /// 이 화면의 자식은 컬렉션 상세(App이 push)뿐이라, 두 번째 이후의 `onAppear`는 항상 "상세에서 복귀"다. + /// 목록엔 본인 공개 컬렉션도 섞여 상세에서 수정·삭제·비공개 전환될 수 있어 그때 재조회한다 + /// (`CollectionListView`의 `hasAppearedOnce`와 같은 이유). + @State private var hasAppearedOnce = false @Environment(\.dismiss) private var dismiss private let onAuthenticationRequired: () -> Void @@ -48,8 +52,15 @@ struct PublicCollectionListView: View { } .background(Color.wssWhite) .wssCustomNavigationBar() - // 카드 탭으로 상세에 다녀와도 다시 부르지 않는다 — 이 목록에 상세에서 바뀔 값(좋아요 수 등)이 없다. - .onAppear { viewModel.handle(.load) } + .onAppear { + if hasAppearedOnce { + // 목록을 비우지 않고 첫 페이지로 교체한다 — 비우면 복귀 순간 로딩 뷰로 깜빡인다. + viewModel.handle(.refresh) + } else { + hasAppearedOnce = true + viewModel.handle(.load) + } + } // 인증 만료 신호 — 실제 로그인 화면 전환은 호출자(App)가 콜백 안에서 수행한다. .onChange(of: viewModel.state.requiresAuthentication) { _, needsAuth in if needsAuth { onAuthenticationRequired() } diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift index 6ea1fb38d..417f89617 100644 --- a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift @@ -36,7 +36,7 @@ final class PublicCollectionListViewModel { enum Action { case load case loadMore - /// 당겨서 새로고침 — 목록을 비우지 않고 첫 페이지로 교체한다(비우면 인디케이터 아래가 깜빡인다). + /// 당겨서 새로고침·상세에서 복귀 — 목록을 비우지 않고 첫 페이지로 교체한다(비우면 인디케이터 아래가 깜빡인다). case refresh /// 실패 뷰(`NetworkErrorView`)의 재시도 — 처음부터 다시 세운다. case retry @@ -166,6 +166,8 @@ private extension PublicCollectionListViewModel { /// (Feature 레이어 "로드 실패 표현 계약": 토스트는 사라지면 재시도 수단이 없다). func presentLoadFailure(_ error: Error, cursor: String?) { // 인증 만료는 실패 뷰 대신 로그인 유도로 일원화 — 실패 플래그보다 먼저 거른다. + // push 화면이라 App 콜백이 루트를 교체해 이 VM째 사라지므로 1회성 신호로 충분하다 + // (`CollectionListViewModel`과 동일 — `.consumeAuthenticationRequired` 같은 소진 처리가 필요 없다). guard (error as? RepositoryError) != .authenticationRequired else { state.requiresAuthentication = true return From 099ce2fd9b6e6fb6e9c771f0fa65ff27e018d801 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:02:13 +0900 Subject: [PATCH 11/25] =?UTF-8?q?[Fix]=20#283=20-=20=ED=99=88=20=EC=BB=AC?= =?UTF-8?q?=EB=A0=89=EC=85=98=20=EC=84=B9=EC=85=98=EC=9D=84=20=EB=B0=B0?= =?UTF-8?q?=EC=A7=80=EB=B3=B4=EB=8B=A4=20=EB=A8=BC=EC=A0=80=20=EB=B0=98?= =?UTF-8?q?=EC=98=81=ED=95=98=EB=8F=84=EB=A1=9D=20=EC=88=98=ED=99=95=20?= =?UTF-8?q?=EC=88=9C=EC=84=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 컬렉션은 추천글과 선호장르 사이에 끼어드는 섹션이라, 배지 응답까지 기다리면 첫 진입 때 선호장르가 더 늦게 밀려난다. 배지는 헤더의 점 하나라 늦어도 레이아웃이 움직이지 않아 뒤로 뺐다. Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/HomeFeature/CLAUDE.md | 3 ++ .../Sources/Home/HomeViewModel.swift | 30 ++++++++++--------- 2 files changed, 19 insertions(+), 14 deletions(-) diff --git a/Projects/Feature/HomeFeature/CLAUDE.md b/Projects/Feature/HomeFeature/CLAUDE.md index 0fdbbfd02..8da244eb5 100644 --- a/Projects/Feature/HomeFeature/CLAUDE.md +++ b/Projects/Feature/HomeFeature/CLAUDE.md @@ -87,6 +87,9 @@ 카드 탭 → 컬렉션 상세(`.collectionDetail`), 작성자 라벨은 탭 없음. 카드는 표지 **4칸 고정**(모자라면 기본 표지). - **부수 콘텐츠라 실패해도 홈을 실패 뷰로 덮지 않는다** — 배지와 같은 lane: 로그만, 토스트 없음, 직전 카드 유지, 첫 로드 실패면 빈 채라 섹션이 숨는다. 추천 3종과 같은 `async let` 묶음이지만 수확은 따로다. + - ⚠️ **수확 순서는 콘텐츠 → 컬렉션 → 배지다** — 컬렉션은 추천글과 선호장르 사이에 끼어드는 섹션이라 늦게 들어올수록 + 선호장르가 아래로 밀리는 점프가 커진다(첫 진입·콜드 스타트 한정, 탭 복귀는 직전 카드가 남아 없음). 배지는 헤더의 점 + 하나라 늦어도 레이아웃이 안 움직이므로 뒤로 뺐다. 배지 뒤로 되돌리지 말 것. - 섹션이 숨으면 추천글↔선호장르 간격은 원래 값(38)으로 돌아가고, 보이면 위아래 32(Figma 실측)를 쓴다. - Figma 카드 헤더의 빈 24pt 프레임(`bookmark-outline`)은 에셋 없는 빈 자리라 그리지 않는다. diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift index 47c3a6ad1..28a342136 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift @@ -85,6 +85,9 @@ final class HomeViewModel { /// 튄다**(성공한 것처럼 보였다가 슬램). 그래서 로드 결과로만 오르내리는 플래그를 따로 둔다. @ObservationIgnored private var hasLoadedContent = false + /// 홈 섹션은 최대 10개(기획) — 가로 스크롤 첫 페이지만 쓰고 더 불러오지 않는다. + private static let publicCollectionCount = 10 + // MARK: - Dependency private let logger: Logger? @@ -102,9 +105,6 @@ final class HomeViewModel { // PushAuthorization private let pushAuthorizationChecker: PushAuthorizationChecker - /// 홈 섹션은 최대 10개(기획) — 가로 스크롤 첫 페이지만 쓰고 더 불러오지 않는다. - private static let publicCollectionCount = 10 - // MARK: - Init init( @@ -192,7 +192,7 @@ private extension HomeViewModel { state.loadFailed = nil defer { state.isLoading = false } - // 둘은 서로 독립이라 동시에 시작한다 — 순차로 펴면 왕복 지연이 그대로 더해지는데, + // 셋은 서로 독립이라 동시에 시작한다 — 순차로 펴면 왕복 지연이 그대로 더해지는데, // 홈은 탭 복귀마다 갱신하는 화면이라 그 비용을 매번 낸다. async let homeData = loadHomeDataUseCase.execute() async let notificationStatus = loadUnreadNotificationStatusUseCase.execute() @@ -221,24 +221,26 @@ private extension HomeViewModel { presentLoadFailure(.unknown) } - // 2) 배지 — 콘텐츠 성패와 무관하게 반드시 수확한다(`async let`은 스코프를 나가기 전에 - // await해야 하고, 콘텐츠가 실패했다고 배지 요청을 버릴 이유도 없다). + // 2) 컬렉션 섹션 — 콘텐츠 성패와 무관하게 수확한다. **배지보다 먼저** 꺼낸다: 콘텐츠 사이에 + // 끼어드는 섹션이라 늦을수록 아래 선호장르가 밀리는 점프가 커지는데, 배지 뒤에 두면 배지 왕복까지 + // 기다리게 된다(배지는 헤더 점 하나라 늦어도 레이아웃이 안 움직인다). do { - let loadedNotificationStatus = try await notificationStatus - state.hasUnreadNotifications = loadedNotificationStatus.hasUnreadNotifications + state.publicCollections = try await publicCollections.items } catch let error as RepositoryError { - presentBadgeFailure(error) + presentPublicCollectionsFailure(error) } catch { - presentBadgeFailure(.unknown) + presentPublicCollectionsFailure(.unknown) } - // 3) 컬렉션 섹션 — 배지와 같은 이유로 콘텐츠 성패와 무관하게 수확한다. + // 3) 배지 — 콘텐츠 성패와 무관하게 반드시 수확한다(`async let`은 스코프를 나가기 전에 + // await해야 하고, 콘텐츠가 실패했다고 배지 요청을 버릴 이유도 없다). do { - state.publicCollections = try await publicCollections.items + let loadedNotificationStatus = try await notificationStatus + state.hasUnreadNotifications = loadedNotificationStatus.hasUnreadNotifications } catch let error as RepositoryError { - presentPublicCollectionsFailure(error) + presentBadgeFailure(error) } catch { - presentPublicCollectionsFailure(.unknown) + presentBadgeFailure(.unknown) } } } From a97e5b59c19e62a839265a062750b59a1f6b6897 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:02:13 +0900 Subject: [PATCH 12/25] =?UTF-8?q?[Docs]=20#283=20-=20=ED=99=88=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=EC=9D=98=20=EB=8F=99=EC=8B=9C=20=EC=9A=94=EC=B2=AD=20?= =?UTF-8?q?=EC=88=98=EC=99=80=20=EC=BB=AC=EB=A0=89=EC=85=98=20=EC=84=B9?= =?UTF-8?q?=EC=85=98=20=ED=8A=B8=EB=9E=98=ED=82=B9=20=EB=A9=94=EB=AA=A8=20?= =?UTF-8?q?=EC=A0=95=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/HomeFeature/CLAUDE.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Projects/Feature/HomeFeature/CLAUDE.md b/Projects/Feature/HomeFeature/CLAUDE.md index 8da244eb5..f5ec48785 100644 --- a/Projects/Feature/HomeFeature/CLAUDE.md +++ b/Projects/Feature/HomeFeature/CLAUDE.md @@ -90,6 +90,7 @@ - ⚠️ **수확 순서는 콘텐츠 → 컬렉션 → 배지다** — 컬렉션은 추천글과 선호장르 사이에 끼어드는 섹션이라 늦게 들어올수록 선호장르가 아래로 밀리는 점프가 커진다(첫 진입·콜드 스타트 한정, 탭 복귀는 직전 카드가 남아 없음). 배지는 헤더의 점 하나라 늦어도 레이아웃이 안 움직이므로 뒤로 뺐다. 배지 뒤로 되돌리지 말 것. + - 섹션 탭(제목·카드) 이벤트 트래킹은 명세에 없어 걸지 않았다(이벤트 이름을 지어내지 않는다). - 섹션이 숨으면 추천글↔선호장르 간격은 원래 값(38)으로 돌아가고, 보이면 위아래 32(Figma 실측)를 쓴다. - Figma 카드 헤더의 빈 24pt 프레임(`bookmark-outline`)은 에셋 없는 빈 자리라 그리지 않는다. @@ -116,7 +117,7 @@ (`LibraryFeature`↔`NovelDomain`과 같은 형태의 이름 불일치). - **홈은 앱에서 손꼽히는 "동시 요청 5건" 지점**이다(#283 컬렉션 섹션으로 4→5) → access token이 만료된 채 진입하면 **401도 5건이 동시에** 난다. 이걸 안전하게 만드는 건 `Networking`의 재발급 직렬화(`SessionRefreshCoordinator`)다 — 그게 없으면 - 재발급이 4번 나가 refresh token 회전 때문에 3건이 실패하고 로그아웃된다(#184). + 재발급이 요청 수만큼(지금 5번) 나가 refresh token 회전 때문에 첫 1건 외엔 실패하고 로그아웃된다(#184 — 당시 4건 기준으로 발견). - ⚠️ **`.load`에 "최초 1회" 가드를 넣지 말 것** — 홈은 밖(피드 작성·선호장르 설정·알림 확인)에서 바뀐 값을 다시 비춰야 해서 **탭 복귀마다 갱신**하기로 정했다(구 WSSiOS도 `viewWillAppear`마다 전체를 다시 불렀다). 중복 요청은 `loadTask` 가드가 막는다. `LibraryFeature`의 `hasLoaded` 패턴을 그대로 옮겨오지 말 것. From dfcc112dda54690dea7089d1dc8b2bf18b485b41 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:02:13 +0900 Subject: [PATCH 13/25] =?UTF-8?q?[Test]=20#283=20-=20=EA=B3=B5=EA=B0=9C=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=20=EB=B9=88=20=ED=8E=98=EC=9D=B4?= =?UTF-8?q?=EC=A7=80=20=EA=B2=BD=EA=B3=84=EA=B0=92=20=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../UseCase/LoadPublicCollectionsUseCaseTests.swift | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift index e1d42bf41..970af1a2b 100644 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift +++ b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift @@ -64,6 +64,19 @@ struct LoadPublicCollectionsUseCaseTests { #expect(page.nextCursor == "next") } + @Test("공개 컬렉션이 하나도 없으면 빈 목록과 함께 다음 페이지가 없다고 전달한다") + func loadEmptyPage() async throws { + let mock = MockCollectionRepository() + mock.fetchPublicCollectionsResult = .success(makePage(cardCount: 0)) + let useCase = DefaultLoadPublicCollectionsUseCase(collectionRepository: mock) + + let page = try await useCase.execute(cursor: nil, size: 10) + + #expect(page.items.isEmpty) + #expect(!page.hasNext) + #expect(page.nextCursor == nil) + } + @Test("조회에 실패하면 에러를 그대로 전달한다") func loadFailure() async { let mock = MockCollectionRepository() From 70145b716e75f1618fe02afd85a4568fbe8ab0a7 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:10:24 +0900 Subject: [PATCH 14/25] =?UTF-8?q?[Fix]=20#283=20-=20=EC=A0=84=EC=B2=B4=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=EB=B7=B0=20=EB=B3=B5=EA=B7=80=20?= =?UTF-8?q?=EB=8F=99=EA=B8=B0=ED=99=94=EA=B0=80=20=EB=B0=9B=EC=9D=80=20?= =?UTF-8?q?=EA=B0=9C=EC=88=98=EB=A5=BC=20=EC=9C=A0=EC=A7=80=ED=95=98?= =?UTF-8?q?=EA=B3=A0=20=EC=8B=A4=ED=8C=A8=ED=95=B4=EB=8F=84=20=EB=AA=A9?= =?UTF-8?q?=EB=A1=9D=EC=9D=84=20=EC=A7=80=ED=82=A4=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 첫 페이지(20개)만 다시 받으면 깊이 스크롤한 뒤 복귀할 때 목록이 잘려 위치가 튀었다. 지금까지 받은 개수만큼(서버 size 상한 100) 다시 받고, 사용자가 누르지 않은 갱신이라 실패하면 직전 목록을 유지한다. Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/CollectionFeature/CLAUDE.md | 12 +++-- .../PublicCollectionListView.swift | 9 ++-- .../PublicCollectionListViewModel.swift | 49 ++++++++++++++++++- 3 files changed, 61 insertions(+), 9 deletions(-) diff --git a/Projects/Feature/CollectionFeature/CLAUDE.md b/Projects/Feature/CollectionFeature/CLAUDE.md index 7b9553a69..cc3e18e59 100644 --- a/Projects/Feature/CollectionFeature/CLAUDE.md +++ b/Projects/Feature/CollectionFeature/CLAUDE.md @@ -236,9 +236,15 @@ - **당겨서 새로고침 + 햅틱(`HapticManager.impact(.light)`)** — 목록을 비우지 않고 첫 페이지로 교체한다. - **실패는 첫 페이지·더보기·새로고침 모두 `NetworkErrorView`로 목록을 대체한다**(Feature 로드 실패 표현 계약 — 같은 모듈 `CollectionListView`의 더보기 실패 토스트와 다르다, 그쪽이 계약 이전 코드다). -- **상세에서 돌아오면 `.refresh`로 첫 페이지를 다시 받는다**(`hasAppearedOnce`, `CollectionListView`와 같은 패턴) — - 목록에 **본인 공개 컬렉션도 섞이므로** 상세에서 수정·삭제·비공개 전환된 카드가 남지 않게 하려는 것. 목록은 비우지 않고 교체한다. - ("이 목록엔 상세에서 바뀔 값이 없다"며 재로드를 뺐다가 리뷰에서 잡혔다 — 되돌리지 말 것.) 0건 빈 상태는 명세에 없어 따로 그리지 않는다. +- **상세에서 돌아오면 `.syncAfterReturn`으로 지금까지 받은 개수만큼(최대 100, 서버 `size` 상한) 첫 페이지부터 다시 받는다** + (`hasAppearedOnce`, 사용자 확정 2026-10-12) — 목록에 **본인 공개 컬렉션도 섞이므로** 상세에서 수정·삭제·비공개 전환된 + 카드가 남지 않게 하려는 것. + - ⚠️ **첫 페이지(20개)만 다시 받지 말 것** — 더보기로 깊이 내려간 뒤 복귀하면 목록이 20개로 잘려 스크롤 위치가 튀고, + 새로 보이게 된 마지막 셀이 더보기를 다시 부른다(리뷰 2라운드에서 잡힘). 받은 개수만큼 받으면 길이가 유지돼 위치도 남는다. + - ⚠️ **이 자동 동기화가 실패하면 실패 뷰로 덮지 않고 직전 목록을 유지한다**(로그만) — 사용자가 누르지 않은 갱신이라 + 멀쩡히 보던 목록을 걷어낼 이유가 없다. 위 "실패는 실패 뷰" 계약의 **의도된 예외**이고, 당겨서 새로고침(`.refresh`)은 + 사용자 액션이라 여전히 실패 뷰다. 보여줄 목록이 없으면(첫 로드 실패·0건) 동기화 대신 처음부터 다시 로드한다. + - ("이 목록엔 상세에서 바뀔 값이 없다"며 재로드를 뺐다가 1라운드 리뷰에서 잡혔다 — 되돌리지 말 것.) 0건 빈 상태는 명세에 없어 따로 그리지 않는다. - 이벤트 트래킹은 명세에 없어 걸지 않았다(이벤트 이름을 지어내지 않는다). ## 주의사항 (작업 중 발견 시 누적) diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift index cbddc5968..8362f7118 100644 --- a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift @@ -18,9 +18,9 @@ import WSSComponent struct PublicCollectionListView: View { @State private var viewModel: PublicCollectionListViewModel - /// 이 화면의 자식은 컬렉션 상세(App이 push)뿐이라, 두 번째 이후의 `onAppear`는 항상 "상세에서 복귀"다. - /// 목록엔 본인 공개 컬렉션도 섞여 상세에서 수정·삭제·비공개 전환될 수 있어 그때 재조회한다 - /// (`CollectionListView`의 `hasAppearedOnce`와 같은 이유). + /// 이 화면의 자식은 컬렉션 상세(App이 push)뿐이라, 두 번째 이후의 `onAppear`는 사실상 "상세에서 복귀"다 + /// (상세에서 스와이프백을 하다 취소해도 다시 불리지만 동기화 1회가 더 나갈 뿐 무해하다). 목록엔 본인 공개 + /// 컬렉션도 섞여 상세에서 수정·삭제·비공개 전환될 수 있어 그때 동기화한다(`CollectionListView`와 같은 이유). @State private var hasAppearedOnce = false @Environment(\.dismiss) private var dismiss @@ -54,8 +54,7 @@ struct PublicCollectionListView: View { .wssCustomNavigationBar() .onAppear { if hasAppearedOnce { - // 목록을 비우지 않고 첫 페이지로 교체한다 — 비우면 복귀 순간 로딩 뷰로 깜빡인다. - viewModel.handle(.refresh) + viewModel.handle(.syncAfterReturn) } else { hasAppearedOnce = true viewModel.handle(.load) diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift index 417f89617..aade42308 100644 --- a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift @@ -36,8 +36,11 @@ final class PublicCollectionListViewModel { enum Action { case load case loadMore - /// 당겨서 새로고침·상세에서 복귀 — 목록을 비우지 않고 첫 페이지로 교체한다(비우면 인디케이터 아래가 깜빡인다). + /// 당겨서 새로고침 — 목록을 비우지 않고 첫 페이지로 교체한다(비우면 인디케이터 아래가 깜빡인다). case refresh + /// 상세에서 복귀 — 본인 컬렉션의 수정·삭제·비공개 전환을 반영하려고 **지금까지 받은 개수만큼** 다시 받는다. + /// 사용자가 누른 게 아니라서 실패해도 실패 뷰로 덮지 않고 직전 목록을 유지한다(사용자 확정 2026-10-12). + case syncAfterReturn /// 실패 뷰(`NetworkErrorView`)의 재시도 — 처음부터 다시 세운다. case retry } @@ -56,6 +59,8 @@ final class PublicCollectionListViewModel { /// 서버 권장 페이지 크기가 따로 없어 화면이 정한다(`CollectionListViewModel`과 같은 값). private static let pageSize = 20 + /// 서버가 받는 `size` 상한(넘으면 `COLLECTION-008`). 복귀 동기화가 받은 개수만큼 다시 받을 때의 천장이다. + private static let maxPageSize = 100 // MARK: - Dependency @@ -87,6 +92,13 @@ final class PublicCollectionListViewModel { reload(clearingItems: false) case .retry: reload(clearingItems: true) + case .syncAfterReturn: + // 보여줄 목록이 없으면(첫 로드 실패·0건) 동기화할 대상이 없으니 처음부터 다시 세운다. + if state.items.isEmpty || state.loadFailed != nil { + reload(clearingItems: true) + } else { + syncLoadedItems() + } } } @@ -118,6 +130,18 @@ private extension PublicCollectionListViewModel { loadTask = Task { await loadPage(cursor: nil, generation: generation) } } + /// 받은 만큼을 첫 페이지부터 한 번에 다시 받는다 — 첫 페이지(20개)만 받으면 깊이 스크롤한 목록이 + /// 잘려 보던 위치가 튄다. 상한(100)을 넘게 내려갔던 경우만 그만큼 잘린다. + func syncLoadedItems() { + generation += 1 + loadTask?.cancel() + state.isLoadingMore = false + + let size = min(max(Self.pageSize, state.items.count), Self.maxPageSize) + let generation = generation + loadTask = Task { await syncPage(size: size, generation: generation) } + } + /// 다음 페이지. 커서는 직전 응답의 `nextCursor`를 그대로 왕복한다. func loadMore() { guard hasNext, loadTask == nil, !state.isLoading, state.loadFailed == nil, @@ -156,6 +180,29 @@ private extension PublicCollectionListViewModel { presentLoadFailure(error, cursor: cursor) } } + + /// 성공하면 목록·커서를 응답으로 교체하고, 실패하면 아무것도 안 바꾼다(직전 목록·커서가 그대로 유효하다). + func syncPage(size: Int, generation: Int) async { + defer { + if self.generation == generation { + loadTask = nil + } + } + do { + let page = try await loadPublicCollectionsUseCase.execute(cursor: nil, size: size) + guard self.generation == generation, !Task.isCancelled else { return } + state.items = page.items + nextCursor = page.nextCursor + hasNext = page.hasNext + } catch { + guard self.generation == generation, !Task.isCancelled else { return } + if error == .authenticationRequired { + state.requiresAuthentication = true + return + } + logger?.error("PublicCollectionList 복귀 동기화 실패(직전 목록 유지): \(String(describing: error))") + } + } } // MARK: - Error Mapping From 6c0efbdf9b2fa2d19686ef13dbb15ae679154c56 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:15:31 +0900 Subject: [PATCH 15/25] =?UTF-8?q?[Fix]=20#283=20-=20=EC=A0=84=EC=B2=B4=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=EB=B7=B0=20=EB=B3=B5=EA=B7=80=20?= =?UTF-8?q?=EB=8F=99=EA=B8=B0=ED=99=94=20=EC=A4=91=20=EB=A7=89=ED=9E=8C=20?= =?UTF-8?q?=EB=8D=94=EB=B3=B4=EA=B8=B0=EB=A5=BC=20=EC=9D=B4=EC=96=B4?= =?UTF-8?q?=EC=84=9C=20=EB=B6=88=EB=9F=AC=EC=98=A4=EB=8F=84=EB=A1=9D=20?= =?UTF-8?q?=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 동기화는 목록 길이와 마지막 카드를 유지해 마지막 셀의 onAppear가 다시 불리지 않으므로, 그동안 막힌 더보기를 버리면 하단에서 무한 스크롤이 멈췄다. 동기화 중 들어온(또는 동기화가 취소한) 더보기를 기억했다가 동기화가 끝나면 이어서 부른다. Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/CollectionFeature/CLAUDE.md | 5 +++++ .../PublicCollectionListView.swift | 2 +- .../PublicCollectionListViewModel.swift | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/Projects/Feature/CollectionFeature/CLAUDE.md b/Projects/Feature/CollectionFeature/CLAUDE.md index cc3e18e59..e3fd11ed9 100644 --- a/Projects/Feature/CollectionFeature/CLAUDE.md +++ b/Projects/Feature/CollectionFeature/CLAUDE.md @@ -244,6 +244,11 @@ - ⚠️ **이 자동 동기화가 실패하면 실패 뷰로 덮지 않고 직전 목록을 유지한다**(로그만) — 사용자가 누르지 않은 갱신이라 멀쩡히 보던 목록을 걷어낼 이유가 없다. 위 "실패는 실패 뷰" 계약의 **의도된 예외**이고, 당겨서 새로고침(`.refresh`)은 사용자 액션이라 여전히 실패 뷰다. 보여줄 목록이 없으면(첫 로드 실패·0건) 동기화 대신 처음부터 다시 로드한다. + - ⚠️ **동기화 중 들어온 더보기는 버리지 말고 기억했다가(`pendingLoadMore`) 동기화가 끝나면 이어 부른다** — 동기화는 목록 + 길이·마지막 카드를 그대로 두므로 마지막 셀의 `onAppear`가 다시 안 불려, 버리면 `hasNext`인데 하단에서 무한 스크롤이 멈춘다 + (리뷰 3라운드에서 잡힘). 진행 중이던 더보기를 동기화가 취소한 경우도 같은 플래그로 재시도한다. + - 상세를 보는 사이 새 컬렉션이 생기면 동기화 결과가 그만큼 아래로 밀린다(같은 길이지만 내용이 k장 이동) — 커서 체계상 + 중복·누락은 없어 감수한다. 다른 탭에 다녀와도 `onAppear`가 다시 불려 동기화가 나가지만 무해하다. - ("이 목록엔 상세에서 바뀔 값이 없다"며 재로드를 뺐다가 1라운드 리뷰에서 잡혔다 — 되돌리지 말 것.) 0건 빈 상태는 명세에 없어 따로 그리지 않는다. - 이벤트 트래킹은 명세에 없어 걸지 않았다(이벤트 이름을 지어내지 않는다). diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift index 8362f7118..cd57f2420 100644 --- a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListView.swift @@ -19,7 +19,7 @@ struct PublicCollectionListView: View { @State private var viewModel: PublicCollectionListViewModel /// 이 화면의 자식은 컬렉션 상세(App이 push)뿐이라, 두 번째 이후의 `onAppear`는 사실상 "상세에서 복귀"다 - /// (상세에서 스와이프백을 하다 취소해도 다시 불리지만 동기화 1회가 더 나갈 뿐 무해하다). 목록엔 본인 공개 + /// (탭 전환·스와이프백 취소로도 다시 불리지만 동기화 1회가 더 나갈 뿐 무해하다). 목록엔 본인 공개 /// 컬렉션도 섞여 상세에서 수정·삭제·비공개 전환될 수 있어 그때 동기화한다(`CollectionListView`와 같은 이유). @State private var hasAppearedOnce = false @Environment(\.dismiss) private var dismiss diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift index aade42308..58a99f13b 100644 --- a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift @@ -56,6 +56,10 @@ final class PublicCollectionListViewModel { @ObservationIgnored private var hasNext = true @ObservationIgnored private var generation = 0 @ObservationIgnored private var loadTask: Task? + /// 지금 `loadTask`가 복귀 동기화인지. 동기화는 목록 길이를 유지해 마지막 셀이 다시 나타나지 않으므로, + /// 그동안 막힌 더보기를 `pendingLoadMore`로 기억했다가 동기화가 끝나면 이어서 부른다(안 그러면 하단에서 멈춘다). + @ObservationIgnored private var isSyncing = false + @ObservationIgnored private var pendingLoadMore = false /// 서버 권장 페이지 크기가 따로 없어 화면이 정한다(`CollectionListViewModel`과 같은 값). private static let pageSize = 20 @@ -116,6 +120,8 @@ private extension PublicCollectionListViewModel { func reload(clearingItems: Bool) { generation += 1 loadTask?.cancel() + isSyncing = false + pendingLoadMore = false nextCursor = nil hasNext = true @@ -135,6 +141,9 @@ private extension PublicCollectionListViewModel { func syncLoadedItems() { generation += 1 loadTask?.cancel() + // 진행 중이던 더보기를 취소하므로 동기화가 끝나면 다시 시도한다. + pendingLoadMore = pendingLoadMore || state.isLoadingMore + isSyncing = true state.isLoadingMore = false let size = min(max(Self.pageSize, state.items.count), Self.maxPageSize) @@ -144,6 +153,10 @@ private extension PublicCollectionListViewModel { /// 다음 페이지. 커서는 직전 응답의 `nextCursor`를 그대로 왕복한다. func loadMore() { + if isSyncing { + pendingLoadMore = true + return + } guard hasNext, loadTask == nil, !state.isLoading, state.loadFailed == nil, let cursor = nextCursor else { return } state.isLoadingMore = true @@ -186,6 +199,11 @@ private extension PublicCollectionListViewModel { defer { if self.generation == generation { loadTask = nil + isSyncing = false + if pendingLoadMore { + pendingLoadMore = false + loadMore() + } } } do { From d6541cbfc635c3dbfbb4f430a07cce1347686bb0 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:20:15 +0900 Subject: [PATCH 16/25] =?UTF-8?q?[Docs]=20#283=20-=20=EC=A0=84=EC=B2=B4=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=EB=B7=B0=20=EC=A1=B0=EB=A6=BD=20?= =?UTF-8?q?=EC=9C=84=EC=B9=98=EC=99=80=20=EC=BB=AC=EB=A0=89=EC=85=98=20?= =?UTF-8?q?=EB=AA=A9=EB=A1=9D=20size=20=EC=83=81=ED=95=9C=20=EB=AC=B8?= =?UTF-8?q?=EC=84=9C=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Projects/App/CLAUDE.md | 11 +++++++---- Projects/Data/CollectionData/CLAUDE.md | 5 ++++- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Projects/App/CLAUDE.md b/Projects/App/CLAUDE.md index ca9eadf02..376a5796d 100644 --- a/Projects/App/CLAUDE.md +++ b/Projects/App/CLAUDE.md @@ -34,7 +34,8 @@ Sources/ │ # makeDetailSearchFilterView로 승격)까지(NovelDetailAssembly/ │ # NovelReviewAssembly/FeedFeatureFactory/UserPageAssembly/ │ # LibraryFactory.makeUserLibraryView(타유저 서재)/SearchAssembly/ -│ # MypageFeatureFactory) 실제 push. +│ # MypageFeatureFactory) 실제 push. 홈 "컬렉션 모음.zip" 섹션의 +│ # 전체 컬렉션뷰·컬렉션 상세도 여기서 push(#283). ├── Feed/ └── FeedRootView.swift # "피드" 탭. FeedFeatureFactory.makeSosoFeedView 조립 + 피드 상세· │ # 작품 상세·작품 평가·피드 작성·타유저 프로필·그 전체 피드 목록· │ # 그 프로필의 타유저 서재·작가 이름 검색(makeFeedDetailView/ @@ -84,9 +85,11 @@ Sources/ │ # switch(#253 — 예전 onEditTapped 기본값 no-op은 #228 죽은 │ # 버튼 사고를 만들어 제거). 타유저 컬렉션은 isMine==false라 │ # 수정 버튼 자체가 안 뜨지만 매핑은 전 호출자가 명시한다. - └── CollectionListAssembly.swift # 컬렉션 목록 조립 공용 헬퍼 — isOwnCollections 기본값 false - # (타유저 프로필 "컬렉션" 헤더 탭). 마이페이지의 "내 컬렉션" - # 목록만 true로 명시 호출. + ├── CollectionListAssembly.swift # 컬렉션 목록 조립 공용 헬퍼 — isOwnCollections 기본값 false + │ # (타유저 프로필 "컬렉션" 헤더 탭). 마이페이지의 "내 컬렉션" + │ # 목록만 true로 명시 호출. + └── PublicCollectionListAssembly.swift # 전체 컬렉션뷰(모든 사용자의 공개 컬렉션) 조립 — 진입점은 + # 홈 컬렉션 섹션 제목 하나뿐이라 HomeRootView만 쓴다(#283). ``` 4탭 콘텐츠 자체(각 Factory의 메인 화면)는 전부 실제 UseCase로 조립돼 있고, 그 안에서 열리는 2차 diff --git a/Projects/Data/CollectionData/CLAUDE.md b/Projects/Data/CollectionData/CLAUDE.md index 7c2c6b12e..1b77d0611 100644 --- a/Projects/Data/CollectionData/CLAUDE.md +++ b/Projects/Data/CollectionData/CLAUDE.md @@ -18,7 +18,7 @@ 어디서도 다시 뒤집지 말 것. - **에러는 상태 코드가 아니라 `code` 문자열로 분기할 여지가 크다(현재는 미구현 — 소비 화면 연결 시 도입 예정).** `400` 하나에 `BAD_REQUEST`·`COLLECTION-002`(작품 1~100개)·`COLLECTION-003`(중복 작품)· - `COLLECTION-004`(대표 작품이 목록에 없음)·`COLLECTION-007`(잘못된 커서)·`COLLECTION-008`(size 범위)이 공존하고, + `COLLECTION-004`(대표 작품이 목록에 없음)·`COLLECTION-007`(잘못된 커서 — 다른 목록의 커서 포함)·`COLLECTION-008`(size가 1~100 밖)이 공존하고, `401`도 `AUTH-000`/`AUTH-001`/`AUTH-003`으로 갈린다. 지금 `DefaultCollectionRepository`는 공용 `NetworkingError.toRepositoryError()`만 쓴다 — Feature가 아직 없어 코드별 구분을 미뤄뒀다. 화면에서만 의미가 다른 코드가 필요해지면 공용 변환에 섞지 말고 이 모듈의 리포지토리 메서드에서 변환할 것 @@ -36,6 +36,9 @@ - 컬렉션 상세와 전체 공개 목록(`GET /collections`)만 `usesTokenIfAvailable`이다(비로그인도 조회 가능 — 공개 목록은 토큰이 있으면 차단 관계 작성자를 빼므로 있으면 붙인다). 나머지는 `requireToken` — 목록 API의 비로그인 허용 여부는 서버 명세에 명시가 없어 보수적으로 잡아뒀다. 비로그인 진입 경로가 생기면 그때 확인해 바꾼다. +- **목록 `size` 상한은 서버 기준 100이다**(`GET /collections` 명세 "1개 이상 100개 이하") — 전체 컬렉션뷰의 상세 복귀 동기화가 + 받은 개수만큼 다시 받을 때 이 값으로 자른다(`PublicCollectionListViewModel.maxPageSize`). 서버 상한이 바뀌면 함께 고칠 것 — + 넘기면 `COLLECTION-008`인데, 그 동기화는 실패해도 조용히 직전 목록을 유지하는 설계라 어긋나도 드러나지 않는다. - **전체 공개 목록은 `CollectionsResponse`를 재사용하지 않고 `PublicCollectionsResponse`를 따로 둔다** — 같은 `nextCursor`·`hasNext` 구조지만 `collectionsCount`·`isPublic`·`representativeNovel`이 없고 `owner`가 있어, 공용 DTO에 optional을 늘리면 기존 두 목록의 필수값 디코딩 검증이 약해진다. 커서는 목록마다 서버가 따로 발급한다(다른 목록 커서를 넣으면 `COLLECTION-007`). From aaf97cc52d0adfb9a3d7324dc462aa5478aef545 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 12 Oct 2026 15:43:48 +0900 Subject: [PATCH 17/25] =?UTF-8?q?[Fix]=20#283=20-=20=EC=B9=B8=EA=B3=BC=20?= =?UTF-8?q?=EB=B9=84=EC=9C=A8=EC=9D=B4=20=EB=8B=A4=EB=A5=B8=20=EC=BB=AC?= =?UTF-8?q?=EB=A0=89=EC=85=98=20=ED=91=9C=EC=A7=80=EA=B0=80=20=EC=B9=B8=20?= =?UTF-8?q?=EB=B0=96=EC=9C=BC=EB=A1=9C=20=EB=84=98=EC=B9=98=EB=8A=94=20?= =?UTF-8?q?=EB=AC=B8=EC=A0=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 표지를 maxWidth/maxHeight만 준 flexible frame으로 감싸 자식 크기가 하한이 되면서, scaledToFill 표지가 비율만큼 칸 밖으로 넘쳤다(세로로 긴 표지는 아래로, 가로로 긴 표지는 옆 칸으로). WSSNovelCoverImage의 aspectRatio로 칸을 비율 고정·클립하고, 재현되도록 홈 Demo Mock 표지 비율을 섞었다. Co-Authored-By: Claude Opus 5.5 --- .../HomeFeature/Demo/HomeFeatureDemoApp.swift | 4 +++- Projects/UI/WSSComponent/CLAUDE.md | 4 ++++ .../Collection/WSSCollectionCoverStack.swift | 14 +++++++++----- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift index 85d083640..9aee8af8e 100644 --- a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift +++ b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift @@ -378,7 +378,9 @@ private struct DemoLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { id: NovelID(index * 10 + novelIndex), title: "작품 \(novelIndex)", author: "작가", - thumbnailImage: URL(string: "https://picsum.photos/seed/wsshome\(index)\(novelIndex)/148/216") + // 실서버 표지는 비율이 제각각이라 세로로 긴·가로로 긴·칸과 같은 비율을 섞는다 — + // 칸 비율(74:108)과 같은 표지만 쓰면 표지가 칸 밖으로 넘치는 회귀가 Mock에서 안 보인다(#283). + thumbnailImage: URL(string: "https://picsum.photos/seed/wsshome\(index)\(novelIndex)/\(["148/300", "240/216", "148/216"][novelIndex % 3])") ) }, owner: Author(userId: UserID(index + 1), nickname: "코띠", profileImage: nil) diff --git a/Projects/UI/WSSComponent/CLAUDE.md b/Projects/UI/WSSComponent/CLAUDE.md index a30677e7a..cf698940a 100644 --- a/Projects/UI/WSSComponent/CLAUDE.md +++ b/Projects/UI/WSSComponent/CLAUDE.md @@ -32,6 +32,10 @@ 양수가 돼 표지가 서로 떨어졌다(#283 실측). 지금은 Figma 겹침 비율(등차 58 ÷ 표지 74)을 고정하고 **표지 크기를 카드 폭에 비례해 키우고 줄이는** `Layout`(`CoverStackLayout`)이다 — 높이도 폭을 따라 바뀌므로 호출부에서 높이를 고정하지 말 것. 폭 제안이 nil·무한대면 Figma 원본 크기로 답한다(무한대 그대로 쓰면 높이까지 무한대가 된다). + ⚠️ **표지는 `WSSNovelCoverImage(aspectRatio:)`로 그린다 — `.frame(maxWidth: .infinity, maxHeight: .infinity)`로 감싸지 말 것.** + flexible frame은 min을 안 주면 **자식 크기를 하한**으로 삼아, 칸과 비율이 다른 표지(`scaledToFill`)가 그만큼 칸 밖으로 넘친다 + — 세로로 긴 표지는 아래로 튀고 가로로 긴 표지는 옆 칸을 덮었다(#283 실기기, 표지 비율에 따라 "가끔"만 보여 놓치기 쉽다). + Demo Mock 표지가 칸과 같은 비율(148×216)뿐이면 재현이 안 되므로 HomeFeature Demo는 일부러 비율을 섞어 둔다. - **`WSSEmptyView`의 CTA는 선택이다** — `action`을 생략(nil)하거나 `type.buttonTitle`이 nil이면 **버튼과 그 위 간격(36)이 함께 사라진다**. 유도할 행동이 없는 빈 상태(`.notification` — 알림 목록)를 화면마다 다시 그리지 않으려고 #181에서 열었다. `action`에 기본값이 있어 기존 호출부는 그대로 동작한다. - ⚠️ **`LibraryFeature`의 `noMatchSection`(필터 0건)은 아직 이 컴포넌트로 옮기지 않았다** — 그쪽은 이미지를 39×48로 줄이고 상단 여백 120을 직접 잡는 등 **렌더가 달라서**, 옮기면 서재 화면 재검증이 필요하다. 옮길 거면 크기 파라미터를 열지 말고 **왜 두 빈 상태의 이미지 크기가 다른지부터** 디자인과 정할 것. - **`NetworkErrorView`는 로드 실패 전면 뷰(재시도 버튼 내장)다** — `init(error: RepositoryError = .unknown, action:)`(#244). 잡은 `RepositoryError`를 받아 title/description을 **3분류로 가른다**: `serverUnavailable`("서버에 문제가\n생겼어요" / "잠시 후 다시 시도해 주세요"), `networkUnavailable`("네트워크 연결에\n실패했어요" / "연결 상태를 확인한 후\n다시 시도해 보세요"), 그 외 `default`("일시적인 오류가\n발생했어요" / "다시 시도해 주세요"). 일러스트(`imgEmptyCatQuestionmark`)·"페이지 다시 불러오기" 버튼·레이아웃은 케이스 불문 **동일** — 문구만 분기. diff --git a/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift index dd1dff456..ab7074c0a 100644 --- a/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift +++ b/Projects/UI/WSSComponent/Sources/Collection/WSSCollectionCoverStack.swift @@ -45,11 +45,12 @@ public struct WSSCollectionCoverStack: View { } } - // 크기는 CoverStackLayout이 제안한 값을 그대로 받는다 — scaledToFill 표지가 넘치지 않도록 - // 프레임으로 그 크기에 묶은 뒤 자른다. + // 크기는 CoverStackLayout이 제안한 값(표지 비율 그대로)을 받는다. ⚠️ `.frame(maxWidth:maxHeight: .infinity)`로 + // 묶지 말 것 — min을 안 주면 자식 크기가 하한이 돼, 칸과 비율이 다른 표지(scaledToFill)가 그만큼 칸 밖으로 + // 넘친다(세로로 긴 표지는 아래로 튀고, 가로로 긴 표지는 옆 칸을 덮었다 — #283 실기기). 컴포넌트의 `aspectRatio:`가 + // 칸을 비율로 고정하고 넘친 그림을 그 안에서 자른다. private func cover(url: URL?) -> some View { - WSSNovelCoverImage(url: url) - .frame(maxWidth: .infinity, maxHeight: .infinity) + WSSNovelCoverImage(url: url, aspectRatio: CoverStackLayout.coverWidthToHeight) .clipShape(RoundedRectangle(cornerRadius: Metric.cornerRadius)) .shadow(color: Color.black.opacity(0.1), radius: 7.5, x: 0, y: 2) } @@ -63,8 +64,11 @@ public struct WSSCollectionCoverStack: View { /// 높이도 폭을 따라 바뀌어야 해서 `GeometryReader`(높이 고정 필요) 대신 `Layout`으로 크기를 보고한다. private struct CoverStackLayout: Layout { + /// 표지 폭 ÷ 높이(Figma 74×108). `WSSNovelCoverImage(aspectRatio:)`가 받는 방향이다. + static let coverWidthToHeight: CGFloat = 74.0 / 108.0 + private enum Metric { - static let coverAspectRatio: CGFloat = 108.0 / 74.0 + static let coverAspectRatio: CGFloat = 1 / CoverStackLayout.coverWidthToHeight /// 다음 표지까지의 거리 ÷ 표지 폭(Figma 58/74). 1보다 작아야 겹친다. static let stepRatio: CGFloat = 58.0 / 74.0 /// 폭 제안이 없거나 무한대일 때 쓰는 Figma 원본 표지 폭. From 13bac9245e02d0c8f99dbc18d6bf42660a5fb7ae Mon Sep 17 00:00:00 2001 From: Guryss Date: Sat, 17 Oct 2026 10:53:13 +0900 Subject: [PATCH 18/25] =?UTF-8?q?[Design]=20#283=20-=20=ED=99=88=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=20=EB=AA=A8=EC=9D=8C.zip=20?= =?UTF-8?q?=EC=84=B9=EC=85=98=EC=9D=84=20=EC=83=81=EC=84=B8=ED=83=90?= =?UTF-8?q?=EC=83=89=20=EB=B0=B0=EB=84=88=20=EC=95=84=EB=9E=98=EB=A1=9C=20?= =?UTF-8?q?=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/HomeFeature/CLAUDE.md | 13 ++++--- .../HomeFeature/Sources/Home/HomeView.swift | 38 +++++++++---------- .../Sources/Home/HomeViewModel.swift | 25 ++++++------ 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/Projects/Feature/HomeFeature/CLAUDE.md b/Projects/Feature/HomeFeature/CLAUDE.md index f5ec48785..18870e8d7 100644 --- a/Projects/Feature/HomeFeature/CLAUDE.md +++ b/Projects/Feature/HomeFeature/CLAUDE.md @@ -30,8 +30,8 @@ 일부러 안 쓴다: 배지는 실패해도 "보이는 고장"이 없어 멀쩡한 홈 위의 에러 토스트가 설명이 안 되고, 탭 복귀 갱신마다 반복 노출만 된다(다음 탭 복귀가 자동 재시도 = self-healing). 인증 만료만은 배지 경로에서도 로그인 라우팅을 태운다(idempotent 계약이라 안전). -- **섹션 5개**: 검색바·상세검색 배너 / 오늘의 발견(가로 캐러셀) / {닉네임}님을 위한 추천글(2개씩 3페이지) / - 컬렉션 모음.zip(공개 컬렉션 가로 스크롤, #283) / 이 웹소설은 어때요?(2열 그리드, 선호장르 미설정이면 설정 유도 CTA). +- **섹션 5개**: 검색바·상세검색 배너 / 컬렉션 모음.zip(공개 컬렉션 가로 스크롤, #283) / 오늘의 발견(가로 캐러셀) / + {닉네임}님을 위한 추천글(2개씩 3페이지) / 이 웹소설은 어때요?(2열 그리드, 선호장르 미설정이면 설정 유도 CTA). - 선택 결과는 전부 콜백으로 상위에 위임한다 — 이 화면은 스스로 화면을 전환하지 않는다. - **홈 진입마다 시스템 푸시 권한을 확인, notDetermined면 그 자리에서 시스템 프롬프트(#193)**: `onAppear`의 `.load`와 별도로 `.checkPushAuthorizationOnEntry`를 함께 보낸다. 회원가입 직후 첫 홈 @@ -87,11 +87,12 @@ 카드 탭 → 컬렉션 상세(`.collectionDetail`), 작성자 라벨은 탭 없음. 카드는 표지 **4칸 고정**(모자라면 기본 표지). - **부수 콘텐츠라 실패해도 홈을 실패 뷰로 덮지 않는다** — 배지와 같은 lane: 로그만, 토스트 없음, 직전 카드 유지, 첫 로드 실패면 빈 채라 섹션이 숨는다. 추천 3종과 같은 `async let` 묶음이지만 수확은 따로다. - - ⚠️ **수확 순서는 콘텐츠 → 컬렉션 → 배지다** — 컬렉션은 추천글과 선호장르 사이에 끼어드는 섹션이라 늦게 들어올수록 - 선호장르가 아래로 밀리는 점프가 커진다(첫 진입·콜드 스타트 한정, 탭 복귀는 직전 카드가 남아 없음). 배지는 헤더의 점 - 하나라 늦어도 레이아웃이 안 움직이므로 뒤로 뺐다. 배지 뒤로 되돌리지 말 것. + - ⚠️ **수확 순서는 컬렉션 → 콘텐츠 → 배지다** — 최상단 섹션이라 콘텐츠 뒤에 들어오면 그 아래 섹션 전부가 밀린다. + 컬렉션을 먼저 state에 넣어도 `hasLoadedContent`가 false인 동안은 로딩 뷰가 덮고 있어 콘텐츠와 같은 프레임에 함께 + 그려진다(동시 요청이라 총 대기시간은 그대로). 배지는 헤더의 점 하나라 늦어도 레이아웃이 안 움직여 맨 뒤다. + 콘텐츠 뒤로 되돌리지 말 것. - 섹션 탭(제목·카드) 이벤트 트래킹은 명세에 없어 걸지 않았다(이벤트 이름을 지어내지 않는다). - - 섹션이 숨으면 추천글↔선호장르 간격은 원래 값(38)으로 돌아가고, 보이면 위아래 32(Figma 실측)를 쓴다. + - 섹션이 숨으면 오늘의 발견이 검색 영역에 바로 붙는다(간격 24 그대로). 보이면 검색 영역↔컬렉션 24, 컬렉션↔오늘의 발견 32. - Figma 카드 헤더의 빈 24pt 프레임(`bookmark-outline`)은 에셋 없는 빈 자리라 그리지 않는다. ### 실서버가 주는 개수 (시안과 일치 — #179 실측) diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift index 32309df42..ee71f40fb 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift @@ -26,12 +26,11 @@ struct HomeView: View { private let onAuthenticationRequired: () -> Void private enum Metric { + static let searchToCollection: CGFloat = 24 + static let collectionToDiscovery: CGFloat = 32 static let searchToDiscovery: CGFloat = 24 static let discoveryToTrending: CGFloat = 32 static let trendingToPreference: CGFloat = 38 - /// 컬렉션 섹션 위아래 간격(Figma 실측 — 추천글 섹션 끝 ↔ 컬렉션 섹션 ↔ 선호장르 섹션 모두 32). - static let trendingToCollection: CGFloat = 32 - static let collectionToPreference: CGFloat = 32 static let bottomInset: CGFloat = 40 static let sectionTitleSpacing: CGFloat = 16 @@ -118,8 +117,22 @@ private extension HomeView { ) // 섹션은 값이 없으면 제목까지 통째로 사라진다 — 아래 섹션이 그만큼 올라붙는다. + // 컬렉션 섹션은 0건이거나 첫 로드에 실패하면 숨는다 — 그땐 오늘의 발견이 검색 영역에 바로 붙는다. + if !state.publicCollections.isEmpty { + Spacer().frame(height: Metric.searchToCollection) + PublicCollectionSection( + collections: state.publicCollections, + onTitleTapped: { onRoute(.publicCollectionList) }, + onCollectionSelected: { onRoute(.collectionDetail($0)) } + ) + } + if !state.todayDiscoveries.isEmpty { - Spacer().frame(height: Metric.searchToDiscovery) + Spacer().frame( + height: state.publicCollections.isEmpty + ? Metric.searchToDiscovery + : Metric.collectionToDiscovery + ) todayDiscoverySection(state.todayDiscoveries) } @@ -135,26 +148,11 @@ private extension HomeView { ) } - // 컬렉션 섹션은 0건이거나 첫 로드에 실패하면 숨는다 — 그땐 추천글↔선호장르 간격이 - // 원래 값(trendingToPreference) 그대로 남는다. - if !state.publicCollections.isEmpty { - Spacer().frame(height: Metric.trendingToCollection) - PublicCollectionSection( - collections: state.publicCollections, - onTitleTapped: { onRoute(.publicCollectionList) }, - onCollectionSelected: { onRoute(.collectionDetail($0)) } - ) - } - // 선호장르 섹션은 0건(설정했으나 추천 0건)이어도 숨기지 않고 설정 유도 카드를 띄운다 // (#222 V1 parity — 빈 자리보다 행동 유도가 낫다). 빈 그리드 vs 유도 카드 분기는 // PreferenceGenreSection이 상태로 판단한다. nil(로드 전)일 때만 섹션을 안 그린다. if let preferenceGenreNovelState = state.preferenceGenreNovelState { - Spacer().frame( - height: state.publicCollections.isEmpty - ? Metric.trendingToPreference - : Metric.collectionToPreference - ) + Spacer().frame(height: Metric.trendingToPreference) PreferenceGenreSection( state: preferenceGenreNovelState, onNovelSelected: { novelID in diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift index 28a342136..3e2b1e264 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift @@ -201,7 +201,19 @@ private extension HomeViewModel { size: Self.publicCollectionCount ) - // 1) 콘텐츠 — 성공하는 즉시 그린다(배지를 기다리지 않는다). + // 1) 컬렉션 섹션 — 콘텐츠 성패와 무관하게 수확한다. **콘텐츠보다 먼저** 꺼낸다: 홈 최상단(검색 영역 바로 + // 아래) 섹션이라 콘텐츠 뒤에 들어오면 그 아래 섹션 전부가 밀리는 점프가 생긴다. 먼저 state에 넣어도 + // `hasLoadedContent`가 아직 false라 로딩 뷰가 덮고 있다가 콘텐츠와 같은 프레임에 함께 그려진다. + // 둘은 동시에 요청했으니 총 대기시간은 max(콘텐츠, 컬렉션) 그대로다. + do { + state.publicCollections = try await publicCollections.items + } catch let error as RepositoryError { + presentPublicCollectionsFailure(error) + } catch { + presentPublicCollectionsFailure(.unknown) + } + + // 2) 콘텐츠 — 성공하는 즉시 그린다(배지를 기다리지 않는다). do { let loadedHomeData = try await homeData @@ -221,17 +233,6 @@ private extension HomeViewModel { presentLoadFailure(.unknown) } - // 2) 컬렉션 섹션 — 콘텐츠 성패와 무관하게 수확한다. **배지보다 먼저** 꺼낸다: 콘텐츠 사이에 - // 끼어드는 섹션이라 늦을수록 아래 선호장르가 밀리는 점프가 커지는데, 배지 뒤에 두면 배지 왕복까지 - // 기다리게 된다(배지는 헤더 점 하나라 늦어도 레이아웃이 안 움직인다). - do { - state.publicCollections = try await publicCollections.items - } catch let error as RepositoryError { - presentPublicCollectionsFailure(error) - } catch { - presentPublicCollectionsFailure(.unknown) - } - // 3) 배지 — 콘텐츠 성패와 무관하게 반드시 수확한다(`async let`은 스코프를 나가기 전에 // await해야 하고, 콘텐츠가 실패했다고 배지 요청을 버릴 이유도 없다). do { From cfd4b92c9ed468f210382c181de6d844e6bcde89 Mon Sep 17 00:00:00 2001 From: Guryss Date: Sat, 17 Oct 2026 10:53:13 +0900 Subject: [PATCH 19/25] =?UTF-8?q?[Feat]=20#283=20-=20=EC=BB=AC=EB=A0=89?= =?UTF-8?q?=EC=85=98=20=ED=88=B4=ED=8C=81=20=ED=99=95=EC=9D=B8=20=EC=97=AC?= =?UTF-8?q?=EB=B6=80=EB=A5=BC=20=EC=A0=80=EC=9E=A5=ED=95=A0=20=EC=98=A8?= =?UTF-8?q?=EB=B3=B4=EB=94=A9=20=ED=9E=8C=ED=8A=B8=20=EC=BC=80=EC=9D=B4?= =?UTF-8?q?=EC=8A=A4=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Projects/Domain/BaseDomain/CLAUDE.md | 2 +- .../Sources/Onboarding/OnboardingHint.swift | 3 +++ .../Tests/UseCase/OnboardingHintUseCaseTests.swift | 11 +++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/Projects/Domain/BaseDomain/CLAUDE.md b/Projects/Domain/BaseDomain/CLAUDE.md index f87e2a7bb..588601baf 100644 --- a/Projects/Domain/BaseDomain/CLAUDE.md +++ b/Projects/Domain/BaseDomain/CLAUDE.md @@ -15,7 +15,7 @@ - **Keyword 서브도메인** (`Keyword/`): `Keyword`, `KeywordCategory`(카테고리 enum), `KeywordGroup`(`category` + `keywords`), `PopularKeywords` Entity + `KeywordRepository` + `SearchKeywordsUseCase`/`LoadTotalKeywordsUseCase`(전부 `Keyword/` 하위로 통합됨). - **`AppURL`** — 앱 전역 외부 웹 링크 카탈로그(예: 작품 등록 문의, 오류 제보 노션 폼). Data가 아니라 여기 있는 이유: Feature는 Data를 import할 수 없어서(`App → Feature → Domain ← Data`), Feature가 직접 참조 가능한 곳이 BaseDomain뿐이다. 순수 `URL?` 상수 나열 — 네트워크 호출·설정 로딩 없음(그런 게 필요해지면 BaseData의 `NetworkingConfig`처럼 Data 레이어로 옮길 것). - **`DeepLink`**(#228) — 딥링크의 **생성(`url`·`kakaoExecutionParameters`)과 파싱(`init?(url:)`)을 한 타입에** 둔다. 만드는 쪽(Feature의 공유 버튼)과 받는 쪽(App `onOpenURL`)이 같은 규칙을 봐야 어긋나지 않아서다 — 새 딥링크 화면을 추가할 땐 case를 늘리고 **양쪽을 같은 커밋에서** 고칠 것(App의 4탭 Root `switch`가 exhaustive라 컴파일러가 잡아준다). `AppURL`과 같은 이유로 여기 있다(Feature가 참조 가능한 유일한 공통 자리). 받는 형식은 둘: `websoso:///<정수 id>`(커스텀 스킴, App `Info.plist` 등록)와 `kakao{APP_KEY}://kakaolink?collectionId=`(카카오톡 공유 카드를 탭하면 카카오톡이 만드는 URL). **세 번째 수신 경로는 FCM 푸시 payload**(`fromNotificationPayload`, #243) — URL이 아니라 `[String:String]`이고 판별자는 **`view` 문자열**(`novelDetail`→작품 상세 / `feedDetail`→피드 상세 / `notificationDetail`→알림 상세, 공지 등), 서버가 `view`에 맞는 id(`novelId`/`feedId`/`notificationId`)만 채운다(실측: 공지 push는 `notificationId`만 채우고 `novelId` 키가 아예 없다 — 그래서 id 부재가 아니라 `view`가 판별자다). 이 세 case는 App만 푸시로 받으니 outbound(`url`/`kakaoExecutionParameters`) 대상이 아니다(전부 nil/[:], 테스트용 `websoso://novels|feeds|notifications/` 파싱만 지원). ⚠️ **`kakaolink` host는 스킴을 검사하지 않는다** — 앱 키는 App 설정에만 있어 이 모듈이 모르고, 어차피 등록된 스킴만 앱에 도착한다. 스킴·host는 대소문자 무시. **ID는 양의 정수만 인정**(`0`·음수는 nil, 리뷰 반영) — 통과시키면 존재할 수 없는 ID로 상세를 열어 404 실패 화면부터 보게 된다. **`websoso://` 생성(`url`)·`kakaoExecutionParameters` 둘 다 지금 프로덕션 호출자가 없다**(#241 — 컬렉션 공유 카드가 Kakao 기본 템플릿(`Link`+실행 파라미터)에서 콘솔 커스텀 템플릿(`templateArgs`의 `${collectionId}` 변수 치환)으로 전환되면서 `kakaoExecutionParameters` 호출부가 사라졌다. `websoso://`는 그 전인 2026-08-29부터 이미 미사용). 테스트(`DeepLinkTests`)만 남아있고, 위 kakaolink URL 자체(파싱 쪽 `init?(url:)`)는 여전히 프로덕션이 받는 형식이라 지우지 말 것 — 시뮬레이터 실측(`simctl openurl`)·Universal Link 전 단계용으로 스킴 등록과 함께 남겨둔 것이니 생성 쪽(`url`/`kakaoExecutionParameters`) 미사용만으로 "죽은 코드"라 지우지 말 것. -- **온보딩 힌트 서브도메인** (`Onboarding/`, #221): `OnboardingHint`(1회성 힌트 종류 enum) + `OnboardingHintRepository` + `OnboardingHintUseCase`. 앱 전역에서 "이 힌트를 봤는가"를 로컬에 저장/조회하는 **범용** 계약 — 화면이 늘면 `OnboardingHint` 케이스만 더한다(힌트마다 저장소/UseCase를 새로 만들지 않는다). ⚠️ **`async throws`가 아니라 동기·비-throwing**이다(순수 로컬 플래그라, 화면 첫 프레임에 표시 여부를 동기로 정해야 깜빡임이 없다). ⚠️ **`OnboardingHint.rawValue`는 저장 키의 일부**라 한 번 정하면 바꾸지 않는다(바꾸면 이미 본 유저에게 다시 뜬다). 구현은 `BaseData`의 `DefaultOnboardingHintRepository`(UserDefaults). 첫 사용처는 작품 상세 첫 진입 평가 안내(`.novelDetailReview`, `NovelDetailFeature`). +- **온보딩 힌트 서브도메인** (`Onboarding/`, #221): `OnboardingHint`(1회성 힌트 종류 enum) + `OnboardingHintRepository` + `OnboardingHintUseCase`. 앱 전역에서 "이 힌트를 봤는가"를 로컬에 저장/조회하는 **범용** 계약 — 화면이 늘면 `OnboardingHint` 케이스만 더한다(힌트마다 저장소/UseCase를 새로 만들지 않는다). ⚠️ **`async throws`가 아니라 동기·비-throwing**이다(순수 로컬 플래그라, 화면 첫 프레임에 표시 여부를 동기로 정해야 깜빡임이 없다). ⚠️ **`OnboardingHint.rawValue`는 저장 키의 일부**라 한 번 정하면 바꾸지 않는다(바꾸면 이미 본 유저에게 다시 뜬다). 구현은 `BaseData`의 `DefaultOnboardingHintRepository`(UserDefaults). 사용처는 작품 상세 첫 진입 평가 안내(`.novelDetailReview`, `NovelDetailFeature`)와 My 탭 컬렉션 툴팁(`.myPageCollectionTooltip`, #283 — Feature가 아니라 App `MainTabView`가 UseCase를 직접 쓴다). - **앱 리뷰 요청 서브도메인** (`AppReview/`, #221): `AppReviewRequestRepository`(순수 저장소) + `AppReviewRequestUseCase`(정책). 앱스토어 평점 프롬프트를 **언제 띄울지** 게이팅하는 **범용** 계약(피드·감상평이 하나를 공유 → 앱 전역 기준). 온보딩처럼 **동기·비-throwing**(저장 성공 직후 동기 판정). 정책은 전부 `DefaultAppReviewRequestUseCase`가 소유 — `recordEngagement()`가 긍정 완료를 세고, `shouldRequestReview()`가 **이번 버전 누적 참여 ≥ 임계치(기본 3, init 파라미터) AND 이번 앱 버전 미요청**일 때만 true, 호출 후 `markReviewRequested()`로 현재 버전 각인. ⚠️ **참여 카운트는 앱 버전(`CFBundleShortVersionString`)이 바뀌면 0부터 다시 센다** — `engagementCountVersion`(카운트가 쌓인 버전)을 현재 버전과 비교해 다르면 0으로 취급(`currentVersionEngagementCount`). 누적이면 한 번 임계치를 넘긴 뒤 새 버전마다 첫 저장에 바로 떠 임계치가 죽으므로, "매 버전 임계치를 다시 채운 활발한 유저에게만 버전당 1회"로 만든 것. 버전 리셋 판정을 **저장소가 아니라 UseCase가** 하는 이유는 Domain에서 테스트 가능하게 하려는 것(저장소는 값만 보관). ⚠️ **enum 없이 2파일**(온보딩과 달리 힌트 종류가 없는 단일 개념)이고, **실제 StoreKit 호출은 여기 없다** — 프롬프트는 Feature의 View가 `@Environment(\.requestReview)`로 띄우고, 이 스택은 "지금 물어볼까?"만 판정한다. 구현은 `BaseData`의 `DefaultAppReviewRequestRepository`(UserDefaults + Bundle 버전). ## 주의사항 (작업 중 발견 시 누적) diff --git a/Projects/Domain/BaseDomain/Sources/Onboarding/OnboardingHint.swift b/Projects/Domain/BaseDomain/Sources/Onboarding/OnboardingHint.swift index 8e66ee499..dd36c4d32 100644 --- a/Projects/Domain/BaseDomain/Sources/Onboarding/OnboardingHint.swift +++ b/Projects/Domain/BaseDomain/Sources/Onboarding/OnboardingHint.swift @@ -16,4 +16,7 @@ import Foundation public enum OnboardingHint: String, Sendable, CaseIterable { /// 작품 상세 첫 진입 시 평가 상태바를 가리키는 안내 오버레이(#221, V1 parity 복원). case novelDetailReview + /// 메인 탭 하단에서 My 탭을 가리키는 "나만의 컬렉션을 만들어보세요" 툴팁(#283). + /// 툴팁이 떠 있는 동안 My 탭을 눌러야만 봤음 처리된다(안 누르고 앱을 끄면 다음 실행에 다시 뜬다). + case myPageCollectionTooltip } diff --git a/Projects/Domain/BaseDomain/Tests/UseCase/OnboardingHintUseCaseTests.swift b/Projects/Domain/BaseDomain/Tests/UseCase/OnboardingHintUseCaseTests.swift index 3243802b5..9d640b328 100644 --- a/Projects/Domain/BaseDomain/Tests/UseCase/OnboardingHintUseCaseTests.swift +++ b/Projects/Domain/BaseDomain/Tests/UseCase/OnboardingHintUseCaseTests.swift @@ -41,4 +41,15 @@ struct OnboardingHintUseCaseTests { #expect(mock.markSeenCalls == [.novelDetailReview]) #expect(usecase.hasSeen(.novelDetailReview) == true) } + + @Test("한 힌트를 봤음 처리해도 다른 힌트는 여전히 안 본 상태다.") + func markSeenDoesNotAffectOtherHints() { + let mock = MockOnboardingHintRepository() + let usecase = DefaultOnboardingHintUseCase(repository: mock) + + usecase.markSeen(.myPageCollectionTooltip) + + #expect(usecase.hasSeen(.myPageCollectionTooltip) == true) + #expect(usecase.hasSeen(.novelDetailReview) == false) + } } From 841384575892feb708e48dba78293eea28e9f8be Mon Sep 17 00:00:00 2001 From: Guryss Date: Sat, 17 Oct 2026 10:53:13 +0900 Subject: [PATCH 20/25] =?UTF-8?q?[Add]=20#283=20-=20=EC=BB=AC=EB=A0=89?= =?UTF-8?q?=EC=85=98=20=ED=88=B4=ED=8C=81=20=EB=A7=90=ED=92=8D=EC=84=A0=20?= =?UTF-8?q?=EC=97=90=EC=85=8B=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../Icons/icCollectionTooltip.imageset/Contents.json | 12 ++++++++++++ .../icCollectionTooltip.svg | 3 +++ 2 files changed, 15 insertions(+) create mode 100644 Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/Contents.json create mode 100644 Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/icCollectionTooltip.svg diff --git a/Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/Contents.json b/Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/Contents.json new file mode 100644 index 000000000..f7efaa541 --- /dev/null +++ b/Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/Contents.json @@ -0,0 +1,12 @@ +{ + "images" : [ + { + "filename" : "icCollectionTooltip.svg", + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/icCollectionTooltip.svg b/Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/icCollectionTooltip.svg new file mode 100644 index 000000000..111a0a8f3 --- /dev/null +++ b/Projects/UI/DesignSystem/Resources/Images.xcassets/Icons/icCollectionTooltip.imageset/icCollectionTooltip.svg @@ -0,0 +1,3 @@ + + + From 7f84020ff0a9399fea4cbba4aac65977343717c4 Mon Sep 17 00:00:00 2001 From: Guryss Date: Sat, 17 Oct 2026 10:53:13 +0900 Subject: [PATCH 21/25] =?UTF-8?q?[Feat]=20#283=20-=20My=20=ED=83=AD?= =?UTF-8?q?=EC=9D=84=20=EA=B0=80=EB=A6=AC=ED=82=A4=EB=8A=94=20=EB=82=98?= =?UTF-8?q?=EB=A7=8C=EC=9D=98=20=EC=BB=AC=EB=A0=89=EC=85=98=20=EB=A7=8C?= =?UTF-8?q?=EB=93=A4=EA=B8=B0=20=ED=88=B4=ED=8C=81=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Projects/App/CLAUDE.md | 6 ++ Projects/App/Sources/Feed/FeedRootView.swift | 3 + Projects/App/Sources/Home/HomeRootView.swift | 3 + .../App/Sources/Library/LibraryRootView.swift | 3 + .../App/Sources/Main/CollectionTooltip.swift | 73 +++++++++++++++++++ Projects/App/Sources/Main/MainTabView.swift | 32 +++++++- 6 files changed, 118 insertions(+), 2 deletions(-) create mode 100644 Projects/App/Sources/Main/CollectionTooltip.swift diff --git a/Projects/App/CLAUDE.md b/Projects/App/CLAUDE.md index 376a5796d..919e21287 100644 --- a/Projects/App/CLAUDE.md +++ b/Projects/App/CLAUDE.md @@ -477,6 +477,12 @@ Core/Analytics는 `AnalyticsTracker` 프로토콜만 알고 이 SDK들을 모른 지금 보이는 서브탭을 최상단으로 스크롤한다. **`$selectedTab`로 되돌리면 피드 재탭-최상단이 조용히 깨진다** — 나머지 탭 전환·딥링크 로직은 `selectedTab`을 그대로 갱신해 영향 없다. 전체 계약(자동 스크롤 흡수 미끼 ScrollView 포함)은 `FeedFeature/CLAUDE.md`가 정본. +- **"나만의 컬렉션을 만들어보세요" 툴팁(#283)은 `MainTabView`가 노출·확인을 판정하고, 홈·피드·서재 Root가 + 각자 NavigationStack **루트 콘텐츠**에 `.collectionTooltip(isPresented:)`(`Sources/Main/CollectionTooltip.swift`)로 그린다.** + 루트 콘텐츠의 하단 safe area가 곧 탭바 상단이라 탭바 위에 붙고, push 화면(탭바 숨김)에선 덮여서 자연히 안 보인다 — + `MainTabView` 전체에 overlay로 걸면 push 화면에서도 허공을 가리키며 떠 있게 되니 옮기지 말 것. 확인 처리는 + `tabSelection` setter에서 **툴팁이 떠 있을 때 My를 고른 경우에만** 한다(플래그는 `OnboardingHint.myPageCollectionTooltip`, + 초기값은 `MainTabView.init`에서 1회 판정 → 확인 안 하고 앱을 끄면 다음 실행에 다시 뜬다). - **서재의 "알림 관리"는 설정 목록 전체가 아니라 `SettingFactory.makeNotificationSettingView`로 바로 진입한다**(사용자 확정, #196) — 서재 맥락에서 필요한 건 알림 설정뿐이라 `SettingFactory.makeView` (설정 메인 목록)를 거치지 않고 그 하위 화면으로 직행한다. `AppDependencies.pushSettingRepository` diff --git a/Projects/App/Sources/Feed/FeedRootView.swift b/Projects/App/Sources/Feed/FeedRootView.swift index 64c91b113..2c8c622eb 100644 --- a/Projects/App/Sources/Feed/FeedRootView.swift +++ b/Projects/App/Sources/Feed/FeedRootView.swift @@ -84,6 +84,8 @@ struct FeedRootView: View { let onDeepLinkDestinationDismissed: () -> Void /// 이 화면이 push하는 작품 상세의 API 호출이 401(갱신 실패 포함)로 막히면 발화 — idempotent해야 한다. let onAuthenticationRequired: () -> Void + /// "나만의 컬렉션을 만들어보세요" 툴팁 노출 여부(#283) — 판정은 `MainTabView`, 이 Root는 루트 화면에 그리기만 한다. + let showsCollectionTooltip: Bool /// 피드 탭바의 **현재(피드) 탭 재탭** 신호(`MainTabView`가 커스텀 selection Binding으로 감지해 증가시키는 /// 카운터). `makeSosoFeedView`로 그대로 흘려보내면 지금 보이는 서브탭 목록이 최상단으로 스크롤된다 /// (시스템 자동 "탭 재탭→최상단"이 상시 mount된 두 ScrollView 중 첫 번째=내 피드에만 걸리는 문제 우회). @@ -147,6 +149,7 @@ struct FeedRootView: View { } } ) + .collectionTooltip(isPresented: showsCollectionTooltip) .navigationDestination(for: Destination.self) { destination in Group { switch destination { diff --git a/Projects/App/Sources/Home/HomeRootView.swift b/Projects/App/Sources/Home/HomeRootView.swift index 4fc01c43f..2d9287322 100644 --- a/Projects/App/Sources/Home/HomeRootView.swift +++ b/Projects/App/Sources/Home/HomeRootView.swift @@ -84,6 +84,8 @@ struct HomeRootView: View { let onDeepLinkDestinationDismissed: () -> Void /// 홈의 API 호출이 401(갱신 실패 포함)로 막히면 발화 — idempotent해야 한다(`HomeFeature/CLAUDE.md`). let onAuthenticationRequired: () -> Void + /// "나만의 컬렉션을 만들어보세요" 툴팁 노출 여부(#283) — 판정은 `MainTabView`, 이 Root는 루트 화면에 그리기만 한다. + let showsCollectionTooltip: Bool @State private var path = NavigationPath() /// 딥링크 화면이 놓인 스택 깊이 — `path.count`가 이보다 작아지면 그 화면이 빠진 것(아래 `.onChange(of: path.count)`). @@ -151,6 +153,7 @@ struct HomeRootView: View { onAuthenticationRequired: onAuthenticationRequired ) .toolbar(.hidden, for: .navigationBar) + .collectionTooltip(isPresented: showsCollectionTooltip) .navigationDestination(for: Destination.self) { destination in Group { switch destination { diff --git a/Projects/App/Sources/Library/LibraryRootView.swift b/Projects/App/Sources/Library/LibraryRootView.swift index 88d868cd3..4e1f445e3 100644 --- a/Projects/App/Sources/Library/LibraryRootView.swift +++ b/Projects/App/Sources/Library/LibraryRootView.swift @@ -76,6 +76,8 @@ struct LibraryRootView: View { /// 딥링크로 push한 화면이 스택에서 빠지면 발화(`HomeRootView`와 동일 규칙). let onDeepLinkDestinationDismissed: () -> Void let onAuthenticationRequired: () -> Void + /// "나만의 컬렉션을 만들어보세요" 툴팁 노출 여부(#283) — 판정은 `MainTabView`, 이 Root는 루트 화면에 그리기만 한다. + let showsCollectionTooltip: Bool @State private var path = NavigationPath() @State private var deepLinkDestinationDepth: Int? @@ -129,6 +131,7 @@ struct LibraryRootView: View { }, onAuthenticationRequired: onAuthenticationRequired ) + .collectionTooltip(isPresented: showsCollectionTooltip) .navigationDestination(for: Destination.self) { destination in Group { switch destination { diff --git a/Projects/App/Sources/Main/CollectionTooltip.swift b/Projects/App/Sources/Main/CollectionTooltip.swift new file mode 100644 index 000000000..cb9ac9e08 --- /dev/null +++ b/Projects/App/Sources/Main/CollectionTooltip.swift @@ -0,0 +1,73 @@ +// +// CollectionTooltip.swift +// WSS-iOS +// +// Copyright © 2026 kr.websoso.app. All rights reserved. +// + +import SwiftUI + +import DesignSystem + +/// 탭바 바로 위에서 My 탭을 가리키는 "나만의 컬렉션을 만들어보세요" 툴팁(#283). +/// 노출·확인 판정은 `MainTabView`가 하고, 이 파일은 그리기와 위치만 맡는다. +private struct CollectionTooltip: View { + + enum Metric { + static let size = CGSize(width: 186, height: 44) + /// 말풍선 몸통 높이 — 나머지 6pt는 아래로 튀어나온 꼬리. + static let bodyHeight: CGFloat = 38 + /// 말풍선 오른쪽 끝 ↔ 꼬리 끝(가운데) 거리. 에셋 원본(회전 전)의 꼬리 중심 x≈31.5. + static let tailFromTrailing: CGFloat = 31.5 + } + + var body: some View { + Text("나만의 컬렉션을 만들어보세요") + .applyWSSFont(.body3, color: .wssWhite) + .frame(width: Metric.size.width, height: Metric.bodyHeight) + .frame(width: Metric.size.width, height: Metric.size.height, alignment: .top) + .background { + // Figma 원본 에셋은 꼬리가 위·왼쪽이고 화면에선 180° 돌려 배치돼 있다 — 돌리면 꼬리가 아래·오른쪽(My 탭 쪽). + WSSImage.icCollectionTooltip.swiftUIImage + .resizable() + .rotationEffect(.degrees(180)) + } + } +} + +extension View { + /// 탭 Root의 **NavigationStack 루트 콘텐츠**에 건다 — 루트 콘텐츠의 하단 safe area가 곧 탭바 상단이라 + /// 탭바 위에 붙고, push 화면(탭바 숨김)에선 그 화면에 덮여 자연히 안 보인다. + func collectionTooltip(isPresented: Bool) -> some View { + overlay { + if isPresented { + GeometryReader { proxy in + CollectionTooltip() + .padding(.trailing, collectionTooltipTrailingInset(containerWidth: proxy.size.width)) + .padding(.bottom, 13) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomTrailing) + } + // 아래 콘텐츠 탭을 막지 않는다 — 툴팁 자체엔 탭 동작이 없다. + .allowsHitTesting(false) + .transition(.opacity) + } + } + } +} + +/// 꼬리 끝이 My 탭 중심에 오도록 하는 말풍선의 오른쪽 여백. +/// ⚠️ 시스템 탭바의 아이템 위치를 SwiftUI로 읽을 방법이 없어 화면 너비로 계산한다 — Figma의 고정 여백(20)은 +/// 화면을 4등분하는 예전 탭바 기준이라, 떠 있는 iOS 26 탭바에선 꼬리가 My 오른쪽으로 크게 벗어났다. +/// - iOS 26+: 탭바가 화면 양옆에서 21pt 들어와 떠 있고 그 안쪽 11pt를 뺀 폭을 4등분한다 +/// (iPhone 17 Pro Max 실측 — 아이템 중심 78.5/172.5/266.5/360.5pt, 간격 94pt). +/// - iOS 17~18: 탭바가 화면 폭을 4등분한다. +private func collectionTooltipTrailingInset(containerWidth: CGFloat) -> CGFloat { + let myTabCenterFromTrailing: CGFloat + if #available(iOS 26.0, *) { + let barInset: CGFloat = 21 + 11 + myTabCenterFromTrailing = barInset + (containerWidth - barInset * 2) / 8 + } else { + myTabCenterFromTrailing = containerWidth / 8 + } + return myTabCenterFromTrailing - CollectionTooltip.Metric.tailFromTrailing +} diff --git a/Projects/App/Sources/Main/MainTabView.swift b/Projects/App/Sources/Main/MainTabView.swift index 0d6015175..c353ebfaa 100644 --- a/Projects/App/Sources/Main/MainTabView.swift +++ b/Projects/App/Sources/Main/MainTabView.swift @@ -49,6 +49,24 @@ struct MainTabView: View { /// 세션을 끝낸 것이라 되살리지 않는다. 어느 탭이 소비했는지도 같이 들어, 다른 탭의 딥링크 화면이 빠질 때 /// 이 값이 지워지지 않게 한다(탭마다 스택이 따로라 홈의 링크 A와 피드의 링크 B가 동시에 살아 있을 수 있다). @State private var deliveredDeepLink: (tab: MainTab, link: DeepLink)? + /// "나만의 컬렉션을 만들어보세요" 툴팁(#283) — 메인 진입 시(이 뷰가 새로 만들어질 때) 미확인이면 띄운다. + /// 홈·피드·서재 탭을 오가도 유지되고, **떠 있는 동안** My 탭을 눌러야만 확인 처리된다(`tabSelection`). + /// 확인 안 하고 앱을 끄면 다음 실행에 다시 뜬다. + @State private var isCollectionTooltipPresented: Bool + + init( + dependencies: AppDependencies, + pendingDeepLink: Binding, + onAuthenticationRequired: @escaping () -> Void + ) { + self.dependencies = dependencies + self._pendingDeepLink = pendingDeepLink + self.onAuthenticationRequired = onAuthenticationRequired + self._isCollectionTooltipPresented = State( + initialValue: !DefaultOnboardingHintUseCase(repository: dependencies.onboardingHintRepository) + .hasSeen(.myPageCollectionTooltip) + ) + } /// `TabView(selection:)`을 감싼 프록시 — 이미 선택된 피드 탭을 다시 탭하면(newValue == 현재 == .feed) /// `feedReselectSignal`을 올린다. SwiftUI는 선택된 탭 아이템을 재탭할 때도 이 setter를 같은 값으로 호출한다 @@ -61,6 +79,13 @@ struct MainTabView: View { if newValue == .feed && selectedTab == .feed { feedReselectSignal += 1 } + if newValue == .my && isCollectionTooltipPresented { + DefaultOnboardingHintUseCase(repository: dependencies.onboardingHintRepository) + .markSeen(.myPageCollectionTooltip) + withAnimation(.easeOut(duration: 0.15)) { + isCollectionTooltipPresented = false + } + } selectedTab = newValue } ) @@ -163,7 +188,8 @@ private extension MainTabView { deepLink: deepLink(for: .home), onDeepLinkConsumed: consumeDeepLink, onDeepLinkDestinationDismissed: { clearDeliveredDeepLink(for: .home) }, - onAuthenticationRequired: restoreDeepLinkAndRequireAuthentication + onAuthenticationRequired: restoreDeepLinkAndRequireAuthentication, + showsCollectionTooltip: isCollectionTooltipPresented ) } @@ -174,6 +200,7 @@ private extension MainTabView { onDeepLinkConsumed: consumeDeepLink, onDeepLinkDestinationDismissed: { clearDeliveredDeepLink(for: .feed) }, onAuthenticationRequired: restoreDeepLinkAndRequireAuthentication, + showsCollectionTooltip: isCollectionTooltipPresented, scrollToTopSignal: feedReselectSignal ) } @@ -184,7 +211,8 @@ private extension MainTabView { deepLink: deepLink(for: .library), onDeepLinkConsumed: consumeDeepLink, onDeepLinkDestinationDismissed: { clearDeliveredDeepLink(for: .library) }, - onAuthenticationRequired: restoreDeepLinkAndRequireAuthentication + onAuthenticationRequired: restoreDeepLinkAndRequireAuthentication, + showsCollectionTooltip: isCollectionTooltipPresented ) } From 7820b00687fb4a76b6814c00184a4e6cc8b147c9 Mon Sep 17 00:00:00 2001 From: Guryss Date: Sat, 17 Oct 2026 11:07:28 +0900 Subject: [PATCH 22/25] =?UTF-8?q?[Feat]=20#283=20-=20=ED=9A=8C=EC=9B=90=20?= =?UTF-8?q?=ED=83=88=ED=87=B4=20=EC=8B=9C=20=EC=98=A8=EB=B3=B4=EB=94=A9=20?= =?UTF-8?q?=ED=9E=8C=ED=8A=B8=20=ED=99=95=EC=9D=B8=20=EA=B8=B0=EB=A1=9D=20?= =?UTF-8?q?=EC=B4=88=EA=B8=B0=ED=99=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 탈퇴 후 재가입은 새 유저라 컬렉션 툴팁·작품 상세 평가 안내를 다시 보여준다. 로그아웃/재로그인은 같은 사람일 가능성이 높아 기록을 유지한다. Co-Authored-By: Claude Opus 5.5 --- Projects/Data/AuthData/CLAUDE.md | 1 + .../Repository/DefaultAuthRepository.swift | 1 + .../Tests/DefaultAuthRepositoryTests.swift | 30 +++++++++++++++++++ Projects/Data/BaseData/CLAUDE.md | 2 +- .../DefaultOnboardingHintRepository.swift | 6 ++++ 5 files changed, 39 insertions(+), 1 deletion(-) diff --git a/Projects/Data/AuthData/CLAUDE.md b/Projects/Data/AuthData/CLAUDE.md index bb1c73969..812cb93f7 100644 --- a/Projects/Data/AuthData/CLAUDE.md +++ b/Projects/Data/AuthData/CLAUDE.md @@ -20,3 +20,4 @@ - ⚠️ **사용자 스코프 캐시 정리(`clearUserScopedCache`)는 세 성공 경로에서 부르고, 키 목록의 완전성은 컴파일러가 못 지켜준다**(#236) — 로그아웃·탈퇴(세션 종료) + **로그인(새 세션 시작 직전)**. 로그인 쪽이 필요한 이유: 401 만료·부트스트랩 `.intro` 낙착처럼 **서버가 세션을 끊은 경로는 종료 시점 정리를 지나지 않아**, 다른 계정으로 로그인한 뒤 프로필 동기화가 실패하면 이전 사용자의 값이 비친다(#236 리뷰에서 발견 — 로그인 선제 삭제가 모든 경로의 수렴점). `StorageKey`에 **사용자 개인 값** 키(userID·nickname·characterID·gender·birthYear·myLibraryFilter 류)를 새로 추가하면 이 목록에도 같이 넣어야 한다 — 빠뜨리면 빌드는 초록인데 **계정을 갈아탄 다음 사용자 화면에 이전 사용자의 값이 비친다**(홈 "{닉네임}님을 위한 추천글"이 첫 노출 지점). 서버 호출이 실패하면 세션 경계를 안 넘은 것이라 토큰과 마찬가지로 캐시도 보존. - ⚠️ **Kakao 로그인의 accessToken은 body가 아니라 `Kakao-Access-Token` 커스텀 헤더로 보내야 한다**(서버 스펙, `KakaoLoginRequestHeader.headers`에 매핑 위치). `AuthEndpoint.additionalHeaders`가 한동안 전 case `nil`로 고정돼 있어 이 헤더가 실제로 전송된 적이 없었다(#196에서 실측 — 항상 401 `AUTH-001`). 새 Endpoint case에 커스텀 헤더가 필요하면 `additionalHeaders`의 `switch self`에 분기를 반드시 추가할 것 — 컴파일은 되니 빠뜨려도 조용히 통과한다. - ⚠️ **`.isRegistered`(온보딩 완료 여부, #257)는 `clearUserScopedCache` 목록에 있으면서도 `login`에서 clear 직후 서버 `isRegister` 값으로 다시 세팅한다** — 다른 사용자 스코프 키(닉네임 등)는 지우기만 하고 이후 async 동기화가 채우지만, 이 값은 로그인 응답에만 있어 **동기적으로** 되채운다. 그래서 `login`의 `clearUserScopedCache() → appStorage.set(.isRegistered, ...)` 순서를 뒤집으면 새 값이 지워진다. 온보딩 완료 시 true로 올리는 건 ProfileData(`registerProfile`), 읽는 건 SplashData 부트스트랩 게이트다(세 모듈이 이 한 키를 나눠 만진다). +- ⚠️ **온보딩 힌트 플래그(`onboardingHint.*`)는 `clearUserScopedCache`에 넣지 않고 `withdraw`에서만 `DefaultOnboardingHintRepository(appStorage:).resetAll()`로 지운다**(#283) — 탈퇴 후 재가입은 새 유저라 힌트를 다시 보여주지만, 로그아웃/로그인(401 만료 포함)은 같은 사람일 가능성이 높아 다시 띄우면 거슬린다. `clearUserScopedCache`로 옮기면 로그아웃·재로그인마다 툴팁이 다시 뜬다. diff --git a/Projects/Data/AuthData/Sources/Repository/DefaultAuthRepository.swift b/Projects/Data/AuthData/Sources/Repository/DefaultAuthRepository.swift index a866ae39d..a9092259d 100644 --- a/Projects/Data/AuthData/Sources/Repository/DefaultAuthRepository.swift +++ b/Projects/Data/AuthData/Sources/Repository/DefaultAuthRepository.swift @@ -115,6 +115,7 @@ struct DefaultAuthRepository: AuthRepository { try await service.postWithdraw(request) try tokenStore.clearTokens() clearUserScopedCache() + DefaultOnboardingHintRepository(appStorage: appStorage).resetAll() logger?.logSuccess(action: action.name) } catch let error as NetworkingError { logger?.logNetworkError(action: action.name, error: error) diff --git a/Projects/Data/AuthData/Tests/DefaultAuthRepositoryTests.swift b/Projects/Data/AuthData/Tests/DefaultAuthRepositoryTests.swift index 9774897a4..2feae5222 100644 --- a/Projects/Data/AuthData/Tests/DefaultAuthRepositoryTests.swift +++ b/Projects/Data/AuthData/Tests/DefaultAuthRepositoryTests.swift @@ -332,6 +332,36 @@ struct DefaultAuthRepositoryTests { #expect(appStorage.get(.isRegistered) == nil) } + @Test("회원 탈퇴 성공 시 온보딩 힌트 확인 기록을 모두 지워 재가입하면 다시 보이게 한다(#283)") + func withdrawResetsOnboardingHints() async throws { + let appStorage = MockAppStorage() + let hintRepository = DefaultOnboardingHintRepository(appStorage: appStorage) + OnboardingHint.allCases.forEach { hintRepository.markSeen($0) } + let sut = makeRepository(appStorage: appStorage) + + try await sut.withdraw(draft: WithdrawalReasonDraft()) + + #expect(OnboardingHint.allCases.allSatisfy { !hintRepository.hasSeen($0) }) + } + + @Test("로그아웃 성공 시 온보딩 힌트 확인 기록은 남긴다(#283)") + func logoutKeepsOnboardingHints() async throws { + let appStorage = MockAppStorage() + let hintRepository = DefaultOnboardingHintRepository(appStorage: appStorage) + OnboardingHint.allCases.forEach { hintRepository.markSeen($0) } + let tokenStore = MockTokenStore() + try tokenStore.saveRefreshToken("refresh") + let sut = makeRepository( + tokenStore: tokenStore, + deviceIdentifierStore: MockDeviceIdentifierStore(deviceIdentifier: "device"), + appStorage: appStorage + ) + + try await sut.logout() + + #expect(OnboardingHint.allCases.allSatisfy { hintRepository.hasSeen($0) }) + } + // MARK: - syncAppleCredential @Test("Apple 계정 연동 성공 시 성공 로그를 남긴다") diff --git a/Projects/Data/BaseData/CLAUDE.md b/Projects/Data/BaseData/CLAUDE.md index 1a740cdae..3445a7700 100644 --- a/Projects/Data/BaseData/CLAUDE.md +++ b/Projects/Data/BaseData/CLAUDE.md @@ -9,7 +9,7 @@ Data 레이어의 **공통 인프라**. 거의 모든 Data 모듈이 의존한 - **에러 변환의 본진**: `NetworkingError.toRepositoryError()` — 401→`authenticationRequired`, 403→`forbidden`, 404→`notFound`, 5xx→`serverUnavailable`, decoding→`invalidData`. ⚠️ **`.unknown(URLError)`은 갈린다**(#244): `URLError.notConnectedToInternet`/`.networkConnectionLost`(진짜 오프라인)만 `networkUnavailable`, 그 밖의 통신 실패(타임아웃·DNS·취소 등)는 `unknown`(재시도 가능한 일반 오류)이다 — 화면이 "인터넷 연결 확인" vs "일시적 오류" 문구를 정확히 가르기 위함(전엔 통신 실패를 전부 `networkUnavailable`로 뭉갰다). `URLError` 검사는 도메인 무관한 Foundation 심볼이라 Core가 아니라 이 변환 지점 몫. (전 Data 모듈이 이걸 씀) - **로컬 저장**: `AppStorage` 프로토콜 + `UserDefaultsStorage` 구현 + `StorageKey`(타입 안전 키). 예: `appStorage.get(.userID)`. -- **온보딩 힌트 저장**(`Onboarding/`, #221): `DefaultOnboardingHintRepository`가 `BaseDomain.OnboardingHintRepository`를 구현 — 힌트별 키를 `onboardingHint.`로 네임스페이스해 `Bool`로 저장한다. ⚠️ **네트워크가 없어(순수 로컬) Factory 없이 App(DI)이 `DefaultOnboardingHintRepository(appStorage:)`로 직접 조립**한다(BaseData는 `factory-exclusivity` 예외라 public struct를 그대로 열어도 됨 — `UserDefaultsStorage`와 같은 결). +- **온보딩 힌트 저장**(`Onboarding/`, #221): `DefaultOnboardingHintRepository`가 `BaseDomain.OnboardingHintRepository`를 구현 — 힌트별 키를 `onboardingHint.`로 네임스페이스해 `Bool`로 저장한다. ⚠️ **네트워크가 없어(순수 로컬) Factory 없이 App(DI)이 `DefaultOnboardingHintRepository(appStorage:)`로 직접 조립**한다(BaseData는 `factory-exclusivity` 예외라 public struct를 그대로 열어도 됨 — `UserDefaultsStorage`와 같은 결). ⚠️ 힌트 플래그는 사용자 스코프 캐시(`clearUserScopedCache`)와 별개라, **회원 탈퇴 시에만** `DefaultAuthRepository`가 `resetAll()`로 전부 지운다(#283 — 재가입은 새 유저라 힌트를 다시 보여줌). 로그아웃·로그인 경로에선 지우지 않는다. - **앱 리뷰 게이트 저장**(`AppReview/`, #221): `DefaultAppReviewRequestRepository`가 `BaseDomain.AppReviewRequestRepository`를 구현 — `appReview.engagementCount`(Int)·`appReview.engagementCountVersion`(String, 그 카운트가 쌓인 버전)·`appReview.lastRequestedVersion`(String) 세 키를 UserDefaults에 저장하고, `currentAppVersion`은 **init에서 `Bundle`(`CFBundleShortVersionString`)을 1회 읽어 고정**(`Bundle` 미보유 → Sendable-safe, `NetworkingConfig`의 plist 읽기와 같은 패턴). ⚠️ 이 repo는 **순수 저장소**라 "버전 바뀌면 카운트 리셋" 같은 정책 판단을 하지 않는다 — 값만 넣고 빼고, 리셋은 `AppReviewRequestUseCase`(Domain)가 `engagementCountVersion` 비교로 한다(테스트 가능성 때문). 온보딩과 마찬가지로 Factory 없이 App(DI)이 직접 조립. ⚠️ **`StorageKey`/`` 키를 `static let`으로 두면 "StorageKey는 Sendable 아님" 컴파일 에러**라 `static var { StorageKey(...) }` computed로 매 접근 새로 만든다(온보딩이 인스턴스 키를 인라인 생성하는 것과 같은 회피). - **로깅**: `DataLogger` (모듈명 + underlying `Logger`). - **에러 타입**: `MappingError`, `CacheError`. diff --git a/Projects/Data/BaseData/Sources/Onboarding/DefaultOnboardingHintRepository.swift b/Projects/Data/BaseData/Sources/Onboarding/DefaultOnboardingHintRepository.swift index 54a596a88..cd97ab91e 100644 --- a/Projects/Data/BaseData/Sources/Onboarding/DefaultOnboardingHintRepository.swift +++ b/Projects/Data/BaseData/Sources/Onboarding/DefaultOnboardingHintRepository.swift @@ -33,6 +33,12 @@ public struct DefaultOnboardingHintRepository: OnboardingHintRepository { appStorage.set(key(for: hint), true) } + /// 모든 힌트의 "봤음" 플래그를 지운다 — 회원 탈퇴 시 `DefaultAuthRepository`가 부른다(#283). + /// 탈퇴 후 재가입은 새 유저라 힌트를 다시 보여준다. 로그아웃은 같은 사람의 재로그인일 가능성이 높아 지우지 않는다. + public func resetAll() { + OnboardingHint.allCases.forEach { appStorage.remove(key(for: $0)) } + } + /// 힌트별 저장 키. ⚠️ `Value`가 `Bool`이라 저장/조회 값도 항상 `Bool`이어야 한다 /// (`UserDefaultsStorage`가 `as? V`라 타입이 어긋나면 조용히 nil — `StorageKey` 주의사항 참고). private func key(for hint: OnboardingHint) -> StorageKey { From 94f2c92695233b102271f64ee7cf64b27ad5d893 Mon Sep 17 00:00:00 2001 From: Guryss Date: Mon, 19 Oct 2026 00:10:24 +0900 Subject: [PATCH 23/25] =?UTF-8?q?[Design]=20#283=20-=20=ED=99=88=20?= =?UTF-8?q?=EC=BB=AC=EB=A0=89=EC=85=98=20=EB=AA=A8=EC=9D=8C.zip=20?= =?UTF-8?q?=EC=B9=B4=EB=93=9C=20=EB=82=B4=EB=B6=80=20=EA=B0=84=EA=B2=A9=20?= =?UTF-8?q?=EC=A1=B0=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- .../HomeFeature/Sources/Home/PublicCollectionSection.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift b/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift index fc3a0f678..34125f328 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift @@ -29,8 +29,8 @@ struct PublicCollectionSection: View { static let cardWidth: CGFloat = 284 static let cardPadding: CGFloat = 16 static let cardCornerRadius: CGFloat = 14 - static let headerToCovers: CGFloat = 12 - static let coversToOwner: CGFloat = 8 + static let headerToCovers: CGFloat = 16 + static let coversToOwner: CGFloat = 16 static let subtitleSpacing: CGFloat = 4 static let coverSlotCount = 4 } From 43a9bb37bfbc2e1932bd4c116028e203e481abf8 Mon Sep 17 00:00:00 2001 From: Guryss Date: Tue, 20 Oct 2026 17:14:01 +0900 Subject: [PATCH 24/25] =?UTF-8?q?[Refactor]=20#283=20-=20=EA=B3=B5?= =?UTF-8?q?=EA=B0=9C=20=EC=BB=AC=EB=A0=89=EC=85=98=20=EC=B9=B4=EB=93=9C?= =?UTF-8?q?=EB=A5=BC=20CollectionCard=EB=A1=9C=20=ED=86=B5=ED=95=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 회의 결정에 따라 사용자별·좋아요·공개 목록이 카드 하나를 공유한다. owner는 사용자별·좋아요 목록 응답에 없어 옵셔널로 두고(서버가 주면 재리팩터링), isMine은 로그인 ID(AppStorage .userID)와 소유자 ID를 비교해 Mapper에서 판정한다. 좋아요 목록은 소유자를 몰라 isMine이 false로 남는 한계를 문서에 기록했다. Co-Authored-By: Claude Opus 5.5 --- Projects/App/Sources/DI/AppDependencies.swift | 1 + Projects/Data/CollectionData/CLAUDE.md | 3 + .../Demo/CollectionDataDemoView.swift | 2 +- .../Factory/CollectionDataFactory.swift | 2 + .../Sources/Mapper/CollectionMapper.swift | 55 ++++++++++++------- .../DefaultCollectionRepository.swift | 16 ++++-- Projects/Domain/CollectionDomain/CLAUDE.md | 20 +++++-- .../Sources/Entity/CollectionCard.swift | 20 +++++-- .../Sources/Entity/PublicCollectionCard.swift | 48 ---------------- .../Repository/CollectionRepository.swift | 2 +- .../LoadPublicCollectionsUseCase.swift | 4 +- .../Mock/MockCollectionRepository.swift | 4 +- .../LoadPublicCollectionsUseCaseTests.swift | 7 ++- Projects/Feature/CollectionFeature/CLAUDE.md | 1 + .../Demo/CollectionFeatureDemoApp.swift | 9 ++- .../PublicCollectionListView.swift | 13 +++-- .../PublicCollectionListViewModel.swift | 2 +- Projects/Feature/HomeFeature/CLAUDE.md | 1 + .../HomeFeature/Demo/HomeFeatureDemoApp.swift | 6 +- .../HomeFeature/Sources/Home/HomeView.swift | 5 +- .../Sources/Home/HomeViewModel.swift | 2 +- .../Home/PublicCollectionSection.swift | 18 +++--- .../Demo/UserPageFeatureDemoApp.swift | 2 + 23 files changed, 132 insertions(+), 111 deletions(-) delete mode 100644 Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift diff --git a/Projects/App/Sources/DI/AppDependencies.swift b/Projects/App/Sources/DI/AppDependencies.swift index df0c7bc19..e4004637d 100644 --- a/Projects/App/Sources/DI/AppDependencies.swift +++ b/Projects/App/Sources/DI/AppDependencies.swift @@ -159,6 +159,7 @@ final class AppDependencies { ) self.collectionRepository = CollectionDataFactory.makeRepository( network: client, + appStorage: UserDefaultsStorage(), logger: DataLogger(moduleName: "CollectionData", underlying: logger) ) self.feedRepository = FeedDataFactory.makeFeedRepository( diff --git a/Projects/Data/CollectionData/CLAUDE.md b/Projects/Data/CollectionData/CLAUDE.md index 1b77d0611..0595c131f 100644 --- a/Projects/Data/CollectionData/CLAUDE.md +++ b/Projects/Data/CollectionData/CLAUDE.md @@ -31,6 +31,9 @@ → `CollectionDetailQuery`가 `uppercased()`로 맞춘다. 도메인 enum을 서버 표기에 맞추려 고치지 말 것(다른 도메인도 쓴다). - **목록 API 하나가 Repository 메서드 셋을 떠받친다.** 미리보기·컬렉션 목록이 같은 `getUserCollections`를 호출하고 Mapper만 갈린다(`collectionPreviews` / `collectionCards`). 엔드포인트를 추가하기 전에 Mapper로 해결되는지 먼저 볼 것. +- **목록 카드의 `isMine`·`isPrivate` 판정에 로그인 사용자 ID가 필요해 Repository가 `AppStorage`를 받는다**(#283, `DefaultNovelRepository`와 + 같은 `.userID` 캐시). 판정 규칙 표는 `CollectionDomain/CLAUDE.md`. 사용자별·좋아요 목록은 같은 `collectionCards`를 쓰고 + `ownerID`로만 갈린다(사용자별 = 요청한 userID, 좋아요 = nil — 소유자를 몰라 `isMine`이 false가 된다). - **Demo 앱은 `TEST_API_KEY`(`Config_Debug.xcconfig`)로 인증한다.** 만료되면 모든 호출이 `AUTH-000`으로 실패한다 — Demo가 안 될 때 코드부터 의심하지 말고 토큰부터 확인할 것. 갱신 방법은 `/api-spec` 스킬 문서에 있다. - 컬렉션 상세와 전체 공개 목록(`GET /collections`)만 `usesTokenIfAvailable`이다(비로그인도 조회 가능 — 공개 목록은 토큰이 diff --git a/Projects/Data/CollectionData/Demo/CollectionDataDemoView.swift b/Projects/Data/CollectionData/Demo/CollectionDataDemoView.swift index 4745ef610..32c732021 100644 --- a/Projects/Data/CollectionData/Demo/CollectionDataDemoView.swift +++ b/Projects/Data/CollectionData/Demo/CollectionDataDemoView.swift @@ -30,7 +30,7 @@ struct CollectionDataDemoView: View { init() { let client = NetworkingClient(tokenStore: DemoSessionTokenStore()) let logger = DataLogger(moduleName: "CollectionData", underlying: OSLogger.collection) - self.repository = CollectionDataFactory.makeRepository(network: client, logger: logger) + self.repository = CollectionDataFactory.makeRepository(network: client, appStorage: UserDefaultsStorage(), logger: logger) } var body: some View { diff --git a/Projects/Data/CollectionData/Sources/Factory/CollectionDataFactory.swift b/Projects/Data/CollectionData/Sources/Factory/CollectionDataFactory.swift index 563b5ff8e..db3586770 100644 --- a/Projects/Data/CollectionData/Sources/Factory/CollectionDataFactory.swift +++ b/Projects/Data/CollectionData/Sources/Factory/CollectionDataFactory.swift @@ -16,11 +16,13 @@ import BaseData public enum CollectionDataFactory { public static func makeRepository( network: NetworkingRequestable, + appStorage: AppStorage, logger: DataLogger? = nil ) -> any CollectionRepository { let service = DefaultCollectionService(network: network) return DefaultCollectionRepository( service: service, + appStorage: appStorage, logger: logger ) } diff --git a/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift b/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift index 22ae27c8f..3f50aaac6 100644 --- a/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift +++ b/Projects/Data/CollectionData/Sources/Mapper/CollectionMapper.swift @@ -29,42 +29,57 @@ enum CollectionMapper { return (previews, dto.collectionsCount) } - /// 컬렉션 리스트·좋아요한 목록용. 같은 응답에서 미리보기 썸네일 줄을 쓴다. + /// 사용자별·좋아요한 컬렉션 목록용. 서버가 소유자를 주지 않아 `owner`는 nil이다. + /// - Parameters: + /// - ownerID: 목록 전체의 소유자. 사용자별 목록은 요청한 사용자, 좋아요 목록은 알 수 없어 nil. + /// - myID: 로그인 사용자. 비로그인이면 nil. /// - Returns: (커서 페이지, 전체 컬렉션 수) - public static func collectionCards(from dto: CollectionsResponse) -> (CursorPaginated, Int) { + public static func collectionCards( + from dto: CollectionsResponse, + ownerID: UserID?, + myID: UserID? + ) -> (CursorPaginated, Int) { + // 소유자를 모르면(좋아요 목록) 내 컬렉션이어도 false가 된다. + let isMine = ownerID != nil && ownerID == myID let page = CursorPaginated( - items: dto.collections.map(collectionCard(from:)), + items: dto.collections.map { + CollectionCard( + id: CollectionID($0.collectionId), + name: $0.collectionName, + description: $0.collectionDescription, + novelCount: $0.novelCount, + // 서버는 "공개인가"를, 도메인·화면은 "나만 보는가"를 말한다. 뒤집기는 여기서만 일어난다. + // 남의 나만 보는 컬렉션은 서버가 내려주지 않아 소유자 여부와 상관없이 그대로 따른다. + isPrivate: $0.isPublic == false, + recentNovels: $0.recentNovels.map(collectionNovel(from:)), + owner: nil, + isMine: isMine + ) + }, hasNext: dto.hasNext, nextCursor: dto.nextCursor ) return (page, dto.collectionsCount) } - private static func collectionCard(from dto: CollectionCardResponse) -> CollectionCard { - CollectionCard( - id: CollectionID(dto.collectionId), - name: dto.collectionName, - description: dto.collectionDescription, - novelCount: dto.novelCount, - // 서버는 "공개인가"를, 도메인·화면은 "나만 보는가"를 말한다. 뒤집기는 여기 한 곳뿐이다. - isPrivate: dto.isPublic == false, - recentNovels: dto.recentNovels.map(collectionNovel(from:)) - ) - } - - /// 홈 컬렉션 섹션·전체 컬렉션뷰용. + /// 홈 컬렉션 섹션·전체 컬렉션뷰용. 공개 컬렉션만 내려오므로 `isPrivate`은 항상 false다. + /// - Parameter myID: 로그인 사용자. 비로그인이면 nil. public static func publicCollectionCards( - from dto: PublicCollectionsResponse - ) -> CursorPaginated { + from dto: PublicCollectionsResponse, + myID: UserID? + ) -> CursorPaginated { CursorPaginated( items: dto.collections.map { - PublicCollectionCard( + let owner = author(from: $0.owner) + return CollectionCard( id: CollectionID($0.collectionId), name: $0.collectionName, description: $0.collectionDescription, novelCount: $0.novelCount, + isPrivate: false, recentNovels: $0.recentNovels.map(collectionNovel(from:)), - owner: author(from: $0.owner) + owner: owner, + isMine: myID != nil && owner.userId == myID ) }, hasNext: dto.hasNext, diff --git a/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift b/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift index 299ffa6ff..d3f3b0d02 100644 --- a/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift +++ b/Projects/Data/CollectionData/Sources/Repository/DefaultCollectionRepository.swift @@ -16,16 +16,24 @@ import BaseData struct DefaultCollectionRepository: CollectionRepository { private let service: CollectionService + private let appStorage: AppStorage private let logger: DataLogger? init( service: CollectionService, + appStorage: AppStorage, logger: DataLogger? ) { self.service = service + self.appStorage = appStorage self.logger = logger } + /// 로그인 사용자. 로그인 직후 `syncUserBasicInfo()`가 채워두는 로컬 캐시다. + private var myID: UserID? { + appStorage.get(.userID).map(UserID.init) + } + // MARK: - 목록 public func fetchCollectionPreviews( @@ -66,7 +74,7 @@ struct DefaultCollectionRepository: CollectionRepository { userID: userID.value, query: CollectionsQuery(cursor: cursor, size: size) ) - let result = CollectionMapper.collectionCards(from: response) + let result = CollectionMapper.collectionCards(from: response, ownerID: userID, myID: myID) logger?.logSuccess(action: action.name) return result } catch let error as NetworkingError { @@ -91,7 +99,7 @@ struct DefaultCollectionRepository: CollectionRepository { let response = try await service.getLikedCollections( query: CollectionsQuery(cursor: cursor, size: size) ) - let result = CollectionMapper.collectionCards(from: response) + let result = CollectionMapper.collectionCards(from: response, ownerID: nil, myID: myID) logger?.logSuccess(action: action.name) return result } catch let error as NetworkingError { @@ -109,14 +117,14 @@ struct DefaultCollectionRepository: CollectionRepository { public func fetchPublicCollections( cursor: String?, size: Int - ) async throws(RepositoryError) -> CursorPaginated { + ) async throws(RepositoryError) -> CursorPaginated { let action = CollectionAction.fetchPublicCollections do { let response = try await service.getPublicCollections( query: CollectionsQuery(cursor: cursor, size: size) ) - let result = CollectionMapper.publicCollectionCards(from: response) + let result = CollectionMapper.publicCollectionCards(from: response, myID: myID) logger?.logSuccess(action: action.name) return result } catch let error as NetworkingError { diff --git a/Projects/Domain/CollectionDomain/CLAUDE.md b/Projects/Domain/CollectionDomain/CLAUDE.md index 425bfcb81..fbb7efea6 100644 --- a/Projects/Domain/CollectionDomain/CLAUDE.md +++ b/Projects/Domain/CollectionDomain/CLAUDE.md @@ -11,7 +11,7 @@ - **한 응답을 두 Entity로 나눠 매핑한다.** 목록 API(`/users/{userId}/collections`)는 `representativeNovel`(대표 작품 하나)과 `recentNovels`(표시 순서 앞 5개)를 **항상 둘 다** 내려주고, 서버가 "무엇을 쓸지는 화면이 정하라"고 명시적으로 위임한다. 그 선택을 화면마다 반복하지 않도록 매핑 시점에 고정했다 → 마이페이지 섹션은 `CollectionPreview`(대표 작품만), - 컬렉션 리스트·좋아요 목록은 `CollectionCard`(미리보기 5개). + 컬렉션 리스트·좋아요 목록·공개 목록은 `CollectionCard`(미리보기 5개). - **마이페이지 컬렉션 섹션에는 전용 API가 없다.** 같은 목록 API를 `size=3`으로 호출해 구성한다(서버 명세가 지시). size는 상수로 박지 말고 화면이 정해 내려보낸다 — 서재에서 같은 이유로 이미 관통시킨 선례가 있다(#184). - **목록 반환은 `(CursorPaginated, Int)` 튜플.** 두 번째 값은 응답 최상위의 `collectionsCount`(조회자가 볼 수 있는 @@ -26,7 +26,6 @@ "대표는 미리보기에 없다"고 가정한 코드를 짜지 말 것. 걸러낼지는 화면이 정한다(서버가 걸러주지 않는다). - **`novelCount`는 컬렉션의 전체 작품 수**다. `recentNovels.count`(최대 5)가 아니다 — 서버 명세가 못박아 둘 만큼 흔한 혼동이다. - 좋아요한 컬렉션 목록 응답에는 카드마다 `likeCount`가 딸려 오지만 그 화면이 좋아요 수를 쓰지 않아 **의도적으로 매핑하지 않는다**. - 필요해지면 `CollectionCard`에 옵셔널로 얹지 말고 그 화면 전용 타입을 두는 편이 낫다(두 목록이 같은 카드를 공유하는 구조가 깨진다). - 작품을 다루지만 `BaseDomain.Novel`을 쓰지 않는다 — 컬렉션 화면은 평점·관심수·장르를 쓰지 않고 서버도 주지 않아서, `Novel`을 쓰면 없는 값을 0으로 채우게 된다. 경량 `CollectionNovel`을 쓴다(`LibraryNovel`·`SosoPick`과 같은 패턴). - **UseCase는 초안을 검증하지 않는다.** 제출 가능 여부(`CollectionDraft.isSubmittable`)는 완료 버튼을 잠그는 화면 몫이고, @@ -59,6 +58,17 @@ 상한은 `addNovel`과 같은 `novelOverLimit` throw(선택 화면이 UI에서 이미 100개로 막아두므로 실사용 경로는 아니지만, "사용자 입력은 거부"라는 `updateName` 방침과 일관되게 clamp 대신 throw를 골랐다). 대표 작품이 새 목록에서 빠지면 `removeNovel`과 동일하게 대표 지정도 함께 풀린다. -- **공개 컬렉션 목록(홈 섹션·전체 컬렉션뷰, #283)은 `PublicCollectionCard`를 따로 쓴다** — 작성자(`owner: Author`)가 필요한데 - 위 권고대로 `CollectionCard`에 얹지 않았다. 공개 목록만 오므로 `isPrivate`이 없고, 서버(`GET /collections`)가 전체 개수를 - 주지 않아 `fetchPublicCollections`는 다른 목록과 달리 `(페이지, 개수)` 튜플이 아니라 페이지만 돌려준다. +- **목록 카드는 `CollectionCard` 하나다**(#283 회의 결정) — 사용자별·좋아요·공개 목록이 이름·설명·작품 수·미리보기·공개 여부·소유자를 + 겹쳐 다뤄, 한때 따로 뒀던 공개 목록용 `PublicCollectionCard`를 합쳤다. 목록마다 서버가 주는 값이 달라 아래처럼 채운다 + (판정은 `CollectionMapper` 한 곳, 로그인 사용자 ID는 Repository가 `AppStorage .userID`로 읽는다): + | 목록 | `owner` | `isMine` | `isPrivate` | + |---|---|---|---| + | 사용자별 | nil(서버 미제공) | 요청한 `userID` == 로그인 ID | 서버 값 그대로 | + | 좋아요 | nil(서버 미제공) | **항상 false**(소유자 미상) | 서버 값 그대로 | + | 공개(`GET /collections`) | 서버 `owner` | `owner.userId` == 로그인 ID | 항상 false | + - ⚠️ **owner가 없다고 로그인 계정으로 채우지 말 것** — 사용자별 목록은 타유저 프로필에서도 쓰이고 좋아요 목록은 대부분 남의 + 컬렉션이라 틀린 값이 된다. 그래서 `owner`는 옵셔널이고 작성자 라벨은 owner가 있을 때만 그린다. + - ⚠️ **좋아요 목록의 `isMine`은 믿을 수 없다**(내가 내 컬렉션에 좋아요를 눌렀어도 false). 지금은 쓰는 화면이 없다 — 필요해지면 + 서버에 owner를 요청할 것. `owner` 옵셔널도 같은 응답 빈틈 때문에 둔 임시 형태라 서버가 owner를 주면 함께 리팩터링한다. + - `isPrivate`은 세 목록 모두 서버 값을 그대로 쓴다 — 남의 나만 보는 컬렉션은 서버가 애초에 내려주지 않는다. + - `fetchPublicCollections`는 서버(`GET /collections`)가 전체 개수를 주지 않아 다른 목록과 달리 `(페이지, 개수)` 튜플이 아니라 페이지만 돌려준다. diff --git a/Projects/Domain/CollectionDomain/Sources/Entity/CollectionCard.swift b/Projects/Domain/CollectionDomain/Sources/Entity/CollectionCard.swift index 75060c3b0..a30f3de1b 100644 --- a/Projects/Domain/CollectionDomain/Sources/Entity/CollectionCard.swift +++ b/Projects/Domain/CollectionDomain/Sources/Entity/CollectionCard.swift @@ -10,10 +10,10 @@ import Foundation import BaseDomain -/// 컬렉션 리스트·좋아요한 컬렉션 목록의 카드. 미리보기 썸네일 줄을 보여준다. +/// 컬렉션 목록 카드. 사용자별·좋아요한 목록과 공개 목록(홈 섹션·전체 컬렉션뷰)이 함께 쓴다. 미리보기 썸네일 줄을 보여준다. /// -/// 좋아요 목록 응답에는 `likeCount`가 함께 오지만 그 화면이 좋아요 수를 쓰지 않아 매핑하지 않는다. -/// 필요해지면 이 타입에 더하지 말고 그 화면 전용 타입을 따로 두는 편이 낫다 — 두 목록이 같은 카드를 쓰는 지금 구조가 깨진다. +/// 세 목록이 다루는 정보가 겹쳐 한 타입으로 통합했다. 서버가 소유자를 공개 목록에만 내려줘 `owner`는 옵셔널이다. +/// 좋아요 목록 응답의 `likeCount`는 쓰는 화면이 없어 매핑하지 않는다. public struct CollectionCard: Sendable { public let id: CollectionID @@ -27,8 +27,16 @@ public struct CollectionCard: Sendable { /// "나만 보는 컬렉션" 여부. 서버의 `isPublic`을 뒤집은 값이다 — 기획·화면 용어가 일관되게 "나만 보는"이라 /// 도메인도 그 방향으로 맞췄다(뒤집기는 Mapper 한 곳에서만 일어난다). + /// 다른 사람의 나만 보는 컬렉션은 조회되지 않으므로, 남의 컬렉션이거나 서버가 공개 여부를 주지 않으면 false다. public let isPrivate: Bool + /// 작성자. 서버가 소유자를 내려주는 공개 목록에서만 있고, 사용자별·좋아요 목록은 nil이다. + public let owner: Author? + + /// 로그인 사용자 소유 여부. 소유자 ID를 로그인 사용자 ID와 비교해 Repository가 정한다. + /// 좋아요 목록은 소유자를 알 수 없어 항상 false다. + public let isMine: Bool + /// 저장된 표시 순서 앞에서부터 최대 5개. 대표 작품을 걸러내지 않으므로 대표와 겹칠 수 있다. public let recentNovels: [CollectionNovel] @@ -38,7 +46,9 @@ public struct CollectionCard: Sendable { description: String?, novelCount: Int, isPrivate: Bool, - recentNovels: [CollectionNovel] + recentNovels: [CollectionNovel], + owner: Author? = nil, + isMine: Bool = false ) { self.id = id self.name = name @@ -46,5 +56,7 @@ public struct CollectionCard: Sendable { self.novelCount = novelCount self.isPrivate = isPrivate self.recentNovels = recentNovels + self.owner = owner + self.isMine = isMine } } diff --git a/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift b/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift deleted file mode 100644 index cd04108c1..000000000 --- a/Projects/Domain/CollectionDomain/Sources/Entity/PublicCollectionCard.swift +++ /dev/null @@ -1,48 +0,0 @@ -// -// PublicCollectionCard.swift -// CollectionDomain -// -// Created by Guryss on 9/28/26. -// Copyright © 2026 kr.websoso.app. All rights reserved. -// - -import Foundation - -import BaseDomain - -/// 홈 컬렉션 섹션·전체 컬렉션뷰의 카드. 모든 사용자의 공개 컬렉션을 작성자 프로필과 함께 보여준다. -/// -/// `CollectionCard`에 `owner`를 옵셔널로 얹지 않고 따로 둔 이유: 사용자별·좋아요 목록은 작성자를 쓰지 않아 -/// 두 목록이 같은 카드를 공유하는 구조가 깨진다. 공개 목록만 공개 컬렉션이 오므로 `isPrivate`도 없다. -public struct PublicCollectionCard: Sendable { - - public let id: CollectionID - public let name: String - - /// 없으면 nil. - public let description: String? - - /// 컬렉션에 든 **전체** 작품 수. `recentNovels.count`가 아니다(미리보기는 최대 5개뿐). - public let novelCount: Int - - /// 저장된 표시 순서 앞에서부터 최대 5개. 홈 섹션은 앞 4개만 쓴다. - public let recentNovels: [CollectionNovel] - - public let owner: Author - - public init( - id: CollectionID, - name: String, - description: String?, - novelCount: Int, - recentNovels: [CollectionNovel], - owner: Author - ) { - self.id = id - self.name = name - self.description = description - self.novelCount = novelCount - self.recentNovels = recentNovels - self.owner = owner - } -} diff --git a/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift b/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift index fbb948d63..41b1fc10f 100644 --- a/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift +++ b/Projects/Domain/CollectionDomain/Sources/Repository/CollectionRepository.swift @@ -49,7 +49,7 @@ public protocol CollectionRepository: Sendable { func fetchPublicCollections( cursor: String?, size: Int - ) async throws(RepositoryError) -> CursorPaginated + ) async throws(RepositoryError) -> CursorPaginated /// 컬렉션 상세. 작품은 페이지네이션 없이 전부 내려온다. /// - Parameter sortType: 작품 정렬. `.recent`는 저장된 표시 순서 그대로, `.old`는 그 역순. diff --git a/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift index 9b036bfcd..b50ad51c2 100644 --- a/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift +++ b/Projects/Domain/CollectionDomain/Sources/UseCase/LoadPublicCollectionsUseCase.swift @@ -14,7 +14,7 @@ public protocol LoadPublicCollectionsUseCase: Sendable { /// 모든 사용자의 공개 컬렉션을 최신순으로 가져온다. /// 홈 섹션은 첫 페이지만(`size` 10), 전체 컬렉션뷰는 커서로 이어서 부른다. /// - Parameter cursor: 직전 응답의 `nextCursor`. 첫 페이지는 nil. - func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated } public final class DefaultLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { @@ -25,7 +25,7 @@ public final class DefaultLoadPublicCollectionsUseCase: LoadPublicCollectionsUse self.collectionRepository = collectionRepository } - public func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + public func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { try await collectionRepository.fetchPublicCollections(cursor: cursor, size: size) } } diff --git a/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift b/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift index 8e5e3bf87..9851be9b6 100644 --- a/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift +++ b/Projects/Domain/CollectionDomain/Testing/Mock/MockCollectionRepository.swift @@ -18,7 +18,7 @@ public final class MockCollectionRepository: CollectionRepository { public var fetchCollectionPreviewsResult: Result<([CollectionPreview], Int), RepositoryError>! public var fetchCollectionsResult: Result<(CursorPaginated, Int), RepositoryError>! public var fetchLikedCollectionsResult: Result<(CursorPaginated, Int), RepositoryError>! - public var fetchPublicCollectionsResult: Result, RepositoryError>! + public var fetchPublicCollectionsResult: Result, RepositoryError>! public var fetchCollectionDetailResult: Result! public var createCollectionResult: Result! public var updateCollectionResult: Result = .success(()) @@ -71,7 +71,7 @@ public final class MockCollectionRepository: CollectionRepository { public func fetchPublicCollections( cursor: String?, size: Int - ) async throws(RepositoryError) -> CursorPaginated { + ) async throws(RepositoryError) -> CursorPaginated { fetchedPublicRequests.append((cursor, size)) return try fetchPublicCollectionsResult.get() } diff --git a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift index 970af1a2b..c0d4ac236 100644 --- a/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift +++ b/Projects/Domain/CollectionDomain/Tests/UseCase/LoadPublicCollectionsUseCaseTests.swift @@ -25,7 +25,7 @@ struct LoadPublicCollectionsUseCaseTests { let page = try await useCase.execute(cursor: nil, size: 10) #expect(page.items.count == 3) - #expect(page.items.first?.owner.nickname == "작성자") + #expect(page.items.first?.owner?.nickname == "작성자") } @Test("서버가 준 순서를 바꾸지 않고 그대로 돌려준다") @@ -94,14 +94,15 @@ private extension LoadPublicCollectionsUseCaseTests { cardCount: Int = 1, hasNext: Bool = false, nextCursor: String? = nil - ) -> CursorPaginated { + ) -> CursorPaginated { CursorPaginated( items: (0.. CursorPaginated { + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { try? await Task.sleep(nanoseconds: 300_000_000) let total = 25 let start = cursor.flatMap(Int.init) ?? 0 let end = min(start + size, total) let cards = (start.. some View { + func collectionCard(_ card: CollectionCard) -> some View { Button { onRoute(.collectionDetail(card.id)) } label: { @@ -128,9 +128,11 @@ private extension PublicCollectionListView { slotCount: Metric.coverSlotCount ) - Spacer().frame(height: 8) + if let owner = card.owner { + Spacer().frame(height: 8) - WSSCollectionOwnerLabel(nickname: card.owner.nickname, profileImage: card.owner.profileImage) + WSSCollectionOwnerLabel(nickname: owner.nickname, profileImage: owner.profileImage) + } } .padding(.horizontal, 17) .padding(.vertical, 16) @@ -157,13 +159,14 @@ private extension PublicCollectionListView { } private struct PreviewLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { - func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { let cards = (0..<5).map { index in - PublicCollectionCard( + CollectionCard( id: CollectionID(index), name: "일이삼사오육칠팔구십일이삼사오육칠팔구십", description: "존잼 수준이 정도를 넘음", novelCount: index + 1, + isPrivate: false, recentNovels: [], owner: Author(userId: UserID(index), nickname: "코띠", profileImage: nil) ) diff --git a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift index 58a99f13b..d8130f507 100644 --- a/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift +++ b/Projects/Feature/CollectionFeature/Sources/PublicCollectionList/PublicCollectionListViewModel.swift @@ -22,7 +22,7 @@ final class PublicCollectionListViewModel { // MARK: - State struct State { - var items: [PublicCollectionCard] = [] + var items: [CollectionCard] = [] /// 초기값 true — onAppear의 `.load`보다 첫 body 평가가 먼저라, false로 시작하면 로드 시작 전 /// 한 프레임 빈 상태가 스친다(`CollectionListViewModel`과 동일 이유). var isLoading = true diff --git a/Projects/Feature/HomeFeature/CLAUDE.md b/Projects/Feature/HomeFeature/CLAUDE.md index 18870e8d7..6aaf779e7 100644 --- a/Projects/Feature/HomeFeature/CLAUDE.md +++ b/Projects/Feature/HomeFeature/CLAUDE.md @@ -85,6 +85,7 @@ - **"컬렉션 모음.zip" 섹션(#283, 사용자 확정 2026-09-28)** — 모든 사용자의 공개 컬렉션을 최신순(왼쪽이 최신)으로 최대 10개(`size=10` 첫 페이지만, 더보기 없음). 제목 줄(`>` 포함) 탭 → 전체 컬렉션뷰(`.publicCollectionList`), 카드 탭 → 컬렉션 상세(`.collectionDetail`), 작성자 라벨은 탭 없음. 카드는 표지 **4칸 고정**(모자라면 기본 표지). + 카드는 공용 `CollectionCard`라 `owner`가 옵셔널이다 — owner가 없으면 작성자 라벨과 그 위 간격을 함께 생략한다(공개 목록은 항상 온다). - **부수 콘텐츠라 실패해도 홈을 실패 뷰로 덮지 않는다** — 배지와 같은 lane: 로그만, 토스트 없음, 직전 카드 유지, 첫 로드 실패면 빈 채라 섹션이 숨는다. 추천 3종과 같은 `async let` 묶음이지만 수확은 따로다. - ⚠️ **수확 순서는 컬렉션 → 콘텐츠 → 배지다** — 최상단 섹션이라 콘텐츠 뒤에 들어오면 그 아래 섹션 전부가 밀린다. diff --git a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift index 9aee8af8e..90107aede 100644 --- a/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift +++ b/Projects/Feature/HomeFeature/Demo/HomeFeatureDemoApp.swift @@ -201,6 +201,7 @@ private struct DemoRootView: View { loadPublicCollectionsUseCase: DefaultLoadPublicCollectionsUseCase( collectionRepository: CollectionDataFactory.makeRepository( network: client, + appStorage: UserDefaultsStorage(), logger: DataLogger(moduleName: "CollectionData", underlying: consoleLogger) ) ) @@ -362,17 +363,18 @@ private enum DemoHomeData { private struct DemoLoadPublicCollectionsUseCase: LoadPublicCollectionsUseCase { let scenario: DemoHomeScenario - func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { guard scenario != .empty else { return CursorPaginated(items: [], hasNext: false, nextCursor: nil) } let cards = (0.. CursorPaginated { + func execute(cursor: String?, size: Int) async throws(RepositoryError) -> CursorPaginated { let cards = (0..<3).map { index in - PublicCollectionCard( + CollectionCard( id: CollectionID(index), name: "개존잼 소설 🤩", description: "존잼 수준이 정도를 넘음", novelCount: index + 1, + isPrivate: false, recentNovels: [], owner: Author(userId: UserID(index), nickname: "코띠", profileImage: nil) ) diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift index 3e2b1e264..57be5d447 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeViewModel.swift @@ -32,7 +32,7 @@ final class HomeViewModel { var preferenceGenreNovelState: PreferenceGenreNovelState? var hasUnreadNotifications = false /// "컬렉션 모음.zip" 섹션. 비면 섹션을 제목까지 숨긴다(첫 로드 실패도 빈 채라 숨는다). - var publicCollections: [PublicCollectionCard] = [] + var publicCollections: [CollectionCard] = [] /// ⚠️ 초깃값 `true` — `onAppear`의 `.load`보다 첫 body 평가가 먼저라, false면 한 프레임 동안 /// "검색바·배너만 있는 빈 홈"이 스친다(Library·NovelDetail과 같은 이유). diff --git a/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift b/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift index 34125f328..44dcd3bfe 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/PublicCollectionSection.swift @@ -17,7 +17,7 @@ import WSSComponent /// 제목 줄 탭은 전체 컬렉션뷰, 카드 탭은 컬렉션 상세로 간다. struct PublicCollectionSection: View { - let collections: [PublicCollectionCard] + let collections: [CollectionCard] let onTitleTapped: () -> Void let onCollectionSelected: (CollectionID) -> Void @@ -81,7 +81,7 @@ private extension PublicCollectionSection { } } - func card(_ collection: PublicCollectionCard) -> some View { + func card(_ collection: CollectionCard) -> some View { Button { onCollectionSelected(collection.id) } label: { @@ -101,12 +101,14 @@ private extension PublicCollectionSection { slotCount: Metric.coverSlotCount ) - Spacer().frame(height: Metric.coversToOwner) + if let owner = collection.owner { + Spacer().frame(height: Metric.coversToOwner) - WSSCollectionOwnerLabel( - nickname: collection.owner.nickname, - profileImage: collection.owner.profileImage - ) + WSSCollectionOwnerLabel( + nickname: owner.nickname, + profileImage: owner.profileImage + ) + } } .padding(Metric.cardPadding) .frame(width: Metric.cardWidth, alignment: .leading) @@ -118,7 +120,7 @@ private extension PublicCollectionSection { } /// "설명 · 작품 N". 설명이 없으면 "작품 N"만 남는다. 설명이 길면 설명만 말줄임되고 작품 수는 지킨다. - func subtitle(_ collection: PublicCollectionCard) -> some View { + func subtitle(_ collection: CollectionCard) -> some View { HStack(spacing: 0) { if let description = collection.description { Text(description) diff --git a/Projects/Feature/UserPageFeature/Demo/UserPageFeatureDemoApp.swift b/Projects/Feature/UserPageFeature/Demo/UserPageFeatureDemoApp.swift index 6c7309639..63a09f041 100644 --- a/Projects/Feature/UserPageFeature/Demo/UserPageFeatureDemoApp.swift +++ b/Projects/Feature/UserPageFeature/Demo/UserPageFeatureDemoApp.swift @@ -288,6 +288,7 @@ private enum DemoFactory { logger: DefaultNetworkLogger(base: consoleLogger), tokenStore: DemoSessionTokenStore() ), + appStorage: UserDefaultsStorage(), logger: DataLogger(moduleName: "CollectionData", underlying: consoleLogger) ) return MypageFeatureFactory.makeView( @@ -319,6 +320,7 @@ private enum DemoFactory { logger: DefaultNetworkLogger(base: consoleLogger), tokenStore: DemoSessionTokenStore() ), + appStorage: UserDefaultsStorage(), logger: DataLogger(moduleName: "CollectionData", underlying: consoleLogger) ) return UserPageFeatureFactory.makeView( From c7383a8c0b7012870c939667fbf7dd28ba631ae1 Mon Sep 17 00:00:00 2001 From: Guryss Date: Tue, 20 Oct 2026 17:19:26 +0900 Subject: [PATCH 25/25] =?UTF-8?q?[Feat]=20#283=20-=20=ED=99=88=20=EC=BB=AC?= =?UTF-8?q?=EB=A0=89=EC=85=98=20=EB=AA=A8=EC=9D=8C.zip=20=EC=84=B9?= =?UTF-8?q?=EC=85=98=20=ED=83=AD=20=EC=9D=B4=EB=B2=A4=ED=8A=B8=20=ED=8A=B8?= =?UTF-8?q?=EB=9E=98=ED=82=B9=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 원본 이벤트 리스트에 이 섹션 이벤트가 없어 기존 홈 이벤트 패턴으로 이름을 정했다 (제목 home_collection_all, 카드 home_collectionlist). Co-Authored-By: Claude Opus 5.5 --- Projects/Feature/HomeFeature/CLAUDE.md | 3 ++- .../HomeFeature/Sources/Home/HomeAnalyticsEvent.swift | 4 ++++ .../Feature/HomeFeature/Sources/Home/HomeView.swift | 10 ++++++++-- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Projects/Feature/HomeFeature/CLAUDE.md b/Projects/Feature/HomeFeature/CLAUDE.md index 6aaf779e7..d838b2354 100644 --- a/Projects/Feature/HomeFeature/CLAUDE.md +++ b/Projects/Feature/HomeFeature/CLAUDE.md @@ -92,7 +92,8 @@ 컬렉션을 먼저 state에 넣어도 `hasLoadedContent`가 false인 동안은 로딩 뷰가 덮고 있어 콘텐츠와 같은 프레임에 함께 그려진다(동시 요청이라 총 대기시간은 그대로). 배지는 헤더의 점 하나라 늦어도 레이아웃이 안 움직여 맨 뒤다. 콘텐츠 뒤로 되돌리지 말 것. - - 섹션 탭(제목·카드) 이벤트 트래킹은 명세에 없어 걸지 않았다(이벤트 이름을 지어내지 않는다). + - 섹션 탭 이벤트(제목 `home_collection_all`·카드 `home_collectionlist`)는 원본 이벤트 리스트에 없어 #283에서 기존 홈 이벤트 + 패턴(`home_<섹션>_<대상>`)으로 사용자와 정했다. 원본 리스트에 정식 이름이 생기면 그쪽으로 맞출 것. - 섹션이 숨으면 오늘의 발견이 검색 영역에 바로 붙는다(간격 24 그대로). 보이면 검색 영역↔컬렉션 24, 컬렉션↔오늘의 발견 32. - Figma 카드 헤더의 빈 24pt 프레임(`bookmark-outline`)은 에셋 없는 빈 자리라 그리지 않는다. diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeAnalyticsEvent.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeAnalyticsEvent.swift index 48c41ef39..1642e3948 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeAnalyticsEvent.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeAnalyticsEvent.swift @@ -16,6 +16,10 @@ enum HomeAnalyticsEvent: String, AnalyticsEvent { case searchBarTapped = "general_search" /// "내 취향에 맞는 웹소설 찾기" 배너 클릭(상세탐색 진입) case detailSearchBannerTapped = "seek" + /// 컬렉션 모음.zip 섹션 제목 클릭(전체 컬렉션뷰 진입). 원본 리스트에 없어 #283에서 홈 이벤트 패턴으로 지었다. + case publicCollectionTitleTapped = "home_collection_all" + /// 컬렉션 모음.zip 카드 클릭. 원본 리스트에 없어 #283에서 홈 이벤트 패턴으로 지었다. + case publicCollectionSelected = "home_collectionlist" /// 오늘의 발견 카드 클릭 case todayDiscoverySelected = "home_today_ranking" /// 추천글(지금 뜨는 수다글) 카드 클릭 diff --git a/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift b/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift index 4f3c03959..17f8b7eea 100644 --- a/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift +++ b/Projects/Feature/HomeFeature/Sources/Home/HomeView.swift @@ -122,8 +122,14 @@ private extension HomeView { Spacer().frame(height: Metric.searchToCollection) PublicCollectionSection( collections: state.publicCollections, - onTitleTapped: { onRoute(.publicCollectionList) }, - onCollectionSelected: { onRoute(.collectionDetail($0)) } + onTitleTapped: { + viewModel.track(.publicCollectionTitleTapped) + onRoute(.publicCollectionList) + }, + onCollectionSelected: { collectionID in + viewModel.track(.publicCollectionSelected) + onRoute(.collectionDetail(collectionID)) + } ) }