### Example JSON Configuration for DeepSeek API Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md An example JSON configuration file structure for interacting with the DeepSeek API, including host, path, API key, model, system prompt, temperature, stream, and timeout settings. ```json // { // "host": "https://api.deepseek.com", // "path": "/chat/completions", // "apiKey": "", // "model": "deepseek-chat", // "systemPrompt": "You are a helpful assistant.", // "temperature": 0.7, // "stream": true, // "timeoutSeconds": 30 // } ``` -------------------------------- ### Install MarkdownDisplayView using CocoaPods Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Instructions for integrating MarkdownDisplayView into your iOS project using CocoaPods by adding the pod to your Podfile and running 'pod install'. Note the dependency on swift-markdown. ```ruby pod 'MarkdownDisplayKit' pod install ``` -------------------------------- ### Supported Markdown Syntax Examples Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Provides examples of standard Markdown syntax supported by the view, including headings, text formatting, and various list types. ```markdown # H1 Heading **Bold text** - [x] Completed task 1. First item ``` -------------------------------- ### Markdown Syntax Examples Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Basic Markdown syntax examples including links, images, blockquotes, tables, horizontal rules, and footnotes. ```markdown [Link text](https://example.com) ![Image description](https://example.com/image.png) > This is a blockquote > Can contain multiple lines >> Nested blockquotes are supported | Column1 | Column2 | Column3 | |---------|---------|---------| | A1 | B1 | C1 | | A2 | B2 | C2 | --- This is text with a footnote[^1] [^1]: This is the footnote content ``` -------------------------------- ### Install MarkdownDisplayView via Swift Package Manager Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Add the MarkdownDisplayView library to your project using Swift Package Manager by including its URL in your Package.swift file or Xcode project settings. ```swift dependencies: [ .package(url: "https://github.com/AgoraIO-Community/MarkdownDisplayView.git", from: "1.6.0") ] ``` -------------------------------- ### Install MarkdownDisplayView via CocoaPods Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Integrate the MarkdownDisplayView library into your iOS project using CocoaPods by adding the 'MarkdownDisplayKit' pod to your Podfile and running 'pod install'. ```ruby pod 'MarkdownDisplayKit', '~> 1.6.9' ``` -------------------------------- ### Simulate Streaming Rendering with startStreaming Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Implement a typewriter effect for Markdown content using the startStreaming method. This method allows progressive display of text with customizable units (character, word, sentence), chunk size, interval, and auto-scrolling. It also provides callbacks for when streaming starts and completes. ```swift import UIKit import MarkdownDisplayView class StreamingViewController: UIViewController { private let markdownView = ScrollableMarkdownViewTextKit() func displayWithTypewriterEffect() { let content = """ # AI Response Here's my analysis of the problem... ## Key Points 1. First consideration 2. Second consideration ```python def solve(x): return x * 2 ``` """ // Start streaming with word-by-word display markdownView.startStreaming( content, unit: .word, // Options: .character, .word, .sentence unitsPerChunk: 2, // Units to display per tick interval: 0.05, // Time between ticks (seconds) autoScrollBottom: true, onStart: { print("Streaming started") }, onComplete: { print("Streaming completed") } ) } func stopStreaming() { markdownView.stopStreaming() } func showAllImmediately() { markdownView.finishStreaming() } } ``` -------------------------------- ### Custom Markdown Extension - View Provider Implementation Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md An example of a custom view provider for a 'mention' type. It defines how to create and calculate the size of a custom view (a styled UILabel) for the mention element, using the provided data and configuration. ```Swift class MentionViewProvider: MarkdownCustomViewProvider { let supportedType = "mention" func createView( for data: CustomElementData, configuration: MarkdownConfiguration, containerWidth: CGFloat ) -> UIView { let label = UILabel() label.text = data.rawText label.textColor = .systemBlue label.font = configuration.bodyFont label.backgroundColor = UIColor.systemBlue.withAlphaComponent(0.1) label.layer.cornerRadius = 4 label.sizeToFit() return label } func calculateSize( for data: CustomElementData, configuration: MarkdownConfiguration, containerWidth: CGFloat ) -> CGSize { let text = data.rawText as NSString let size = text.size(withAttributes: [.font: configuration.bodyFont]) return CGSize(width: size.width + 8, height: size.height + 4) } } ``` -------------------------------- ### Custom Markdown Extension - Parser Implementation Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Provides an example of implementing a custom Markdown parser for a 'mention' syntax (`@username`). It defines the identifier, regex pattern, and a method to parse matches into custom element data. ```Swift class MentionParser: MarkdownCustomParser { let identifier = "mention" let pattern = "@([a-zA-Z0-9_]+)" // Regex pattern func parse(match: NSTextCheckingResult, in text: String) -> CustomElementData? { guard let range = Range(match.range(at: 1), in: text) else { return nil } let username = String(text[range]) return CustomElementData( type: "mention", rawText: "@\(username)", payload: ["username": username] ) } } ``` -------------------------------- ### Custom Markdown Extension - Action Handler Implementation Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Example of a custom action handler for a 'mention' type. It defines how to handle tap gestures on mention elements, in this case, printing a navigation message with the username. ```Swift class MentionActionHandler: MarkdownCustomActionHandler { let supportedType = "mention" func handleTap(data: CustomElementData, sourceView: UIView, presentingViewController: UIViewController?) { guard let username = data.payload["username"] else { return } print("Navigate to user profile: \(username)") } } ``` -------------------------------- ### Configure Themes and Custom Styles Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Explains how to apply preset themes or create a custom configuration object to modify fonts, colors, and layout spacing. ```swift markdownView.configuration = .dark var config = MarkdownConfiguration.default config.bodyFont = .systemFont(ofSize: 17) config.textColor = .label config.paragraphSpacing = 16 markdownView.configuration = config ``` -------------------------------- ### Initialize MarkdownViewTextKit Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Demonstrates how to instantiate the core MarkdownViewTextKit component and monitor height or interaction events. ```swift let markdownView = MarkdownViewTextKit() markdownView.onHeightChange = { newHeight in print("Content height changed to: \(newHeight)") } markdownView.onLinkTap = { [weak self] url in if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } markdownView.onImageTap = { imageURL in _ = ImageCacheManager.shared.image(for: imageURL) } ``` -------------------------------- ### Configure LaTeX Formula Rendering in Swift Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Demonstrates how to initialize MarkdownViewTextKit and customize LaTeX rendering properties such as font size, alignment, and background color. ```swift import UIKit import MarkdownDisplayView let markdownView = MarkdownViewTextKit() var config = MarkdownConfiguration.default config.latexFontSize = 22 config.latexAlignment = .center config.latexBackgroundColor = UIColor.systemGray6.withAlphaComponent(0.5) config.latexPadding = 20 markdownView.configuration = config markdownView.markdown = "# Math Examples\n\nInline formula: $E = mc^2$\n\nDisplay formula:\n\n$$\n\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}\n$$" ``` -------------------------------- ### Real-Time Streaming with MarkdownDisplayView Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Demonstrates how to use the real-time streaming API to handle incremental parsing and rendering of content from a network source. It simulates receiving data in chunks and appending it to the Markdown view, with options for auto-scrolling and smart buffering. ```swift import UIKit import MarkdownDisplayView class RealStreamingViewController: UIViewController { private let markdownView = ScrollableMarkdownViewTextKit() func startRealTimeStreaming() { // Begin streaming mode markdownView.markdownView.beginRealStreaming( autoScrollBottom: true, useSmartBuffer: true, // Enable smart module detection onComplete: { print("All content rendered") } ) // Simulate receiving chunks from network simulateNetworkChunks() } private func simulateNetworkChunks() { let chunks = [ "# Hello", " World\n\n", "This is **streaming** ", "content from an API.\n\n", "```swift\n", "let x = 1\n", "```" ] var index = 0 Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { [weak self] timer in guard let self = self, index < chunks.count else { timer.invalidate() // End streaming mode self?.markdownView.markdownView.endRealStreaming { print("Streaming ended") } return } // Append chunk as it arrives self.markdownView.markdownView.appendStreamData(chunks[index]) index += 1 } } // Alternative: append complete blocks func appendCompleteBlock(_ block: String) { markdownView.markdownView.appendBlock(block) } } ``` -------------------------------- ### Initialize and Display Markdown Content Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Demonstrates how to instantiate the ScrollableMarkdownViewTextKit, add it to the view hierarchy with Auto Layout constraints, and set the markdown text property. ```swift import UIKit import MarkdownDisplayView class ViewController: UIViewController { private let markdownView = ScrollableMarkdownViewTextKit() override func viewDidLoad() { super.viewDidLoad() view.addSubview(markdownView) markdownView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ markdownView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), markdownView.leadingAnchor.constraint(equalTo: view.leadingAnchor), markdownView.trailingAnchor.constraint(equalTo: view.trailingAnchor), markdownView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) markdownView.markdown = "# Welcome to MarkdownDisplayView\n\nThis is a **powerful** Markdown rendering component." } } ``` -------------------------------- ### Manage Table of Contents Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Demonstrates how to retrieve TOC items, generate a clickable TOC view, and handle scroll-to-heading functionality. ```swift let tocItems = markdownView.tableOfContents for item in tocItems { print("Level \(item.level): \(item.title)") } let tocView = markdownView.generateTOCView() view.addSubview(tocView) markdownView.onTOCItemTap = { item in markdownView.scrollToTOCItem(item) } ``` -------------------------------- ### Handle User Interactions Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Shows how to implement callbacks for link taps and image interactions within the Markdown view. ```swift markdownView.onLinkTap = { url in if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } markdownView.onImageTap = { imageURL in print("Image tapped: \(imageURL)") } ``` -------------------------------- ### MarkdownDisplayView Initialization Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md How to initialize and add the MarkdownDisplayView to your view hierarchy and set its content. ```APIDOC ## Initialization and Content ### Description Initializes the `ScrollableMarkdownViewTextKit` component and assigns Markdown-formatted string content to the view. ### Method N/A (Swift Class Implementation) ### Parameters - **markdown** (String) - Required - The raw Markdown string to be rendered. ### Request Example ```swift let markdownView = ScrollableMarkdownViewTextKit() markdownView.markdown = "# Title\nThis is a paragraph." ``` ``` -------------------------------- ### Configure Syntax Highlighting Themes in Swift Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Shows how to apply built-in Xcode themes or define custom color schemes for syntax highlighting within Markdown code blocks. ```swift import UIKit import MarkdownDisplayView var config = MarkdownConfiguration.default config.syntaxColors = .xcode config.syntaxColorsDark = .xcodeDark config.syntaxColors = SyntaxHighlightColors( keyword: UIColor(red: 0.78, green: 0.24, blue: 0.59, alpha: 1.0), string: UIColor(red: 0.84, green: 0.19, blue: 0.16, alpha: 1.0), number: UIColor(red: 0.11, green: 0.27, blue: 0.53, alpha: 1.0), comment: UIColor(red: 0.42, green: 0.47, blue: 0.50, alpha: 1.0), type: UIColor(red: 0.11, green: 0.43, blue: 0.55, alpha: 1.0), function: UIColor(red: 0.26, green: 0.40, blue: 0.55, alpha: 1.0), property: UIColor(red: 0.26, green: 0.40, blue: 0.55, alpha: 1.0), preprocessor: UIColor(red: 0.54, green: 0.36, blue: 0.20, alpha: 1.0) ) let markdownView = MarkdownViewTextKit() markdownView.configuration = config ``` -------------------------------- ### Registering Built-in Video Extension Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Demonstrates how to register the built-in video extension for MarkdownDisplayKit in the application delegate. This allows embedding videos using the `[video:filename]` syntax. ```Swift import MarkdownDisplayKit func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Register video extension MarkdownCustomExtensionManager.shared.registerVideoExtension() return true } ``` -------------------------------- ### Configure Streaming Haptic Feedback Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Sets up haptic feedback styles and intervals for user interactions. Includes an enum for selecting the feedback intensity. ```swift public var streamingHapticFeedbackStyle: StreamingHapticFeedbackStyle public var streamingHapticMinInterval: TimeInterval public enum StreamingHapticFeedbackStyle { case none, light, medium, heavy, soft, rigid } var config = MarkdownConfiguration.default config.streamingHapticFeedbackStyle = .light config.streamingHapticMinInterval = 0.05 markdownView.configuration = config ``` -------------------------------- ### Real-Time LLM Streaming with MarkdownDisplayView Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Enables real-time streaming of content from LLM APIs like ChatGPT. It supports appending chunks, finishing the stream, and configuring typewriter effects. Smart buffering handles incomplete Markdown structures for incremental rendering. ```Swift class ChatViewController: UIViewController { private let scrollableMarkdownView = ScrollableMarkdownViewTextKit() // Start real streaming mode func startLLMStream() { scrollableMarkdownView.markdownView.startRealStreaming() } // Append chunks as they arrive from the API func onChunkReceived(_ chunk: String) { scrollableMarkdownView.markdownView.appendStreamContent(chunk) } // Call when stream completes func onStreamComplete() { scrollableMarkdownView.markdownView.finishStreaming() } } ``` ```Swift var config = MarkdownConfiguration.default config.typewriterTextMode = .append config.typewriterHeightUpdateInterval = 20 config.streamMinModuleLength = 20 scrollableMarkdownView.markdownView.configuration = config ``` -------------------------------- ### Streaming Rendering API Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Simulates streaming output with a typewriter effect using the `startStreaming()` method for a progressive display of content. ```APIDOC ## Streaming Rendering (Fake Streaming) For simulating streaming output (like typing effects), use `startStreaming()` which takes a complete text and displays it progressively with typewriter animation. This is ideal for displaying pre-loaded content with visual effects. ### Method `startStreaming()` ### Endpoint N/A (Method on `ScrollableMarkdownViewTextKit`) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import UIKit import MarkdownDisplayView class StreamingViewController: UIViewController { private let markdownView = ScrollableMarkdownViewTextKit() func displayWithTypewriterEffect() { let content = """ # AI Response Here's my analysis of the problem... ## Key Points 1. First consideration 2. Second consideration ```python def solve(x): return x * 2 ``` """ // Start streaming with word-by-word display markdownView.startStreaming( content, unit: .word, // Options: .character, .word, .sentence unitsPerChunk: 2, // Units to display per tick interval: 0.05, // Time between ticks (seconds) autoScrollBottom: true, onStart: { print("Streaming started") }, onComplete: { print("Streaming completed") } ) } func stopStreaming() { markdownView.stopStreaming() } func showAllImmediately() { markdownView.finishStreaming() } } ``` ### Response #### Success Response (200) N/A (Streaming effect) #### Response Example N/A (Streaming effect) ``` -------------------------------- ### Add MarkdownDisplayView via Swift Package Manager (Package.swift) Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md How to add MarkdownDisplayView as a dependency in your project's Package.swift file. ```swift dependencies: [ .package(url: "https://github.com/zjc19891106/MarkdownDisplayView.git", from: "1.6.8") ] ``` -------------------------------- ### Implement Custom Markdown Syntax Extensions Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Provides a template for extending Markdown syntax by implementing custom parsers, view providers, and action handlers for specific patterns like @mentions. ```swift class MentionParser: MarkdownCustomParser { var identifier: String { "mention" } var pattern: String { "@(\\w+)" } func parse(match: NSTextCheckingResult, in text: String) -> CustomElementData? { guard let range = Range(match.range(at: 1), in: text) else { return nil } let username = String(text[range]) return CustomElementData(type: "mention", rawText: "@\(username)", payload: ["username": username]) } } let manager = MarkdownCustomExtensionManager.shared manager.register(parser: MentionParser()) manager.register(viewProvider: MentionViewProvider()) manager.register(actionHandler: MentionActionHandler()) ``` -------------------------------- ### Table of Contents Generation and Navigation in MarkdownDisplayView Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Illustrates how to generate and interact with a table of contents (TOC) from Markdown headings. The code shows how to access TOC items, generate a TOC view widget, handle taps on TOC items for navigation, and programmatically scroll to specific items. ```swift import UIKit import MarkdownDisplayView class TOCViewController: UIViewController { private let markdownView = ScrollableMarkdownViewTextKit() private var tocView: UIView? override func viewDidLoad() { super.viewDidLoad() markdownView.markdown = """ # Introduction Some intro text... ## Getting Started How to begin... ### Installation Install steps... ## Advanced Usage Advanced topics... """ // Access the table of contents let tocItems = markdownView.tableOfContents for item in tocItems { print("Level \(item.level): \(item.title) (id: \(item.id))") } // Generate a TOC view widget tocView = markdownView.generateTOCView() // Handle TOC item tap markdownView.onTOCItemTap = { [weak self] item in print("Navigating to: \(item.title)") self?.markdownView.scrollToTOCItem(item) } // Scroll to a specific TOC item programmatically if let firstItem = tocItems.first { markdownView.scrollToTOCItem(firstItem) } // Check if document has a TOC section if markdownView.hasTableOfContentsSection { markdownView.backToTableOfContentsSection() } } } ``` -------------------------------- ### Advanced Usage: Monitor Height Changes Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Demonstrates how to monitor height changes of the Markdown view and set up callbacks for link and image taps. ```APIDOC ## Advanced Usage: Monitor Height Changes ### Description This section explains how to track the content height changes of the Markdown view and configure callbacks for user interactions like tapping on links or images. ### Code Example ```swift let markdownView = MarkdownViewTextKit() markdownView.onHeightChange = { newHeight in print("Content height changed to: \(newHeight)") // Can be used to dynamically adjust container height } // Set link tap callback markdownView.onLinkTap = { [weak self] url in // Handle link tap if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } markdownView.onImageTap = { imageURL in // Get image if already loaded _ = ImageCacheManager.shared.image(for: imageURL) } markdownView.onTOCItemTap = { item in print("title:\(item.title), level:\(item.level), id:\(item.id)") } ``` ``` -------------------------------- ### Registering Custom Markdown Extensions Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Shows how to register custom Markdown extensions (parser, view provider, and action handler) with the `MarkdownCustomExtensionManager` to enable custom syntax and behavior. ```Swift let manager = MarkdownCustomExtensionManager.shared manager.register(parser: MentionParser()) manager.register(viewProvider: MentionViewProvider()) manager.register(actionHandler: MentionActionHandler()) ``` -------------------------------- ### Implement ScrollableMarkdownViewTextKit Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Configures a scrollable markdown view with auto-layout constraints and event handling for links and images. ```swift let scrollableView = ScrollableMarkdownViewTextKit() view.addSubview(scrollableMarkdownView) scrollableMarkdownView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ scrollableMarkdownView.topAnchor.constraint(equalTo: view.topAnchor, constant: 88), scrollableMarkdownView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollableMarkdownView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollableMarkdownView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) scrollableMarkdownView.markdown = sampleMarkdown ``` -------------------------------- ### MarkdownConfiguration API Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Demonstrates how to customize various visual aspects of Markdown rendering using the MarkdownConfiguration struct. ```APIDOC ## Configuration and Styling The `MarkdownConfiguration` struct provides extensive customization options for fonts, colors, spacing, and behavior. All visual aspects of the rendered Markdown can be customized. ### Method N/A (Configuration Struct) ### Endpoint N/A (Configuration Struct) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import UIKit import MarkdownDisplayView // Create a custom configuration var config = MarkdownConfiguration.default // Font customization config.bodyFont = .systemFont(ofSize: 17) config.h1Font = .systemFont(ofSize: 32, weight: .bold) config.h2Font = .systemFont(ofSize: 26, weight: .bold) config.h3Font = .systemFont(ofSize: 22, weight: .semibold) config.codeFont = .monospacedSystemFont(ofSize: 14, weight: .regular) // Color customization config.textColor = .label config.headingColor = .label config.linkColor = .systemBlue config.linkUnderlineEnabled = true config.codeTextColor = .label config.codeBackgroundColor = UIColor.systemGray6 config.blockquoteTextColor = .secondaryLabel config.blockquoteBarColor = .systemGray3 // Spacing customization config.paragraphSpacing = 12 config.headingTopSpacing = 20 config.headingBottomSpacing = 12 config.paragraphTopSpacing = 8 config.paragraphBottomSpacing = 5 config.listIndent = 12 // LaTeX configuration config.latexFontSize = 22 config.latexAlignment = .center config.latexBackgroundColor = UIColor.systemGray6.withAlphaComponent(0.5) config.latexPadding = 20 // Table configuration config.tableMinColumnWidth = 80 config.tableMaxColumnWidth = 200 config.tableRowHeight = 44 // Code syntax highlighting (Xcode-style themes) config.syntaxColors = .xcode // Light theme config.syntaxColorsDark = .xcodeDark // Dark theme // Apply configuration let markdownView = MarkdownViewTextKit() markdownView.configuration = config // Use dark theme preset let darkConfig = MarkdownConfiguration.dark markdownView.configuration = darkConfig ``` ### Response N/A (Configuration Struct) ``` -------------------------------- ### Configure Markdown Elements Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Defines the configuration properties for LaTeX formulas, blockquotes, tables, lists, and collapsible details. These properties allow customization of fonts, colors, padding, and spacing. ```swift public var latexFontSize: CGFloat public var latexAlignment: NSTextAlignment public var latexBackgroundColor: UIColor public var latexPadding: CGFloat public var blockquoteBackgroundColor: UIColor public var blockquoteBarWidth: CGFloat public var blockquoteContentSpacing: CGFloat public var blockquoteContentPadding: CGFloat public var tableMinColumnWidth: CGFloat public var tableMaxColumnWidth: CGFloat public var tableRowHeight: CGFloat public var tableCellPadding: CGFloat public var tableSeparatorHeight: CGFloat public var listItemSpacing: CGFloat public var listMarkerMinWidth: CGFloat public var listMarkerSpacing: CGFloat public var detailsSummaryFont: UIFont public var detailsSummaryTextColor: UIColor public var detailsSummaryMinHeight: CGFloat public var detailsContentPadding: CGFloat public var detailsSpacing: CGFloat ``` -------------------------------- ### Configure Syntax Highlighting Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Defines the structure for syntax highlighting colors and themes. It supports both light and dark modes via the SyntaxHighlightColors struct. ```swift public var syntaxColors: SyntaxHighlightColors public var syntaxColorsDark: SyntaxHighlightColors public struct SyntaxHighlightColors { public var keyword: UIColor public var string: UIColor public var number: UIColor public var comment: UIColor public var type: UIColor public var function: UIColor public var property: UIColor public var preprocessor: UIColor public static var xcode: SyntaxHighlightColors public static var xcodeDark: SyntaxHighlightColors } ``` -------------------------------- ### Advanced Usage: Core View Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Explains how to use the core Markdown view directly when manual scroll management is required. ```APIDOC ## Advanced Usage: Using Core View Directly ### Description This section covers how to use the `MarkdownViewTextKit` directly when you need to manage the scroll container yourself, offering more control over the layout and scrolling behavior. ### Usage ```swift let markdownView = MarkdownViewTextKit() // You need to manage the scroll container yourself ``` ``` -------------------------------- ### Configuration API Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Customizing the appearance of the Markdown view using the MarkdownConfiguration object. ```APIDOC ## Configuration ### Description Allows customization of fonts, colors, and layout spacing using the `MarkdownConfiguration` struct. ### Parameters - **configuration** (MarkdownConfiguration) - Required - The configuration object defining visual styles. ### Configuration Options - **Fonts**: bodyFont, h1Font, h2Font, codeFont, etc. - **Colors**: textColor, linkColor, codeBackgroundColor, tableBorderColor, etc. - **Spacing**: paragraphSpacing, headingSpacing, imageMaxHeight, etc. ### Request Example ```swift var config = MarkdownConfiguration.default config.bodyFont = .systemFont(ofSize: 17) config.textColor = .label markdownView.configuration = config ``` ``` -------------------------------- ### Configure Typewriter Effect in MarkdownDisplayView Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Explains how to configure the typewriter animation engine for character-by-character or element-by-element text reveal. It covers settings for animation speed, delays, text reveal modes, height update intervals, and haptic feedback during streaming. ```swift import UIKit import MarkdownDisplayView let markdownView = MarkdownViewTextKit() // Enable/disable typewriter effect markdownView.enableTypewriterEffect = true // Configure typewriter speed markdownView.updateTypewriterSpeed( charsPerStep: 6, // Characters revealed per step baseDuration: 0.012, // Base delay between steps (seconds) elementGapDuration: 0.04 // Delay between block elements ) // Set text reveal mode var config = MarkdownConfiguration.default config.typewriterTextMode = .reveal // Options: .reveal (show gradually), .append (add character by character) config.typewriterHeightUpdateInterval = 20 // Update height every N characters markdownView.configuration = config // Haptic feedback during streaming config.streamingHapticFeedbackStyle = .light // Options: .none, .light, .medium, .heavy, .soft, .rigid config.streamingHapticMinInterval = 0.05 // Minimum interval between vibrations ``` -------------------------------- ### Add MarkdownDisplayView via Swift Package Manager (Xcode) Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Instructions for adding the MarkdownDisplayView dependency to your Xcode project using Swift Package Manager by providing the repository URL. ```swift File -> Add Package Dependencies... Enter the repository URL: https://github.com/zjc19891106/MarkdownDisplayView.git Select the version and click Add Package. ``` -------------------------------- ### Event Handling Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Callbacks for handling user interactions such as tapping links or images within the rendered Markdown. ```APIDOC ## Event Handling ### Description Defines closures to handle interactions when a user taps on a link or an image inside the rendered view. ### Parameters - **onLinkTap** (URL -> Void) - Optional - Callback triggered when a link is tapped. - **onImageTap** (URL -> Void) - Optional - Callback triggered when an image is tapped. ### Request Example ```swift markdownView.onLinkTap = { url in UIApplication.shared.open(url) } markdownView.onImageTap = { imageURL in print("Image tapped: \(imageURL)") } ``` ``` -------------------------------- ### Advanced Usage: Scrollable View Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Details the recommended usage of the scrollable Markdown view, including layout constraints and event callbacks. ```APIDOC ## Advanced Usage: Using Scrollable View (Recommended) ### Description This is the recommended way to use the Markdown Display View, as it provides a built-in `UIScrollView` for automatic scrolling and handles layout efficiently. ### Usage ```swift let scrollableView = ScrollableMarkdownViewTextKit() view.addSubview(scrollableView) scrollableMarkdownView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ scrollableMarkdownView.topAnchor.constraint( equalTo: view.topAnchor, constant: 88), scrollableMarkdownView.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollableMarkdownView.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollableMarkdownView.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) // Built-in UIScrollView, automatically handles scrolling scrollableMarkdownView.onLinkTap = { [weak self] url in // Handle link tap if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) } } scrollableMarkdownView.onImageTap = { imageURL in // Get image if already loaded _ = ImageCacheManager.shared.image(for: imageURL) } scrollableMarkdownView.onTOCItemTap = { item in print("title:\(item.title), level:\(item.level), id:\(item.id)") } scrollableMarkdownView.markdown = sampleMarkdown // Back to table of contents scrollableMarkdownView.backToTableOfContentsSection() ``` ``` -------------------------------- ### Markdown Rendering Features Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Demonstrates the basic Markdown syntax supported by the view, including links, images, blockquotes, code blocks, tables, horizontal rules, details, and footnotes. ```APIDOC ## Markdown Rendering Features ### Description This section showcases the various Markdown elements that can be rendered by the Markdown Display View. ### Supported Elements - **Links and Images** ```markdown [Link text](https://example.com) ![Image description](https://example.com/image.png) ``` - **Blockquotes** ```markdown > This is a blockquote > Can contain multiple lines >> Nested blockquotes are supported ``` - **Code Blocks** Supports syntax highlighting for various languages. ````markdown ```swift func greet(name: String) -> String { return "Hello, \(name)!" } print(greet(name: "World")) ``` ```` - **Tables** ```markdown | Column1 | Column2 | Column3 | |---------|---------|---------| | A1 | B1 | C1 | | A2 | B2 | C2 | ``` - **Horizontal Rules** ```markdown --- *** ___ ``` - **Details (Collapsible Sections)** ```html
Click to expand This is the collapsed content Can contain any Markdown syntax
``` - **Footnotes** ```markdown This is text with a footnote[^1] [^1]: This is the footnote content ``` ``` -------------------------------- ### Advanced Usage: Streaming Markdown Display Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Explains how to implement a streaming (typewriter effect) display for Markdown content. ```APIDOC ## Advanced Usage: Streaming Markdown Display ### Description This section covers the advanced feature of displaying Markdown content with a streaming or typewriter effect. Other aspects are consistent with the scrollable markdown view. ### Streaming Render ```swift // Difference is in displaying content private func loadSampleMarkdown() { // Streaming render (typewriter effect) scrollableMarkdownView.startStreaming( sampleMarkdown, unit: .word, unitsPerChunk: 2, interval: 0.1, ) } // If you need to show all content immediately (e.g., user clicks skip) @objc private func skipButtonTapped() { scrollableMarkdownView.markdownView.finishStreaming() } ``` ``` -------------------------------- ### Configure Markdown Appearance with MarkdownConfiguration Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Customize fonts, colors, spacing, and other visual properties of Markdown rendering using the MarkdownConfiguration struct. This includes settings for headings, text, links, code blocks, LaTeX, and tables. It also supports Xcode-style syntax highlighting themes for code. ```swift import UIKit import MarkdownDisplayView // Create a custom configuration var config = MarkdownConfiguration.default // Font customization config.bodyFont = .systemFont(ofSize: 17) config.h1Font = .systemFont(ofSize: 32, weight: .bold) config.h2Font = .systemFont(ofSize: 26, weight: .bold) config.h3Font = .systemFont(ofSize: 22, weight: .semibold) config.codeFont = .monospacedSystemFont(ofSize: 14, weight: .regular) // Color customization config.textColor = .label config.headingColor = .label config.linkColor = .systemBlue config.linkUnderlineEnabled = true config.codeTextColor = .label config.codeBackgroundColor = UIColor.systemGray6 config.blockquoteTextColor = .secondaryLabel config.blockquoteBarColor = .systemGray3 // Spacing customization config.paragraphSpacing = 12 config.headingTopSpacing = 20 config.headingBottomSpacing = 12 config.paragraphTopSpacing = 8 config.paragraphBottomSpacing = 5 config.listIndent = 12 // LaTeX configuration config.latexFontSize = 22 config.latexAlignment = .center config.latexBackgroundColor = UIColor.systemGray6.withAlphaComponent(0.5) config.latexPadding = 20 // Table configuration config.tableMinColumnWidth = 80 config.tableMaxColumnWidth = 200 config.tableRowHeight = 44 // Code syntax highlighting (Xcode-style themes) config.syntaxColors = .xcode // Light theme config.syntaxColorsDark = .xcodeDark // Dark theme // Apply configuration let markdownView = MarkdownViewTextKit() markdownView.configuration = config // Use dark theme preset let darkConfig = MarkdownConfiguration.dark markdownView.configuration = darkConfig ``` -------------------------------- ### Basic Markdown Rendering with MarkdownViewTextKit Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Renders standard Markdown content within an iOS view using MarkdownViewTextKit. It automatically handles various Markdown elements and provides callbacks for link and image taps, as well as height changes for dynamic layout adjustments. ```swift import UIKit import MarkdownDisplayView class ViewController: UIViewController { private let markdownView = MarkdownViewTextKit() override func viewDidLoad() { super.viewDidLoad() view.addSubview(markdownView) markdownView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ markdownView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16), markdownView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16), markdownView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16), ]) // Set Markdown content markdownView.markdown = """ # Welcome to MarkdownDisplayView This is a **powerful** Markdown renderer for iOS. ## Features - Syntax highlighting for 20+ languages - LaTeX formula support: $E = mc^2$ - Tables and collapsible sections ```swift let greeting = "Hello, World!" print(greeting) ``` """ // Handle link taps markdownView.onLinkTap = { url in UIApplication.shared.open(url) } // Handle image taps markdownView.onImageTap = { imageSource in print("Image tapped: \(imageSource)") } // Listen to height changes for dynamic layout markdownView.onHeightChange = { newHeight in print("Content height changed to: \(newHeight)") } } } ``` -------------------------------- ### Performance Optimization Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Details the performance enhancements implemented in the Markdown Display View, such as asynchronous rendering, incremental updates, lazy image loading, regex caching, and view reuse. ```APIDOC ## Performance Optimization ### Description The Markdown Display View is optimized for performance to ensure a smooth user experience, especially with large or complex Markdown content. ### Optimization Techniques - **Asynchronous Rendering**: Markdown parsing and rendering execute in a background queue, preventing the main thread from blocking. - **Incremental Updates**: Utilizes a Diff algorithm to only update the changed parts of the content, improving efficiency. - **Lazy Image Loading**: Images are loaded asynchronously with a caching mechanism to reduce initial load times. - **Regex Caching**: Syntax highlighting regular expressions are cached and reused to speed up parsing. - **View Reuse**: Employs an efficient view update strategy to minimize view creation and destruction overhead. ``` -------------------------------- ### Implement Custom Mermaid Code Block Renderer Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Defines a custom renderer for Mermaid diagrams by conforming to the MarkdownCodeBlockRenderer protocol. It uses a WKWebView to render the diagram and provides size calculation logic for the layout. ```swift public final class MermaidRenderer: MarkdownCodeBlockRenderer { public let supportedLanguage = "mermaid" public func renderCodeBlock( code: String, configuration: MarkdownConfiguration, containerWidth: CGFloat ) -> UIView { let view = MermaidWebView(code: code, frame: ...) return view } public func calculateSize( code: String, configuration: MarkdownConfiguration, containerWidth: CGFloat ) -> CGSize { return CGSize(width: containerWidth - 32, height: estimatedHeight) } } ``` -------------------------------- ### SwiftUI Integration for MarkdownDisplayView Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt This snippet demonstrates how to integrate MarkdownDisplayView into a SwiftUI view using UIViewRepresentable. It allows rendering Markdown strings within a SwiftUI environment and handling link taps. ```swift import SwiftUI import MarkdownDisplayView struct MarkdownView: UIViewRepresentable { let markdown: String var configuration: MarkdownConfiguration = .default var onLinkTap: ((URL) -> Void)? func makeUIView(context: Context) -> ScrollableMarkdownViewTextKit { let view = ScrollableMarkdownViewTextKit() view.configuration = configuration view.onLinkTap = onLinkTap return view } func updateUIView(_ uiView: ScrollableMarkdownViewTextKit, context: Context) { uiView.markdown = markdown uiView.configuration = configuration } } // Usage in SwiftUI struct ContentView: View { @State private var markdownText = """# SwiftUI Integration This is **Markdown** rendered in SwiftUI! - Item 1 - Item 2 """ var body: some View { VStack { MarkdownView( markdown: markdownText, onLinkTap: { url in print("Link tapped: \(url)") } ) .frame(maxWidth: .infinity, maxHeight: .infinity) } } } ``` -------------------------------- ### Streaming Markdown Display Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Configures the view to render markdown content incrementally, creating a typewriter effect. ```swift private func loadSampleMarkdown() { scrollableMarkdownView.startStreaming( sampleMarkdown, unit: .word, unitsPerChunk: 2, interval: 0.1 ) } @objc private func skipButtonTapped() { scrollableMarkdownView.markdownView.finishStreaming() } ``` -------------------------------- ### Real-Time Streaming API Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Endpoints and methods for handling real-time streaming content from LLM APIs within the ScrollableMarkdownView. ```APIDOC ## Real-Time Streaming API ### Description Methods to initialize, append, and finalize streaming content from LLM sources like ChatGPT or Claude. ### Methods - `startRealStreaming()`: Initializes the streaming state. - `appendStreamContent(String)`: Appends a chunk of text to the view. - `finishStreaming()`: Completes the stream and finalizes rendering. ### Configuration - **typewriterTextMode** (Enum) - Controls the animation style. - **typewriterHeightUpdateInterval** (Int) - Frequency of height updates during streaming. - **streamMinModuleLength** (Int) - Minimum length before module rendering triggers. ### Request Example ```swift scrollableMarkdownView.markdownView.startRealStreaming() scrollableMarkdownView.markdownView.appendStreamContent("Hello, ") scrollableMarkdownView.markdownView.finishStreaming() ``` ``` -------------------------------- ### Custom Extension API Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md API for registering and implementing custom Markdown extensions including parsers, view providers, and action handlers. ```APIDOC ## Custom Extension API ### Description Extend MarkdownDisplayKit functionality by implementing custom parsers, view providers, and action handlers. ### Registration - `MarkdownCustomExtensionManager.shared.register(parser: ...)` - `MarkdownCustomExtensionManager.shared.register(viewProvider: ...)` - `MarkdownCustomExtensionManager.shared.register(actionHandler: ...)` ### Required Protocols - **MarkdownCustomParser**: Defines regex patterns and extracts payload data. - **MarkdownCustomViewProvider**: Defines how the element is rendered in the UI. - **MarkdownCustomActionHandler**: Defines interactions (e.g., taps) for the custom element. ### Syntax Example - **Video**: `[video:filename]` - **Mention**: `@username` - **Emoji**: `::emoji_name::` ``` -------------------------------- ### Scrollable Markdown Rendering with ScrollableMarkdownViewTextKit Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt Provides a scrollable view for Markdown content by embedding MarkdownViewTextKit within a UIScrollView. This is suitable for content that may exceed the screen height and allows access to the inner Markdown view's callbacks. ```swift import UIKit import MarkdownDisplayView class ScrollableViewController: UIViewController { private let scrollableMarkdown = ScrollableMarkdownViewTextKit() override func viewDidLoad() { super.viewDidLoad() view.addSubview(scrollableMarkdown) scrollableMarkdown.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ scrollableMarkdown.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), scrollableMarkdown.leadingAnchor.constraint(equalTo: view.leadingAnchor), scrollableMarkdown.trailingAnchor.constraint(equalTo: view.trailingAnchor), scrollableMarkdown.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) // Set content scrollableMarkdown.markdown = longMarkdownContent // Access the inner MarkdownViewTextKit for callbacks scrollableMarkdown.onLinkTap = { url in print("Link tapped: \(url)") } // Scroll to bottom scrollableMarkdown.scrollToBottom(animated: true) // Scroll to top scrollableMarkdown.scrollToTop(animated: true) } } ``` -------------------------------- ### Register Custom Code Block Renderer Source: https://github.com/zjc19891106/markdowndisplayview/blob/master/README.md Registers the custom Mermaid renderer with the shared MarkdownCustomExtensionManager to enable support for Mermaid code blocks in the Markdown viewer. ```swift let manager = MarkdownCustomExtensionManager.shared manager.register(codeBlockRenderer: MermaidRenderer()) ``` -------------------------------- ### Register Custom Mermaid Code Block Renderer in Swift Source: https://context7.com/zjc19891106/markdowndisplayview/llms.txt This Swift code defines a custom renderer for 'mermaid' code blocks, allowing for custom rendering of diagrams. It registers this renderer with the MarkdownCustomExtensionManager. The renderer provides methods for rendering the code block view and calculating its size. It's designed to be used with the MarkdownDisplayView library. ```swift import UIKit import MarkdownDisplayView // Create a custom code block renderer class MermaidRenderer: MarkdownCodeBlockRenderer { var supportedLanguage: String { "mermaid" } func renderCodeBlock( code: String, configuration: MarkdownConfiguration, containerWidth: CGFloat ) -> UIView { // Create your custom view for Mermaid diagrams let container = UIView() container.backgroundColor = .systemGray6 container.layer.cornerRadius = 8 let label = UILabel() label.text = "[Mermaid Diagram]\n\(code)" label.numberOfLines = 0 label.font = configuration.codeFont label.translatesAutoresizingMaskIntoConstraints = false container.addSubview(label) NSLayoutConstraint.activate([ label.topAnchor.constraint(equalTo: container.topAnchor, constant: 12), label.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 12), label.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -12), label.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -12), ]) return container } func calculateSize( code: String, configuration: MarkdownConfiguration, containerWidth: CGFloat ) -> CGSize { // Calculate the required size return CGSize(width: containerWidth, height: 200) } } // Register the renderer MarkdownCustomExtensionManager.shared.register(codeBlockRenderer: MermaidRenderer()) // Now mermaid code blocks use your custom renderer let markdownView = MarkdownViewTextKit() markdownView.markdown = """ ```mermaid graph TD A[Start] --> B{Decision} B -->|Yes| C[Action] B -->|No| D[End] ``` """ ```