Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions Sources/Textual/InlineText/InlineText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ import SwiftUI
/// .textual.inlineStyle(style)
/// ```
public struct InlineText: View {
@State private var attributedString = AttributedString()
@State private var parsedMarkup = Memo<String, AttributedString>()

private let markup: String
private let parser: any MarkupParser
Expand All @@ -111,16 +111,17 @@ public struct InlineText: View {
}

public var body: some View {
WithAttachments(attributedString) {
WithAttachments(parsedMarkup.value(for: markup, derive: parse)) {
WithInlineStyle($0) {
TextFragment($0)
.modifier(TextSelectionInteraction())
}
}
.coordinateSpace(.textContainer)
.onChange(of: markup, initial: true) { _, value in
self.attributedString = (try? parser.attributedString(for: value)) ?? .init()
}
}

private func parse(_ markup: String) -> AttributedString {
(try? parser.attributedString(for: markup)) ?? .init()
}
}

Expand Down
27 changes: 27 additions & 0 deletions Sources/Textual/Internal/Helpers/Memo.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import Foundation

// MARK: - Overview
//
// `Memo` keeps the last value derived from an input. A view holds one in `@State` to derive a
// value in `body`, so the value is ready on the view's first layout pass and is derived again only
// when the input changes.
//
// Deriving in `body`, instead of writing `@State` from `onChange(of:initial:)`, matters when a
// container measures a view before its state settles. A `List` sizes its rows in a pass of their
// own, so a value that only arrives through `onChange` changes the row's height after the list
// measured it.

@MainActor
final class Memo<Input: Equatable, Output> {
private var last: (input: Input, output: Output)?

func value(for input: Input, derive: (Input) -> Output) -> Output {
if let last, last.input == input {
return last.output
}

let output = derive(input)
last = (input, output)
return output
}
}
19 changes: 11 additions & 8 deletions Sources/Textual/Internal/InlineText/WithInlineStyle.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ struct WithInlineStyle<Content: View>: View {
@Environment(\.inlineStyle) private var style
@Environment(\.textEnvironment) private var environment

@State private var output: AttributedString?
@State private var output = Memo<
Tuple<AttributedString, InlineStyle, TextEnvironmentValues>, AttributedString
>()

private let input: AttributedString
private let content: (AttributedString) -> Content
Expand All @@ -33,21 +35,22 @@ struct WithInlineStyle<Content: View>: View {
}

var body: some View {
content(output ?? AttributedString())
.onChange(of: Tuple(input, style, environment), initial: true) { _, newValue in
content(
output.value(for: Tuple(input, style, environment)) {
resolve(
attributedString: newValue.values.0,
style: newValue.values.1,
in: newValue.values.2
attributedString: $0.values.0,
style: $0.values.1,
in: $0.values.2
)
}
)
}

private func resolve(
attributedString: AttributedString,
style: InlineStyle,
in environment: TextEnvironmentValues
) {
) -> AttributedString {
var output = attributedString

for run in attributedString.runs {
Expand Down Expand Up @@ -78,6 +81,6 @@ struct WithInlineStyle<Content: View>: View {
output[run.range].mergeAttributes(attributes, mergePolicy: .keepNew)
}

self.output = output
return output
}
}
21 changes: 10 additions & 11 deletions Sources/Textual/Internal/StructuredText/BlockQuote.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,17 @@ extension StructuredText {
}

var body: some View {
let configuration = BlockStyleConfiguration(
label: .init(
BlockContent(
parent: intent,
content: content
)
),
indentationLevel: indentationLevel
)
let resolvedStyle = blockQuoteStyle.resolve(configuration: configuration)
Group(subviews: BlockContent(parent: intent, content: content)) { label in
let configuration = BlockStyleConfiguration(
label: .init(label),
indentationLevel: indentationLevel
)
let resolvedStyle = blockQuoteStyle.resolve(configuration: configuration)

AnyView(resolvedStyle)
AnyView(resolvedStyle)
// The style can place the label inside a container, which hides its spacing
.containerValue(\.nestedBlockSpacing, label.blockSpacing)
}
}

private var indentationLevel: Int {
Expand Down
30 changes: 30 additions & 0 deletions Sources/Textual/Internal/StructuredText/BlockSpacingKey.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
import SwiftUI

// MARK: - Overview
//
// A block sets its spacing with `textual.blockSpacing(_:)`, which a `BlockVStack` reads in two
// ways:
//
// - As container values, which the stack reads in the same pass as the block. `blockSpacing` holds
// the spacing a block sets on its root view. `nestedBlockSpacing` holds the spacing of the blocks
// inside a block, such as the paragraphs in a list or a block quote.
// - As a preference, which also reaches the stack from views inside containers, but only after the
// first layout pass. When it arrives, it replaces the container values.

extension StructuredText {
struct BlockSpacingKey: PreferenceKey, LayoutValueKey {
static let defaultValue = BlockSpacing()
Expand All @@ -9,3 +20,22 @@ extension StructuredText {
}
}
}

extension ContainerValues {
@Entry var blockSpacing: StructuredText.BlockSpacing? = nil
@Entry var nestedBlockSpacing = StructuredText.BlockSpacing()
}

extension Subview {
/// The spacing the block sets on its root view, otherwise the spacing of the blocks inside it.
var blockSpacing: StructuredText.BlockSpacing {
containerValues.blockSpacing ?? containerValues.nestedBlockSpacing
}
}

extension SubviewsCollection {
/// The spacing of these blocks combined, which the block that contains them takes.
var blockSpacing: StructuredText.BlockSpacing {
reduce(StructuredText.BlockSpacing()) { $0.union($1.blockSpacing) }
}
}
26 changes: 19 additions & 7 deletions Sources/Textual/Internal/StructuredText/BlockVStack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import SwiftUI
//
// List items can override block spacing with environment-driven list item spacing for consistent
// spacing within lists regardless of individual block preferences.
//
// The stack passes the spacing of its blocks on to the block that contains it, so a list or a
// block quote has the spacing of its content from the first layout pass.

extension StructuredText {
struct BlockVStack<Content: View>: View {
Expand All @@ -26,6 +29,7 @@ extension StructuredText {
BlockLayoutView($0)
}
}
.containerValue(\.nestedBlockSpacing, children.blockSpacing)
}
}
}
Expand All @@ -36,27 +40,35 @@ extension StructuredText {
static let defaultValue: TextAlignment? = nil
}

fileprivate struct BlockLayoutView<Content: View>: View {
fileprivate struct BlockLayoutView: View {
@Environment(\.listItemSpacingEnabled) private var listItemSpacingEnabled
@Environment(\.resolvedListItemSpacing) private var resolvedListItemSpacing

@State private var blockSpacing = BlockSpacing()
@State private var preferredBlockSpacing: BlockSpacing?

private let content: Content
private let content: Subview

init(_ content: Content) {
init(_ content: Subview) {
self.content = content
}

var body: some View {
// Read the block spacing preference and apply it as a layout value
content
.onPreferenceChange(BlockSpacingKey.self) { @MainActor value in
// Override with the resolved list item spacing if enabled
blockSpacing = listItemSpacingEnabled ? resolvedListItemSpacing : value
preferredBlockSpacing = value
}
.layoutValue(key: BlockSpacingKey.self, value: blockSpacing)
}

private var blockSpacing: BlockSpacing {
// Override with the resolved list item spacing if enabled
if listItemSpacingEnabled {
return resolvedListItemSpacing
}
// The preference also covers spacing set inside containers, but it arrives after the first
// layout pass, so until then use the spacing from the container values
return preferredBlockSpacing ?? content.blockSpacing
}
}

fileprivate struct BlockVStackLayout: Layout {
Expand Down
23 changes: 11 additions & 12 deletions Sources/Textual/Internal/StructuredText/OrderedList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,19 +64,18 @@ extension StructuredText {
}

var body: some View {
let configuration = ListItemStyleConfiguration(
marker: .init(marker),
block: .init(
BlockContent(
parent: intent,
content: content
)
),
indentationLevel: indentationLevel
)
let resolvedStyle = listItemStyle.resolve(configuration: configuration)
Group(subviews: BlockContent(parent: intent, content: content)) { block in
let configuration = ListItemStyleConfiguration(
marker: .init(marker),
block: .init(block),
indentationLevel: indentationLevel
)
let resolvedStyle = listItemStyle.resolve(configuration: configuration)

AnyView(resolvedStyle)
AnyView(resolvedStyle)
// The style can place the block inside a container, which hides its spacing
.containerValue(\.nestedBlockSpacing, block.blockSpacing)
}
}

private var marker: some View {
Expand Down
23 changes: 11 additions & 12 deletions Sources/Textual/Internal/StructuredText/UnorderedList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,18 @@ extension StructuredText {
}

var body: some View {
let configuration = ListItemStyleConfiguration(
marker: .init(marker),
block: .init(
BlockContent(
parent: intent,
content: content
)
),
indentationLevel: indentationLevel
)
let resolvedStyle = listItemStyle.resolve(configuration: configuration)
Group(subviews: BlockContent(parent: intent, content: content)) { block in
let configuration = ListItemStyleConfiguration(
marker: .init(marker),
block: .init(block),
indentationLevel: indentationLevel
)
let resolvedStyle = listItemStyle.resolve(configuration: configuration)

AnyView(resolvedStyle)
AnyView(resolvedStyle)
// The style can place the block inside a container, which hides its spacing
.containerValue(\.nestedBlockSpacing, block.blockSpacing)
}
}

private var marker: some View {
Expand Down
17 changes: 7 additions & 10 deletions Sources/Textual/Internal/TextFragment/TextFragment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import SwiftUI

struct TextFragment<Content: AttributedStringProtocol>: View {
@Environment(\.textEnvironment) private var textEnvironment
@State private var textBuilder: TextBuilder?
@State private var textBuilder = Memo<Content, TextBuilder>()

private let content: Content

Expand All @@ -36,23 +36,20 @@ struct TextFragment<Content: AttributedStringProtocol>: View {
}

var body: some View {
text
let textBuilder = self.textBuilder.value(for: content) {
TextBuilder($0, environment: textEnvironment)
}

textBuilder.text
.customAttribute(TextFragmentAttribute())
.onGeometryChange(for: CGSize?.self, of: \.textContainerSize) { size in
guard let size, let textBuilder else { return }
guard let size else { return }
textBuilder.sizeChanged(size, environment: textEnvironment)
}
.onChange(of: content, initial: true) { _, newValue in
self.textBuilder = TextBuilder(newValue, environment: textEnvironment)
}
.modifier(TextSelectionBackground())
.modifier(AttachmentOverlay(attachments: content.attachments()))
.modifier(TextLinkInteraction())
}

private var text: Text {
textBuilder?.text ?? Text(verbatim: "")
}
}

struct TextFragmentAttribute: TextAttribute {
Expand Down
11 changes: 4 additions & 7 deletions Sources/Textual/StructuredText/StructuredText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ import SwiftUI
/// When you need to parse something other than Markdown, use ``init(_:parser:)`` with a custom
/// ``MarkupParser`` implementation.
public struct StructuredText: View {
@State private var attributedString = AttributedString()
@State private var parsedMarkup = Memo<String, AttributedString>()

private let markup: String
private let parser: any MarkupParser
Expand All @@ -116,21 +116,18 @@ public struct StructuredText: View {
}

public var body: some View {
WithAttachments(attributedString) {
WithAttachments(parsedMarkup.value(for: markup, derive: parse)) {
BlockContent(content: $0)
.modifier(TextSelectionInteraction())
.modifier(TextSelectionCoordination())
}
.coordinateSpace(.textContainer)
.onChange(of: markup, initial: true) {
markupDidChange(markup)
}
// Disable line limit to avoid per-fragment truncation
.lineLimit(nil)
}

private func markupDidChange(_ markup: String) {
self.attributedString = (try? parser.attributedString(for: markup)) ?? .init()
private func parse(_ markup: String) -> AttributedString {
(try? parser.attributedString(for: markup)) ?? .init()
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ extension StructuredText {
makeLabel(configuration: configuration)
.textual.fontScale(fontScale)
.textual.lineSpacing(.fontScaled(0.125))
.textual.blockSpacing(.init(top: 24, bottom: 16))
.fontWeight(.semibold)
if headingLevel <= 2 {
Divider()
.overlay(DynamicColor.gitHubDivider)
}
}
.textual.blockSpacing(.init(top: 24, bottom: 16))
}
}

Expand Down
Loading