Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

FeaturePastedText.swift

71 lines2.8 KB

1import Foundation
2​
3enum FeaturePastedText {
4 // Keep these limits in sync with client-runtime/textPaste.ts and contracts/orchestration.ts.
5 static let attachmentThresholdBytes = 32 * 1024
6 static let maximumInputCharacters = 120_000
7​
8 enum Disposition: Equatable {
9 case inline
10 case attachment
11 case rejected
12 }
13​
14 /// Call off the main actor. Drafts and outbox entries retain the owned file,
15 /// so a large clipboard value is never copied into their JSON documents.
16 static func attachment(
17 text: String, fileName: String, maximumBytes: Int,
18 fileStore: ManagedAttachmentFileStore = .init()
19 ) throws -> FeatureDraftAttachment {
20 let id = UUID()
21 let file = try fileStore.writeOwnedFile(
22 data: Data(text.utf8), attachmentID: id, originalFileName: fileName, maximumBytes: maximumBytes
23 )
24 return FeatureDraftAttachment(id: id, ownedFile: file, filename: fileName, mimeType: "text/plain", source: .pastedText)
25 }
26​
27 static func maximumAttachmentBytes(
28 advertisedMaximum: Int?,
29 attachmentCount: Int,
30 pendingCount: Int
31 ) -> Int? {
32 guard let advertisedMaximum, advertisedMaximum > 0,
33 attachmentCount + pendingCount < FeatureImageAttachmentLimits.maximumCount else {
34 return nil
35 }
36 return min(advertisedMaximum, ManagedAttachmentFileStore.maximumBytes)
37 }
38​
39 /// Input limits use UTF-16 offsets, as on web. Attachment limits use UTF-8 bytes.
40 static func disposition(
41 text: String,
42 currentTextLength: Int,
43 selection: NSRange,
44 maximumAttachmentBytes: Int?,
45 bypassAutoAttachment: Bool = false
46 ) -> Disposition {
47 guard !bypassAutoAttachment, !text.isEmpty else { return .inline }
48 let start = min(max(0, selection.location), currentTextLength)
49 let selectedLength = min(max(0, selection.length), currentTextLength - start)
50 let wouldExceedInputLimit = currentTextLength - selectedLength + text.utf16.count
51 > maximumInputCharacters
52 let byteCount = text.utf8.count
53 guard wouldExceedInputLimit || byteCount >= attachmentThresholdBytes else {
54 return .inline
55 }
56 if let maximumAttachmentBytes, byteCount <= maximumAttachmentBytes {
57 return .attachment
58 }
59 return wouldExceedInputLimit ? .rejected : .inline
60 }
61​
62 static func nextFileName(existingNames: [String]) -> String {
63 let names = Set(existingNames.map { $0.lowercased() })
64 guard names.contains("pasted-text.txt") else { return "pasted-text.txt" }
65 var sequence = 2
66 while names.contains("pasted-text-\(sequence).txt") {
67 sequence += 1
68 }
69 return "pasted-text-\(sequence).txt"
70 }