Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / StudioAppearance.swift

1import SwiftUI
2#if os(macOS)
3import InkspringSchedule
4#endif
5#if os(macOS)
6import AppKit
7#else
8import UIKit
9#endif
10
11struct XArticleChoice: Identifiable {
12 let id: String
13 let title: String
14}
15
16struct StudioXPostEditor: View {
17 @Environment(\.studioPalette) private var palette
18 @Binding var text: String
19 @Binding var format: String
20 var articles: [XArticleChoice] = []
21 var openingLimit = 280
22 @State private var editingPart: Int?
23
24 private var posts: [String] {
25 format == "post" ? [text] : XThreadText.parts(in: text)
26 }
27
28 var body: some View {
29 #if os(macOS)
30 VStack(alignment: .leading, spacing: 12) { controls }
31 #else
32 if let index = editingPart, posts.indices.contains(index) {
33 MobileXReplyEditor(text: part(index), identifier: "x.postText.\(index)", count: XThreadText.weight(posts[index]), back: { editingPart = nil })
34 .id(index)
35 } else { ScrollView { VStack(alignment: .leading, spacing: 16) { controls }.padding(12) } }
36 #endif
37 }
38
39 @ViewBuilder private var controls: some View {
40 Picker("X post type", selection: Binding(get: { format }, set: changeFormat)) {
41 ForEach(XPostStyle.allCases) { style in
42 Text(style.title).tag(style.rawValue)
43 .disabled(posts.contains { XReplyArticle($0).reference != nil } &&
44 (style.rawValue == "post" || (style.rawValue == "followup" && posts.count > 2)))
45 }
46 }
47 .pickerStyle(.menu)
48 .accessibilityIdentifier("x.postType")
49 ForEach(posts.indices, id: \.self) { index in
50 let title = index == 0 ? "Opening post" : "Follow-up reply \(index)"
51 #if os(iOS)
52 Button { editingPart = index } label: {
53 VStack(alignment: .leading, spacing: 5) {
54 Text(title).font(.subheadline.weight(.semibold))
55 Text(part(index).wrappedValue.isEmpty ? "Write this post…" : part(index).wrappedValue)
56 .font(.body).lineLimit(3).foregroundStyle(palette.text)
57 counter(posts[index], limit: index == 0 ? openingLimit : 280)
58 }.frame(maxWidth: .infinity, alignment: .leading).padding(.vertical, 5)
59 }.buttonStyle(.plain)
60 .accessibilityIdentifier("x.editPost.\(index)")
61 #else
62 MacReplyWritingField(title: title, text: part(index),
63 identifier: "x.postText.\(index)", count: counter(posts[index], limit: index == 0 ? openingLimit : 280))
64 #endif
65 if index > 0 {
66 let link = XReplyArticle(posts[index])
67 if !articles.isEmpty || link.reference != nil {
68 Menu {
69 ForEach(articles) { article in
70 Button(article.title + " · " + article.id) { setArticle(article.id, at: index) }
71 }
72 if link.reference != nil { Button("Unlink article") { setArticle(nil, at: index) } }
73 } label: {
74 Label(link.reference.map { ref in articles.first { $0.id == ref }?.title ?? ref } ?? "Link X article", systemImage: "link")
75 }
76 }
77 Button("Remove reply", role: .destructive) { remove(index) }
78 }
79 }
80 Button("Add follow-up reply", systemImage: "plus") {
81 let parts = posts + [""]
82 text = parts.joined(separator: XThreadText.separator)
83 format = parts.count == 2 ? "followup" : "thread"
84 }
85 .disabled(posts.count >= XThreadText.limit || posts.last?.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == true)
86 .accessibilityIdentifier("x.addReply")
87 }
88
89 private func counter(_ post: String, limit: Int) -> some View {
90 let weight = XThreadText.weight(post)
91 return Text("\(weight)/\(limit)").font(.caption).foregroundStyle(weight > limit ? palette.danger : palette.muted)
92 }
93
94 private func part(_ index: Int) -> Binding<String> {
95 Binding(get: { posts.indices.contains(index) ? XReplyArticle(posts[index]).copy : "" }, set: { value in
96 var values = posts
97 guard values.indices.contains(index) else { return }
98 values[index] = XReplyArticle.attach(XReplyArticle(values[index]).reference, to: value)
99 text = format == "post" ? value : values.joined(separator: XThreadText.separator)
100 })
101 }
102
103 private func setArticle(_ reference: String?, at index: Int) {
104 var values = posts
105 guard values.indices.contains(index) else { return }
106 values[index] = XReplyArticle.attach(reference, to: XReplyArticle(values[index]).copy)
107 text = values.joined(separator: XThreadText.separator)
108 }
109
110 private func changeFormat(_ value: String) {
111 guard value != format else { return }
112 var values = format == "post" ? [XThreadText.singlePost(text)] : posts
113 if value == "post" {
114 text = values.joined(separator: "\n")
115 } else {
116 if value == "followup", values.count > 2 { values = [values[0], values.dropFirst().joined(separator: "\n")] }
117 while values.count < (value == "followup" ? 2 : 3) { values.append("") }
118 text = values.joined(separator: XThreadText.separator)
119 }
120 format = value
121 }
122
123 private func remove(_ index: Int) {
124 var values = posts
125 guard values.indices.contains(index) else { return }
126 values.remove(at: index)
127 text = values.joined(separator: XThreadText.separator)
128 format = values.count == 1 ? "post" : values.count == 2 ? "followup" : "thread"
129 }
130}
131
132struct StudioCopyReference: View {
133 @Environment(\.studioPalette) private var palette
134 let reference: String
135 @State private var copiedReference: String?
136
137 var body: some View {
138 Button {
139 #if os(macOS)
140 NSPasteboard.general.clearContents()
141 guard NSPasteboard.general.setString(reference, forType: .string) else { return }
142 #else
143 UIPasteboard.general.string = reference
144 #endif
145 copiedReference = reference
146 } label: {
147 Label {
148 Text(reference).monospaced()
149 } icon: {
150 Image(systemName: copiedReference == reference ? "checkmark" : "doc.on.doc")
151 }
152 }
153 #if os(macOS)
154 .buttonStyle(StudioActionStyle())
155 #else
156 .buttonStyle(.bordered)
157 .tint(palette.accent)
158 #endif
159 .accessibilityLabel(copiedReference == reference ? "Copied \(reference)" : "Copy ID \(reference)")
160 .accessibilityIdentifier("content.copyID")
161 #if os(macOS)
162 .help("Copy ID \(reference)")
163 #endif
164 }
165}
166
167enum StudioTheme: String, CaseIterable, Identifiable {
168 case graphite
169 case paper = "warm-paper"
170 case light = "native-light"
171 case system
172
173 static let preferenceKey = "theme"
174 static let defaultPreference: Self = .paper
175 var id: Self { self }
176
177 var title: String {
178 switch self {
179 case .graphite: "Graphite"
180 case .paper: "Warm Paper"
181 case .light: "Native Light"
182 case .system: "Match System"
183 }
184 }
185
186 init(preference: Any?) {
187 self = (preference as? String).flatMap(Self.init(rawValue:)) ?? Self.defaultPreference
188 }
189
190 func resolve(for colorScheme: ColorScheme) -> Self {
191 self == .system ? (colorScheme == .dark ? .graphite : .light) : self
192 }
193}
194
195/// OpenTalon's appearance colors, with Inkspring's editorial type kept in InkspringTypography.
196struct StudioPalette {
197 let theme: StudioTheme
198 var dark: Bool { theme == .graphite }
199 var colorScheme: ColorScheme { dark ? .dark : .light }
200
201 var canvas: Color { shade(0xf5f2ec, 0x141518, 0xfafbfc) }
202 var sidebar: Color { shade(0xeae3d9, 0x101114, 0xeef0f3) }
203 var card: Color { shade(0xfffdf9, 0x202125, 0xffffff) }
204 var panel: Color { shade(0xfaf7f1, 0x191a1e, 0xffffff) }
205 var text: Color { shade(0x2b2723, 0xf1f1f3, 0x1b1d21) }
206 var muted: Color { shade(0x746b61, 0xa8aab0, 0x6c717a) }
207 var disabledText: Color { shade(0x61574e, 0xa8aab0, 0x606570) }
208 var scrollThumb: Color { shade(0x927969, 0x767985, 0x76818f) }
209 var line: Color { shade(0xded7cc, 0x303136, 0xe0e3e8) }
210 var well: Color { shade(0xece6dc, 0x18191d, 0xf0f2f5) }
211 var control: Color { theme == .paper ? well : card }
212 var hover: Color { shade(0xe4dacd, 0x24252b, 0xe4e7ec) }
213 var active: Color { shade(0xe7cdbb, 0x303139, 0xdde1e7) }
214 var accent: Color { shade(0xb9603a, 0xe4e5ea, 0x202328) }
215 // Match OpenTalon's action colors for native themes.
216 var iconAccent: Color { shade(0xb9603a, 0x61d9e3, 0x056370) }
217 var primaryAction: Color { shade(0xa94d28, 0x61d9e3, 0x056370) }
218 var accentText: Color { shade(0xfffdf9, 0x1e1f25, 0xffffff) }
219 var danger: Color { shade(0xb44036, 0xf18d85, 0xba413a) }
220 var success: Color { shade(0x356641, 0x87c697, 0x246b45) }
221
222 private func shade(_ paper: UInt32, _ graphite: UInt32, _ light: UInt32) -> Color {
223 Color(studioRGB: theme == .paper ? paper : dark ? graphite : light)
224 }
225
226 func project(_ hex: String) -> Color {
227 let value = hex.hasPrefix("#") ? String(hex.dropFirst()) : hex
228 guard value.count == 6, let rgb = UInt32(value, radix: 16) else { return accent }
229 return Color(studioRGB: rgb)
230 }
231}
232
233private extension Color {
234 init(studioRGB rgb: UInt32) {
235 self.init(.sRGB, red: Double((rgb >> 16) & 255) / 255,
236 green: Double((rgb >> 8) & 255) / 255, blue: Double(rgb & 255) / 255)
237 }
238}
239
240private struct StudioPaletteKey: EnvironmentKey {
241 static let defaultValue = StudioPalette(theme: .paper)
242}
243
244extension EnvironmentValues {
245 var studioPalette: StudioPalette {
246 get { self[StudioPaletteKey.self] }
247 set { self[StudioPaletteKey.self] = newValue }
248 }
249}
250
251struct StudioNewIdeaButton: View {
252 @Environment(\.studioPalette) private var palette
253 @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
254 let action: () -> Void
255
256 var body: some View {
257 Button(action: action) { surface }
258 .buttonStyle(.plain)
259 .accessibilityLabel("Draft a new idea")
260 .accessibilityIdentifier("idea.new")
261 }
262
263 @ViewBuilder private var surface: some View {
264 let icon = Image(systemName: "plus")
265 .font(.system(size: 18, weight: .semibold))
266 .foregroundStyle(palette.primaryAction)
267 .frame(width: 44, height: 44)
268 .contentShape(Circle())
269 if #available(macOS 26, iOS 26, *), !reduceTransparency {
270 icon.glassEffect(.regular.tint(palette.primaryAction.opacity(0.38)).interactive(), in: .circle)
271 } else {
272 icon.background(palette.primaryAction.opacity(0.12), in: Circle())
273 .overlay { Circle().strokeBorder(palette.primaryAction.opacity(0.35)).allowsHitTesting(false) }
274 }
275 }
276}
277
278enum StudioRadius {
279 static let row: CGFloat = 8
280 static let control: CGFloat = 10
281 static let card: CGFloat = 14
282}
283
284struct PlatformMark: View {
285 let name: String
286 var fallback = "link"
287
288 private static func assetURL(_ name: String) -> URL? {
289 Bundle.main.url(forResource: name.lowercased(), withExtension: "png", subdirectory: "PlatformIcons")
290 }
291
292 static func image(_ name: String) -> Image? {
293 if name.lowercased() == "x-article" { return image("x") }
294 if name.lowercased() == "youtube" { return Image(systemName: "play.rectangle.fill") }
295#if os(macOS)
296 guard let url = assetURL(name), let image = NSImage(contentsOf: url) else { return nil }
297 image.size = NSSize(width: 14, height: 14)
298 image.isTemplate = true
299 return Image(nsImage: image)
300#else
301 return bitmap(name).map { Image(uiImage: $0).renderingMode(.template) }
302#endif
303 }
304
305#if os(iOS)
306 static func bitmap(_ name: String) -> UIImage? {
307 assetURL(name).flatMap { UIImage(contentsOfFile: $0.path) }
308 }
309#endif
310
311 static func markScale(for name: String) -> CGFloat {
312 switch name.lowercased() {
313 case "claude-mark": 1.5 // The asset includes transparent padding around the starburst.
314 case "gemini": 1.15 // Match the visual weight of the OpenAI mark.
315 default: 1
316 }
317 }
318
319 var body: some View {
320 (Self.image(name) ?? Image(systemName: fallback))
321 .resizable().scaledToFit()
322 .frame(width: 14, height: 14)
323 .scaleEffect(Self.markScale(for: name))
324 // Align the base of the LinkedIn wordmark with the adjacent text.
325 .offset(y: name.lowercased() == "linkedin" ? -3 : 0)
326 .accessibilityHidden(true)
327 }
328}
329
330struct StudioPlatformLabel: View {
331 let name: String
332 let title: String
333 var iconOffset: CGFloat = 0
334
335 var body: some View {
336 Label { Text(title) } icon: {
337 PlatformMark(name: name, fallback: name == "news" ? "newspaper" : "link")
338 .offset(y: iconOffset)
339 }
340 }
341}
342
343struct StudioIconLabelStyle: LabelStyle {
344 @Environment(\.studioPalette) private var palette
345 var inverted = false
346 var muted = false
347
348 func makeBody(configuration: Configuration) -> some View {
349 HStack(spacing: 8) {
350 configuration.icon
351 .foregroundStyle(muted ? palette.disabledText : inverted ? palette.accentText : palette.iconAccent)
352 configuration.title
353 .foregroundStyle(muted ? palette.disabledText : inverted ? palette.accentText : palette.text)
354 }
355 }
356}
357
358struct StudioExternalArrow: View {
359 @Environment(\.studioPalette) private var palette
360
361 var body: some View {
362 Image(systemName: "arrow.up.right")
363 .font(.caption.weight(.medium))
364 .foregroundStyle(palette.iconAccent)
365 .accessibilityHidden(true)
366 }
367}
368
369struct StudioLinkOutLabel<Content: View>: View {
370 @ViewBuilder let content: () -> Content
371
372 var body: some View {
373 HStack(spacing: 7) {
374 content()
375 StudioExternalArrow()
376 }
377 .accessibilityElement(children: .combine)
378 }
379}
380
381struct StudioExternalLink: View {
382 let title: String
383 let destination: URL
384
385 init(_ title: String, destination: URL) {
386 self.title = title
387 self.destination = destination
388 }
389
390 var body: some View {
391 Link(destination: destination) {
392 StudioLinkOutLabel { Text(title) }
393 }
394 }
395}
396
397extension View {
398#if os(macOS)
399 func studioAppearance(_ palette: StudioPalette) -> some View {
400 self
401 .font(InkspringTypography.interface(14))
402 .foregroundStyle(palette.text, palette.muted)
403 .tint(palette.accent)
404 .labelStyle(StudioIconLabelStyle())
405 .buttonStyle(StudioActionStyle())
406 .toggleStyle(StudioToggleStyle())
407 .menuStyle(.borderlessButton)
408 .groupBoxStyle(StudioGroupStyle())
409 .environment(\.studioPalette, palette)
410 .environment(\.colorScheme, palette.colorScheme)
411 }
412
413 func studioPage() -> some View {
414 self
415 .frame(maxWidth: 1344, alignment: .leading)
416 .padding(.horizontal, 36)
417 .padding(.vertical, 28)
418 .frame(maxWidth: .infinity, alignment: .center)
419 }
420
421 func studioGlassControl(tint: Color? = nil, interactive: Bool = true) -> some View {
422 modifier(StudioControlGlass(tint: tint, interactive: interactive))
423 }
424
425 func studioInput() -> some View {
426 textFieldStyle(.plain)
427 .padding(.horizontal, 10)
428 .padding(.vertical, 6)
429 .modifier(StudioControlGlass(interactive: false, isInput: true))
430 }
431#endif
432
433 func studioSurface(_ radius: CGFloat = StudioRadius.card, fill: Color? = nil) -> some View {
434 modifier(StudioSurface(radius: radius, fill: fill))
435 }
436
437 func studioPaperControl<S: InsettableShape>(in shape: S, fill: Color) -> some View {
438 modifier(StudioPaperControl(shape: shape, fill: fill))
439 }
440}
441
442private struct StudioPaperControl<S: InsettableShape>: ViewModifier {
443 @Environment(\.studioPalette) private var palette
444 @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
445 let shape: S
446 let fill: Color
447
448 func body(content: Content) -> some View {
449 content.background {
450 shape.fill(fill)
451 .overlay {
452 if !reduceTransparency {
453 shape.fill(.linearGradient(colors: [palette.card.opacity(0.20), .clear],
454 startPoint: .top, endPoint: .bottom))
455 }
456 }
457 .overlay { shape.strokeBorder(palette.line) }
458 }
459 }
460}
461
462private struct StudioSurface: ViewModifier {
463 @Environment(\.studioPalette) private var palette
464 let radius: CGFloat
465 let fill: Color?
466
467 func body(content: Content) -> some View {
468 let shape = RoundedRectangle(cornerRadius: radius, style: .continuous)
469 content
470 .background(fill ?? palette.card, in: shape)
471 .overlay { shape.strokeBorder(palette.line).allowsHitTesting(false) }
472 }
473}
474
475#if os(macOS)
476struct StudioRule: View {
477 @Environment(\.studioPalette) private var palette
478 var axis: Axis = .horizontal
479
480 var body: some View {
481 Rectangle()
482 .fill(palette.line)
483 .frame(width: axis == .vertical ? 1 : nil, height: axis == .horizontal ? 1 : nil)
484 .accessibilityHidden(true)
485 .allowsHitTesting(false)
486 }
487}
488struct StudioActionStyle: ButtonStyle {
489 static let standardHeight: CGFloat = 30
490 @Environment(\.studioPalette) private var palette
491 @Environment(\.isEnabled) private var enabled
492 @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
493 var prominent = false
494 var fillsWidth = false
495
496 func makeBody(configuration: Configuration) -> some View {
497 let destructive = configuration.role == .destructive
498 let emphasized = prominent && !destructive
499 let usesAccent = emphasized && enabled
500 configuration.label
501 .labelStyle(StudioIconLabelStyle(inverted: usesAccent, muted: !enabled))
502 .font(InkspringTypography.interface(13).weight(emphasized ? .semibold : .medium))
503 .padding(.horizontal, fillsWidth ? 14 : emphasized ? 15 : 12)
504 .frame(maxWidth: fillsWidth ? .infinity : nil,
505 minHeight: fillsWidth ? 36 : prominent ? 35 : Self.standardHeight, alignment: .leading)
506 .fixedSize(horizontal: !fillsWidth, vertical: false)
507 .foregroundStyle(!enabled ? palette.disabledText : usesAccent ? palette.accentText : destructive ? palette.danger : palette.text)
508 .modifier(StudioActionSurface(
509 tint: usesAccent ? palette.primaryAction : nil,
510 fill: !enabled ? palette.well : usesAccent ? palette.primaryAction : configuration.isPressed ? palette.hover : palette.control,
511 line: palette.line, interactive: enabled, reduceTransparency: reduceTransparency || !enabled
512 ))
513 .contentShape(Capsule())
514 .opacity(enabled && configuration.isPressed ? 0.82 : 1)
515 }
516}
517
518struct StudioIconButtonStyle: ButtonStyle {
519 @Environment(\.studioPalette) private var palette
520 @Environment(\.isEnabled) private var enabled
521 var size: CGFloat = StudioActionStyle.standardHeight
522
523 func makeBody(configuration: Configuration) -> some View {
524 configuration.label
525 .labelStyle(.iconOnly)
526 .foregroundStyle(enabled ? palette.iconAccent : palette.disabledText)
527 .font(.system(size: 13, weight: .semibold))
528 .frame(width: size, height: size)
529 .fixedSize()
530 .studioGlassControl()
531 .contentShape(Circle())
532 .opacity(enabled && configuration.isPressed ? 0.82 : 1)
533 }
534}
535
536struct StudioMoreMenu<Actions: View>: View {
537 let title: String
538 var size: CGFloat = StudioActionStyle.standardHeight
539 @ViewBuilder let actions: () -> Actions
540
541 var body: some View {
542 Menu(content: actions) {
543 Image(systemName: "ellipsis")
544 }
545 .menuStyle(.button)
546 .menuIndicator(.hidden)
547 .buttonStyle(StudioIconButtonStyle(size: size))
548 .fixedSize()
549 .accessibilityLabel(title)
550 .help(title)
551 }
552}
553
554struct StudioSearchField: View {
555 @Environment(\.studioPalette) private var palette
556 let title: String
557 @Binding var text: String
558
559 var body: some View {
560 HStack(spacing: 8) {
561 Image(systemName: "magnifyingglass")
562 .foregroundStyle(palette.iconAccent)
563 .accessibilityHidden(true)
564 TextField(title, text: $text, prompt: Text(title).foregroundStyle(palette.muted))
565 .textFieldStyle(.plain)
566 .foregroundStyle(palette.text)
567 }
568 .font(InkspringTypography.interface(13))
569 .padding(.horizontal, 12)
570 .frame(minHeight: StudioActionStyle.standardHeight)
571 .modifier(StudioControlGlass(interactive: false, isInput: true))
572 .overlay { Capsule().strokeBorder(palette.muted.opacity(0.32)).allowsHitTesting(false) }
573 }
574}
575
576private struct StudioControlGlass: ViewModifier {
577 @Environment(\.studioPalette) private var palette
578 @Environment(\.isEnabled) private var enabled
579 @Environment(\.accessibilityReduceTransparency) private var reduceTransparency
580 var tint: Color?
581 var interactive = true
582 var isInput = false
583
584 func body(content: Content) -> some View {
585 let base = isInput && palette.theme == .paper ? palette.panel : palette.control
586 return content.modifier(StudioActionSurface(tint: enabled ? tint : nil, fill: enabled ? tint ?? base : palette.well,
587 line: palette.line, interactive: interactive && enabled,
588 reduceTransparency: reduceTransparency || !enabled))
589 }
590}
591
592private struct StudioActionSurface: ViewModifier {
593 @Environment(\.studioPalette) private var palette
594 let tint: Color?
595 let fill: Color
596 let line: Color
597 let interactive: Bool
598 let reduceTransparency: Bool
599
600 @ViewBuilder func body(content: Content) -> some View {
601 if palette.theme == .paper {
602 content.studioPaperControl(in: Capsule(), fill: fill)
603 } else if #available(macOS 26, *), !reduceTransparency {
604 if let tint {
605 // Keep the button's color behind its label when an inactive window clears glass tint.
606 content
607 .background(tint, in: Capsule())
608 .glassEffect(.regular.interactive(interactive), in: .capsule)
609 } else {
610 content.glassEffect(.regular.interactive(interactive), in: .capsule)
611 }
612 } else {
613 content.background(fill, in: Capsule())
614 .overlay { Capsule().strokeBorder(line).allowsHitTesting(false) }
615 }
616 }
617}
618
619private struct StudioToggleStyle: ToggleStyle {
620 @Environment(\.studioPalette) private var palette
621 @Environment(\.isEnabled) private var enabled
622
623 func makeBody(configuration: Configuration) -> some View {
624 Button { configuration.isOn.toggle() } label: {
625 HStack(spacing: 8) {
626 Image(systemName: configuration.isOn ? "checkmark.circle.fill" : "circle")
627 .foregroundStyle(!enabled ? palette.disabledText : configuration.isOn ? palette.iconAccent : palette.muted)
628 configuration.label
629 }
630 }
631 .buttonStyle(StudioActionStyle())
632 .accessibilityRepresentation {
633 Toggle(isOn: configuration.$isOn) { configuration.label }.toggleStyle(.switch)
634 }
635 }
636}
637
638struct StudioRowStyle: ButtonStyle {
639 @Environment(\.studioPalette) private var palette
640 var selected = false
641 var indicator = false
642
643 func makeBody(configuration: Configuration) -> some View {
644 Row(configuration: configuration, selected: selected, indicator: indicator, palette: palette)
645 }
646
647 private struct Row: View {
648 let configuration: ButtonStyle.Configuration
649 let selected: Bool
650 let indicator: Bool
651 let palette: StudioPalette
652 @State private var hovering = false
653
654 var body: some View {
655 configuration.label
656 .background(selected ? palette.active : hovering || configuration.isPressed ? palette.hover : .clear,
657 in: RoundedRectangle(cornerRadius: StudioRadius.row, style: .continuous))
658 .overlay(alignment: .leading) {
659 if selected && indicator {
660 Capsule().fill(palette.accent).frame(width: 2, height: 17)
661 }
662 }
663 .contentShape(Rectangle())
664 .onHover { hovering = $0 }
665 }
666 }
667}
668
669struct StudioGroupStyle: GroupBoxStyle {
670 @Environment(\.studioPalette) private var palette
671
672 func makeBody(configuration: Configuration) -> some View {
673 VStack(alignment: .leading, spacing: 12) {
674 configuration.label
675 .font(InkspringTypography.interface(14).weight(.semibold))
676 .foregroundStyle(palette.text)
677 configuration.content
678 }
679 .frame(maxWidth: .infinity, alignment: .leading)
680 .padding(16)
681 .studioSurface()
682 }
683}
684
685struct StudioFilterMenu<Choices: View>: View {
686 @Environment(\.studioPalette) private var palette
687 let title: String
688 let value: String
689 @ViewBuilder let choices: () -> Choices
690
691 var body: some View {
692 Menu(content: choices) {
693 HStack(spacing: 8) {
694 Text(value).lineLimit(1)
695 Image(systemName: "chevron.up.chevron.down")
696 .font(.system(size: 8, weight: .semibold))
697 .foregroundStyle(palette.muted)
698 .accessibilityHidden(true)
699 }
700 .font(InkspringTypography.interface(13))
701 .foregroundStyle(palette.text)
702 .padding(.horizontal, 8)
703 .frame(minHeight: StudioActionStyle.standardHeight)
704 }
705 .menuStyle(.borderlessButton)
706 .menuIndicator(.hidden)
707 .tint(palette.text)
708 .fixedSize(horizontal: true, vertical: false)
709 .padding(.horizontal, 6)
710 .frame(minHeight: StudioActionStyle.standardHeight)
711 .studioGlassControl()
712 .accessibilityLabel(title)
713 .accessibilityValue(value)
714 }
715}
716
717struct StudioChoicePicker<Value: Hashable>: View {
718 @Environment(\.studioPalette) private var palette
719 @State private var showingChoices = false
720 let title: String
721 @Binding var selection: Value
722 let options: [Value]
723 let label: (Value) -> String
724 var icon: ((Value) -> Image?)? = nil
725
726 var body: some View {
727 if let icon {
728 Button { showingChoices.toggle() } label: {
729 HStack(spacing: 7) {
730 choiceLabel(selection, icon: icon(selection))
731 Image(systemName: "chevron.up.chevron.down")
732 .font(.system(size: 8, weight: .semibold))
733 .foregroundStyle(palette.muted)
734 .accessibilityHidden(true)
735 }
736 }
737 .accessibilityLabel(title)
738 .accessibilityValue(label(selection))
739 .popover(isPresented: $showingChoices, arrowEdge: .top) {
740 VStack(alignment: .leading, spacing: 3) {
741 ForEach(options, id: \.self) { option in
742 Button {
743 selection = option
744 showingChoices = false
745 } label: {
746 HStack(spacing: 8) {
747 choiceLabel(option, icon: icon(option))
748 Spacer(minLength: 12)
749 if selection == option {
750 Image(systemName: "checkmark")
751 .font(.caption.weight(.semibold))
752 .foregroundStyle(palette.iconAccent)
753 .accessibilityHidden(true)
754 }
755 }
756 .padding(.horizontal, 9)
757 .padding(.vertical, 6)
758 }
759 .buttonStyle(StudioRowStyle(selected: selection == option))
760 .accessibilityAddTraits(selection == option ? .isSelected : [])
761 }
762 }
763 .font(InkspringTypography.interface(13))
764 .padding(6)
765 .frame(minWidth: 126)
766 .fixedSize(horizontal: true, vertical: false)
767 .background(palette.card, in: RoundedRectangle(cornerRadius: StudioRadius.control))
768 .overlay {
769 RoundedRectangle(cornerRadius: StudioRadius.control)
770 .strokeBorder(palette.scrollThumb.opacity(0.55))
771 .allowsHitTesting(false)
772 }
773 .shadow(color: .black.opacity(palette.dark ? 0.5 : 0.24), radius: 8, x: 0, y: 4)
774 .padding(8)
775 .studioAppearance(palette)
776 }
777 } else {
778 StudioFilterMenu(title: title, value: label(selection)) {
779 Picker(title, selection: $selection) {
780 ForEach(options, id: \.self) { option in Text(label(option)).tag(option) }
781 }
782 .pickerStyle(.inline)
783 }
784 }
785 }
786
787 private func choiceLabel(_ option: Value, icon: Image?) -> some View {
788 HStack(spacing: 7) {
789 if let icon {
790 icon.resizable().scaledToFit().frame(width: 14, height: 14)
791 .foregroundStyle(palette.iconAccent)
792 .accessibilityHidden(true)
793 }
794 Text(label(option))
795 }
796 }
797}
798
799struct StudioLabeledChoice<Value: Hashable>: View {
800 let title: String
801 @Binding var selection: Value
802 let options: [Value]
803 let label: (Value) -> String
804 var icon: ((Value) -> Image?)? = nil
805
806 var body: some View {
807 HStack {
808 Text(title).accessibilityHidden(true)
809 Spacer(minLength: 12)
810 StudioChoicePicker(title: title, selection: $selection, options: options, label: label, icon: icon)
811 }
812 }
813}
814
815struct StudioSegmentedControl<Value: Hashable, SegmentLabel: View>: View {
816 @Environment(\.studioPalette) private var palette
817 @Environment(\.accessibilityReduceMotion) private var reduceMotion
818 @Namespace private var highlight
819 @Binding var selection: Value
820 let options: [Value]
821 @ViewBuilder let label: (Value) -> SegmentLabel
822
823 var body: some View {
824 HStack(spacing: 0) {
825 ForEach(options, id: \.self) { option in
826 Button { selection = option } label: {
827 label(option)
828 .font(InkspringTypography.interface(13).weight(selection == option ? .semibold : .medium))
829 .padding(.horizontal, 14)
830 .frame(minHeight: 28)
831 .background {
832 if selection == option {
833 Capsule().fill(palette.active)
834 .overlay { Capsule().strokeBorder(palette.muted.opacity(0.45)) }
835 .matchedGeometryEffect(id: "selection", in: highlight)
836 }
837 }
838 .contentShape(Capsule())
839 }
840 .buttonStyle(.plain)
841 .accessibilityAddTraits(selection == option ? .isSelected : [])
842 }
843 }
844 .padding(3)
845 .studioGlassControl(interactive: false)
846 .fixedSize()
847 .animation(reduceMotion ? nil : .easeInOut(duration: 0.18), value: selection)
848 .accessibilityElement(children: .contain)
849 }
850}
851
852struct StudioDateTimePicker: View {
853 @Binding var selection: Date
854 var includesMinute = true
855 var includesFiveMinuteShortcut = false
856
857 var body: some View {
858 VStack(alignment: .leading, spacing: 16) {
859 if includesFiveMinuteShortcut {
860 Button("In 5 minutes", systemImage: "clock") { selection = PostScheduling.fiveMinutesFromNow() }
861 .help("Select a time at least five minutes from now, rounded up to the next minute.")
862 }
863 StudioScheduleCalendar(selection: $selection)
864 .frame(maxWidth: .infinity, alignment: .leading)
865 .padding(12)
866 .studioSurface()
867 StudioLabeledChoice(title: "Hour", selection: component(.hour), options: Array(0..<24), label: hourLabel)
868 if includesMinute {
869 StudioLabeledChoice(title: "Minute", selection: component(.minute), options: Array(0..<60),
870 label: { String(format: "%02d", $0) })
871 }
872 Text("Time zone: \(TimeZone.current.identifier)")
873 .font(InkspringTypography.interface(11))
874 .foregroundStyle(.secondary)
875 }
876 }
877
878 private func component(_ component: Calendar.Component) -> Binding<Int> {
879 Binding(get: { Calendar.current.component(component, from: selection) }, set: { value in
880 let calendar = Calendar.current
881 var parts = calendar.dateComponents([.hour, .minute], from: selection)
882 if component == .hour { parts.hour = value } else { parts.minute = value }
883 if let date = calendar.date(bySettingHour: parts.hour ?? 0, minute: parts.minute ?? 0, second: 0,
884 of: selection, matchingPolicy: .strict),
885 calendar.isDate(date, inSameDayAs: selection) {
886 selection = date
887 }
888 })
889 }
890
891 private func hourLabel(_ hour: Int) -> String {
892 let date = Calendar.current.date(from: DateComponents(year: 2001, month: 1, day: 15, hour: hour))!
893 return date.formatted(.dateTime.hour())
894 }
895}
896
897private struct StudioScheduleCalendar: View {
898 @Environment(\.studioPalette) private var palette
899 @Environment(\.calendar) private var calendar
900 @Environment(\.locale) private var locale
901 @Binding var selection: Date
902 @State private var shownDate: Date?
903 @FocusState private var focusedDay: Date?
904
905 private var month: DateInterval? { calendar.dateInterval(of: .month, for: shownDate ?? selection) }
906 private var today: Date { calendar.startOfDay(for: .now) }
907
908 var body: some View {
909 if let month {
910 VStack(alignment: .leading, spacing: 6) {
911 HStack(spacing: 6) {
912 Text(month.start.formatted(.dateTime.month(.wide).year().locale(locale)))
913 .font(.callout.weight(.semibold))
914 Spacer(minLength: 4)
915 monthButton("Previous month", icon: "chevron.left") { moveMonth(-1) }
916 .disabled(month.contains(today))
917 monthButton("Today", icon: "circle") { choose(today) }
918 monthButton("Next month", icon: "chevron.right") { moveMonth(1) }
919 }
920 LazyVGrid(columns: Array(repeating: GridItem(.fixed(27), spacing: 3), count: 7), spacing: 2) {
921 let weekdays = calendar.veryShortStandaloneWeekdaySymbols
922 ForEach(0..<7, id: \.self) { offset in
923 Text(weekdays[(calendar.firstWeekday - 1 + offset) % 7])
924 .font(.caption2.weight(.semibold))
925 .foregroundStyle(palette.muted)
926 .accessibilityHidden(true)
927 }
928 let firstColumn = (calendar.component(.weekday, from: month.start) - calendar.firstWeekday + 7) % 7
929 ForEach(0..<firstColumn, id: \.self) { _ in
930 Color.clear.frame(height: 21).accessibilityHidden(true)
931 }
932 ForEach(Array(calendar.range(of: .day, in: .month, for: month.start) ?? 1..<1), id: \.self) { number in
933 if let date = calendar.date(byAdding: .day, value: number - 1, to: month.start) {
934 dayButton(number, date: date)
935 }
936 }
937 }
938 }
939 .frame(width: 207)
940 .accessibilityElement(children: .contain)
941 .accessibilityLabel("Date")
942 .onChange(of: selection) { shownDate = selection }
943 }
944 }
945
946 private func monthButton(_ title: String, icon: String, action: @escaping () -> Void) -> some View {
947 Button(action: action) {
948 Image(systemName: icon)
949 .font(.caption2.weight(.semibold))
950 .foregroundStyle(palette.iconAccent)
951 .frame(width: 20, height: 19)
952 .contentShape(.rect)
953 }
954 .buttonStyle(.plain)
955 .accessibilityLabel(title)
956 .help(title)
957 }
958
959 private func dayButton(_ number: Int, date: Date) -> some View {
960 let selected = calendar.isDate(date, inSameDayAs: selection)
961 return Button { choose(date) } label: {
962 Text(number.formatted(.number.locale(locale)))
963 .font(.caption.monospacedDigit().weight(selected ? .semibold : .regular))
964 .foregroundStyle(selected ? palette.accentText : date < today ? palette.muted : palette.text)
965 .frame(width: 27, height: 21)
966 .background(selected ? palette.primaryAction : .clear, in: .rect(cornerRadius: 5))
967 .overlay {
968 if !selected && date == today {
969 RoundedRectangle(cornerRadius: 5).strokeBorder(palette.primaryAction)
970 }
971 }
972 .contentShape(.rect)
973 }
974 .buttonStyle(.plain)
975 .disabled(date < today)
976 .focused($focusedDay, equals: date)
977 .accessibilityLabel(date.formatted(date: .complete, time: .omitted))
978 .accessibilityAddTraits(selected ? .isSelected : [])
979 .onKeyPress(.leftArrow) { moveFocus(from: date, by: -1) }
980 .onKeyPress(.rightArrow) { moveFocus(from: date, by: 1) }
981 .onKeyPress(.upArrow) { moveFocus(from: date, by: -7) }
982 .onKeyPress(.downArrow) { moveFocus(from: date, by: 7) }
983 }
984
985 private func moveMonth(_ offset: Int) {
986 guard let month else { return }
987 shownDate = calendar.date(byAdding: .month, value: offset, to: month.start)
988 }
989
990 private func moveFocus(from date: Date, by offset: Int) -> KeyPress.Result {
991 if let target = calendar.date(byAdding: .day, value: offset, to: date), target >= today {
992 shownDate = target
993 focusedDay = target
994 }
995 return .handled
996 }
997
998 private func choose(_ date: Date) {
999 let time = calendar.dateComponents([.hour, .minute], from: selection)
1000 if let selected = calendar.date(bySettingHour: time.hour ?? 0, minute: time.minute ?? 0, second: 0, of: date),
1001 calendar.isDate(selected, inSameDayAs: date) {
1002 selection = selected
1003 shownDate = selected
1004 }
1005 }
1006}
1007
1008struct StudioTabs<Value: Hashable>: View {
1009 @Environment(\.studioPalette) private var palette
1010 @Binding var selection: Value
1011 let tabs: [Value]
1012 let label: (Value) -> String
1013 var count: ((Value) -> Int)? = nil
1014 var platform: ((Value) -> String)? = nil
1015
1016 var body: some View {
1017 ScrollView(.horizontal) {
1018 HStack(spacing: 8) {
1019 ForEach(tabs, id: \.self) { tab in
1020 Button { selection = tab } label: {
1021 HStack(spacing: 6) {
1022 if let platform {
1023 PlatformMark(name: platform(tab), fallback: "newspaper")
1024 .foregroundStyle(palette.iconAccent)
1025 }
1026 Text(label(tab)).fontWeight(selection == tab ? .semibold : .regular)
1027 if let count {
1028 Text(count(tab).formatted())
1029 .font(InkspringTypography.interface(11).monospacedDigit())
1030 .foregroundStyle(palette.muted)
1031 }
1032 }
1033 .font(InkspringTypography.interface(13))
1034 .foregroundStyle(palette.text)
1035 .padding(.horizontal, 10)
1036 .frame(minHeight: 29)
1037 .studioGlassControl(tint: selection == tab ? palette.accent.opacity(0.2) : nil)
1038 .contentShape(Capsule())
1039 }
1040 .buttonStyle(.plain)
1041 .accessibilityAddTraits(selection == tab ? .isSelected : [])
1042 }
1043 }
1044 .padding(.horizontal, 4)
1045 .padding(.top, 5)
1046 .padding(.bottom, 14)
1047 }
1048 .scrollIndicators(.hidden)
1049 .overlay(alignment: .bottom) { StudioRule().opacity(0.6) }
1050 }
1051}
1052#endif
1053
1054#if os(iOS)
1055struct MobileWritingTextView: UIViewRepresentable {
1056 @Binding var text: String
1057 var identifier: String
1058 var findRequest = 0
1059 var autofocus = true
1060 var monospaced = false
1061 var onFocusLost: (() -> Void)? = nil
1062 @Environment(\.studioPalette) private var palette
1063
1064 func makeCoordinator() -> Coordinator { Coordinator(self) }
1065
1066 func makeUIView(context: Context) -> UITextView {
1067 let view = UITextView()
1068 view.delegate = context.coordinator
1069 view.isFindInteractionEnabled = true
1070 view.backgroundColor = .clear
1071 view.alwaysBounceVertical = true
1072 view.keyboardDismissMode = .interactive
1073 view.textContainerInset = UIEdgeInsets(top: 14, left: 12, bottom: 24, right: 12)
1074 view.adjustsFontForContentSizeCategory = true
1075 view.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
1076 view.text = text
1077 if autofocus { DispatchQueue.main.async { view.becomeFirstResponder() } }
1078 return view
1079 }
1080
1081 func updateUIView(_ view: UITextView, context: Context) {
1082 context.coordinator.parent = self
1083 view.accessibilityIdentifier = identifier
1084 view.accessibilityLabel = identifier == "newsletter.markdown" ? "Markdown" : "Post text"
1085 let font = monospaced ? UIFontMetrics.default.scaledFont(for: .monospacedSystemFont(ofSize: 17, weight: .regular)) : .preferredFont(forTextStyle: .body)
1086 if view.font != font { view.font = font }
1087 view.textColor = UIColor(palette.text)
1088 view.tintColor = UIColor(palette.iconAccent)
1089 // SwiftUI recomputes on autosave/sync. Never assign identical text: UIKit would reset selection.
1090 if view.text != text, view.markedTextRange == nil {
1091 let selection = view.selectedRange
1092 let offset = view.contentOffset
1093 view.text = text
1094 view.selectedRange = NSRange(location: min(selection.location, (text as NSString).length), length: 0)
1095 view.setContentOffset(offset, animated: false)
1096 }
1097 if context.coordinator.findRequest != findRequest {
1098 context.coordinator.findRequest = findRequest
1099 view.findInteraction?.presentFindNavigator(showingReplace: false)
1100 }
1101 }
1102
1103 final class Coordinator: NSObject, UITextViewDelegate {
1104 var parent: MobileWritingTextView
1105 var findRequest = 0
1106 init(_ parent: MobileWritingTextView) { self.parent = parent }
1107 func textViewDidChange(_ textView: UITextView) { parent.text = textView.text }
1108 func textViewDidEndEditing(_ textView: UITextView) { parent.onFocusLost?() }
1109 }
1110}
1111#endif
1112
1113#if os(iOS)
1114private struct MobileXReplyEditor: View {
1115 @Binding var text: String
1116 let identifier: String
1117 let count: Int
1118 let back: () -> Void
1119 @State private var findRequest = 0
1120 var body: some View {
1121 VStack(spacing: 8) {
1122 HStack {
1123 Button("Back to thread", systemImage: "chevron.left", action: back).accessibilityIdentifier("x.backToThread")
1124 Spacer()
1125 Text("\(count)/280").font(.caption)
1126 }.padding(.horizontal, 12)
1127 MobileWritingTextView(text: $text, identifier: identifier, findRequest: findRequest)
1128 .frame(maxWidth: .infinity, maxHeight: .infinity)
1129 }
1130 .toolbar { ToolbarItem(placement: .topBarTrailing) {
1131 Button("Find", systemImage: "magnifyingglass") { findRequest += 1 }.accessibilityIdentifier("editor.find")
1132 } }
1133 }
1134}
1135#endif
1136
1137#if os(macOS)
1138// The page owns scrolling, so keyboard navigation and Find must reveal their range in that page.
1139private final class MacDocumentTextView: NSTextView {
1140 override func scrollRangeToVisible(_ range: NSRange) {
1141 super.scrollRangeToVisible(range)
1142 let length = (string as NSString).length
1143 guard let document = enclosingScrollView?.documentView, let layout = layoutManager,
1144 let container = textContainer, range.location <= length, length > 0 else { return }
1145 let character = NSRange(location: min(range.location, length - 1), length: 1)
1146 layout.ensureLayout(forCharacterRange: character)
1147 let glyph = layout.glyphRange(forCharacterRange: character, actualCharacterRange: nil)
1148 var line = layout.boundingRect(forGlyphRange: glyph, in: container)
1149 if range.location == length, !layout.extraLineFragmentRect.isEmpty { line = layout.extraLineFragmentRect }
1150 let target = convert(line.offsetBy(dx: textContainerOrigin.x, dy: textContainerOrigin.y), to: document)
1151 let visible = document.visibleRect
1152 if target.minY < visible.minY || target.maxY > visible.maxY {
1153 document.scroll(NSPoint(x: visible.minX, y: max(0, target.midY - visible.height / 2)))
1154 }
1155 }
1156}
1157
1158struct MacWritingTextView: NSViewRepresentable {
1159 @Binding var text: String
1160 var findRequest = 0
1161 var focusRequest = 0
1162 var monospaced = false
1163 var documentMinimumHeight: CGFloat?
1164 var textInsets = NSSize(width: 8, height: 10)
1165 var lineSpacing: CGFloat = 0
1166 var onFocusLost: (() -> Void)? = nil
1167 @Environment(\.studioPalette) private var palette
1168
1169 func makeCoordinator() -> Coordinator { Coordinator(self) }
1170 func makeNSView(context: Context) -> NSView {
1171 let root: NSView
1172 let view: NSTextView
1173 if documentMinimumHeight != nil {
1174 view = MacDocumentTextView(usingTextLayoutManager: false)
1175 view.isHorizontallyResizable = false
1176 view.isVerticallyResizable = true
1177 view.textContainer?.widthTracksTextView = true
1178 root = view
1179 } else {
1180 let scroll = NSTextView.scrollableTextView()
1181 scroll.drawsBackground = false
1182 view = scroll.documentView as! NSTextView
1183 root = scroll
1184 }
1185 view.delegate = context.coordinator
1186 view.isRichText = false
1187 view.allowsUndo = true
1188 view.usesFindBar = true
1189 view.isIncrementalSearchingEnabled = true
1190 view.drawsBackground = false
1191 view.textContainerInset = textInsets
1192 if lineSpacing > 0 {
1193 let style = NSMutableParagraphStyle()
1194 style.lineSpacing = lineSpacing
1195 view.defaultParagraphStyle = style
1196 }
1197 replaceText(in: view)
1198 return root
1199 }
1200 func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSView, context: Context) -> CGSize? {
1201 guard let documentMinimumHeight, let width = proposal.width, width.isFinite, width > 0,
1202 let view = nsView as? NSTextView, let storage = view.textStorage else { return nil }
1203 // SwiftUI may probe several widths. Measure those without rewrapping the live editor.
1204 let measure = context.coordinator.measurement
1205 if measure.textStorage !== storage { storage.addLayoutManager(measure) }
1206 guard let container = measure.textContainers.first else { return nil }
1207 let inset = view.textContainerInset
1208 container.containerSize = NSSize(width: max(1, width - inset.width * 2), height: .greatestFiniteMagnitude)
1209 measure.ensureLayout(for: container)
1210 let bottom = max(measure.usedRect(for: container).maxY, measure.extraLineFragmentRect.maxY)
1211 return CGSize(width: width, height: max(documentMinimumHeight, ceil(bottom + inset.height * 2)))
1212 }
1213
1214 func updateNSView(_ root: NSView, context: Context) {
1215 context.coordinator.parent = self
1216 let scroll = root as? NSScrollView
1217 guard let view = (root as? NSTextView) ?? (scroll?.documentView as? NSTextView) else { return }
1218 let font: NSFont = monospaced ? .monospacedSystemFont(ofSize: 14, weight: .regular) : .systemFont(ofSize: 16)
1219 if view.font != font { view.font = font }
1220 view.textColor = NSColor(palette.text)
1221 view.insertionPointColor = NSColor(palette.iconAccent)
1222 if view.string != text, !view.hasMarkedText() {
1223 let selection = view.selectedRange()
1224 let origin = scroll?.contentView.bounds.origin
1225 replaceText(in: view)
1226 view.setSelectedRange(NSRange(location: min(selection.location, (text as NSString).length), length: 0))
1227 if let origin { scroll?.contentView.scroll(to: origin) }
1228 }
1229 if context.coordinator.focusRequest != focusRequest {
1230 context.coordinator.focusRequest = focusRequest
1231 view.window?.makeFirstResponder(view)
1232 }
1233 if context.coordinator.findRequest != findRequest {
1234 context.coordinator.findRequest = findRequest
1235 DispatchQueue.main.async {
1236 view.window?.makeFirstResponder(view)
1237 let action = NSMenuItem()
1238 action.tag = NSTextFinder.Action.showFindInterface.rawValue
1239 view.performFindPanelAction(action)
1240 }
1241 }
1242 }
1243
1244 private func replaceText(in view: NSTextView) {
1245 view.string = text
1246 guard lineSpacing > 0, let style = view.defaultParagraphStyle, let storage = view.textStorage else { return }
1247 storage.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: storage.length))
1248 view.typingAttributes[.paragraphStyle] = style
1249 }
1250
1251 final class Coordinator: NSObject, NSTextViewDelegate {
1252 lazy var measurement: NSLayoutManager = {
1253 let layout = NSLayoutManager()
1254 layout.addTextContainer(NSTextContainer())
1255 return layout
1256 }()
1257 var parent: MacWritingTextView
1258 var findRequest = 0
1259 var focusRequest = 0
1260 init(_ parent: MacWritingTextView) { self.parent = parent }
1261 func textDidChange(_ notification: Notification) {
1262 if let view = notification.object as? NSTextView { parent.text = view.string }
1263 }
1264 func textViewDidChangeSelection(_ notification: Notification) {
1265 guard let view = notification.object as? MacDocumentTextView,
1266 view.enclosingScrollView?.isFindBarVisible == true,
1267 view.selectedRange().length > 0 else { return }
1268 view.scrollRangeToVisible(view.selectedRange())
1269 }
1270 func textDidEndEditing(_ notification: Notification) { parent.onFocusLost?() }
1271 }
1272}
1273#endif
1274
1275#if os(macOS)
1276private struct MacReplyWritingField<Count: View>: View {
1277 let title: String
1278 @Binding var text: String
1279 let identifier: String
1280 let count: Count
1281 @State private var findRequest = 0
1282 var body: some View {
1283 VStack(alignment: .leading, spacing: 5) {
1284 HStack(spacing: 9) {
1285 Text(title).font(.callout.weight(.semibold))
1286 Spacer()
1287 count
1288 Button { findRequest += 1 } label: { Image(systemName: "magnifyingglass") }
1289 .buttonStyle(.borderless)
1290 .help("Find in \(title.lowercased())")
1291 .accessibilityLabel("Find in \(title.lowercased())")
1292 }
1293 MacWritingTextView(text: $text, findRequest: findRequest, documentMinimumHeight: 41,
1294 textInsets: NSSize(width: 14, height: 10), lineSpacing: 4)
1295 .studioSurface()
1296 .accessibilityIdentifier(identifier)
1297 }
1298 }
1299}
1300#endif
1301
1302enum StudioRevisionRequestCopy {
1303 static let heading = "Revision requests"
1304 static let field = "Revision request"
1305 static let add = "Add revision request"
1306 static let send = "Send revision request"
1307 static let actedOn = "Acted on"
1308 static let ideaExample = "For example, focus this idea on one concrete claim."
1309 static let draftExample = "For example, tighten the opening and keep the source links."
1310}
1311
1312struct StudioWritingRequest: Identifiable {
1313 let id: String
1314 let text: String
1315 var state: String
1316 var date: String?
1317 var withdraw: (@MainActor () throws -> Void)?
1318
1319 init(id: String, text: String, state: String, date: String? = nil) {
1320 self.id = id
1321 self.text = text
1322 self.state = state
1323 self.date = date
1324 }
1325
1326 init(_ request: CompanionLibrary.RevisionRequest) {
1327 let state = switch request.state {
1328 case .actedOn: StudioRevisionRequestCopy.actedOn
1329 case .pending: "Waiting for your Mac to revise"
1330 case .waitingForEditable: "Waiting for an editable item"
1331 case .savedNote: "Saved note"
1332 }
1333 self.init(id: request.id, text: request.text, state: state, date: request.date)
1334 }
1335}
1336
1337struct StudioRevisionRequestRow: View {
1338 @Environment(\.studioPalette) private var palette
1339 let request: StudioWritingRequest
1340
1341 @State private var withdrawalError: String?
1342
1343 var body: some View {
1344 let actedOn = request.state == StudioRevisionRequestCopy.actedOn
1345 VStack(alignment: .leading, spacing: 5) {
1346 Text(request.text).textSelection(.enabled)
1347 HStack(spacing: 8) {
1348 if actedOn {
1349 Label(request.state, systemImage: "checkmark.circle.fill")
1350 .foregroundStyle(palette.success)
1351 } else {
1352 Text(request.state)
1353 }
1354 if let raw = request.date,
1355 let date = (try? Date(raw, strategy: .iso8601)) ??
1356 (try? Date(raw, strategy: Date.ISO8601FormatStyle(includingFractionalSeconds: true))) {
1357 Text(date, format: .dateTime.month(.abbreviated).day().hour().minute())
1358 }
1359 }
1360 .font(.footnote)
1361 .foregroundStyle(palette.muted)
1362 if let withdraw = request.withdraw {
1363 Button {
1364 do { try withdraw(); withdrawalError = nil }
1365 catch { withdrawalError = error.localizedDescription }
1366 } label: {
1367 Label("Withdraw request", systemImage: "arrow.uturn.backward")
1368 .font(.footnote.weight(.medium)).frame(minHeight: 44)
1369 }
1370 .buttonStyle(.borderless)
1371 .accessibilityLabel("Withdraw revision request: " + request.text)
1372 .accessibilityIdentifier("revision.withdraw." + request.id)
1373 }
1374 if let withdrawalError { Text(withdrawalError).font(.caption).foregroundStyle(palette.danger) }
1375 }
1376 }
1377}
1378
1379struct StudioWritingAssistant: View {
1380 let agent: String
1381 let requests: [StudioWritingRequest]
1382 var reply: String?
1383 var error: String?
1384 let submit: (String) throws -> Void
1385 @Environment(\.studioPalette) private var palette
1386 @State private var prompt = ""
1387 @State private var message: String?
1388 @State private var composing = false
1389 private var agentTitle: String {
1390 switch agent { case "claude", "anthropic": "Claude"; case "codex": "Codex"; case "openai": "OpenAI"; case "gemini", "antigravity": "Gemini"; default: "your agent" }
1391 }
1392 private var agentIcon: String { ["claude", "anthropic"].contains(agent) ? "claude-mark" : ["codex", "openai"].contains(agent) ? "openai-mark" : agent == "antigravity" ? "gemini" : agent }
1393 var body: some View {
1394 VStack(alignment: .leading, spacing: 12) {
1395 StudioPlatformLabel(name: agentIcon, title: "Ask \(agentTitle)")
1396 .font(.headline)
1397 Text("Your Mac applies the request using its writing connection. Every change is kept in revision history.")
1398 .font(.caption).foregroundStyle(palette.muted)
1399 if composing {
1400 TextField(StudioRevisionRequestCopy.field, text: $prompt,
1401 prompt: Text(StudioRevisionRequestCopy.draftExample), axis: .vertical)
1402 .lineLimit(3...6).textFieldStyle(.plain).padding(10)
1403 .studioSurface(StudioRadius.control, fill: palette.well)
1404 .accessibilityIdentifier("writing.prompt")
1405 HStack {
1406 Text("\(prompt.utf16.count)/1,000").font(.caption).foregroundStyle(palette.muted)
1407 Spacer()
1408 Button("Cancel") { composing = false }
1409 Button(StudioRevisionRequestCopy.send) { send(prompt) }
1410 .disabled(prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || prompt.utf16.count > 1_000)
1411 .accessibilityIdentifier("writing.send")
1412 }
1413 } else {
1414 Button(StudioRevisionRequestCopy.add, systemImage: "plus") { composing = true }
1415 .accessibilityIdentifier("writing.addRevisionRequest")
1416 }
1417 HStack {
1418 Button("Summarize this") { send("Summarize this draft into a concise brief, preserving the key facts and relevant links.") }
1419 Button("Tighten the writing") { send("Make this draft clearer and more concise while preserving my voice, facts and links.") }
1420 }.font(.caption)
1421 if let error { Text(error).font(.caption).foregroundStyle(palette.danger).accessibilityIdentifier("writing.error") }
1422 if let message { Text(message).font(.caption).foregroundStyle(palette.muted).accessibilityIdentifier("writing.status") }
1423 if !requests.isEmpty {
1424 ScrollView {
1425 VStack(alignment: .leading, spacing: 10) {
1426 ForEach(requests) { request in
1427 StudioRevisionRequestRow(request: request)
1428 .frame(maxWidth: .infinity, alignment: .leading).padding(10).studioSurface(fill: palette.well)
1429 }
1430 }
1431 }.frame(maxHeight: 160)
1432 }
1433 if let reply, !reply.isEmpty { Text(reply).font(.callout).accessibilityIdentifier("writing.reply") }
1434 }
1435 .foregroundStyle(palette.text)
1436 .onChange(of: reply) { message = nil }
1437 }
1438 private func send(_ text: String) {
1439 do {
1440 try submit(text.trimmingCharacters(in: .whitespacesAndNewlines))
1441 prompt = ""
1442 composing = false
1443 message = "Request saved. Your Mac will apply it while Inkspring is open."
1444 } catch { message = error.localizedDescription }
1445 }
1446}
1447
1448#if os(iOS)
1449struct MobileWritingTools: View {
1450 @Binding var title: String
1451 @Binding var text: String
1452 @Binding var presented: Bool
1453 let agent: String
1454 let providers: [CompanionLibrary.WritingProvider]?
1455 let requests: [StudioWritingRequest]
1456 var reply: String?
1457 var error: String?
1458 let request: (String, CompanionLibrary.WritingSelection?) throws -> Void
1459 @State private var tab = "Ask AI"
1460 @State private var selection: CompanionLibrary.WritingSelection?
1461 @Environment(\.studioPalette) private var palette
1462 var body: some View {
1463 Button("Writing tools", systemImage: "bubble.left.and.text.bubble.right") { presented = true }
1464 .accessibilityIdentifier("writing.tools")
1465 .popover(isPresented: $presented) {
1466 ScrollView {
1467 VStack(alignment: .leading, spacing: 16) {
1468 HStack {
1469 Text("Writing tools").font(.headline)
1470 Spacer()
1471 Button("Done") { presented = false }.accessibilityIdentifier("writing.close")
1472 }
1473 HStack(spacing: 4) {
1474 ForEach(["Ask AI", "Proofread"], id: \.self) { option in
1475 Button { tab = option } label: {
1476 Text(option).font(.subheadline.weight(.semibold))
1477 .frame(maxWidth: .infinity).padding(.vertical, 10)
1478 .background(tab == option ? palette.active : .clear, in: Capsule())
1479 }
1480 .buttonStyle(.plain)
1481 .accessibilityAddTraits(tab == option ? .isSelected : [])
1482 }
1483 }
1484 .padding(3).background(palette.well, in: Capsule())
1485 .overlay { Capsule().strokeBorder(palette.line).allowsHitTesting(false) }
1486 .accessibilityLabel("Writing tool")
1487 if tab == "Ask AI" {
1488 if let providers, !providers.isEmpty {
1489 MobileWritingPicker(providers: providers, preferredProvider: agent, selection: $selection)
1490 }
1491 let writer = MobileWritingPicker.resolved(selection, providers: providers, preferred: agent)
1492 StudioWritingAssistant(agent: writer?.provider ?? agent, requests: requests, reply: reply, error: error) {
1493 try request($0, writer)
1494 selection = nil
1495 }
1496 .disabled(!MobileWritingPicker.canSend(writer, providers: providers))
1497 } else {
1498 StudioProofreadAction(document: .init(title: title, body: text), unavailable: MobileProofreading.availabilityMessage,
1499 check: MobileProofreading.check) { title = $0.title; text = $0.body }
1500 }
1501 }.padding(20)
1502 }.frame(minWidth: 300, idealWidth: 380, minHeight: 350, idealHeight: 520).background(palette.canvas)
1503 }
1504 }
1505}
1506#endif