Cotton code
279 lines · 11.9 KB · SwiftRaw
// The blocks drawn in the text: a picture at the column's full width, tapped// to open; a table as a real grid whose cells are written in place, a row or// a column added or taken away, sliding sideways when it is wider than the// column. Every change to a table is the core's (`table.*` asks); the grid// only says which cell and what was written.#if canImport(UIKit)import UIKit@MainActorprotocol WritingBlockView: UIView {    var key: String { get }    /// The block's height at `width`.    func height(for width: CGFloat) -> CGFloat}/// A picture in the text.@MainActorfinal class WritingImageBlock: UIView, WritingBlockView {    let key: String    let src: String    private let image = UIImageView()    private var aspect: CGFloat?    var onOpen: ((String) -> Void)?    /// A hold: the host offers the picture's widths.    var onHold: ((String) -> Void)?    /// Called when the picture arrived and its height changed.    var onSized: (() -> Void)?    /// The share of the column the picture stands at (small, medium, full: CONTRACT.md §8).    var share: CGFloat = 1    init(key: String, src: String, look: WritingLook) {        self.key = key        self.src = src        super.init(frame: .zero)        image.contentMode = .scaleAspectFill        image.clipsToBounds = true        image.layer.cornerRadius = 10        image.backgroundColor = look.theme.code        addSubview(image)        isAccessibilityElement = true        accessibilityTraits = [.image, .button]        accessibilityIdentifier = "writing-image"        addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped)))        addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(held(_:))))    }    @objc private func held(_ press: UILongPressGestureRecognizer) {        guard press.state == .began else { return }        UIImpactFeedbackGenerator(style: .light).impactOccurred()        onHold?(src)    }    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }    func load(from store: (any WritingMedia)?, width: CGFloat) {        guard let store, aspect == nil else { return }        let src = src        Task { [weak self] in            let picture = await store.image(src, width: width)            guard let self, let picture, picture.size.width > 0 else { return }            image.image = picture            aspect = picture.size.height / picture.size.width            onSized?()        }    }    func height(for width: CGFloat) -> CGFloat {        guard let aspect else { return WritingLayoutManager.pending }        let w = width * share        return min(w * aspect, w * 1.6).rounded()    }    override func layoutSubviews() {        super.layoutSubviews()        // At its width, from the column's start.        image.frame = CGRect(x: 0, y: 0, width: (bounds.width * share).rounded(), height: bounds.height)    }    @objc private func tapped() { onOpen?(src) }}/// A table in the text.@MainActorfinal class WritingTableBlock: UIView, WritingBlockView, UITextFieldDelegate {    let key: String    private(set) var table: WritingTable    private let look: WritingLook    private let words: WritingWords    private let scroll = UIScrollView()    private let grid = UIView()    private var fields: [[UITextField]] = []    private var widths: [CGFloat] = []    static let rowHeight: CGFloat = 44    static let addSize: CGFloat = 32    /// A table key (`table_cell`, `table_row_add`, …), the selection it is    /// pressed at (a cell's own range), and its value (a cell's words).    var onAsk: ((WritingAction, NSRange) -> Void)?    /// Return in the last cell: the editor puts the keyboard away the app's one way.    var onPutAway: (() -> Void)?    init(key: String, table: WritingTable, look: WritingLook, words: WritingWords) {        self.key = key        self.table = table        self.look = look        self.words = words        super.init(frame: .zero)        scroll.showsHorizontalScrollIndicator = true        scroll.accessibilityIdentifier = "writing-table"        addSubview(scroll)        scroll.addSubview(grid)        build()    }    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }    /// The core read the table again: its cells are written in, a cell being    /// written keeps its words.    func update(_ table: WritingTable) {        let shapeChanged = table.rows.count != self.table.rows.count || table.columns != self.table.columns        let wordsChanged = table.words != self.table.words        self.table = table        if shapeChanged { build() } else if wordsChanged {            for (r, row) in table.rows.enumerated() {                for (c, cell) in row.enumerated() where r < fields.count && c < fields[r].count {                    if !fields[r][c].isFirstResponder { fields[r][c].text = cell.text }                }            }        }    }    func height(for width: CGFloat) -> CGFloat {        CGFloat(table.rows.count) * Self.rowHeight + Self.addSize + 6    }    private func build() {        grid.subviews.forEach { $0.removeFromSuperview() }        fields = []        let columns = max(1, table.columns)        let body = look.font([])        let head = look.font(.bold)        widths = (0..<columns).map { c in            let widest = table.rows.enumerated().map { r, row -> CGFloat in                let said = c < row.count ? row[c].text : ""                return (said as NSString).size(withAttributes: [.font: r == 0 ? head : body]).width            }.max() ?? 0            return min(260, max(88, widest + 28))        }        var y: CGFloat = 0        for (r, row) in table.rows.enumerated() {            var x: CGFloat = 0            var line: [UITextField] = []            for c in 0..<columns {                let field = UITextField(frame: CGRect(x: x, y: y, width: widths[c], height: Self.rowHeight))                field.text = c < row.count ? row[c].text : ""                field.font = r == 0 ? head : body                field.textColor = look.theme.ink                field.adjustsFontForContentSizeCategory = true                field.textAlignment = alignment(c)                field.delegate = self                field.tag = r * 10_000 + c                field.returnKeyType = .next                field.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 1))                field.leftViewMode = .always                field.rightView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 1))                field.rightViewMode = .always                field.backgroundColor = r == 0 ? look.theme.code : .clear                field.layer.borderColor = look.theme.rule.cgColor                field.layer.borderWidth = 0.5                field.accessibilityLabel = words.cell(r + 1, c + 1)                field.accessibilityIdentifier = "writing-table-cell-\(r)-\(c)"                field.addInteraction(UIContextMenuInteraction(delegate: self))                grid.addSubview(field)                line.append(field)                x += widths[c]            }            fields.append(line)            y += Self.rowHeight        }        let width = widths.reduce(0, +)        let addRow = button(words.word("add_row"), identifier: "writing-table-add-row") { [weak self] in            guard let self, let last = table.rows.last?.first else { return }            onAsk?(WritingAction("table_row_add"), NSRange(location: last.start, length: 0))        }        addRow.frame = CGRect(x: 0, y: y + 4, width: Self.addSize, height: Self.addSize)        let addColumn = button(words.word("add_column"), identifier: "writing-table-add-column") { [weak self] in            guard let self, let last = table.rows.first?.last else { return }            onAsk?(WritingAction("table_column_add"), NSRange(location: last.start, length: 0))        }        addColumn.frame = CGRect(x: width + 4, y: 0, width: Self.addSize, height: Self.addSize)        grid.frame = CGRect(x: 0, y: 0, width: width + Self.addSize + 8, height: y + Self.addSize + 6)        scroll.contentSize = grid.frame.size    }    private func alignment(_ column: Int) -> NSTextAlignment {        switch column < table.align.count ? table.align[column] : "none" {        case "center": .center        case "right": .right        default: .natural        }    }    private func button(_ label: String, identifier: String, _ action: @escaping () -> Void) -> UIButton {        let button = UIButton(type: .system, primaryAction: UIAction { _ in action() })        button.setImage(UIImage(systemName: "plus", withConfiguration: UIImage.SymbolConfiguration(pointSize: 13, weight: .semibold)), for: .normal)        button.tintColor = look.theme.accent        button.backgroundColor = look.theme.chip        button.layer.cornerRadius = Self.addSize / 2        button.accessibilityLabel = label        button.accessibilityIdentifier = identifier        grid.addSubview(button)        return button    }    override func layoutSubviews() {        super.layoutSubviews()        scroll.frame = bounds    }    // MARK: Cells    fileprivate func cell(of field: UITextField) -> (row: Int, column: Int) { (field.tag / 10_000, field.tag % 10_000) }    /// Where a cell's words stand in the text: the selection its keys are pressed at.    fileprivate func at(_ row: Int, _ column: Int) -> NSRange {        guard row < table.rows.count else { return NSRange(location: table.start, length: 0) }        let cells = table.rows[row]        guard let cell = column < cells.count ? cells[column] : cells.last else { return NSRange(location: table.start, length: 0) }        return NSRange(location: cell.start, length: max(0, cell.end - cell.start))    }    func textFieldDidEndEditing(_ field: UITextField) {        let (row, column) = cell(of: field)        let old = row < table.rows.count && column < table.rows[row].count ? table.rows[row][column].text : ""        let said = field.text ?? ""        guard said != old else { return }        onAsk?(WritingAction("table_cell", ["row": .number(Double(row)), "column": .number(Double(column)), "text": .text(said)]), at(row, column))    }    func textFieldShouldReturn(_ field: UITextField) -> Bool {        let (row, column) = cell(of: field)        if column + 1 < (fields[safe: row]?.count ?? 0) {            fields[row][column + 1].becomeFirstResponder()        } else if row + 1 < fields.count {            fields[row + 1][0].becomeFirstResponder()        } else {            onPutAway?()        }        return false    }}extension WritingTableBlock: UIContextMenuInteractionDelegate {    func contextMenuInteraction(_ interaction: UIContextMenuInteraction,                                configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {        guard let field = interaction.view as? UITextField else { return nil }        let (row, column) = cell(of: field)        let here = at(row, column)        let words = words        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { [weak self] _ in            UIMenu(children: [                UIAction(title: words.word("add_row"), image: UIImage(systemName: "plus")) { _ in self?.onAsk?(WritingAction("table_row_add"), here) },                UIAction(title: words.word("add_column"), image: UIImage(systemName: "plus")) { _ in self?.onAsk?(WritingAction("table_column_add"), here) },                UIAction(title: words.word("remove_row"), image: UIImage(systemName: "minus"), attributes: .destructive) { _ in                    self?.onAsk?(WritingAction("table_row_remove"), here)                },                UIAction(title: words.word("remove_column"), image: UIImage(systemName: "minus"), attributes: .destructive) { _ in                    self?.onAsk?(WritingAction("table_column_remove"), here)                },            ])        }    }}extension Array {    subscript(safe index: Int) -> Element? { indices.contains(index) ? self[index] : nil }}#endif