From 52a558873b7131b25e2c75eec8fca0a08b87d64c Mon Sep 17 00:00:00 2001 From: Tony Li Date: Mon, 3 Nov 2025 14:40:54 +1300 Subject: [PATCH 1/3] Post Settings: Support custom taxonomies --- .../WordPressKit/RemotePostParameters.swift | 65 +++++++++-- .../WordPressKitObjC/PostServiceRemoteREST.m | 38 +++++- .../PostServiceRemoteXMLRPC.m | 15 +++ Modules/Sources/WordPressKitObjC/RemotePost.m | 19 +++ .../Sources/WordPressKitObjC/RemotePostTerm.m | 74 ++++++++++++ .../WordPressKitObjC/include/RemotePost.h | 6 + .../WordPressKitObjC/include/RemotePostTerm.h | 23 ++++ Sources/WordPressData/Blog+Extensions.swift | 11 ++ .../WordPressData/Objective-C/AbstractPost.m | 24 ++++ Sources/WordPressData/Objective-C/Blog.m | 1 + .../WordPressData/Objective-C/PostHelper.m | 1 + .../Objective-C/include/AbstractPost.h | 7 ++ .../WordPressData/Objective-C/include/Blog.h | 2 + .../WordPress 156.xcdatamodel/contents | 2 + .../RemotePostCreateParameters+Helpers.swift | 1 + .../WordPressData/Swift/SiteTaxonomy.swift | 46 ++++++++ .../Models/PostTermComparisonTests.swift | 108 ++++++++++++++++++ .../Classes/Services/BlogService+Swift.swift | 26 +++++ WordPress/Classes/Services/BlogService.m | 7 +- .../BlogDetailsViewController+Swift.swift | 2 +- .../SiteSettingsViewController+Swift.swift | 4 +- .../Post/PostSettings/PostSettings.swift | 14 +++ .../Post/PostSettings/PostSettingsView.swift | 21 ++++ .../PostSettings/PostSettingsViewModel.swift | 26 +++++ .../Views/PostSettingsCustomTaxonomyRow.swift | 40 +++++++ .../PostSettings/Views/PostTagsView.swift | 63 ++++++---- .../ViewRelated/Tags/EditTagView.swift | 8 +- .../Tags/SiteCustomTaxonomiesView.swift | 10 +- .../ViewRelated/Tags/SiteTaxonomy.swift | 19 --- .../ViewRelated/Tags/TagsService.swift | 16 +-- .../ViewRelated/Tags/TagsViewModel.swift | 24 ++-- 31 files changed, 639 insertions(+), 84 deletions(-) create mode 100644 Modules/Sources/WordPressKitObjC/RemotePostTerm.m create mode 100644 Modules/Sources/WordPressKitObjC/include/RemotePostTerm.h create mode 100644 Sources/WordPressData/Swift/SiteTaxonomy.swift create mode 100644 Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift create mode 100644 WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostSettingsCustomTaxonomyRow.swift delete mode 100644 WordPress/Classes/ViewRelated/Tags/SiteTaxonomy.swift diff --git a/Modules/Sources/WordPressKit/RemotePostParameters.swift b/Modules/Sources/WordPressKit/RemotePostParameters.swift index f735267c6e5a..d4e1c2f02999 100644 --- a/Modules/Sources/WordPressKit/RemotePostParameters.swift +++ b/Modules/Sources/WordPressKit/RemotePostParameters.swift @@ -21,6 +21,7 @@ public struct RemotePostCreateParameters: Equatable { public var format: String? public var isSticky = false public var tags: [String] = [] + public var otherTerms: [String: [String]] = [:] public var categoryIDs: [Int] = [] public var metadata: Set = [] public var discussion: RemotePostDiscussionSettings = .default @@ -52,6 +53,7 @@ public struct RemotePostUpdateParameters: Equatable { public var format: String?? public var isSticky: Bool? public var tags: [String]? + public var otherTerms: [String: [String]]? public var categoryIDs: [Int]? public var metadata: Set? public var discussion: RemotePostDiscussionSettings? @@ -138,6 +140,9 @@ extension RemotePostCreateParameters { if previous.tags != tags { changes.tags = tags } + if !RemotePost.compareOtherTerms(previous.otherTerms, withAnother: otherTerms) { + changes.otherTerms = otherTerms + } if Set(previous.categoryIDs) != Set(categoryIDs) { changes.categoryIDs = categoryIDs } @@ -191,6 +196,9 @@ extension RemotePostCreateParameters { if let tags = changes.tags { self.tags = tags } + if let otherTerms = changes.otherTerms { + self.otherTerms = otherTerms + } if let categoryIDs = changes.categoryIDs { self.categoryIDs = categoryIDs } @@ -253,9 +261,19 @@ struct RemotePostCreateParametersWordPressComEncoder: Encodable { // Posts try container.encodeIfPresent(parameters.format, forKey: .format) + + // Terms (including tags) + var terms = [String: [String]]() if !parameters.tags.isEmpty { - try container.encode([RemotePostWordPressComCodingKeys.postTags: parameters.tags], forKey: .terms) + terms[RemotePostWordPressComCodingKeys.postTags] = parameters.tags } + if !parameters.otherTerms.isEmpty { + terms.merge(parameters.otherTerms) { old, _ in old } + } + if !terms.isEmpty { + try container.encode(terms, forKey: .terms) + } + if !parameters.categoryIDs.isEmpty { try container.encodeIfPresent(parameters.categoryIDs, forKey: .categoryIDs) } @@ -330,6 +348,18 @@ struct RemotePostUpdateParametersWordPressComEncoder: Encodable { try container.encode(metadata, forKey: .metadata) } + // Terms (including tags) + var terms = [String: [String]]() + if let tags = parameters.tags, !tags.isEmpty { + terms[RemotePostWordPressComCodingKeys.postTags] = tags + } + if let otherTerms = parameters.otherTerms, !otherTerms.isEmpty { + terms.merge(otherTerms) { old, _ in old } + } + if !terms.isEmpty { + try container.encode(terms, forKey: .terms) + } + // Pages if let parentPageID = parameters.parentPageID { try container.encodeNullableID(parentPageID, forKey: .parentPageID) @@ -337,9 +367,6 @@ struct RemotePostUpdateParametersWordPressComEncoder: Encodable { // Posts try container.encodeIfPresent(parameters.format, forKey: .format) - if let tags = parameters.tags { - try container.encode([RemotePostWordPressComCodingKeys.postTags: tags], forKey: .terms) - } try container.encodeIfPresent(parameters.categoryIDs, forKey: .categoryIDs) try container.encodeIfPresent(parameters.isSticky, forKey: .isSticky) if let discussion = parameters.discussion { @@ -395,14 +422,23 @@ struct RemotePostCreateParametersXMLRPCEncoder: Encodable { try container.encode(metadata, forKey: .metadata) } + // Terms (including tags) + var terms = [String: [String]]() + if !parameters.tags.isEmpty { + terms[RemotePostXMLRPCCodingKeys.taxonomyTag] = parameters.tags + } + if !parameters.otherTerms.isEmpty { + terms.merge(parameters.otherTerms) { old, _ in old } + } + if !terms.isEmpty { + try container.encode(terms, forKey: .termNames) + } + // Pages try container.encodeIfPresent(parameters.parentPageID, forKey: .parentPageID) // Posts try container.encodeIfPresent(parameters.format, forKey: .format) - if !parameters.tags.isEmpty { - try container.encode([RemotePostXMLRPCCodingKeys.taxonomyTag: parameters.tags], forKey: .termNames) - } if !parameters.categoryIDs.isEmpty { try container.encode([RemotePostXMLRPCCodingKeys.taxonomyCategory: parameters.categoryIDs], forKey: .terms) } @@ -438,6 +474,18 @@ struct RemotePostUpdateParametersXMLRPCEncoder: Encodable { try container.encode(metadata, forKey: .metadata) } + // Terms (including tags) + var terms = [String: [String]]() + if let tags = parameters.tags, !tags.isEmpty { + terms[RemotePostXMLRPCCodingKeys.taxonomyTag] = tags + } + if let otherTerms = parameters.otherTerms, !otherTerms.isEmpty { + terms.merge(otherTerms) { old, _ in old } + } + if !terms.isEmpty { + try container.encode(terms, forKey: .termNames) + } + // Pages if let parentPageID = parameters.parentPageID { try container.encodeNullableID(parentPageID, forKey: .parentPageID) @@ -445,9 +493,6 @@ struct RemotePostUpdateParametersXMLRPCEncoder: Encodable { // Posts try container.encodeStringIfPresent(parameters.format, forKey: .format) - if let tags = parameters.tags { - try container.encode([RemotePostXMLRPCCodingKeys.taxonomyTag: tags], forKey: .termNames) - } if let categoryIDs = parameters.categoryIDs { try container.encode([RemotePostXMLRPCCodingKeys.taxonomyCategory: categoryIDs], forKey: .terms) } diff --git a/Modules/Sources/WordPressKitObjC/PostServiceRemoteREST.m b/Modules/Sources/WordPressKitObjC/PostServiceRemoteREST.m index b4e28dc6e37b..524886af418a 100644 --- a/Modules/Sources/WordPressKitObjC/PostServiceRemoteREST.m +++ b/Modules/Sources/WordPressKitObjC/PostServiceRemoteREST.m @@ -1,6 +1,7 @@ #import "PostServiceRemoteREST.h" #import "RemotePost.h" #import "RemotePostCategory.h" +#import "RemotePostTerm.h" #import "FilePart.h" #import "WPMapFilterReduce.h" #import "DisplayableImageHelper.h" @@ -453,6 +454,7 @@ + (RemotePost *)remotePostFromJSONDictionary:(NSDictionary *)jsonPost { post.categories = [self remoteCategoriesFromJSONArray:[categories allValues]]; } post.tags = [self tagNamesFromJSONDictionary:jsonPost[@"tags"]]; + post.otherTerms = [RemotePostTerm simpleMappingRepresentation:[self otherTermsFromJSONDictionary:jsonPost[@"terms"]]]; post.revisions = [jsonPost arrayForKey:@"revisions"]; @@ -522,11 +524,19 @@ - (NSDictionary *)parametersWithRemotePost:(RemotePost *)post parameters[@"categories_by_id"] = [post.categories valueForKey:@"categoryID"]; } - if (post.tags) { - NSArray *tags = post.tags; - NSDictionary *postTags = @{@"post_tag":tags}; - parameters[@"terms"] = postTags; + { + NSMutableDictionary *terms = [NSMutableDictionary dictionary]; + if (post.tags) { + terms[@"post_tag"] = post.tags; + } + [post.otherTerms enumerateKeysAndObjectsUsingBlock:^(NSString *taxonomy, NSArray *theTerms, BOOL *stop) { + terms[taxonomy] = theTerms; + }]; + if (terms.count > 0) { + parameters[@"terms"] = terms; + } } + if (post.format) { parameters[@"format"] = post.format; } @@ -596,6 +606,26 @@ + (NSArray *)tagNamesFromJSONDictionary:(NSDictionary *)jsonTags { return [jsonTags allKeys]; } ++ (NSArray *)otherTermsFromJSONDictionary:(NSDictionary *)terms { + NSMutableArray *otherTerms = [NSMutableArray array]; + + for (NSString *taxonomySlug in terms) { + if ([taxonomySlug isEqualToString:@"category"] || + [taxonomySlug isEqualToString:@"post_tag"] || + [taxonomySlug isEqualToString:@"post_format"]) { + continue; + } + + NSDictionary *taxonomyTerms = terms[taxonomySlug]; + for (NSString *termKey in taxonomyTerms) { + NSDictionary *termData = taxonomyTerms[termKey]; + [otherTerms addObject:[[RemotePostTerm alloc] initWithRESTAPIResponse:termData taxonomySlug:taxonomySlug]]; + } + } + + return [otherTerms copy]; +} + /** * @brief Returns an array of RemoteLikeUser based on provided JSON * representation of users. diff --git a/Modules/Sources/WordPressKitObjC/PostServiceRemoteXMLRPC.m b/Modules/Sources/WordPressKitObjC/PostServiceRemoteXMLRPC.m index e3fbaaeef2ae..ee9055fe840f 100644 --- a/Modules/Sources/WordPressKitObjC/PostServiceRemoteXMLRPC.m +++ b/Modules/Sources/WordPressKitObjC/PostServiceRemoteXMLRPC.m @@ -1,6 +1,7 @@ #import "PostServiceRemoteXMLRPC.h" #import "RemotePost.h" #import "RemotePostCategory.h" +#import "RemotePostTerm.h" #import "NSMutableDictionary+Helpers.h" #import "NSString+Helpers.h" #import "WPMapFilterReduce.h" @@ -333,6 +334,7 @@ + (RemotePost *)remotePostFromXMLRPCDictionary:(NSDictionary *)xmlrpcDictionary NSArray *terms = [xmlrpcDictionary arrayForKey:@"terms"]; post.tags = [self tagsFromXMLRPCTermsArray:terms]; post.categories = [self remoteCategoriesFromXMLRPCTermsArray:terms]; + post.otherTerms = [RemotePostTerm simpleMappingRepresentation:[self otherTermsFromXMLRPCTermsArray:terms]]; post.commentsStatus = [xmlrpcDictionary stringForKey:@"comment_status"]; post.pingsStatus = [xmlrpcDictionary stringForKey:@"ping_status"]; @@ -373,6 +375,15 @@ + (NSArray *)remoteCategoriesFromXMLRPCTermsArray:(NSArray *)terms { }]; } ++ (NSArray *)otherTermsFromXMLRPCTermsArray:(NSArray *)terms { + return [[terms wpkit_filter:^BOOL(NSDictionary *category) { + return ![[category stringForKey:@"taxonomy"] isEqualToString:@"category"] + && ![[category stringForKey:@"taxonomy"] isEqualToString:@"post_tag"]; + }] wpkit_map:^id(NSDictionary *term) { + return [[RemotePostTerm alloc] initWithXMLRPCResponse:term]; + }]; +} + + (RemotePostCategory *)remoteCategoryFromXMLRPCDictionary:(NSDictionary *)xmlrpcCategory { RemotePostCategory *category = [RemotePostCategory new]; category.categoryID = [xmlrpcCategory numberForKey:@"term_id"]; @@ -425,6 +436,10 @@ - (NSDictionary *)parametersWithRemotePost:(RemotePost *)post postParams[@"categories"] = categoryNames; } + if (post.otherTerms.count > 0) { + postParams[@"terms_names"] = post.otherTerms; + } + if ([post.metadata count] > 0) { postParams[@"custom_fields"] = post.metadata; } diff --git a/Modules/Sources/WordPressKitObjC/RemotePost.m b/Modules/Sources/WordPressKitObjC/RemotePost.m index ef7960fef890..a510dab3fd96 100644 --- a/Modules/Sources/WordPressKitObjC/RemotePost.m +++ b/Modules/Sources/WordPressKitObjC/RemotePost.m @@ -23,6 +23,25 @@ - (id)initWithSiteID:(NSNumber *)siteID status:(NSString *)status title:(NSStrin return self; } ++ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs +{ + if (lhs.count != rhs.count) { + return NO; + } + + NSMutableDictionary *> *lhsNormalized = [NSMutableDictionary dictionary]; + for (NSString *key in lhs) { + lhsNormalized[key] = [NSSet setWithArray:lhs[key]]; + } + + NSMutableDictionary *> *rhsNormalized = [NSMutableDictionary dictionary]; + for (NSString *key in rhs) { + rhsNormalized[key] = [NSSet setWithArray:rhs[key]]; + } + + return [lhsNormalized isEqualToDictionary:rhsNormalized]; +} + - (NSString *)debugDescription { NSDictionary *properties = [self debugProperties]; return [NSString stringWithFormat:@"<%@: %p> (%@)", NSStringFromClass([self class]), self, properties]; diff --git a/Modules/Sources/WordPressKitObjC/RemotePostTerm.m b/Modules/Sources/WordPressKitObjC/RemotePostTerm.m new file mode 100644 index 000000000000..c6e45e546cf7 --- /dev/null +++ b/Modules/Sources/WordPressKitObjC/RemotePostTerm.m @@ -0,0 +1,74 @@ +#import "RemotePostTerm.h" + +@import NSObject_SafeExpectations; + +@implementation RemotePostTerm + +- (instancetype)initWithXMLRPCResponse:(NSDictionary *)response +{ + self = [super init]; + if (self) { + self.termID = [response numberForKey:@"term_id"]; + self.name = [response stringForKey:@"name"]; + self.slug = [response stringForKey:@"slug"]; + self.taxonomySlug = [response stringForKey:@"taxonomy"]; + self.termDescription = [response stringForKey:@"description"]; + self.count = [response numberForKey:@"count"]; + } + return self; +} + +- (instancetype)initWithRESTAPIResponse:(NSDictionary *)response taxonomySlug:(NSString *)taxonomySlug +{ + self = [super init]; + if (self) { + self.termID = [response numberForKey:@"ID"]; + self.name = [response stringForKey:@"name"]; + self.slug = [response stringForKey:@"slug"]; + self.taxonomySlug = taxonomySlug; + self.termDescription = [response stringForKey:@"description"]; + self.count = [response numberForKey:@"post_count"]; + } + return self; +} + +- (NSDictionary *)RESTAPIRepresentation +{ + return @{ + @"ID": self.termID, + @"name": self.name, + @"slug": self.slug, + @"description": self.termDescription ?: @"", + @"post_count": self.count + }; +} + ++ (NSDictionary *> *)simpleMappingRepresentation:(NSArray *)terms +{ + NSMutableDictionary *> *dict = [NSMutableDictionary dictionary]; + for (RemotePostTerm *term in terms) { + NSMutableArray *termNames = dict[term.taxonomySlug]; + if (termNames == nil) { + termNames = [NSMutableArray array]; + dict[term.taxonomySlug] = termNames; + } + [termNames addObject:term.name]; + } + return [dict copy]; +} + +- (NSString *)debugDescription +{ + NSDictionary *properties = @{ + @"ID": self.termID, + @"name": self.name + }; + return [NSString stringWithFormat:@"<%@: %p> (%@)", NSStringFromClass([self class]), self, properties]; +} + +- (NSString *)description +{ + return [NSString stringWithFormat:@"<%@: %p> %@[%@]", NSStringFromClass([self class]), self, self.name, self.termID]; +} + +@end diff --git a/Modules/Sources/WordPressKitObjC/include/RemotePost.h b/Modules/Sources/WordPressKitObjC/include/RemotePost.h index 63d1850c5cab..c8ee3f0e31f7 100644 --- a/Modules/Sources/WordPressKitObjC/include/RemotePost.h +++ b/Modules/Sources/WordPressKitObjC/include/RemotePost.h @@ -1,5 +1,7 @@ #import + @class RemotePostAutosave; +@class RemotePostTerm; extern NSString * const PostStatusDraft; extern NSString * const PostStatusPending; @@ -54,6 +56,8 @@ extern NSString * const PostStatusDeleted; @property (nonatomic, strong) NSArray *categories; @property (nonatomic, strong) NSArray *revisions; @property (nonatomic, strong) NSArray *tags; +//@property (nonatomic, strong) NSArray *otherTerms; +@property (nonatomic, strong) NSDictionary *> *otherTerms; @property (nonatomic, strong) NSString *pathForDisplayImage; @property (nonatomic, assign) NSNumber *isStickyPost; @property (nonatomic, assign) BOOL isFeaturedImageChanged; @@ -63,6 +67,8 @@ extern NSString * const PostStatusDeleted; */ @property (nonatomic, strong) NSArray *metadata; ++ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs; + // Featured images? // Geolocation? // Attachments? diff --git a/Modules/Sources/WordPressKitObjC/include/RemotePostTerm.h b/Modules/Sources/WordPressKitObjC/include/RemotePostTerm.h new file mode 100644 index 000000000000..bfcf78556e73 --- /dev/null +++ b/Modules/Sources/WordPressKitObjC/include/RemotePostTerm.h @@ -0,0 +1,23 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface RemotePostTerm : NSObject + +@property (nonatomic, strong) NSNumber *termID; +@property (nonatomic, strong) NSString *name; +@property (nonatomic, strong) NSString *slug; +@property (nonatomic, strong) NSString *taxonomySlug; +@property (nonatomic, strong) NSString *termDescription; +@property (nonatomic, strong) NSNumber *count; + +- (instancetype)initWithXMLRPCResponse:(NSDictionary *)response; +- (instancetype)initWithRESTAPIResponse:(NSDictionary *)response taxonomySlug:(NSString *)taxonomySlug; + +- (NSDictionary *)RESTAPIRepresentation; + ++ (NSDictionary *> *)simpleMappingRepresentation:(NSArray *)terms; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Sources/WordPressData/Blog+Extensions.swift b/Sources/WordPressData/Blog+Extensions.swift index 91254b696f1b..3d391d9c6b10 100644 --- a/Sources/WordPressData/Blog+Extensions.swift +++ b/Sources/WordPressData/Blog+Extensions.swift @@ -1,6 +1,7 @@ import Foundation import CoreData import WordPressShared +import WordPressAPI extension Blog { @@ -80,4 +81,14 @@ extension Blog { (lhs.order?.intValue ?? 0) < (rhs.order?.intValue ?? 0) } } + + public var taxonomies: [SiteTaxonomy] { + get throws { + try rawTaxonomies.flatMap { try JSONDecoder().decode([SiteTaxonomy].self, from: $0) } ?? [] + } + } + + public func setTaxonomies(_ taxonomies: [SiteTaxonomy]) throws { + self.rawTaxonomies = try JSONEncoder().encode(taxonomies) + } } diff --git a/Sources/WordPressData/Objective-C/AbstractPost.m b/Sources/WordPressData/Objective-C/AbstractPost.m index 1eb86f2e5dbc..8c7acf649564 100644 --- a/Sources/WordPressData/Objective-C/AbstractPost.m +++ b/Sources/WordPressData/Objective-C/AbstractPost.m @@ -24,6 +24,7 @@ @implementation AbstractPost @dynamic foreignID; @dynamic order; @dynamic rawMetadata; +@dynamic rawOtherTerms; @synthesize voiceContent; #pragma mark - Life Cycle Methods @@ -346,4 +347,27 @@ - (void)updatePathForDisplayImageBasedOnContent self.pathForDisplayImage = result; } +- (void)setParsedOtherTerms:(NSDictionary *> *)data +{ + if (data == nil) { + self.rawOtherTerms = nil; + } else { + self.rawOtherTerms = [NSJSONSerialization dataWithJSONObject:data options:0 error:nil]; + } +} + +- (NSDictionary *> *)parseOtherTerms +{ + if (self.rawOtherTerms == nil) { + return [NSDictionary dictionary]; + } + + return [NSJSONSerialization JSONObjectWithData:self.rawOtherTerms options:0 error:nil] ?: [NSDictionary dictionary]; +} + ++ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs +{ + return [RemotePost compareOtherTerms:lhs withAnother:rhs]; +} + @end diff --git a/Sources/WordPressData/Objective-C/Blog.m b/Sources/WordPressData/Objective-C/Blog.m index e246132c7d72..2416fc07bb89 100644 --- a/Sources/WordPressData/Objective-C/Blog.m +++ b/Sources/WordPressData/Objective-C/Blog.m @@ -91,6 +91,7 @@ @implementation Blog @dynamic quotaSpaceUsed; @dynamic pageTemplateCategories; @dynamic publicizeInfo; +@dynamic rawTaxonomies; @synthesize videoPressEnabled; @synthesize xmlrpcApi = _xmlrpcApi; diff --git a/Sources/WordPressData/Objective-C/PostHelper.m b/Sources/WordPressData/Objective-C/PostHelper.m index c56e61034ce5..a63d4df433ca 100644 --- a/Sources/WordPressData/Objective-C/PostHelper.m +++ b/Sources/WordPressData/Objective-C/PostHelper.m @@ -60,6 +60,7 @@ + (void)updatePost:(AbstractPost *)post withRemotePost:(RemotePost *)remotePost post.rawMetadata = [PostHelper makeRawMetadataFrom:remotePost]; post.foreignID = [PostHelper getForeignIDFor:remotePost]; + [post setParsedOtherTerms:remotePost.otherTerms]; post.autosaveTitle = remotePost.autosave.title; post.autosaveExcerpt = remotePost.autosave.excerpt; diff --git a/Sources/WordPressData/Objective-C/include/AbstractPost.h b/Sources/WordPressData/Objective-C/include/AbstractPost.h index 7d0eeb837219..19bc3f527ca8 100644 --- a/Sources/WordPressData/Objective-C/include/AbstractPost.h +++ b/Sources/WordPressData/Objective-C/include/AbstractPost.h @@ -58,6 +58,8 @@ typedef NS_ENUM(NSUInteger, AbstractPostRemoteStatus) { /// Jetpack plugin metadata.` @property (nonatomic, strong, nullable) NSData *rawMetadata; +@property (nonatomic, strong, nullable) NSData *rawOtherTerms; + @property (nonatomic, strong, nullable) NSString *voiceContent; // Revision management @@ -128,6 +130,11 @@ typedef NS_ENUM(NSUInteger, AbstractPostRemoteStatus) { */ - (void)updatePathForDisplayImageBasedOnContent; +- (void)setParsedOtherTerms:(NSDictionary *> *)data; +- (NSDictionary *> *)parseOtherTerms; + ++ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs; + @end @interface AbstractPost (CoreDataGeneratedAccessors) diff --git a/Sources/WordPressData/Objective-C/include/Blog.h b/Sources/WordPressData/Objective-C/include/Blog.h index 37c2fc18cab2..ddc4e41575d4 100644 --- a/Sources/WordPressData/Objective-C/include/Blog.h +++ b/Sources/WordPressData/Objective-C/include/Blog.h @@ -179,6 +179,8 @@ typedef NS_ENUM(NSInteger, SiteVisibility) { @property (nonatomic, strong, readwrite, nullable) NSNumber *quotaSpaceUsed; @property (nullable, nonatomic, retain) NSSet *pageTemplateCategories; +@property (nullable, nonatomic, retain) NSData *rawTaxonomies; + /** * @details Maps to a BlogSettings instance, which contains a collection of the available preferences, * and their values. diff --git a/Sources/WordPressData/Resources/WordPress.xcdatamodeld/WordPress 156.xcdatamodel/contents b/Sources/WordPressData/Resources/WordPress.xcdatamodeld/WordPress 156.xcdatamodel/contents index 54abb1f612d6..1ab48e3fdbc7 100644 --- a/Sources/WordPressData/Resources/WordPress.xcdatamodeld/WordPress 156.xcdatamodel/contents +++ b/Sources/WordPressData/Resources/WordPress.xcdatamodeld/WordPress 156.xcdatamodel/contents @@ -13,6 +13,7 @@ + @@ -156,6 +157,7 @@ + diff --git a/Sources/WordPressData/Swift/RemotePostCreateParameters+Helpers.swift b/Sources/WordPressData/Swift/RemotePostCreateParameters+Helpers.swift index 21f74f6f5c03..00252229528d 100644 --- a/Sources/WordPressData/Swift/RemotePostCreateParameters+Helpers.swift +++ b/Sources/WordPressData/Swift/RemotePostCreateParameters+Helpers.swift @@ -20,6 +20,7 @@ extension RemotePostCreateParameters { excerpt = post.mt_excerpt slug = post.wp_slug featuredImageID = post.featuredImage?.mediaID?.intValue + otherTerms = post.parseOtherTerms() switch post { case let page as Page: parentPageID = page.parentID?.intValue diff --git a/Sources/WordPressData/Swift/SiteTaxonomy.swift b/Sources/WordPressData/Swift/SiteTaxonomy.swift new file mode 100644 index 000000000000..549f65b3e4e6 --- /dev/null +++ b/Sources/WordPressData/Swift/SiteTaxonomy.swift @@ -0,0 +1,46 @@ +import Foundation +import WordPressAPI +import WordPressAPIInternal + +public struct SiteTaxonomy: Codable { + public struct LocalizedLabels: Codable { + public var name: String? + public var newItemName: String? + public var addNewItem: String? + public var nameFieldDescription: String? + public var descFieldDescription: String? + public var noTerms: String? + public var searchItems: String? + } + + public var slug: String + public var name: String + public var labels: LocalizedLabels + public var supportedPostTypes: [String] = [] + + var restBase: String + + public init(details: TaxonomyTypeDetailsWithEditContext) { + self.slug = details.slug + self.name = details.name + self.restBase = details.restBase + self.labels = LocalizedLabels( + name: details.labels[.name] ?? nil, + newItemName: details.labels[.newItemName] ?? nil, + addNewItem: details.labels[.addNewItem] ?? nil, + nameFieldDescription: details.labels[.nameFieldDescription] ?? nil, + descFieldDescription: details.labels[.descFieldDescription] ?? nil, + noTerms: details.labels[.noTerms] ?? nil, + searchItems: details.labels[.searchItems] ?? nil + ) + self.supportedPostTypes = details.types + } + + public var localizedName: String { + labels.name ?? name + } + + public var endpoint: TermEndpointType { + .custom(restBase) + } +} diff --git a/Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift b/Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift new file mode 100644 index 000000000000..98cb8dbaa3c2 --- /dev/null +++ b/Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift @@ -0,0 +1,108 @@ +import Testing +@testable import WordPressKit +@testable import WordPressKitObjC + +struct PostTermComparisonTests { + + @Test + func emptyDictionaries() { + let lhs: [String: [String]] = [:] + let rhs: [String: [String]] = [:] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + } + + @Test + func identicalDictionaries() { + let lhs: [String: [String]] = [ + "category": ["1", "2", "3"], + "post_tag": ["tag1", "tag2"] + ] + let rhs: [String: [String]] = [ + "category": ["1", "2", "3"], + "post_tag": ["tag1", "tag2"] + ] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + } + + @Test + func sameValuesInDifferentOrder() { + let lhs: [String: [String]] = [ + "category": ["1", "2", "3"], + "post_tag": ["tag1", "tag2"] + ] + let rhs: [String: [String]] = [ + "category": ["3", "1", "2"], + "post_tag": ["tag2", "tag1"] + ] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + } + + @Test + func differentKeys() { + let lhs: [String: [String]] = [ + "category": ["1", "2", "3"] + ] + let rhs: [String: [String]] = [ + "post_tag": ["tag1", "tag2"] + ] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == false) + } + + @Test + func differentValues() { + let lhs: [String: [String]] = [ + "category": ["1", "2", "3"] + ] + let rhs: [String: [String]] = [ + "category": ["1", "2", "4"] + ] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == false) + } + + @Test + func differentCounts() { + let lhs: [String: [String]] = [ + "category": ["1", "2", "3"], + "post_tag": ["tag1", "tag2"] + ] + let rhs: [String: [String]] = [ + "category": ["1", "2", "3"] + ] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == false) + } + + @Test + func duplicateValuesInArrays() { + let lhs: [String: [String]] = [ + "category": ["1", "2", "2", "3"] + ] + let rhs: [String: [String]] = [ + "category": ["1", "2", "3"] + ] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + } + + @Test + func multipleTaxonomies() { + let lhs: [String: [String]] = [ + "category": ["1", "2"], + "post_tag": ["tag1", "tag2"], + "custom_tax": ["term1"] + ] + let rhs: [String: [String]] = [ + "category": ["2", "1"], + "post_tag": ["tag2", "tag1"], + "custom_tax": ["term1"] + ] + + #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + } + +} diff --git a/WordPress/Classes/Services/BlogService+Swift.swift b/WordPress/Classes/Services/BlogService+Swift.swift index 4eaa3cec5771..ac248c13f19e 100644 --- a/WordPress/Classes/Services/BlogService+Swift.swift +++ b/WordPress/Classes/Services/BlogService+Swift.swift @@ -1,6 +1,8 @@ import Foundation import WordPressData import WordPressShared +import WordPressCore +import WordPressAPI extension BlogService { @objc public func unscheduleBloggingReminders(for blog: Blog) { @@ -73,6 +75,30 @@ extension BlogService { } } + public func syncTaxnomies(for blogId: TaggedManagedObjectID) async throws { + let client = try await self.coreDataStack.performQuery { context in + let blog = try context.existingObject(with: blogId) + return try WordPressClient(site: .init(blog: blog)) + } + + let result = try await client.api.taxonomies.listWithEditContext(params: .init()).data.taxonomyTypes.values + try await ContextManager.shared.performAndSave { context in + let blog = try context.existingObject(with: blogId) + try blog.setTaxonomies(result.map(SiteTaxonomy.init)) + } + } + + @objc + public func syncTaxnomies(for blog: Blog, completion: @escaping () -> Void) { + let blogId = TaggedManagedObjectID(blog) + Task { @MainActor in + defer { + completion() + } + try await self.syncTaxnomies(for: blogId) + } + } + static func blog(with site: JetpackSiteRef, context: NSManagedObjectContext = ContextManager.shared.mainContext) -> Blog? { let blog: Blog? diff --git a/WordPress/Classes/Services/BlogService.m b/WordPress/Classes/Services/BlogService.m index 2ec076a5b688..1df554172984 100644 --- a/WordPress/Classes/Services/BlogService.m +++ b/WordPress/Classes/Services/BlogService.m @@ -220,7 +220,12 @@ - (void)syncBlogAndAllMetadata:(Blog *)blog completionHandler:(void (^)(void))co dispatch_group_leave(syncGroup); }]; } - + + dispatch_group_enter(syncGroup); + [self syncTaxnomiesFor:blog completion:^{ + dispatch_group_leave(syncGroup); + }]; + // When everything has left the syncGroup (all calls have ended with success // or failure) perform the completionHandler dispatch_group_notify(syncGroup, dispatch_get_main_queue(),^{ diff --git a/WordPress/Classes/ViewRelated/Blog/Blog Details/BlogDetailsViewController+Swift.swift b/WordPress/Classes/ViewRelated/Blog/Blog Details/BlogDetailsViewController+Swift.swift index 73ed96163ef3..0e6222631b08 100644 --- a/WordPress/Classes/ViewRelated/Blog/Blog Details/BlogDetailsViewController+Swift.swift +++ b/WordPress/Classes/ViewRelated/Blog/Blog Details/BlogDetailsViewController+Swift.swift @@ -350,7 +350,7 @@ extension BlogDetailsViewController { } @objc public func showApplicationPasswords() { - let feature = NSLocalizedString("applicationPasswordRequired.feature.users", value: "Application Passwords Management", comment: "Feature name for managing application passwords in the app") + let feature = NSLocalizedString("applicationPasswordRequired.feature.applicationPasswords", value: "Application Passwords Management", comment: "Feature name for managing application passwords in the app") let view = ApplicationPasswordRequiredView(blog: blog, localizedFeatureName: feature, presentingViewController: self) { ApplicationTokenListView(dataProvider: ApplicationPasswordService(api: $0)) } diff --git a/WordPress/Classes/ViewRelated/Blog/Site Settings/SiteSettingsViewController+Swift.swift b/WordPress/Classes/ViewRelated/Blog/Site Settings/SiteSettingsViewController+Swift.swift index d09f0f248013..06039e8865b6 100644 --- a/WordPress/Classes/ViewRelated/Blog/Site Settings/SiteSettingsViewController+Swift.swift +++ b/WordPress/Classes/ViewRelated/Blog/Site Settings/SiteSettingsViewController+Swift.swift @@ -58,7 +58,7 @@ extension SiteSettingsViewController { @objc public func showCustomTaxonomies() { let viewController: UIViewController if let client = try? WordPressClient(site: .init(blog: blog)) { - let rootView = SiteCustomTaxonomiesView(blog: self.blog, api: client.api) + let rootView = SiteCustomTaxonomiesView(blog: self.blog, client: client) viewController = UIHostingController(rootView: rootView) } else { let feature = NSLocalizedString( @@ -67,7 +67,7 @@ extension SiteSettingsViewController { comment: "Feature name for managing terms and taxonomies in the app" ) let rootView = ApplicationPasswordRequiredView(blog: self.blog, localizedFeatureName: feature, presentingViewController: self) { client in - SiteCustomTaxonomiesView(blog: self.blog, api: client.api) + SiteCustomTaxonomiesView(blog: self.blog, client: client) } viewController = UIHostingController(rootView: rootView) } diff --git a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift index 727f5036c84d..116f2a441940 100644 --- a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift +++ b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift @@ -20,6 +20,7 @@ struct PostSettings: Hashable { var author: Author? var categoryIDs: Set = [] var tags: String = "" + var otherTerms: [String: [String]] = [:] var featuredImageID: Int? var metadata: PostMetadata @@ -53,6 +54,7 @@ struct PostSettings: Hashable { } featuredImageID = post.featuredImage?.mediaID?.intValue + otherTerms = post.parseOtherTerms() metadata = PostMetadata(post) @@ -110,6 +112,10 @@ struct PostSettings: Hashable { post.featuredImage = nil } + if !AbstractPost.compareOtherTerms(post.parseOtherTerms(), withAnother: otherTerms) { + post.setParsedOtherTerms(otherTerms) + } + var postMetadataContainer = PostMetadataContainer(post) if PostMetadata(from: postMetadataContainer) != metadata { metadata.encode(in: &postMetadataContainer) @@ -230,6 +236,14 @@ extension PostSettings { .sorted { $0.localizedCaseInsensitiveCompare($1) == .orderedAscending } .map { $0.stringByDecodingXMLCharacters() } } + + func getTerms(forTaxonomySlug taxonomySlug: String) -> [String] { + otherTerms[taxonomySlug] ?? [] + } + + mutating func setTerms(_ terms: String, forTaxonomySlug taxonomySlug: String) { + otherTerms[taxonomySlug] = AbstractPost.makeTags(from: terms) + } } /// A value-type representation of `PublicizeService` for the current blog that's simplified for the auto-sharing flow. diff --git a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsView.swift b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsView.swift index bf1d0a6d0536..313517e17955 100644 --- a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsView.swift +++ b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsView.swift @@ -181,6 +181,7 @@ struct PostSettingsFormContentView: View { categoriesRow tagsRow suggestedTagsRow + customTaxonomyRow } header: { SectionHeader(Strings.taxonomyHeader) } @@ -217,6 +218,26 @@ struct PostSettingsFormContentView: View { } } + @ViewBuilder + private var customTaxonomyRow: some View { + if let client = viewModel.client, !viewModel.customTaxonomies.isEmpty { + ForEach(viewModel.customTaxonomies, id: \.slug) { taxonomy in + NavigationLink { + PostTagsView( + blog: viewModel.post.blog, + client: client, + taxonomy: taxonomy, + selectedTerms: viewModel.settings.getTerms(forTaxonomySlug: taxonomy.slug).joined(separator: ",") + ) { terms in + viewModel.didSelectTerms(terms, forTaxonomySlug: taxonomy.slug) + } + } label: { + PostSettingsCustomTaxonomyRow(taxonomy: taxonomy, terms: viewModel.settings.getTerms(forTaxonomySlug: taxonomy.slug)) + } + } + } + } + // MARK: - "Excerpt" Section @ViewBuilder diff --git a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsViewModel.swift b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsViewModel.swift index d6bdd270be90..77c184761848 100644 --- a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsViewModel.swift +++ b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettingsViewModel.swift @@ -3,7 +3,9 @@ import BuildSettingsKit import SwiftUI import WordPressData import WordPressKit +import WordPressCore import WordPressShared +import WordPressAPIInternal import Combine @MainActor @@ -12,6 +14,7 @@ final class PostSettingsViewModel: NSObject, ObservableObject { let isStandalone: Bool let context: Context let featuredImageViewModel: PostSettingsFeaturedImageViewModel + let client: WordPressClient? @Published var settings: PostSettings { didSet { @@ -24,6 +27,7 @@ final class PostSettingsViewModel: NSObject, ObservableObject { @Published private(set) var displayedCategories: [String] = [] @Published private(set) var displayedTags: [String] = [] @Published private(set) var suggestedTags: [String] = [] + @Published private(set) var customTaxonomies: [SiteTaxonomy] = [] @Published private(set) var parentPageText: String? @Published private(set) var socialSharingState: SocialSharingSectionState? @@ -155,6 +159,7 @@ final class PostSettingsViewModel: NSObject, ObservableObject { self.isStandalone = isStandalone self.context = context self.preferences = preferences + self.client = try? WordPressClient(site: .init(blog: post.blog)) // Initialize settings from the post let initialSettings = PostSettings(from: post) @@ -174,6 +179,7 @@ final class PostSettingsViewModel: NSObject, ObservableObject { // Initialize all cached properties refreshDisplayedCategories() refreshDisplayedTags() + refreshCustomTaxonomies() refreshParentPageText() refreshSocialSharingState() @@ -219,6 +225,22 @@ final class PostSettingsViewModel: NSObject, ObservableObject { }) } + private func refreshCustomTaxonomies() { + let postType: String? = switch post { + case is Post: "post" + case is Page: "page" + default: nil + } + guard let postType else { return } + + let customTaxonomies = try? post.blog.taxonomies + .filter { + $0.slug != "post_tag" && $0.slug != "category" && $0.supportedPostTypes.contains(postType) + } + .sorted(using: KeyPathComparator(\.name)) + self.customTaxonomies = customTaxonomies ?? [] + } + // MARK: - Refresh private func refresh(from old: PostSettings, to new: PostSettings) { @@ -371,6 +393,10 @@ final class PostSettingsViewModel: NSObject, ObservableObject { isSuggestedTagsRefreshNeeded = true } + func didSelectTerms(_ terms: String, forTaxonomySlug taxonomySlug: String) { + settings.setTerms(terms, forTaxonomySlug: taxonomySlug) + } + // MARK: - Social Sharing private func refreshSocialSharingState() { diff --git a/WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostSettingsCustomTaxonomyRow.swift b/WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostSettingsCustomTaxonomyRow.swift new file mode 100644 index 000000000000..b4c44c92ff4d --- /dev/null +++ b/WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostSettingsCustomTaxonomyRow.swift @@ -0,0 +1,40 @@ +import Foundation +import SwiftUI +import WordPressAPI +import WordPressAPIInternal +import WordPressCore + +struct PostSettingsCustomTaxonomyRow: View { + let taxonomy: SiteTaxonomy + let terms: [String] + + var body: some View { + HStack { + PostSettingsIconView("wpdl-tag") + .padding(.trailing, 2) + + VStack(alignment: .leading, spacing: 2) { + Text(taxonomy.localizedName) + .font(.body) + .foregroundColor(.primary) + if terms.isEmpty { + Text(String.localizedStringWithFormat(Strings.addNewFormat, taxonomy.localizedName)) + .font(.subheadline) + .foregroundColor(Color(.tertiaryLabel)) + } else { + PostSettingsTruncatedArrayTextView(values: terms) + } + } + + Spacer() + } + } +} + +private enum Strings { + static let addNewFormat = NSLocalizedString( + "siteTaxonomy.addNew.format", + value: "Add %1$@", + comment: "Format string for adding a new taxonomy term. %1$@ is the taxonomy name." + ) +} diff --git a/WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostTagsView.swift b/WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostTagsView.swift index da117e2b116a..da1e8f45a409 100644 --- a/WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostTagsView.swift +++ b/WordPress/Classes/ViewRelated/Post/PostSettings/Views/PostTagsView.swift @@ -3,6 +3,8 @@ import Combine import WordPressUI import WordPressKit import WordPressData +import WordPressAPI +import WordPressCore struct PostTagsView: View { @StateObject var viewModel: TagsViewModel @@ -17,6 +19,14 @@ struct PostTagsView: View { self._viewModel = StateObject(wrappedValue: viewModel) } + /// - note: The tags are encoded as a comma-separate list. + init(blog: Blog, client: WordPressClient, taxonomy: SiteTaxonomy, selectedTerms: String? = nil, onSelectionChanged: @escaping (String) -> Void) { + let viewModel = TagsViewModel(blog: blog, client: client, taxonomy: taxonomy, selectedTerms: selectedTerms, mode: .selection(onSelectedTagsChanged: { tags in + onSelectionChanged(tags) + })) + self._viewModel = StateObject(wrappedValue: viewModel) + } + var body: some View { GeometryReader { proxy in ScrollViewReader { proxy in @@ -47,7 +57,7 @@ struct PostTagsView: View { .onAppear { viewModel.onAppear() } - .navigationTitle(Strings.title) + .navigationTitle(viewModel.labels.name) .navigationBarTitleDisplayMode(.inline) } @@ -103,7 +113,7 @@ struct PostTagsView: View { // We want to keep the focus on text field, after tapping the return key, which is not supported // by `SwiftUI.TextField`. AddTagsTextField( - placeholder: Strings.searchPlaceholder, + placeholder: Strings.searchPlaceholder(viewModel.localizedTaxonomyName), text: $viewModel.searchText, onSubmit: addTag ) @@ -115,7 +125,7 @@ struct PostTagsView: View { Button(action: addTag) { Image(systemName: "plus") } - .accessibilityLabel(Strings.addTag) + .accessibilityLabel(Strings.addTag(viewModel.localizedTaxonomyName)) } } .textFieldStyle(.plain) @@ -233,7 +243,7 @@ private struct SelectedTagsView: View { } .padding(.horizontal) } else { - Text(Strings.noTagsSelected) + Text(Strings.noTagsSelected(viewModel.localizedTaxonomyName)) .font(.body) .foregroundColor(.secondary) .padding(.horizontal) @@ -341,23 +351,30 @@ private extension View { } private enum Strings { - static let title = NSLocalizedString( - "postTags.title", - value: "Tags", - comment: "Title for the tags screen" - ) - - static let searchPlaceholder = NSLocalizedString( - "postTags.searchOrAdd.placeholder", - value: "Search or add tags", - comment: "Placeholder text for the tag search field" - ) - - static let noTagsSelected = NSLocalizedString( - "postTags.selectionEmpty", - value: "No tags are selected", - comment: "Message shown when no tags are selected" - ) - - static let addTag = NSLocalizedString("postTags.addTag", value: "Add tag", comment: "Button to add a new tag. %1$@ is the tag name.") + static func searchPlaceholder(_ taxonomyName: String) -> String { + let format = NSLocalizedString( + "postTags.searchOrAdd.placeholder", + value: "Search or add %1$@", + comment: "Placeholder text for the taxonomy search field. %1$@ is the taxonomy name (e.g., 'tags', 'categories')." + ) + return String.localizedStringWithFormat(format, taxonomyName.lowercased()) + } + + static func noTagsSelected(_ taxonomyName: String) -> String { + let format = NSLocalizedString( + "postTags.selectionEmpty", + value: "No %1$@ are selected", + comment: "Message shown when no taxonomy terms are selected. %1$@ is the taxonomy name (e.g., 'tags', 'categories')." + ) + return String.localizedStringWithFormat(format, taxonomyName.lowercased()) + } + + static func addTag(_ taxonomyName: String) -> String { + let format = NSLocalizedString( + "postTags.addTag", + value: "Add %1$@", + comment: "Button to add a new taxonomy term. %1$@ is the taxonomy name (e.g., 'tags', 'categories')." + ) + return String.localizedStringWithFormat(format, taxonomyName.lowercased()) + } } diff --git a/WordPress/Classes/ViewRelated/Tags/EditTagView.swift b/WordPress/Classes/ViewRelated/Tags/EditTagView.swift index 76dd3f0563ca..2f4bdda03ac8 100644 --- a/WordPress/Classes/ViewRelated/Tags/EditTagView.swift +++ b/WordPress/Classes/ViewRelated/Tags/EditTagView.swift @@ -191,10 +191,10 @@ private struct LocalizedLabels { static func from(taxonomy: SiteTaxonomy) -> Self { Self( - newPlaceholder: (taxonomy.details.labels[.newItemName] ?? nil) ?? "", - newItemTitle: (taxonomy.details.labels[.addNewItem] ?? nil) ?? "", - nameFieldDescription: taxonomy.details.labels[.nameFieldDescription] ?? nil, - descriptionFieldDescription: taxonomy.details.labels[.descFieldDescription] ?? nil + newPlaceholder: taxonomy.labels.newItemName ?? "", + newItemTitle: taxonomy.labels.addNewItem ?? "", + nameFieldDescription: taxonomy.labels.nameFieldDescription, + descriptionFieldDescription: taxonomy.labels.descFieldDescription ) } diff --git a/WordPress/Classes/ViewRelated/Tags/SiteCustomTaxonomiesView.swift b/WordPress/Classes/ViewRelated/Tags/SiteCustomTaxonomiesView.swift index 20fc7ac36d15..a23a92ea267d 100644 --- a/WordPress/Classes/ViewRelated/Tags/SiteCustomTaxonomiesView.swift +++ b/WordPress/Classes/ViewRelated/Tags/SiteCustomTaxonomiesView.swift @@ -8,22 +8,22 @@ import WordPressUI struct SiteCustomTaxonomiesView: View { let blog: Blog - let api: WordPressAPI + let client: WordPressClient @State private var isLoading: Bool = false @State private var taxonomies: [SiteTaxonomy]? = nil @State private var error: Error? - init(blog: Blog, api: WordPressAPI) { + init(blog: Blog, client: WordPressClient) { self.blog = blog - self.api = api + self.client = client } var body: some View { List { ForEach(taxonomies ?? [], id: \.slug) { taxonomy in NavigationLink { - SiteTagsView(viewModel: .init(blog: blog, api: api, taxonomy: taxonomy, mode: .browse)) + SiteTagsView(viewModel: .init(blog: blog, client: client, taxonomy: taxonomy, mode: .browse)) } label: { Text(taxonomy.localizedName) } @@ -56,7 +56,7 @@ struct SiteCustomTaxonomiesView: View { self.error = nil do { - let result = try await api.taxonomies.listWithEditContext(params: .init()).data + let result = try await client.api.taxonomies.listWithEditContext(params: .init()).data // The "Categories" and "Tags" are displayed in its own views. This view only displays custom taxonomies. let customTaxonomies: [TaxonomyTypeDetailsWithEditContext] = result.taxonomyTypes.compactMap { (type, taxonomy) in switch type { diff --git a/WordPress/Classes/ViewRelated/Tags/SiteTaxonomy.swift b/WordPress/Classes/ViewRelated/Tags/SiteTaxonomy.swift deleted file mode 100644 index 8cf031e4c5e9..000000000000 --- a/WordPress/Classes/ViewRelated/Tags/SiteTaxonomy.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation -import WordPressAPI -import WordPressAPIInternal - -struct SiteTaxonomy { - let details: TaxonomyTypeDetailsWithEditContext - - var slug: String { - details.slug - } - - var localizedName: String { - (details.labels[.name] ?? nil) ?? details.name - } - - var endpoint: TermEndpointType { - .custom(details.restBase) - } -} diff --git a/WordPress/Classes/ViewRelated/Tags/TagsService.swift b/WordPress/Classes/ViewRelated/Tags/TagsService.swift index 13a1e5b8d62c..162960b74b1e 100644 --- a/WordPress/Classes/ViewRelated/Tags/TagsService.swift +++ b/WordPress/Classes/ViewRelated/Tags/TagsService.swift @@ -182,12 +182,12 @@ extension AnyTermWithViewContext { } class AnyTermService: TaxonomyServiceProtocol { - private let api: WordPressAPI + private let client: WordPressClient let endpoint: TermEndpointType - init(api: WordPressAPI, endpoint: TermEndpointType) { + init(client: WordPressClient, endpoint: TermEndpointType) { self.endpoint = endpoint - self.api = api + self.client = client } func getTags(page: Int = 0, recentlyUsed: Bool = false) async throws -> [AnyTermWithViewContext] { @@ -199,7 +199,7 @@ class AnyTermService: TaxonomyServiceProtocol { orderby: recentlyUsed ? .count : .name ) - let response = try await api.terms.listWithViewContext( + let response = try await client.api.terms.listWithViewContext( termEndpointType: endpoint, params: params ) @@ -217,7 +217,7 @@ class AnyTermService: TaxonomyServiceProtocol { search: query ) - let response = try await api.terms.listWithViewContext( + let response = try await client.api.terms.listWithViewContext( termEndpointType: endpoint, params: params ) @@ -231,7 +231,7 @@ class AnyTermService: TaxonomyServiceProtocol { description: description.isEmpty ? nil : description ) - let response = try await api.terms.create( + let response = try await client.api.terms.create( termEndpointType: endpoint, params: params ) @@ -245,7 +245,7 @@ class AnyTermService: TaxonomyServiceProtocol { description: description ) - let response = try await api.terms.update( + let response = try await client.api.terms.update( termEndpointType: endpoint, termId: term.id, params: params @@ -255,7 +255,7 @@ class AnyTermService: TaxonomyServiceProtocol { } func deleteTag(_ term: AnyTermWithViewContext) async throws { - _ = try await api.terms.delete( + _ = try await client.api.terms.delete( termEndpointType: endpoint, termId: term.id ) diff --git a/WordPress/Classes/ViewRelated/Tags/TagsViewModel.swift b/WordPress/Classes/ViewRelated/Tags/TagsViewModel.swift index 93fabede6599..5fc36184848f 100644 --- a/WordPress/Classes/ViewRelated/Tags/TagsViewModel.swift +++ b/WordPress/Classes/ViewRelated/Tags/TagsViewModel.swift @@ -33,6 +33,10 @@ class TagsViewModel: ObservableObject { let labels: TaxonomyLocalizedLabels let taxonomy: SiteTaxonomy? + var localizedTaxonomyName: String { + taxonomy?.localizedName ?? Strings.tags + } + var isBrowseMode: Bool { if case .browse = mode { return true @@ -49,9 +53,9 @@ class TagsViewModel: ObservableObject { self.selectedTagsSet = Set(self.selectedTags.map { $0.lowercased() }) } - init(blog: Blog, api: WordPressAPI, taxonomy: SiteTaxonomy, selectedTerms: String? = nil, mode: TagsViewMode) { + init(blog: Blog, client: WordPressClient, taxonomy: SiteTaxonomy, selectedTerms: String? = nil, mode: TagsViewMode) { self.taxonomy = taxonomy - self.tagsService = AnyTermService(api: api, endpoint: taxonomy.endpoint) + self.tagsService = AnyTermService(client: client, endpoint: taxonomy.endpoint) self.mode = mode self.labels = TaxonomyLocalizedLabels.from(taxonomy: taxonomy) self.selectedTags = AbstractPost.makeTags(from: selectedTerms ?? "") @@ -200,11 +204,11 @@ struct TaxonomyLocalizedLabels { static func from(taxonomy: SiteTaxonomy) -> Self { Self( name: taxonomy.localizedName, - empty: (taxonomy.details.labels[.noTerms] ?? nil) - ?? String.localizedStringWithFormat(Strings.defaultNoTermsFormat, taxonomy.details.name), - emptyDescription: String.localizedStringWithFormat(Strings.defaultEmptyDescriptionFormat, taxonomy.details.name), - searchPlaceholder: (taxonomy.details.labels[.searchItems] ?? nil) - ?? String.localizedStringWithFormat(Strings.defaultSearchFormat, taxonomy.details.name) + empty: taxonomy.labels.noTerms + ?? String.localizedStringWithFormat(Strings.defaultNoTermsFormat, taxonomy.name), + emptyDescription: String.localizedStringWithFormat(Strings.defaultEmptyDescriptionFormat, taxonomy.name), + searchPlaceholder: taxonomy.labels.searchItems + ?? String.localizedStringWithFormat(Strings.defaultSearchFormat, taxonomy.name) ) } @@ -235,6 +239,12 @@ struct TaxonomyLocalizedLabels { } private enum Strings { + static let tags = NSLocalizedString( + "Tags", + value: "Tags", + comment: "Post tags." + ) + static let defaultNoTermsFormat = NSLocalizedString( "localizedLabels.defaultNoTerms.format", value: "No %1$@", From a71460b7cc645d1d14ad7399a46272cee6cb22b3 Mon Sep 17 00:00:00 2001 From: Tony Li Date: Tue, 4 Nov 2025 15:21:08 +1300 Subject: [PATCH 2/3] Implement comparing terms function in Swift --- Modules/Sources/WordPressKit/RemotePost.swift | 10 ++++++++++ .../WordPressKit/RemotePostParameters.swift | 2 +- Modules/Sources/WordPressKitObjC/RemotePost.m | 19 ------------------- .../WordPressKitObjC/include/RemotePost.h | 3 --- .../WordPressData/Objective-C/AbstractPost.m | 5 ----- .../Objective-C/include/AbstractPost.h | 2 -- .../Models/PostTermComparisonTests.swift | 16 ++++++++-------- .../Post/PostSettings/PostSettings.swift | 2 +- 8 files changed, 20 insertions(+), 39 deletions(-) create mode 100644 Modules/Sources/WordPressKit/RemotePost.swift diff --git a/Modules/Sources/WordPressKit/RemotePost.swift b/Modules/Sources/WordPressKit/RemotePost.swift new file mode 100644 index 000000000000..f0723da36cf6 --- /dev/null +++ b/Modules/Sources/WordPressKit/RemotePost.swift @@ -0,0 +1,10 @@ +import Foundation +import WordPressKitObjC + +extension RemotePost { + public static func compare(otherTerms lhs: [String: [String]], withAnother rhs: [String: [String]]) -> Bool { + guard lhs.count == rhs.count else { return false } + + return lhs.mapValues { Set($0) } == rhs.mapValues { Set($0) } + } +} diff --git a/Modules/Sources/WordPressKit/RemotePostParameters.swift b/Modules/Sources/WordPressKit/RemotePostParameters.swift index d4e1c2f02999..63c386f0bd20 100644 --- a/Modules/Sources/WordPressKit/RemotePostParameters.swift +++ b/Modules/Sources/WordPressKit/RemotePostParameters.swift @@ -140,7 +140,7 @@ extension RemotePostCreateParameters { if previous.tags != tags { changes.tags = tags } - if !RemotePost.compareOtherTerms(previous.otherTerms, withAnother: otherTerms) { + if !RemotePost.compare(otherTerms: previous.otherTerms, withAnother: otherTerms) { changes.otherTerms = otherTerms } if Set(previous.categoryIDs) != Set(categoryIDs) { diff --git a/Modules/Sources/WordPressKitObjC/RemotePost.m b/Modules/Sources/WordPressKitObjC/RemotePost.m index a510dab3fd96..ef7960fef890 100644 --- a/Modules/Sources/WordPressKitObjC/RemotePost.m +++ b/Modules/Sources/WordPressKitObjC/RemotePost.m @@ -23,25 +23,6 @@ - (id)initWithSiteID:(NSNumber *)siteID status:(NSString *)status title:(NSStrin return self; } -+ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs -{ - if (lhs.count != rhs.count) { - return NO; - } - - NSMutableDictionary *> *lhsNormalized = [NSMutableDictionary dictionary]; - for (NSString *key in lhs) { - lhsNormalized[key] = [NSSet setWithArray:lhs[key]]; - } - - NSMutableDictionary *> *rhsNormalized = [NSMutableDictionary dictionary]; - for (NSString *key in rhs) { - rhsNormalized[key] = [NSSet setWithArray:rhs[key]]; - } - - return [lhsNormalized isEqualToDictionary:rhsNormalized]; -} - - (NSString *)debugDescription { NSDictionary *properties = [self debugProperties]; return [NSString stringWithFormat:@"<%@: %p> (%@)", NSStringFromClass([self class]), self, properties]; diff --git a/Modules/Sources/WordPressKitObjC/include/RemotePost.h b/Modules/Sources/WordPressKitObjC/include/RemotePost.h index c8ee3f0e31f7..2de95cf61f67 100644 --- a/Modules/Sources/WordPressKitObjC/include/RemotePost.h +++ b/Modules/Sources/WordPressKitObjC/include/RemotePost.h @@ -56,7 +56,6 @@ extern NSString * const PostStatusDeleted; @property (nonatomic, strong) NSArray *categories; @property (nonatomic, strong) NSArray *revisions; @property (nonatomic, strong) NSArray *tags; -//@property (nonatomic, strong) NSArray *otherTerms; @property (nonatomic, strong) NSDictionary *> *otherTerms; @property (nonatomic, strong) NSString *pathForDisplayImage; @property (nonatomic, assign) NSNumber *isStickyPost; @@ -67,8 +66,6 @@ extern NSString * const PostStatusDeleted; */ @property (nonatomic, strong) NSArray *metadata; -+ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs; - // Featured images? // Geolocation? // Attachments? diff --git a/Sources/WordPressData/Objective-C/AbstractPost.m b/Sources/WordPressData/Objective-C/AbstractPost.m index 8c7acf649564..146c0870a505 100644 --- a/Sources/WordPressData/Objective-C/AbstractPost.m +++ b/Sources/WordPressData/Objective-C/AbstractPost.m @@ -365,9 +365,4 @@ - (void)setParsedOtherTerms:(NSDictionary *> *)d return [NSJSONSerialization JSONObjectWithData:self.rawOtherTerms options:0 error:nil] ?: [NSDictionary dictionary]; } -+ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs -{ - return [RemotePost compareOtherTerms:lhs withAnother:rhs]; -} - @end diff --git a/Sources/WordPressData/Objective-C/include/AbstractPost.h b/Sources/WordPressData/Objective-C/include/AbstractPost.h index 19bc3f527ca8..15ea1d078026 100644 --- a/Sources/WordPressData/Objective-C/include/AbstractPost.h +++ b/Sources/WordPressData/Objective-C/include/AbstractPost.h @@ -133,8 +133,6 @@ typedef NS_ENUM(NSUInteger, AbstractPostRemoteStatus) { - (void)setParsedOtherTerms:(NSDictionary *> *)data; - (NSDictionary *> *)parseOtherTerms; -+ (BOOL)compareOtherTerms:(NSDictionary *> *)lhs withAnother:(NSDictionary *> *)rhs; - @end @interface AbstractPost (CoreDataGeneratedAccessors) diff --git a/Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift b/Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift index 98cb8dbaa3c2..0a15cf2e863e 100644 --- a/Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift +++ b/Tests/WordPressKitTests/WordPressKitTests/Tests/Models/PostTermComparisonTests.swift @@ -9,7 +9,7 @@ struct PostTermComparisonTests { let lhs: [String: [String]] = [:] let rhs: [String: [String]] = [:] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == true) } @Test @@ -23,7 +23,7 @@ struct PostTermComparisonTests { "post_tag": ["tag1", "tag2"] ] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == true) } @Test @@ -37,7 +37,7 @@ struct PostTermComparisonTests { "post_tag": ["tag2", "tag1"] ] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == true) } @Test @@ -49,7 +49,7 @@ struct PostTermComparisonTests { "post_tag": ["tag1", "tag2"] ] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == false) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == false) } @Test @@ -61,7 +61,7 @@ struct PostTermComparisonTests { "category": ["1", "2", "4"] ] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == false) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == false) } @Test @@ -74,7 +74,7 @@ struct PostTermComparisonTests { "category": ["1", "2", "3"] ] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == false) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == false) } @Test @@ -86,7 +86,7 @@ struct PostTermComparisonTests { "category": ["1", "2", "3"] ] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == true) } @Test @@ -102,7 +102,7 @@ struct PostTermComparisonTests { "custom_tax": ["term1"] ] - #expect(RemotePost.compareOtherTerms(lhs, withAnother: rhs) == true) + #expect(RemotePost.compare(otherTerms: lhs, withAnother: rhs) == true) } } diff --git a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift index 116f2a441940..03eebba2a96a 100644 --- a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift +++ b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift @@ -112,7 +112,7 @@ struct PostSettings: Hashable { post.featuredImage = nil } - if !AbstractPost.compareOtherTerms(post.parseOtherTerms(), withAnother: otherTerms) { + if !RemotePost.compare(otherTerms:post.parseOtherTerms(), withAnother: otherTerms) { post.setParsedOtherTerms(otherTerms) } From a90d52e71a494ee45b8e27d86b5e837584ac1597 Mon Sep 17 00:00:00 2001 From: Tony Li Date: Tue, 4 Nov 2025 15:23:46 +1300 Subject: [PATCH 3/3] Fix a swiftlint issue --- .../Classes/ViewRelated/Post/PostSettings/PostSettings.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift index 03eebba2a96a..51cffb4821fd 100644 --- a/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift +++ b/WordPress/Classes/ViewRelated/Post/PostSettings/PostSettings.swift @@ -112,7 +112,7 @@ struct PostSettings: Hashable { post.featuredImage = nil } - if !RemotePost.compare(otherTerms:post.parseOtherTerms(), withAnother: otherTerms) { + if !RemotePost.compare(otherTerms: post.parseOtherTerms(), withAnother: otherTerms) { post.setParsedOtherTerms(otherTerms) }