ReadViewSDK/Sources/RDReaderView/EPUBCore/RDEPUBAssetRepository.swift

87 lines
3.7 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// RDEPUBAssetRepository.swift
// EPUBCore
// EPUB JS HTML
// {{token}}
import Foundation
/// EPUB
enum RDEPUBAsset: String {
/// Rangy core Web range/selection
case rangyCoreScript = "rangy-core"
/// Rangy serializer DOM range /
case rangySerializerScript = "rangy-serializer"
/// WXRead CSS
case cssInjectorScript = "cssInjector"
/// WXRead WeReadApi JS-Native
case weReadAPIScript = "WeReadApi"
/// JS epub-bridge.js WebView -JS
case bridgeScript = "epub-bridge"
/// HTML epub-fixed-layout.html pre-paginated EPUB
case fixedLayoutTemplate = "epub-fixed-layout"
/// WXRead default.css
case wxReadDefaultCSS = "wxread-default"
/// WXRead replace.css
case wxReadReplaceCSS = "wxread-replace"
/// WXRead dark.css
case wxReadDarkCSS = "wxread-dark"
/// WXRead replaceForLatinLanguageBook.css
case wxReadLatinReplaceCSS = "wxread-replace-latin"
///
var fileExtension: String {
switch self {
case .rangyCoreScript, .rangySerializerScript, .cssInjectorScript, .weReadAPIScript, .bridgeScript:
return "js"
case .fixedLayoutTemplate:
return "html"
case .wxReadDefaultCSS, .wxReadReplaceCSS, .wxReadDarkCSS, .wxReadLatinReplaceCSS:
return "css"
}
}
}
///
enum RDEPUBAssetRepository {
/// {{key}}
/// - Parameters:
/// - asset:
/// - replacements: key value
/// - Returns:
static func string(for asset: RDEPUBAsset, replacements: [String: String] = [:]) -> String {
guard let url = resourceBundle.url(forResource: asset.rawValue, withExtension: asset.fileExtension),
var content = try? String(contentsOf: url, encoding: .utf8) else {
assertionFailure("Missing EPUB asset: \(asset.rawValue).\(asset.fileExtension)")
return ""
}
for (token, value) in replacements {
content = content.replacingOccurrences(of: "{{\(token)}}", with: value)
}
return content
}
/// Bundle使 bundle宿 bundle
private static var resourceBundle: Bundle {
if let bundle = resolvedBundle {
return bundle
}
return Bundle(for: RDEPUBAssetBundleToken.self)
}
/// RDReaderViewAssets.bundle 宿 bundle framework
private static var resolvedBundle: Bundle? = {
let hostBundles = [Bundle(for: RDEPUBAssetBundleToken.self), Bundle.main] + Bundle.allFrameworks + Bundle.allBundles
for hostBundle in hostBundles {
if let url = hostBundle.url(forResource: "RDReaderViewAssets", withExtension: "bundle"),
let bundle = Bundle(url: url) {
return bundle
}
}
return nil
}()
}
/// Bundle
private final class RDEPUBAssetBundleToken {}