@@ -579,4 +579,58 @@ class TextStorageTests: XCTestCase {
579579 let result = storage. getHTML ( )
580580 XCTAssertEqual ( expectedResult, result)
581581 }
582+
583+ /// Verifies that missing Heading attributes are retained on string replacements when appropriate
584+ ///
585+ func testMissingHeadingAttributeIsRetained( ) {
586+ let formatter = HeaderFormatter ( headerLevel: . h2)
587+ storage. replaceCharacters ( in: storage. rangeOfEntireString, with: " Hello i'm a header " )
588+ formatter. applyAttributes ( to: storage, at: storage. rangeOfEntireString)
589+
590+ let originalAttributes = storage. attributes ( at: 0 , effectiveRange: nil )
591+ XCTAssertEqual ( storage. string, " Hello i'm a header " )
592+ XCTAssertEqual ( originalAttributes. count, 3 )
593+ XCTAssertNotNil ( originalAttributes [ . headingRepresentation] )
594+
595+ let autoCorrectedAttributes = originalAttributes. filter { $0. key != . headingRepresentation }
596+
597+ let autoCorrectedString = NSAttributedString (
598+ string: " I'm " ,
599+ attributes: autoCorrectedAttributes
600+ )
601+
602+ let range = NSRange ( location: 6 , length: 3 )
603+ storage. replaceCharacters ( in: range, with: autoCorrectedString)
604+
605+ let finalAttributes = storage. attributes ( at: range. location, effectiveRange: nil )
606+ XCTAssertEqual ( storage. string, " Hello I'm a header " )
607+ XCTAssertEqual ( originalAttributes. keys, finalAttributes. keys)
608+ }
609+
610+ /// Verifies that converting a Heading to a Paragraph doesn't retain the heading attribute
611+ ///
612+ func testHeadingToParagraphDoesNotRetainHeadingAttribute( ) {
613+ let headerFormatter = HeaderFormatter ( headerLevel: . h2)
614+ storage. replaceCharacters ( in: storage. rangeOfEntireString, with: " Hello I'm a header " )
615+ headerFormatter. applyAttributes ( to: storage, at: storage. rangeOfEntireString)
616+
617+ let originalAttributes = storage. attributes ( at: 0 , effectiveRange: nil )
618+ XCTAssertEqual ( storage. string, " Hello I'm a header " )
619+ XCTAssertNotNil ( originalAttributes [ . headingRepresentation] )
620+
621+ let paragraphAttributes : [ NSAttributedString . Key : Any ] = [
622+ . font: UIFont . systemFont ( ofSize: 14 ) ,
623+ . paragraphStyle: ParagraphStyle . default
624+ ]
625+
626+ let paragraphString = NSAttributedString (
627+ string: " Hello I'm a paragraph " ,
628+ attributes: paragraphAttributes
629+ )
630+ storage. replaceCharacters ( in: storage. rangeOfEntireString, with: paragraphString)
631+
632+ let finalAttributes = storage. attributes ( at: 0 , effectiveRange: nil )
633+ XCTAssertEqual ( storage. string, " Hello I'm a paragraph " )
634+ XCTAssertNil ( finalAttributes [ . headingRepresentation] )
635+ }
582636}
0 commit comments