Skip to content

Add Highlightr for the Markdown.CodeBlockView #41

@erikbasargin

Description

@erikbasargin

Describe the solution you'd like

An example of how we could add the Highlightr

import Highlightr

Add to Markdown.CodeBlockView the next code:

var body: some View {
    switch unit.type {
    case let .codeBlock(_, code):
        if let lang = codeType {
            content(codeType: codeType, code: code)
        } else {
            content(code: code)
        }
    default:
        EmptyView()
    }
}

private func content(codeType: String?, code: String) -> some View {
    ScrollView(.horizontal, showsIndicators: true) {
        CodeView(codeType: codeType, code: code)
            .scaledToFit()
    }
    .padding([.leading, .top, .trailing], 12)
    .background(Color.background)
    .cornerRadius(6)
    .padding(.bottom, 3)
}

Example of the CodeView:

fileprivate struct CodeView: UIViewRepresentable {
    let codeType: String?
    let code: String

    init(codeType: String?, code: String) {
        self.codeType = codeType
        self.code = code
    }

    private var textStorage = CodeAttributedString()

    func makeUIView(context: Context) -> UITextView {
        textStorage.language = codeType?.lowercased()
        let layoutManager = NSLayoutManager()
        textStorage.addLayoutManager(layoutManager)

        let textContainer = NSTextContainer(size: .zero)
        layoutManager.addTextContainer(textContainer)

        let textView = UITextView(frame: .zero, textContainer: textContainer)
        textView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        textView.autocorrectionType = UITextAutocorrectionType.no
        textView.autocapitalizationType = UITextAutocapitalizationType.none
        textView.font = UIFont(name: "Menlo-Regular", size: 13)
        textView.textColor = UIColor(named: "codeBlockForeground")
        textView.isSelectable = true
        textView.isUserInteractionEnabled = true
        textView.isEditable = false
        textView.isScrollEnabled = false
        textView.dataDetectorTypes = .all
        textView.backgroundColor = .clear
        textView.textContainer.lineFragmentPadding = .zero
        textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
        textView.text = code

        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {}
}

Metadata

Metadata

Assignees

Labels

LowLow priorityfeatureNew feature or request

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions