#if os(iOS) import RastrilloApple import SwiftUI import UIKit /// What the iPhone document's text view needs from its window, created once /// per document window and compared by identity: the header's state, the /// keyboard bar's model, and how Aa opens the Format sheet. @MainActor final class DocsPhoneEditorChrome { let model: DocsModel let team: String? let header = DocumentHeaderState() /// Aa, from the keyboard bar. var openFormat: () -> Void = {} init(model: DocsModel, team: String?) { self.model = model; self.team = team } /// The keyboard bar: a `UIInputView` hosting the SwiftUI capsule (spec /// §3, "Keyboard bar"), never `ToolbarItemGroup(placement: .keyboard)`, /// which does not attach reliably to a wrapped UITextView. func makeKeyboardBar(hide: @escaping () -> Void) -> UIView { let input = UIInputView(frame: CGRect(x: 0, y: 0, width: 320, height: 60), inputViewStyle: .keyboard) input.allowsSelfSizing = true let host = UIHostingController(rootView: DocsKeyboardBar(model: model, openFormat: { [weak self] in self?.openFormat() }, hide: hide)) host.view.backgroundColor = .clear host.view.translatesAutoresizingMaskIntoConstraints = false host.sizingOptions = [.intrinsicContentSize] // With a hardware keyboard the bar sits on the bottom edge, over the // home indicator: the screen's inset is not the bar's to pad. host.safeAreaRegions = [] input.addSubview(host.view) NSLayoutConstraint.activate([ host.view.leadingAnchor.constraint(equalTo: input.leadingAnchor), host.view.trailingAnchor.constraint(equalTo: input.trailingAnchor), host.view.topAnchor.constraint(equalTo: input.topAnchor), host.view.bottomAnchor.constraint(equalTo: input.bottomAnchor), ]) objc_setAssociatedObject(input, &DocsPhoneEditorChrome.hostKey, host, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return input } /// The bar's hosting controller (tests). static func host(of bar: UIView) -> UIHostingController? { objc_getAssociatedObject(bar, &hostKey) as? UIHostingController } nonisolated(unsafe) private static var hostKey = 0 } /// The quick format bar above the keyboard, a writer's: Aa, Bold, Italic, /// Bulleted list, Numbered list, Quote, then Hide keyboard. Marks and lists /// show `.isSelected` from `DocumentToolbarSelection`; targets are 44pt, and /// at accessibility sizes the capsule scrolls rather than shrinking. @MainActor struct DocsKeyboardBar: View { let model: DocsModel let openFormat: () -> Void let hide: () -> Void var body: some View { let selection = model.toolbarSelection ScrollView(.horizontal) { HStack(spacing: 0) { button("docs.editor.inspector.toggle", identifier: "docs.keyboard.format", selected: false) { Text(verbatim: "Aa").font(.body.weight(.semibold)) } action: { openFormat() } symbol("docs.editor.toolbar.bold", "bold", identifier: "docs.keyboard.bold", selected: selection.marks.contains("strong")) { ready { $0.perform("bold") } } symbol("docs.editor.toolbar.italic", "italic", identifier: "docs.keyboard.italic", selected: selection.marks.contains("em")) { ready { $0.perform("italic") } } symbol("docs.editor.toolbar.bulletlist", "list.bullet", identifier: "docs.keyboard.bullets", selected: selection.blocks.contains("bullet_list")) { ready { $0.block("bullet_list") } } symbol("docs.editor.toolbar.orderedlist", "list.number", identifier: "docs.keyboard.numbers", selected: selection.blocks.contains("ordered_list")) { ready { $0.block("ordered_list") } } symbol("docs.editor.toolbar.quote", "text.quote", identifier: "docs.keyboard.quote", selected: selection.blocks.contains("blockquote")) { ready { $0.block("blockquote") } } Rectangle().fill(OficinaPalette.line).frame(width: 1, height: 24).padding(.horizontal, DocsSpacing.sp1) symbol("native.keyboard.hide", "keyboard.chevron.compact.down", identifier: "docs.keyboard.hide", selected: false) { hide() } } .padding(.horizontal, DocsSpacing.sp1) .background(Capsule().fill(OficinaPalette.surface).shadow(color: .black.opacity(0.12), radius: 8, y: 2)) .padding(.horizontal, DocsSpacing.sp2) .padding(.vertical, DocsSpacing.sp1) } .scrollIndicators(.hidden) .scrollBounceBehavior(.basedOnSize, axes: .horizontal) .disabled(model.commandsHeld) .accessibilityElement(children: .contain) .accessibilityIdentifier("docs.keyboard.bar") } private func ready(_ command: @escaping @MainActor (DocumentCommands) -> Void) { model.whenCommandsReady(command) } private func symbol(_ key: String, _ name: String, identifier: String, selected: Bool, action: @escaping () -> Void) -> some View { button(key, identifier: identifier, selected: selected) { Image(systemName: name).font(.body.weight(.medium)) } action: { action() } } private func button(_ key: String, identifier: String, selected: Bool, @ViewBuilder label: () -> Label, action: @escaping () -> Void) -> some View { Button(action: action) { label() .frame(minWidth: 44, minHeight: 44) .foregroundStyle(selected ? OficinaPalette.accent(.docs) : OficinaPalette.text) .background(Circle().fill(selected ? OficinaPalette.accentSoft(.docs) : .clear).frame(width: 38, height: 38)) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle)) .accessibilityAddTraits(selected ? .isSelected : []) .accessibilityIdentifier(identifier) } } /// The Format sheet (Paul's ruling 3; spec §3, "Format sheet"): the web /// inspector's sections in one screen at the default size, at the `.medium` /// detent with the text still live above it. Every control applies to the /// current selection and the sheet stays up. @MainActor struct DocsFormatSheet: View { let model: DocsModel let close: () -> Void @Environment(\.dynamicTypeSize) private var typeSize @Environment(\.locale) private var locale static let sizes = [8, 9, 10, 11, 12, 14, 18, 24, 36, 48, 72] var body: some View { let selection = model.toolbarSelection let twoRows = typeSize >= .accessibility1 ScrollView { VStack(alignment: .leading, spacing: DocsSpacing.sp4) { HStack { Text("docs.editor.inspector.label", bundle: DocsResources.bundle) .font(.title3.bold()) .accessibilityAddTraits(.isHeader) Spacer() Button(action: close) { Image(systemName: "xmark").font(.body.weight(.semibold)) .frame(width: 44, height: 44) .background(Circle().fill(OficinaPalette.sunk).frame(width: 32, height: 32)) } .buttonStyle(.plain) .accessibilityLabel(Text("native.close", bundle: DocsResources.bundle)) .accessibilityIdentifier("docs.format.close") } section("docs.editor.toolbar.group.style") { styles(selection) } section("docs.editor.toolbar.font") { fontAndSize(selection, twoRows: twoRows) } section("docs.editor.toolbar.group.text") { rows(twoRows, [ DocsSheetSegment(key: "docs.editor.toolbar.bold", icon: "bold", on: selection.marks.contains("strong"), identifier: "docs.format.bold") { ready { $0.perform("bold") } }, DocsSheetSegment(key: "docs.editor.toolbar.italic", icon: "italic", on: selection.marks.contains("em"), identifier: "docs.format.italic") { ready { $0.perform("italic") } }, DocsSheetSegment(key: "docs.editor.toolbar.code", icon: "chevron.left.forwardslash.chevron.right", on: selection.marks.contains("code"), identifier: "docs.format.code") { ready { $0.perform("code") } }, ], ["left", "center", "right"].map { value in DocsSheetSegment(key: "docs.editor.toolbar.align." + value, icon: "text.align" + value, on: selection.alignment == value, identifier: "docs.format.align." + value) { ready { $0.blockAttribute("align", value: value == "left" ? nil : value) } } }) } section("docs.editor.toolbar.group.lists") { rows(twoRows, [ DocsSheetSegment(key: "docs.editor.toolbar.bulletlist", icon: "list.bullet", on: selection.blocks.contains("bullet_list"), identifier: "docs.format.bullets") { ready { $0.block("bullet_list") } }, DocsSheetSegment(key: "docs.editor.toolbar.orderedlist", icon: "list.number", on: selection.blocks.contains("ordered_list"), identifier: "docs.format.numbers") { ready { $0.block("ordered_list") } }, DocsSheetSegment(key: "docs.editor.toolbar.quote", icon: "text.quote", on: selection.blocks.contains("blockquote"), identifier: "docs.format.quote") { ready { $0.block("blockquote") } }, ], [ DocsSheetSegment(key: "docs.editor.menu.format.outdent", icon: "decrease.indent", on: false, mirrors: true, identifier: "docs.format.outdent") { ready { $0.perform("outdent") } }, DocsSheetSegment(key: "docs.editor.menu.format.indent", icon: "increase.indent", on: false, mirrors: true, identifier: "docs.format.indent") { ready { $0.perform("indent") } }, DocsSheetSegment(key: "docs.editor.menu.format.clear", icon: "eraser", on: false, enabled: selection.hasSelection, identifier: "docs.format.clear") { ready { $0.perform("clear-format") } }, ]) } } .padding(.horizontal, DocsSpacing.sp5) .padding(.top, DocsSpacing.sp4) .padding(.bottom, DocsSpacing.sp5) } .scrollBounceBehavior(.basedOnSize) .disabled(model.commandsHeld) .accessibilityElement(children: .contain) .accessibilityLabel(Text("docs.editor.inspector.label", bundle: DocsResources.bundle)) .accessibilityIdentifier("docs.format.sheet") } private func ready(_ command: @escaping @MainActor (DocumentCommands) -> Void) { model.whenCommandsReady(command) } private func section(_ key: String, @ViewBuilder content: () -> Content) -> some View { VStack(alignment: .leading, spacing: DocsSpacing.sp2) { Text(LocalizedStringKey(key), bundle: DocsResources.bundle) .font(.footnote.weight(.semibold)) .foregroundStyle(OficinaPalette.textMuted) .accessibilityAddTraits(.isHeader) content() } .accessibilityElement(children: .contain) .accessibilityLabel(Text(LocalizedStringKey(key), bundle: DocsResources.bundle)) } /// Body text and Heading 1–3 as chips, each in its own face; the current /// one outlined in the accent. They wrap onto more rows when they do not /// fit (spec §9: the sheet re-flows, nothing is clipped). private func styles(_ selection: DocumentToolbarSelection) -> some View { let strings = DocsStrings(locale: locale) let entries: [(id: String, key: String, size: CGFloat, heading: Bool)] = [ ("paragraph", "docs.editor.toolbar.block.paragraph", 17, false), ("heading1", EditorToolbar.headingKey(1), 24, true), ("heading2", EditorToolbar.headingKey(2), 20, true), ("heading3", EditorToolbar.headingKey(3), 17, true), ] return DocsFlowLayout(spacing: DocsSpacing.sp2) { ForEach(entries, id: \.id) { entry in let on = selection.style == entry.id Button { if entry.heading, let level = Int(entry.id.dropFirst("heading".count)) { ready { $0.block("heading", level: level) } } else { ready { $0.block("paragraph") } } } label: { Text(verbatim: strings(entry.key)) // The style's own face, scaling with Dynamic // Type from its size (spec §9). .font(.custom(DocsFonts.font(marks: [:], size: entry.size, heading: entry.heading).fontName, size: entry.size, relativeTo: .body)) // Whole at every size: a chip wider than the // row wraps its words. .fixedSize(horizontal: false, vertical: true) .padding(.horizontal, DocsSpacing.sp4) .frame(minHeight: 52) .foregroundStyle(on ? OficinaPalette.accent(.docs) : OficinaPalette.text) .background(RoundedRectangle(cornerRadius: 14).fill(on ? OficinaPalette.accentSoft(.docs) : OficinaPalette.sunk)) .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(on ? OficinaPalette.accent(.docs) : .clear, lineWidth: 1.5)) } .buttonStyle(.plain) .accessibilityAddTraits(on ? .isSelected : []) .accessibilityIdentifier("docs.format.style." + entry.id) } } } /// The font picker (families in their own faces), then the size: − the /// value + over the eleven sizes. @ViewBuilder private func fontAndSize(_ selection: DocumentToolbarSelection, twoRows: Bool) -> some View { let layout = twoRows ? AnyLayout(VStackLayout(alignment: .leading, spacing: DocsSpacing.sp2)) : AnyLayout(HStackLayout(spacing: DocsSpacing.sp2)) layout { DocsFontPickerButton(selected: selection.font) { key in ready { $0.setFont(key) } } .padding(.horizontal, DocsSpacing.sp3) .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading) .background(RoundedRectangle(cornerRadius: 12).strokeBorder(OficinaPalette.line, lineWidth: 1)) stepper(selection.size) } } private func stepper(_ size: Int) -> some View { let sizes = Self.sizes let index = sizes.firstIndex(of: size) ?? sizes.firstIndex { $0 > size }.map { max(0, $0 - 1) } ?? sizes.count - 1 func set(_ value: Int) { ready { $0.format("size_" + String(value), exclusive: sizes.map { "size_" + String($0) } + ["size_sm", "size_lg", "size_xl"]) } } return HStack(spacing: 0) { Button { if index > 0 { set(sizes[index - 1]) } } label: { Image(systemName: "minus").frame(width: 44, height: 44).contentShape(Rectangle()) } .disabled(index == 0) .accessibilityLabel(Text("native.format.size.smaller", bundle: DocsResources.bundle)) .accessibilityIdentifier("docs.format.size.smaller") Text(size.formatted(.number.locale(locale))) .font(.body.monospacedDigit()) .frame(minWidth: 36) .accessibilityLabel(Text("docs.editor.toolbar.size", bundle: DocsResources.bundle)) .accessibilityValue(Text(size.formatted(.number.locale(locale)))) Button { if index + 1 < sizes.count { set(sizes[index + 1]) } } label: { Image(systemName: "plus").frame(width: 44, height: 44).contentShape(Rectangle()) } .disabled(index + 1 >= sizes.count) .accessibilityLabel(Text("native.format.size.larger", bundle: DocsResources.bundle)) .accessibilityIdentifier("docs.format.size.larger") } .buttonStyle(.plain) .foregroundStyle(OficinaPalette.text) .background(RoundedRectangle(cornerRadius: 12).fill(OficinaPalette.sunk)) .fixedSize() } /// Two groups on one row, or one each from AX1 (spec §9). private func rows(_ twoRows: Bool, _ first: [DocsSheetSegment], _ second: [DocsSheetSegment]) -> some View { let layout = twoRows ? AnyLayout(VStackLayout(spacing: DocsSpacing.sp2)) : AnyLayout(HStackLayout(spacing: DocsSpacing.sp2)) return layout { DocsSheetSegmentRow(items: first) DocsSheetSegmentRow(items: second) } } } /// One button of a joined row in the Format sheet. struct DocsSheetSegment { let key: String let icon: String let on: Bool var mirrors = false var enabled = true let identifier: String let action: @MainActor () -> Void } /// A joined row of 44pt buttons: Bold, Italic, Code and the like. @MainActor struct DocsSheetSegmentRow: View { let items: [DocsSheetSegment] var body: some View { HStack(spacing: 2) { ForEach(items, id: \.identifier) { item in Button { item.action() } label: { Image(systemName: item.icon) .font(.body.weight(.medium)) .flipsForRightToLeftLayoutDirection(item.mirrors) .frame(maxWidth: .infinity, minHeight: 44) .foregroundStyle(item.on ? OficinaPalette.accent(.docs) : OficinaPalette.text) .background(RoundedRectangle(cornerRadius: 10).fill(item.on ? OficinaPalette.accentSoft(.docs) : .clear)) .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(item.on ? OficinaPalette.accent(.docs) : .clear, lineWidth: 1.5)) .contentShape(Rectangle()) } .buttonStyle(.plain) .disabled(!item.enabled) .opacity(item.enabled ? 1 : 0.4) .accessibilityLabel(Text(LocalizedStringKey(item.key), bundle: DocsResources.bundle)) .accessibilityAddTraits(item.on ? .isSelected : []) .accessibilityIdentifier(item.identifier) } } .padding(2) .background(RoundedRectangle(cornerRadius: 12).fill(OficinaPalette.sunk)) } } /// Its subviews left to right (leading to trailing), onto a new row when /// the next would not fit; one wider than a row is offered the row's width. struct DocsFlowLayout: Layout { var spacing: CGFloat private func rows(_ subviews: Subviews, width: CGFloat) -> [[(index: Int, size: CGSize)]] { var rows: [[(index: Int, size: CGSize)]] = [[]] var x: CGFloat = 0 for index in subviews.indices { var size = subviews[index].sizeThatFits(.unspecified) if size.width > width { size = subviews[index].sizeThatFits(ProposedViewSize(width: width, height: nil)) } if !rows[rows.count - 1].isEmpty, x + spacing + size.width > width { rows.append([]); x = 0 } x += (rows[rows.count - 1].isEmpty ? 0 : spacing) + size.width rows[rows.count - 1].append((index, size)) } return rows } func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { let rows = rows(subviews, width: proposal.width ?? .infinity) let widths = rows.map { row in row.reduce(0) { $0 + $1.size.width } + spacing * CGFloat(max(row.count - 1, 0)) } let heights = rows.map { row in row.map(\.size.height).max() ?? 0 } return CGSize(width: proposal.width ?? widths.max() ?? 0, height: heights.reduce(0, +) + spacing * CGFloat(max(rows.count - 1, 0))) } func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { var y = bounds.minY for row in rows(subviews, width: bounds.width) { var x = bounds.minX for item in row { subviews[item.index].place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(item.size)) x += item.size.width + spacing } y += (row.map(\.size.height).max() ?? 0) + spacing } } } #endif