Skip to content
Merged
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
9 changes: 9 additions & 0 deletions feature/vault/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ dependencies {
// uses for donation-address QR codes (DonateScreen.kt), pinned via the
// catalog here rather than repeating that module's inline version string.
implementation("com.google.zxing:core:${libs.versions.zxing.get()}")
// Markdown rendering for vault content (#442) — same external renderer
// feature:reader uses (com.mikepenz.markdown.m3.Markdown), added directly
// here rather than depending on feature:reader itself, same
// EPUB/PDF-precedent split as the Readium artifacts just below: pull the
// third-party library in independently per module, don't take on
// feature:reader's much heavier dependency set (Readium x3, pdf-viewer,
// jsoup, webkit, room, tts) for one composable. See
// VaultMarkdownReaderScreen.kt for the (deliberately v1-scoped) renderer.
implementation(libs.markdown.renderer.m3)
// EPUB rendering for vault content — same Readium artifacts/versions as
// feature:reader, pinned via the catalog rather than feature:reader's own
// hardcoded version strings (not fixed here, out of scope for this PR).
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package xyz.libravault.feature.vault

import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.isSpecified
import androidx.compose.ui.unit.sp
import com.mikepenz.markdown.m3.Markdown
import com.mikepenz.markdown.m3.markdownTypography
import com.mikepenz.markdown.model.MarkdownTypography
import xyz.libravault.core.ui.theme.OpenDyslexicFontFamily
import androidx.compose.ui.text.font.FontFamily as ComposeFontFamily

/**
* Extra letter-spacing (in sp) bundled with [VaultReaderFontFamily.OPEN_DYSLEXIC]
* (#423) — same value/rationale as `feature:reader`'s
* `DYSLEXIA_FRIENDLY_LETTER_SPACING_SP`, duplicated for the same "parallel, not
* shared" reason as the rest of this module (see [VaultMarkdownReaderScreen]'s
* doc comment).
*/
private const val VAULT_DYSLEXIA_FRIENDLY_LETTER_SPACING_SP = 0.4f

/**
* Renders a decrypted vault Markdown file's whole text via
* [com.mikepenz.markdown.m3.Markdown] — the same Compose-native CommonMark
* renderer `feature:reader`'s non-vault Markdown reader uses (issue #442).
*
* Deliberately v1-scoped, matching what's documented as out of scope on the
* issue: one [Markdown] call for the whole document (no per-section
* TOC/scroll-position tracking), no image transformer (the renderer's own
* default already no-ops relative image references rather than crashing —
* there's no vault equivalent of the SAF directory tree `feature:reader`'s
* `CoilMarkdownImageTransformer` resolves them against), and no mermaid
* diagram support. Reading position for vault Markdown isn't persisted for
* the same reason — see [VaultReaderScreen]'s bookmark/highlight actions,
* which stay disabled while this state is active.
*
* Typography is adapted from [VaultReaderSettings] via
* [rememberVaultMarkdownTypography] rather than reusing `feature:reader`'s
* `rememberMarkdownTypography` — this module doesn't depend on
* `feature:reader` (see [VaultReaderTopBar]'s doc comment for the same,
* already-established rationale). Reading-theme colors need no adapter here,
* same as the non-vault reader, since mikepenz's default colors already read
* `MaterialTheme.colorScheme`, which `VaultReaderScreen` already themes.
*/
@Composable
fun VaultMarkdownReaderScreen(
text: String,
settings: VaultReaderSettings,
modifier: Modifier = Modifier,
) {
val typography = rememberVaultMarkdownTypography(settings)
Markdown(
content = text,
typography = typography,
modifier = modifier
.fillMaxSize()
.verticalScroll(rememberScrollState())
.padding(16.dp),
)
}

/**
* Adapts mikepenz's Material3-derived default typography to
* [VaultReaderSettings]'s font family / size / line-spacing preferences —
* duplicated from `feature:reader`'s `rememberMarkdownTypography` rather
* than shared, same rationale as the rest of this module's settings/UI
* duplication (see [VaultMarkdownReaderScreen]'s doc comment).
*/
@Composable
internal fun rememberVaultMarkdownTypography(settings: VaultReaderSettings): MarkdownTypography {
val composeFontFamily = when (settings.fontFamily) {
VaultReaderFontFamily.SYSTEM -> ComposeFontFamily.Default
VaultReaderFontFamily.SERIF -> ComposeFontFamily.Serif
VaultReaderFontFamily.SANS_SERIF -> ComposeFontFamily.SansSerif
VaultReaderFontFamily.MONOSPACE -> ComposeFontFamily.Monospace
VaultReaderFontFamily.OPEN_DYSLEXIC -> OpenDyslexicFontFamily
}

fun TextStyle.scaled(overrideFontFamily: ComposeFontFamily = composeFontFamily): TextStyle = copy(
fontFamily = overrideFontFamily,
fontSize = fontSize * settings.fontSize,
lineHeight = if (lineHeight.isSpecified) {
lineHeight * settings.fontSize * settings.lineSpacing
} else {
lineHeight
},
letterSpacing = if (overrideFontFamily == composeFontFamily &&
settings.fontFamily == VaultReaderFontFamily.OPEN_DYSLEXIC
) {
val base = if (letterSpacing.isSpecified) letterSpacing.value else 0f
(base + VAULT_DYSLEXIA_FRIENDLY_LETTER_SPACING_SP).sp
} else {
letterSpacing
},
)

val typography = MaterialTheme.typography
val bodyLarge = typography.bodyLarge.scaled()

return markdownTypography(
h1 = typography.displayLarge.scaled(),
h2 = typography.displayMedium.scaled(),
h3 = typography.displaySmall.scaled(),
h4 = typography.headlineMedium.scaled(),
h5 = typography.headlineSmall.scaled(),
h6 = typography.titleLarge.scaled(),
text = bodyLarge,
code = typography.bodyMedium.scaled(overrideFontFamily = ComposeFontFamily.Monospace),
inlineCode = bodyLarge.copy(
fontFamily = ComposeFontFamily.Monospace,
letterSpacing = TextUnit.Unspecified,
),
quote = typography.bodyMedium.scaled().plus(SpanStyle(fontStyle = FontStyle.Italic)),
paragraph = bodyLarge,
ordered = bodyLarge,
bullet = bodyLarge,
list = bodyLarge,
link = bodyLarge.copy(fontWeight = FontWeight.Bold, textDecoration = TextDecoration.Underline),
table = bodyLarge,
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,11 @@ fun VaultReaderScreen(
scrollToPage = pendingPdfPage,
onScrollConsumed = viewModel::clearPendingNavigation,
)
is VaultReaderState.MarkdownReady -> VaultMarkdownReaderScreen(
text = s.text,
settings = settings,
modifier = Modifier.fillMaxSize(),
)
}

// Warmth / blue-light overlay (#422) — screen-level tint drawn on top of
Expand Down Expand Up @@ -183,6 +188,7 @@ fun VaultReaderScreen(
private fun titleFor(state: VaultReaderState): String = when (state) {
is VaultReaderState.EpubReady -> state.title
is VaultReaderState.PdfReady -> state.title
is VaultReaderState.MarkdownReady -> state.title
else -> "Vault"
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ sealed class VaultReaderState {
* unlike EPUB where Readium owns the read lifecycle once [Publication]
* exists. */
data class PdfReady(val title: String) : VaultReaderState()
/** [text] is the whole decoded document — v1 renders it as a single
* scrollable document (see [VaultMarkdownReaderScreen]), no TOC/mermaid/
* relative-image parity with `feature:reader`'s non-vault Markdown
* reader yet (issue #442). */
data class MarkdownReady(val title: String, val text: String) : VaultReaderState()
/** Not a reading format — the caller should have routed audio to
* [VaultPlayerScreen] instead; surfaced here only as a defensive
* fallback if that dispatch is ever wrong. */
Expand Down Expand Up @@ -144,6 +149,10 @@ class VaultReaderViewModel @Inject constructor(
},
)
"PDF" -> _state.value = VaultReaderState.PdfReady(entry.title)
"MARKDOWN" -> {
val bytes = r.readAt(0L, r.plainSize.toInt())
_state.value = VaultReaderState.MarkdownReady(entry.title, bytes.toString(Charsets.UTF_8))
}
else -> _state.value = VaultReaderState.Error("Unsupported format: ${entry.format}")
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,10 @@ class VaultReaderViewModelTest {
@Test
fun `an unsupported format surfaces an Error state`() = runTest {
every { sessionManager.isUnlocked("vault-1") } returns true
coEvery { vaultStore.listEntries() } returns listOf(entry("MARKDOWN"))
// Not a real MediaFormat case — this is standing in for "some future or
// corrupted manifest entry this build doesn't understand", to keep the
// `else` branch under test now that MARKDOWN is a handled format (#442).
coEvery { vaultStore.listEntries() } returns listOf(entry("MOBI"))
every { vaultStore.openReader(fileId) } returns mockk<VaultFileReader>(relaxed = true)

val vm = viewModel()
Expand All @@ -178,6 +181,26 @@ class VaultReaderViewModelTest {
assertInstanceOf(VaultReaderState.Error::class.java, vm.state.value)
}

@Test
fun `a MARKDOWN entry opens a reader and decodes the text into MarkdownReady`() = runTest {
val markdownText = "# Heading\n\nSome body text."
val bytes = markdownText.toByteArray(Charsets.UTF_8)
every { sessionManager.isUnlocked("vault-1") } returns true
coEvery { vaultStore.listEntries() } returns listOf(entry("MARKDOWN"))
val reader = mockk<VaultFileReader>(relaxed = true)
every { reader.plainSize } returns bytes.size.toLong()
every { reader.readAt(0L, bytes.size) } returns bytes
every { vaultStore.openReader(fileId) } returns reader

val vm = viewModel()
advanceUntilIdle()

val state = vm.state.value
assertInstanceOf(VaultReaderState.MarkdownReady::class.java, state)
assertEquals("Title", (state as VaultReaderState.MarkdownReady).title)
assertEquals(markdownText, state.text)
}

// ── Bookmarks & highlights ───────────────────────────────────────────────

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import SwiftUI
struct VaultReaderView: View {
@StateObject private var viewModel: VaultReaderViewModel
@Environment(\.dismiss) private var dismiss
@Environment(\.colorScheme) private var colorScheme
@State private var showBookmarksSheet = false

init(vaultId: String, fileId: Data, sessionManager: VaultSessionManager) {
Expand Down Expand Up @@ -79,6 +80,7 @@ struct VaultReaderView: View {
private var title: String {
switch viewModel.state {
case .epubReady(let title), .pdfReady(let title): return title
case .markdownReady(let title, _): return title
default: return "Vault"
}
}
Expand Down Expand Up @@ -108,6 +110,8 @@ struct VaultReaderView: View {
epubContent
case .pdfReady:
pdfContent
case .markdownReady:
markdownContent
}
}

Expand Down Expand Up @@ -165,4 +169,31 @@ struct VaultReaderView: View {
}
}
}

/// v1-scoped, matching what's documented as out of scope on #442: no
/// per-user theme/font-size/line-spacing controls exist for the Vault
/// reader at all yet (unlike Android's `VaultReaderSettingsSheet`) — this
/// resolves colors from the system color scheme the same way `epubContent`
/// implicitly does via `LibraVaultColor.onSurface`, and uses fixed
/// typography defaults matching `ReaderView`'s own (fontSize: 1.0,
/// lineSpacing: 1.4, fontDesign: .default). No image loading (`images: [:]`
/// — no vault equivalent of the security-scoped folder access
/// `ReaderView.markdownImages` resolves relative references against), no
/// TOC navigation, and reading position isn't persisted (`initialScrollFraction:
/// 0`, `onScrollFractionChanged` a no-op) — bookmarks/highlights stay
/// disabled for this state (see `isReady`) for the same reason.
private var markdownContent: some View {
let theme: ConcreteReadingTheme = colorScheme == .dark ? .dark : .light
return MarkdownReaderContent(
blocks: viewModel.markdownBlocks,
images: [:],
colors: LibraVaultColorScheme.forReadingTheme(theme),
fontSize: 1.0,
lineSpacing: 1.4,
fontDesign: .default,
readingTheme: theme,
initialScrollFraction: 0,
onScrollFractionChanged: { _ in }
)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ enum VaultReaderState: Equatable {
case error(String)
case epubReady(title: String)
case pdfReady(title: String)
/// `text` is the whole decoded document — v1 renders it as a single
/// scrollable document via `MarkdownReaderContent`, no TOC/mermaid/
/// relative-image parity with the non-vault reader yet (issue #442).
case markdownReady(title: String, text: String)
/// Not a reading format — the caller should have routed audio to
/// `VaultPlayerView` instead. Surfaced only as a defensive fallback if
/// that dispatch is ever wrong, mirroring Android's identical
Expand All @@ -29,6 +33,7 @@ enum VaultReaderState: Equatable {
case (.error(let a), .error(let b)): return a == b
case (.epubReady(let a), .epubReady(let b)): return a == b
case (.pdfReady(let a), .pdfReady(let b)): return a == b
case (.markdownReady(let at, let ax), .markdownReady(let bt, let bx)): return at == bt && ax == bx
case (.wrongScreen(let a), .wrongScreen(let b)): return a == b
default: return false
}
Expand Down Expand Up @@ -61,6 +66,7 @@ final class VaultReaderViewModel: ObservableObject {
@Published private(set) var state: VaultReaderState = .loading
@Published private(set) var chapters: [BookChapter] = []
@Published private(set) var pdfDocument: PDFDocument?
@Published private(set) var markdownBlocks: [MarkdownBlock] = []
@Published private(set) var bookmarks: [VaultBookmark] = []
@Published private(set) var highlights: [VaultHighlight] = []
@Published var currentChapterIndex: Int = 0
Expand Down Expand Up @@ -113,6 +119,10 @@ final class VaultReaderViewModel: ObservableObject {
}
pdfDocument = document
state = .pdfReady(title: entry.title)
case "markdown":
let text = String(decoding: content, as: UTF8.self)
markdownBlocks = MarkdownDocumentParser.parse(text)
state = .markdownReady(title: entry.title, text: text)
default:
state = .error("Unsupported format: \(entry.format)")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,16 @@ final class VaultReaderViewModelTests: XCTestCase {
return entry.fileId
}

private func importFixtureMarkdown(into manager: VaultSessionManager, vaultId: String, text: String) async throws -> Data {
let data = Data(text.utf8)
let store = await manager.requireUnlocked(vaultId)
let input = InputStream(data: data)
input.open()
let entry = try store.importFile(input: input, declaredSize: Int64(data.count), title: "My Notes", author: nil, format: "markdown")
input.close()
return entry.fileId
}

/// Regression coverage for the QA gap this file originally shipped
/// with: nothing exercised `VaultReaderViewModel.load()`'s
/// `PDFDocument(data:)` success branch through to `.pdfReady` — every
Expand Down Expand Up @@ -152,6 +162,20 @@ final class VaultReaderViewModelTests: XCTestCase {
}
}

/// #442 — a "markdown" entry used to fall through to the `default` branch
/// and surface "Unsupported format: markdown" instead of opening.
func testLoadMarkdownReadyExposesTheDecodedTextAndParsedBlocks() async throws {
let (manager, id) = try await makeUnlockedVault()
let markdownText = "# Heading\n\nSome body text."
let fileId = try await importFixtureMarkdown(into: manager, vaultId: id, text: markdownText)

let vm = VaultReaderViewModel(vaultId: id, fileId: fileId, sessionManager: manager)
await vm.load()

XCTAssertEqual(vm.state, .markdownReady(title: "My Notes", text: markdownText))
XCTAssertEqual(vm.markdownBlocks.count, 2)
}

/// Round-trips a bookmark through the encrypted manifest — #203's
/// acceptance criterion — by reading it back from a *second*, freshly
/// constructed view model against the same vault, not just the same
Expand Down
Loading