| 1 | import Foundation |
| 2 | import XCTest |
| 3 | @testable import DocsKit |
| 4 | |
| 5 | final class DocumentWordCountsTests: XCTestCase { |
| 6 | @MainActor func testSelectedWordsIgnoreInlineHardBreakAndImage() throws { |
| 7 | let data = Data(#"{"children":[{"id":"p","type":"paragraph","children":[{"id":"a","type":"text","runs":[{"insert":"before"}]},{"id":"br","type":"hard_break"},{"id":"b","type":"text","runs":[{"insert":"middle"}]},{"id":"im","type":"image","attrs":{"alt":"excluded"}},{"id":"c","type":"text","runs":[{"insert":"after"}]}]}],"canUndo":false,"canRedo":false}"#.utf8) |
| 8 | let projection = try JSONDecoder().decode(CRDTProjection.self, from: data) |
| 9 | let content = NativeTextProjection.render(projection) |
| 10 | let counts = DocumentWordCounts(projection: projection, content: content, selection: NSRange(location: 0, length: content.length)) |
| 11 | XCTAssertEqual(counts.words, 1) |
| 12 | XCTAssertEqual(counts.selectedWords, counts.words) |
| 13 | } |
| 14 | func testUnicodeWordsAreNotWhitespaceChunks() { |
| 15 | XCTAssertEqual(DocumentWordCounts.countWords("Hello,world!"), 2) |
| 16 | XCTAssertGreaterThan(DocumentWordCounts.countWords("私は日本語を話します"), 1) |
| 17 | XCTAssertEqual(DocumentWordCounts.countWords(" — … 😀"), 0) |
| 18 | } |
| 19 | |
| 20 | @MainActor func testDocumentSemanticsAndSelectedText() throws { |
| 21 | let data = Data(#"{"children":[{"id":"p1","type":"paragraph","children":[{"id":"t1","type":"text","runs":[{"insert":"Hi 😀"}]},{"id":"im","type":"image","attrs":{"alt":"never count image alt"}}]},{"id":"list","type":"bullet_list","children":[{"id":"li","type":"list_item","children":[{"id":"p2","type":"paragraph","children":[{"id":"t2","type":"text","runs":[{"insert":"two words"}]}]}]}]},{"id":"rule","type":"horizontal_rule"}],"canUndo":false,"canRedo":false}"#.utf8) |
| 22 | let projection = try JSONDecoder().decode(CRDTProjection.self, from: data) |
| 23 | let content = NativeTextProjection.render(projection) |
| 24 | let selected = (content.string as NSString).range(of: "two words") |
| 25 | let counts = DocumentWordCounts(projection: projection, content: content, selection: selected) |
| 26 | XCTAssertEqual(counts.words, 3) |
| 27 | // Each visited block separates text, as in the web model walker. |
| 28 | XCTAssertEqual(counts.characters, "Hi 😀 two words ".utf16.count) |
| 29 | XCTAssertEqual(counts.charactersNoSpaces, "Hi😀twowords".utf16.count) |
| 30 | XCTAssertEqual(counts.paragraphs, 2) |
| 31 | XCTAssertEqual(counts.selectedWords, 2) |
| 32 | XCTAssertNil(DocumentWordCounts(projection: projection, content: content, selection: NSRange(location: 0, length: 0)).selectedWords) |
| 33 | } |
| 34 | } |
| 35 | |