-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathComposeView.swift
More file actions
1182 lines (1103 loc) · 50.9 KB
/
Copy pathComposeView.swift
File metadata and controls
1182 lines (1103 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import SwiftUI
import PhotosUI
import UniformTypeIdentifiers
import Observation
/// Cross-surface channel for the autosaved draft. `ComposeView` writes the
/// draft here from its autosave-on-dismiss path; `MainView` watches it and
/// raises the shared `SuccessToast` ("Draft saved", tap to reopen). Lives
/// outside the View so reply / quote composers presented from `PostCardView`
/// or `NotificationComposer` light up the same pill without each entry point
/// threading a callback up to the tab root.
@MainActor
@Observable
final class DraftSavedToastStore {
static let shared = DraftSavedToastStore()
var pendingDraft: Nip37.Draft? = nil
private init() {}
}
struct ComposeView: View {
@State var viewModel: ComposeViewModel
@Environment(\.dismiss) private var dismiss
@FocusState private var contentFocused: Bool
@State private var showScheduleSheet = false
@State private var showCancelConfirm = false
@State private var showGifPicker = false
@State private var showDraftsSheet = false
@State private var photosPickerMaxCount: Int = 8
@State private var showAccountPicker = false
/// Draft to load on first appear. Nil for `.new` and `.reply`/`.quote` composers.
/// Loaded from `.task` rather than `init` to defeat SwiftUI's State preservation
/// (which ignores `State(initialValue:)` when state already exists for this view identity).
private let initialDraft: Nip37.Draft?
/// Media handed off from the Share Extension (see `PendingShareStore` /
/// `wispApp.onOpenURL`), loaded the same way as a `PhotosPicker`
/// selection once the view appears.
private let pendingAttachmentProviders: [NSItemProvider]
private let previewAnchorID = "composer-preview-card"
init(keypair: Keypair, mode: ComposeMode = .new) {
self.initialDraft = nil
self.pendingAttachmentProviders = []
_viewModel = State(initialValue: ComposeViewModel(keypair: keypair, mode: mode))
}
init(keypair: Keypair, draft: Nip37.Draft) {
self.initialDraft = draft
self.pendingAttachmentProviders = []
_viewModel = State(initialValue: ComposeViewModel(keypair: keypair, mode: .new))
}
init(keypair: Keypair, initialText: String) {
self.initialDraft = nil
self.pendingAttachmentProviders = []
_viewModel = State(initialValue: ComposeViewModel(keypair: keypair, initialText: initialText))
}
init(keypair: Keypair, pendingAttachmentProviders: [NSItemProvider]) {
self.initialDraft = nil
self.pendingAttachmentProviders = pendingAttachmentProviders
_viewModel = State(initialValue: ComposeViewModel(keypair: keypair, mode: .new))
}
var body: some View {
NavigationStack {
ZStack {
Color.wispBackground.ignoresSafeArea()
VStack(spacing: 0) {
contextHeader
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 12) {
if viewModel.galleryMode {
galleryArea
}
// Avatar + "posting as" label rendered as a slim
// header row above the editor so the editor
// itself can take the full content width.
// Hidden entirely for single-account users —
// nothing to switch to, so the row would just
// be visual noise. Tapping the row (when
// multi-account) opens a sheet picker —
// SwiftUI `Menu` items can't render arbitrary
// images, so a custom picker is the only way
// to show real avatars next to names.
if viewModel.availableSigningAccounts.count > 1 {
VStack(alignment: .leading, spacing: 2) {
signingAccountHeader
.padding(.horizontal, 12)
textEditor
}
} else {
textEditor
}
quoteContextHeader
actionsRow
if viewModel.pollEnabled {
PollOptionsEditor(viewModel: viewModel)
.padding(.horizontal, 12)
.transition(.opacity.combined(with: .move(edge: .top)))
}
if !viewModel.attachments.isEmpty, !viewModel.galleryMode {
attachmentsRow
}
if !viewModel.hashtags.isEmpty {
HashtagChipsView(hashtags: viewModel.hashtags)
}
if viewModel.explicit {
nsfwBanner
}
if !viewModel.mentionCandidates.isEmpty || viewModel.isMentionSearchingRemote {
mentionPopup
}
if !viewModel.emojiCandidates.isEmpty {
emojiPopup
}
if shouldShowPreview {
ComposerPreviewCard(
content: viewModel.previewContent,
tags: previewTags,
userProfile: ProfileRepository.shared.get(viewModel.signingKeypair.pubkey)
)
.id(previewAnchorID)
}
if let error = viewModel.lastError {
Text(error)
.font(.caption)
.foregroundStyle(.red)
.padding(.horizontal, 12)
}
Color.clear.frame(height: 80)
}
.padding(.top, 12)
}
.onChange(of: viewModel.countdownSeconds) { oldValue, newValue in
// When the undo countdown starts, bring the post
// preview into view (top-aligned) so the user can
// spot-check what's about to publish before the
// window closes.
guard oldValue == nil, newValue != nil, shouldShowPreview else { return }
withAnimation(.easeInOut(duration: 0.3)) {
proxy.scrollTo(previewAnchorID, anchor: .top)
}
}
}
if viewModel.scheduleEnabled {
scheduleBanner
}
Divider().overlay(Color.wispSurfaceVariant.opacity(0.5))
bottomBar
}
}
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button {
cancelTapped()
} label: {
Image(systemName: "chevron.left")
.font(.body.weight(.semibold))
}
.accessibilityLabel("Close")
.disabled(isPublishInFlight)
}
ToolbarItem(placement: .topBarTrailing) {
Button {
contentFocused = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
showDraftsSheet = true
}
} label: {
Image(systemName: "tray.full")
}
.accessibilityLabel("Drafts")
.disabled(isPublishInFlight)
}
ToolbarItem(placement: .topBarTrailing) {
if viewModel.mode.allowsGalleryToggle {
// No principal title — the pill itself identifies
// the current post type ("Switch to Gallery" means
// we're in Text, vice versa), and reply / quote
// modes use `contextHeader` to show the parent
// event. Dropping the title freed enough trailing
// space to fit the full label.
Button {
viewModel.toggleGallery()
} label: {
HStack(spacing: 6) {
Image(systemName: viewModel.galleryMode ? "doc.plaintext" : "photo.on.rectangle")
.font(.system(size: 13, weight: .semibold))
.symbolEffectsRemoved()
.transaction { $0.animation = nil }
Text(viewModel.galleryMode ? "Switch to Text" : "Switch to Gallery")
.font(.subheadline.weight(.semibold))
.transaction { $0.animation = nil }
}
.foregroundStyle(Color.wispPrimary)
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(
Capsule()
.strokeBorder(Color.wispPrimary.opacity(0.5), lineWidth: 1)
)
}
.buttonStyle(.plain)
.disabled(isPublishInFlight)
.opacity(isPublishInFlight ? 0.4 : 1)
}
}
}
.navigationBarTitleDisplayMode(.inline)
}
.task {
if let draft = initialDraft, viewModel.currentDraftId != draft.dTag {
viewModel.loadDraft(draft)
}
await viewModel.start()
contentFocused = true
// Drafts / reply prefills land before the view observes
// `content`, so warm their links once on open too.
viewModel.prefetchSocialPreviews()
if !pendingAttachmentProviders.isEmpty {
await viewModel.addMediaProviders(pendingAttachmentProviders)
}
}
.interactiveDismissDisabled(
viewModel.isPublishing
|| viewModel.countdownSeconds != nil
// Block swipe-dismiss while an upload is in flight so the draft
// autosave on disappear catches the finished URLs.
|| viewModel.uploadProgress != nil
)
.sheet(isPresented: $showScheduleSheet) {
ScheduleSheet(
initialDate: viewModel.scheduleAt,
onConfirm: { date in viewModel.setSchedule(date) },
onCancel: { /* keep existing schedule */ }
)
}
.sheet(isPresented: $showDraftsSheet) {
DraftsScheduledView(keypair: viewModel.keypair)
}
.sheet(isPresented: $showAccountPicker) {
accountPickerSheet
}
// GIF picker is presented as a true UIKit modal via a hidden
// representable rather than a SwiftUI .sheet / .fullScreenCover.
// Embedding `GiphyViewController` as a child view (which is what
// SwiftUI's modal hosts do) breaks its internal layout — the
// bottom search bar collides with the trending-suggestions
// carousel because Giphy assumes it owns its modal context.
.background(
GifPickerPresenter(isPresented: $showGifPicker) { gifUrl in
appendGifUrl(gifUrl)
}
)
// `.alert` rather than `.confirmationDialog` so the cancel-role
// "Keep Editing" button renders as an explicit choice. iOS 26
// hides the cancel button on confirmation dialogs presented over
// sheets, leaving only Save Draft / Discard visible.
.alert(
"Discard this post?",
isPresented: $showCancelConfirm
) {
Button("Save Draft") {
Task {
await viewModel.saveDraft()
viewModel.cancelPublish()
dismiss()
}
}
Button("Discard", role: .destructive) {
viewModel.cancelPublish()
viewModel.explicitlyDiscarded = true
viewModel.clearLocalAutosave()
dismiss()
}
Button("Keep Editing", role: .cancel) {}
} message: {
Text("You have unsaved content.")
}
.onChange(of: viewModel.draftSaved) { _, saved in
if saved { dismiss() }
}
.onChange(of: viewModel.content) { _, _ in
viewModel.scheduleLocalAutosave()
viewModel.prefetchSocialPreviews()
}
.onChange(of: viewModel.attachments.map { $0.url ?? "" }) { _, _ in
viewModel.scheduleLocalAutosave()
}
.onChange(of: viewModel.explicit) { _, _ in
viewModel.scheduleLocalAutosave()
}
.onChange(of: viewModel.powEnabled) { _, _ in
viewModel.scheduleLocalAutosave()
}
.onChange(of: viewModel.scheduleAt) { _, _ in
viewModel.scheduleLocalAutosave()
}
.onDisappear {
// The local autosave is debounced off the keystroke, so the last
// few characters may not be persisted yet. Flush them now — unless
// an explicit discard / successful publish already cleared the
// bucket (those paths call `clearLocalAutosave()`), in which case
// just drop the pending debounce so it can't resurrect the bucket.
if viewModel.explicitlyDiscarded || viewModel.publishedEventId != nil {
viewModel.clearLocalAutosave()
} else {
viewModel.flushLocalAutosave()
}
// Auto-save on dismiss when the user navigated away without publishing
// or explicitly discarding (e.g. swipe-to-dismiss the sheet). Fires
// for reply / quote / new alike — `saveDraft` builds the appropriate
// reply context tags via `buildBaseTags`, so re-opening the draft
// restores the parent thread.
guard viewModel.hasUnsavedContent,
viewModel.publishedEventId == nil,
!viewModel.explicitlyDiscarded,
!viewModel.draftSaved else { return }
let vm = viewModel
Task {
if let draft = await vm.saveDraft() {
await MainActor.run {
withAnimation(.spring(response: 0.55, dampingFraction: 0.82)) {
DraftSavedToastStore.shared.pendingDraft = draft
}
}
}
}
}
}
// MARK: - Sub-areas
private var isPublishInFlight: Bool {
viewModel.isPublishing
|| viewModel.countdownSeconds != nil
|| viewModel.uploadProgress != nil
}
/// Discard-confirmation pivot used by both the leading chevron and any
/// programmatic dismiss. Confirms before dropping unsaved content.
/// Open the system photo picker via the imperative service rather
/// than a SwiftUI `.background(PhotosPickerPresenter)` host. The
/// service walks to the topmost presented VC and presents the
/// picker directly, bypassing the unreliable representable/host
/// plumbing that was tearing down the picker after ~1s on
/// iPhone 13 Pro Max.
private func presentPhotoPicker(max: Int) {
contentFocused = false
PhotoPickerService.present(maxCount: max) { providers in
// Synchronous progress flip so the dismiss-disabled guard
// catches before the addMedia task hops onto a runloop.
viewModel.uploadProgress = providers.count > 1
? "Loading \(providers.count) items…"
: "Loading…"
Task { await viewModel.addMediaProviders(providers) }
}
}
private func cancelTapped() {
if viewModel.hasUnsavedContent {
showCancelConfirm = true
} else {
viewModel.cancelPublish()
viewModel.explicitlyDiscarded = true
dismiss()
}
}
@ViewBuilder
private var contextHeader: some View {
switch viewModel.mode {
case .reply(let parent, _):
replyContextRow(parent: parent)
.padding(.horizontal, 12)
.padding(.top, 8)
case .quote, .new:
EmptyView()
}
}
@ViewBuilder
private var quoteContextHeader: some View {
if case .quote(let q) = viewModel.mode {
quoteContextRow(quoted: q)
.padding(.horizontal, 12)
}
}
private func replyContextRow(parent: NostrEvent) -> some View {
let profile = ProfileRepository.shared.get(parent.pubkey)
let recipientName = profile?.displayString ?? Nip19.shortNpub(hex: parent.pubkey)
return HStack(alignment: .top, spacing: 8) {
CachedAvatarView(url: profile?.picture, size: 28)
VStack(alignment: .leading, spacing: 2) {
HStack(spacing: 4) {
if viewModel.isPrivate {
Image(systemName: "lock.fill")
.font(.caption2)
.foregroundStyle(Color.wispPrimary)
}
Text(viewModel.isPrivate
? "Replying privately to \(recipientName)"
: "Replying to \(recipientName)")
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
}
Text(previewContent(parent.content, max: 140))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(2)
}
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.wispSurfaceVariant.opacity(0.4),
in: RoundedRectangle(cornerRadius: 10))
}
private func quoteContextRow(quoted: NostrEvent) -> some View {
let profile = ProfileRepository.shared.get(quoted.pubkey)
return HStack(alignment: .top, spacing: 8) {
CachedAvatarView(url: profile?.picture, size: 28)
VStack(alignment: .leading, spacing: 2) {
Text("Quoting \(profile?.displayString ?? Nip19.shortNpub(hex: quoted.pubkey))")
.font(.caption.weight(.semibold))
.foregroundStyle(.secondary)
Text(previewContent(quoted.content, max: 200))
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(3)
}
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.wispSurfaceVariant.opacity(0.4),
in: RoundedRectangle(cornerRadius: 10))
}
/// Render-friendly preview of an event's `.content`. When the content is
/// itself a serialized Nostr event (some clients embed events inside the
/// `content` string of a kind-1), surface the inner `content` field
/// instead of dumping the raw JSON envelope into the reply / quote
/// context card. Mentions are resolved before truncation so a long
/// `nostr:nprofile1…` token that straddles the cutoff still collapses
/// to its `@displayName` instead of leaking a half bech32 string.
private func previewContent(_ raw: String, max: Int) -> String {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
let source: String
if trimmed.hasPrefix("{"),
let data = trimmed.data(using: .utf8),
let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
obj["id"] is String, obj["pubkey"] is String {
let inner = (obj["content"] as? String)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if inner.isEmpty { return "[shared event]" }
source = inner
} else {
source = raw
}
let collapsed = collapseMediaUrls(source)
let resolved = resolveNostrMentions(collapsed)
return String(resolved.prefix(max))
}
private static let previewImageExts: Set<String> = ["jpg", "jpeg", "png", "gif", "webp", "heic", "heif", "avif", "svg"]
private static let previewVideoExts: Set<String> = ["mp4", "mov", "webm", "m3u8"]
private func collapseMediaUrls(_ content: String) -> String {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return content }
let ns = content as NSString
let matches = detector.matches(in: content, range: NSRange(location: 0, length: ns.length))
guard !matches.isEmpty else { return content }
var out = ""
var lastEnd = 0
for match in matches {
out += ns.substring(with: NSRange(location: lastEnd, length: match.range.location - lastEnd))
let urlStr = ns.substring(with: match.range)
let ext = (urlStr as NSString).pathExtension.lowercased()
if Self.previewImageExts.contains(ext) { out += "[image]" }
else if Self.previewVideoExts.contains(ext) { out += "[video]" }
else { out += urlStr }
lastEnd = match.range.upperBound
}
out += ns.substring(from: lastEnd)
return out
}
private func resolveNostrMentions(_ content: String) -> String {
let pattern = #"nostr:(?:npub1|nprofile1)[a-z0-9]+|(?<!\w)(?:npub1|nprofile1)[a-z0-9]{50,}(?!\w)"#
guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else { return content }
let ns = content as NSString
let fullRange = NSRange(location: 0, length: ns.length)
let matches = regex.matches(in: content, range: fullRange)
guard !matches.isEmpty else { return content }
var urlRanges: [NSRange] = []
if let linkDetector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) {
urlRanges = linkDetector.matches(in: content, range: fullRange).map(\.range)
}
var out = ""
var lastEnd = 0
for match in matches {
out += ns.substring(with: NSRange(location: lastEnd, length: match.range.location - lastEnd))
let token = ns.substring(with: match.range)
let insideURL = urlRanges.contains { NSIntersectionRange($0, match.range).length > 0 }
if insideURL {
out += token
} else {
let uri = token.lowercased().hasPrefix("nostr:") ? token : "nostr:\(token)"
if case .profileRef(let pk, _)? = Nip19.decodeNostrUri(uri) {
let name = ProfileRepository.shared.get(pk)?.displayString ?? Nip19.shortNpub(hex: pk)
out += "@\(name)"
} else {
out += token
}
}
lastEnd = match.range.upperBound
}
out += ns.substring(from: lastEnd)
return out
}
// MARK: - Signing account header
/// Slim "posting as" header row rendered above the text editor. The
/// avatar + display-name combo identifies the active signing
/// keypair; tapping (when multiple accounts are signable) opens
/// `accountPickerSheet`. Single-account users see a non-tappable
/// row, still useful as a visual reinforcement of "this is your
/// post". The `.id(pubkey)` on the avatar guards against a
/// SwiftUI quirk where a reused `CachedAvatarView` keeps the
/// previous account's image when the URL changes — forces a
/// fresh view instance on switch as a belt-and-braces on top of
/// the in-view URL-change reset.
@ViewBuilder
private var signingAccountHeader: some View {
let pubkey = viewModel.signingKeypair.pubkey
let profile = ProfileRepository.shared.get(pubkey)
let multiAccount = viewModel.availableSigningAccounts.count > 1
let name = profile?.displayString ?? Nip19.shortNpub(hex: pubkey)
Button {
guard multiAccount else { return }
showAccountPicker = true
} label: {
HStack(spacing: 8) {
CachedAvatarView(url: profile?.picture, size: 28)
.id(pubkey)
Text(name)
.font(.subheadline.weight(.semibold))
.foregroundStyle(Color.wispOnSurface)
.lineLimit(1)
if multiAccount {
Image(systemName: "chevron.down")
.font(.system(size: 11, weight: .semibold))
.foregroundStyle(.secondary)
}
Spacer(minLength: 0)
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.disabled(!multiAccount)
}
/// Bottom-sheet picker for the signing account. Replaces a SwiftUI
/// `Menu` because Menu items can only show SF Symbols — not real
/// avatar images — and the picker is significantly more legible
/// with profile pictures next to names.
private var accountPickerSheet: some View {
NavigationStack {
ZStack {
Color.wispBackground.ignoresSafeArea()
List {
ForEach(viewModel.availableSigningAccounts, id: \.pubkey) { keypair in
let kProfile = ProfileRepository.shared.get(keypair.pubkey)
let active = keypair.pubkey == viewModel.signingKeypair.pubkey
let kName = kProfile?.displayString ?? Nip19.shortNpub(hex: keypair.pubkey)
Button {
viewModel.switchSigningAccount(keypair)
showAccountPicker = false
} label: {
HStack(spacing: 12) {
CachedAvatarView(url: kProfile?.picture, size: 40)
.id(keypair.pubkey)
VStack(alignment: .leading, spacing: 2) {
Text(kName)
.font(.subheadline.weight(.semibold))
.foregroundStyle(Color.wispOnSurface)
.lineLimit(1)
Text(Nip19.shortNpub(hex: keypair.pubkey))
.font(.caption2)
.foregroundStyle(.secondary)
}
Spacer()
if active {
Image(systemName: "checkmark")
.font(.system(size: 15, weight: .semibold))
.foregroundStyle(Color.wispPrimary)
}
}
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.listRowBackground(Color.wispSurfaceVariant.opacity(0.4))
}
}
.scrollContentBackground(.hidden)
}
.navigationTitle("Post as")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("Done") { showAccountPicker = false }
}
}
}
.presentationDetents([.medium])
}
private var textEditor: some View {
VStack(alignment: .leading, spacing: 4) {
ZStack(alignment: .topLeading) {
if viewModel.content.isEmpty {
Text(placeholderText)
.foregroundStyle(.tertiary)
.padding(.horizontal, 16)
.padding(.top, 12)
}
MentionComposerTextView(viewModel: viewModel)
.frame(minHeight: viewModel.galleryMode ? 80 : 160, alignment: .topLeading)
.padding(.horizontal, 12)
}
if let progress = viewModel.uploadProgress {
HStack(spacing: 6) {
ProgressView().controlSize(.small)
Text(progress).font(.caption).foregroundStyle(.secondary)
}
.padding(.horizontal, 16)
}
}
}
private var galleryArea: some View {
VStack(spacing: 8) {
if viewModel.attachments.isEmpty {
Button {
presentPhotoPicker(max: 8)
} label: {
VStack(spacing: 6) {
Image(systemName: "photo.on.rectangle.angled")
.font(.system(size: 28))
.foregroundStyle(.secondary)
Text("Add photos or video")
.font(.subheadline.weight(.medium))
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.frame(height: 180)
.background(Color.wispSurfaceVariant.opacity(0.4),
in: RoundedRectangle(cornerRadius: 12))
}
.buttonStyle(.plain)
.tint(Color(.secondaryLabel))
.padding(.horizontal, 12)
} else {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(viewModel.attachments) { attachment in
attachmentThumb(attachment, size: 140)
}
Button {
presentPhotoPicker(max: 8)
} label: {
VStack(spacing: 4) {
Image(systemName: "plus")
.font(.system(size: 22, weight: .semibold))
Text("Add").font(.caption2)
}
.frame(width: 140, height: 140)
.background(Color.wispSurfaceVariant.opacity(0.4),
in: RoundedRectangle(cornerRadius: 12))
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.tint(Color(.secondaryLabel))
}
.padding(.horizontal, 12)
}
}
}
}
private var attachmentsRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 8) {
ForEach(viewModel.attachments) { attachment in
attachmentThumb(attachment, size: 80)
}
}
.padding(.horizontal, 12)
}
}
private func attachmentThumb(_ attachment: ComposeAttachment, size: CGFloat) -> some View {
ZStack(alignment: .topTrailing) {
ZStack {
if let bytes = attachment.localBytes,
AnimatedImageHint.isLikelyAnimated(url: "", mime: attachment.mime),
let payload = AnimatedImageDecoder.decode(data: bytes, maxPixelSize: size * UIScreen.main.scale) {
// Animated GIF / animated WebP / APNG — render with the
// per-frame decoder so the thumbnail plays before publish.
// The simple `UIImage(data:)` path freezes on frame 0.
AnimatedImageRenderer(payload: payload, contentMode: .scaleAspectFill)
} else if let bytes = attachment.localBytes, let img = UIImage(data: bytes) {
Image(uiImage: img)
.resizable()
.scaledToFill()
} else if let url = attachment.url,
AnimatedImageHint.isLikelyAnimated(url: url, mime: attachment.mime) {
// Post-upload: bytes have been cleared but the attachment
// is animated. Fetch + animate from the Blossom URL.
AnimatedImageView(
url: URL(string: url),
aspect: nil,
contentMode: .fill,
placeholder: { Color.wispSurfaceVariant },
failure: { Color.wispSurfaceVariant }
)
} else if let url = attachment.url {
AsyncImage(url: URL(string: url)) { phase in
switch phase {
case .success(let img): img.resizable().scaledToFill()
default: Color.wispSurfaceVariant
}
}
} else {
Color.wispSurfaceVariant
}
if attachment.isVideo {
Image(systemName: "play.circle.fill")
.font(.system(size: 28))
.foregroundStyle(.white.opacity(0.9))
.shadow(radius: 4)
}
if attachment.url == nil {
Color.black.opacity(0.4)
ProgressView().tint(.white)
}
}
.frame(width: size, height: size)
.clipShape(RoundedRectangle(cornerRadius: 10))
Button {
viewModel.removeMedia(id: attachment.id)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 18))
.foregroundStyle(.white)
.background(Circle().fill(.black.opacity(0.5)))
}
.padding(4)
}
}
private var scheduleBanner: some View {
let date = viewModel.scheduleAt ?? Date()
let formatter = DateFormatter()
formatter.dateFormat = "MMM d, yyyy 'at' h:mm a"
let formatted = formatter.string(from: date)
return HStack(spacing: 8) {
Image(systemName: "clock.fill")
.foregroundStyle(Color.wispPrimary)
Text("Scheduled for \(formatted)")
.font(.caption.weight(.medium))
Spacer()
Button {
viewModel.setSchedule(nil)
} label: {
Image(systemName: "xmark.circle.fill")
.font(.system(size: 16))
.foregroundStyle(.secondary)
}
}
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.wispPrimary.opacity(0.1))
}
private var nsfwBanner: some View {
HStack(spacing: 8) {
Image(systemName: "exclamationmark.triangle.fill")
Text("Content marked as NSFW")
.font(.caption.weight(.medium))
Spacer()
}
.foregroundStyle(.orange)
.padding(10)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Color.orange.opacity(0.1), in: RoundedRectangle(cornerRadius: 10))
.padding(.horizontal, 12)
}
private var mentionPopup: some View {
// Display-name collision detection. Search relays surface
// impersonators using the same display name as a real account
// (different pubkeys, identical bio). We can't safely dedupe
// by content, so we surface a short npub beneath the colliding
// names so the user can tell them apart.
let nameCounts: [String: Int] = viewModel.mentionCandidates.reduce(into: [:]) { acc, c in
acc[c.name.lowercased(), default: 0] += 1
}
return VStack(alignment: .leading, spacing: 0) {
ForEach(viewModel.mentionCandidates) { candidate in
Button {
viewModel.selectMention(candidate)
} label: {
let isCollision = (nameCounts[candidate.name.lowercased()] ?? 0) > 1
MentionCandidateRow(
candidate: candidate,
disambiguationNpub: isCollision ? Nip19.shortNpub(hex: candidate.pubkey) : nil
)
}
.buttonStyle(.plain)
Divider().overlay(Color.wispSurfaceVariant.opacity(0.4))
}
if viewModel.isMentionSearchingRemote {
// Pinned at the bottom so any local matches stay clickable
// at the top while we wait on the relay. The spinner is the
// signal that "more results may yet arrive" — without it
// the popup looks like it's already final.
HStack(spacing: 8) {
ProgressView().scaleEffect(0.7)
Text("Searching…")
.font(.subheadline)
.foregroundStyle(.secondary)
}
.padding(.horizontal, 12)
.padding(.vertical, 10)
}
}
.background(Color.wispSurfaceVariant.opacity(0.3),
in: RoundedRectangle(cornerRadius: 10))
.padding(.horizontal, 12)
}
private var emojiPopup: some View {
EmojiSuggestionBar(candidates: viewModel.emojiCandidates) { emoji in
viewModel.selectEmoji(emoji)
}
}
// MARK: - Actions row (under text editor)
private var actionsRow: some View {
ScrollView(.horizontal, showsIndicators: false) {
HStack(spacing: 22) {
if !viewModel.galleryMode, !viewModel.pollEnabled {
Button {
presentPhotoPicker(max: 4)
} label: {
Image(systemName: "photo.on.rectangle")
.font(.system(size: 22))
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.tint(Color(.secondaryLabel))
}
if !viewModel.pollEnabled {
Button {
pasteImageFromClipboard()
} label: {
Image(systemName: "doc.on.clipboard")
.font(.system(size: 22))
.foregroundStyle(.secondary)
}
.buttonStyle(.plain)
.accessibilityLabel("Paste image from clipboard")
}
if !viewModel.pollEnabled {
Button {
// Resign the compose text field before presenting so the
// keyboard animation finishes ahead of the modal. Without
// the hop, the keyboard collapse mid-present can cancel
// the in-flight UIKit modal and SwiftUI flips
// `showGifPicker` back to false — same shape as the
// drafts-sheet keyboard race.
contentFocused = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
showGifPicker = true
}
} label: {
Text("GIF")
.font(.system(size: 11, weight: .bold))
.foregroundStyle(.secondary)
.frame(width: 28, height: 28)
.overlay(
RoundedRectangle(cornerRadius: 5)
.stroke(Color.secondary, lineWidth: 1.5)
)
}
.buttonStyle(.plain)
.accessibilityLabel("Add GIF")
}
Button {
viewModel.toggleNsfw()
} label: {
Image(systemName: "exclamationmark.triangle\(viewModel.explicit ? ".fill" : "")")
.font(.system(size: 22))
.foregroundStyle(viewModel.explicit ? Color.orange : .secondary)
}
Button {
viewModel.togglePow()
} label: {
Image(systemName: "shield\(viewModel.powEnabled ? ".fill" : "")")
.font(.system(size: 22))
.foregroundStyle(viewModel.powEnabled ? Color.wispPrimary : .secondary)
}
if viewModel.mode.allowsPollToggle {
Button {
withAnimation(.easeInOut(duration: 0.2)) {
viewModel.togglePoll()
}
} label: {
Image(systemName: "chart.bar")
.font(.system(size: 22))
.foregroundStyle(viewModel.pollEnabled ? Color.wispPrimary : .secondary)
}
.accessibilityLabel(viewModel.pollEnabled ? "Disable poll" : "Create poll")
}
// Private-reply toggle — only meaningful for `.reply` mode. Locked
// (no-op) when the parent is itself a private rumor; the icon stays
// filled to signal the chain stays encrypted.
if case .reply = viewModel.mode {
Button {
viewModel.togglePrivate()
} label: {
Image(systemName: viewModel.isPrivate ? "lock.fill" : "lock")
.font(.system(size: 22))
.foregroundStyle(viewModel.isPrivate ? Color.wispPrimary : .secondary)
}
.disabled(viewModel.isPrivateLocked)
.accessibilityLabel(viewModel.isPrivate ? "Disable private reply" : "Send privately")
}
Button {
showScheduleSheet = true
} label: {
Image(systemName: "clock\(viewModel.scheduleEnabled ? ".fill" : "")")
.font(.system(size: 22))
.foregroundStyle(viewModel.scheduleEnabled ? Color.wispPrimary : .secondary)
}
.disabled(viewModel.isPrivate)
}
.padding(.horizontal, 16)
.padding(.top, 4)
}
}
// MARK: - Bottom publish bar
private var bottomBar: some View {
HStack(spacing: 12) {
if viewModel.countdownSeconds != nil {
Button(role: .destructive) {
viewModel.cancelPublish()
} label: {
Image(systemName: "xmark")
.font(.system(size: 15, weight: .bold))
.foregroundStyle(.white)