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
2 changes: 2 additions & 0 deletions SeforimApp/src/commonMain/composeResources/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@
<string name="no_notes_for_selection">אין הערות על השורות שנבחרו. בחר טקסט ולחץ "הוסף הערה".</string>
<string name="notes_info_word_level">אין צורך לכתוב הערה על השורה כולה: ניתן לסמן מילים מסוימות, ללחוץ לחיצה ימנית ולבחור "הוסף הערה" כדי לכתוב הערה על קטע מדויק בלבד.</string>
<string name="delete_note">מחק הערה</string>
<string name="note_edit">עריכה</string>
<string name="note_preview">תצוגה</string>

<!-- Book Content Screen - End Vertical Bar -->
<string name="tools">כלים</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import io.github.kdroidfilter.seforimapp.core.favorites.FavoriteEntry
import io.github.kdroidfilter.seforimapp.core.favorites.FavoriteFolder
import io.github.kdroidfilter.seforimapp.core.history.VisitEntry
import io.github.kdroidfilter.seforimapp.core.history.VisitKind
import io.github.kdroidfilter.seforimapp.core.presentation.text.markdownToPlainText
import io.github.kdroidfilter.seforimapp.core.presentation.theme.AccentColor
import io.github.kdroidfilter.seforimapp.core.presentation.theme.IntUiThemes
import io.github.kdroidfilter.seforimapp.core.presentation.utils.hasFindInPage
Expand Down Expand Up @@ -399,7 +400,7 @@ fun AppNativeMenuBar(
Separator()
recentNotes.forEach { bookNote ->
Item(
text = bookNote.note.note.take(MENU_TITLE_MAX_LENGTH),
text = markdownToPlainText(bookNote.note.note).take(MENU_TITLE_MAX_LENGTH),
icon = NsMenuItemImage.SystemSymbol("square.and.pencil"),
) {
tabsViewModel.openTab(noteDestination(bookNote))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupProperties
import io.github.kdroidfilter.seforim.tabs.TabType
import io.github.kdroidfilter.seforimapp.core.presentation.text.markdownToPlainText
import io.github.kdroidfilter.seforimapp.features.notes.noteDestination
import io.github.kdroidfilter.seforimapp.features.notes.openNotesTab
import io.github.kdroidfilter.seforimapp.features.notes.rememberUserNotes
Expand Down Expand Up @@ -104,7 +105,7 @@ private fun NotesPopupContent(onDismiss: () -> Unit) {
item(key = "book-$bookId") { PopupSectionHeader(userNotes.bookTitles[bookId].orEmpty()) }
items(bookNotes, key = { "note-" + it.note.id }) { bookNote ->
PopupRow(
label = bookNote.note.note,
label = markdownToPlainText(bookNote.note.note),
tabType = TabType.NOTES,
onClick = {
tabsViewModel.openTab(noteDestination(bookNote))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package io.github.kdroidfilter.seforimapp.core.presentation.text

/** Characters Markdown lets a backslash escape (CommonMark: any ASCII punctuation; these are the ones that matter here). */
private const val ESCAPABLE = "\\`*_{}[]()#+-.!>~|<"

/** Private-use base: an escaped or code-span character is parked at [PROTECT_BASE] + its code until the very end. */
private const val PROTECT_BASE = 0xE000

private val ESCAPE = Regex("""\\([\\`*_{}\[\]()#+\-.!>~|<])""")
private val CODE_SPAN = Regex("""(`+)(.+?)\1""")
private val FENCE = Regex("""^\s*(```|~~~).*$""")
private val HORIZONTAL_RULE = Regex("""^\s*([-*_])(\s*\1){2,}\s*$""")
private val BLOCKQUOTE = Regex("""^\s*(>\s?)+""")
private val HEADING = Regex("""^\s*#{1,6}(\s+|$)""")
private val CLOSING_HASHES = Regex("""\s+#+\s*$""")
private val LIST_MARKER = Regex("""^\s*([-*+]|\d{1,9}[.)])\s+""")
private val TASK_BOX = Regex("""^\[[ xX]]\s+""")
private val IMAGE = Regex("""!\[([^\]]*)]\([^)]*\)""")
private val LINK = Regex("""\[([^\]]*)]\([^)]*\)""")
private val AUTOLINK = Regex("""<((?:https?|mailto):[^>\s]+)>""")
private val STRONG_STARS = Regex("""\*\*(.+?)\*\*""")
private val EM_STAR = Regex("""\*(\S(?:.*?\S)?)\*""")

// Underscore emphasis only counts at word boundaries, so snake_case (or Hebrew joined by "_") stays intact.
private val STRONG_UNDERSCORES = Regex("""(?<![\p{L}\p{N}])__(.+?)__(?![\p{L}\p{N}])""")
private val EM_UNDERSCORE = Regex("""(?<![\p{L}\p{N}])_(\S(?:.*?\S)?)_(?![\p{L}\p{N}])""")
private val STRIKETHROUGH = Regex("""~~(.+?)~~""")
private val WHITESPACE = Regex("""\s+""")

/**
* Flattens a Markdown note to a single line of plain text, for places that show it as a title or a
* menu entry: drops headings, emphasis (`*`, `_`, `**`, `__`, `~~`), inline code, link and image syntax
* (keeping the visible text), list markers, task boxes, blockquotes, fences and horizontal rules, then
* joins the remaining lines with single spaces. Backslash escapes resolve to the literal character.
*/
fun markdownToPlainText(markdown: String): String {
if (markdown.isBlank()) return ""
val protected = ESCAPE.replace(markdown) { protect(it.groupValues[1]) }
return protected
.lineSequence()
.filterNot { FENCE.matches(it) || HORIZONTAL_RULE.matches(it) }
.map(::stripLine)
.filter { it.isNotBlank() }
.joinToString(" ")
.replace(WHITESPACE, " ")
.trim()
.let(::unprotect)
}

private fun stripLine(line: String): String {
// Code spans first: their content is literal, so park it out of reach of the emphasis rules.
var text = CODE_SPAN.replace(line) { protect(it.groupValues[2].trim()) }
text = BLOCKQUOTE.replace(text, "")
if (HEADING.containsMatchIn(text)) {
text = CLOSING_HASHES.replace(HEADING.replace(text, ""), "")
}
text = LIST_MARKER.replace(text, "")
text = TASK_BOX.replace(text, "")
text = IMAGE.replace(text) { it.groupValues[1] }
text = LINK.replace(text) { it.groupValues[1] }
text = AUTOLINK.replace(text) { it.groupValues[1] }
text = STRONG_STARS.replace(text) { it.groupValues[1] }
text = STRONG_UNDERSCORES.replace(text) { it.groupValues[1] }
text = EM_STAR.replace(text) { it.groupValues[1] }
text = EM_UNDERSCORE.replace(text) { it.groupValues[1] }
text = STRIKETHROUGH.replace(text) { it.groupValues[1] }
return text
}

/** Maps Markdown punctuation in [text] to private-use characters, so no later rule treats it as syntax. */
private fun protect(text: String): String =
buildString(text.length) {
for (c in text) {
append(if (c in ESCAPABLE) (PROTECT_BASE + c.code).toChar() else c)
}
}

private fun unprotect(text: String): String =
buildString(text.length) {
for (c in text) {
val original = c.code - PROTECT_BASE
append(if (original in 0..0x7F && original.toChar() in ESCAPABLE) original.toChar() else c)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
Expand All @@ -54,6 +55,8 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import io.github.kdroidfilter.seforim.htmlparser.buildAnnotatedFromHtml
import io.github.kdroidfilter.seforimapp.core.annotations.NoteStore
import io.github.kdroidfilter.seforimapp.core.presentation.components.AccentMarkdown
import io.github.kdroidfilter.seforimapp.core.presentation.utils.UrlOpener
import io.github.kdroidfilter.seforimapp.features.bookcontent.BookContentEvent
import io.github.kdroidfilter.seforimapp.features.bookcontent.PlainTextMenus
import io.github.kdroidfilter.seforimapp.features.bookcontent.state.BookContentState
Expand All @@ -72,12 +75,15 @@ import org.jetbrains.jewel.ui.component.IconActionButton
import org.jetbrains.jewel.ui.component.InlineInformationBanner
import org.jetbrains.jewel.ui.component.Text
import org.jetbrains.jewel.ui.component.TextArea
import org.jetbrains.jewel.ui.component.Tooltip
import org.jetbrains.jewel.ui.icons.AllIconsKeys
import seforimapp.seforimapp.generated.resources.Res
import seforimapp.seforimapp.generated.resources.delete_note
import seforimapp.seforimapp.generated.resources.no_notes_for_selection
import seforimapp.seforimapp.generated.resources.no_notes_saved
import seforimapp.seforimapp.generated.resources.note_body_placeholder
import seforimapp.seforimapp.generated.resources.note_edit
import seforimapp.seforimapp.generated.resources.note_preview
import seforimapp.seforimapp.generated.resources.notes_info_word_level
import seforimapp.seforimapp.generated.resources.notes_pane
import java.time.Instant
Expand Down Expand Up @@ -408,11 +414,15 @@ private fun NoteCard(
}

/**
* Auto-saving note editor: a multi-line field plus a footer carrying the last-edit stamp and a
* hover-revealed trash button. Text changes are debounced and pushed to [onPersist] (no explicit
* save). [onDelete] removes the note (or the draft's created note); when [clearOnDelete] is true the
* field is also emptied so the draft editor stays in place. [timestampMillis] (when > 0) renders the
* footer stamp; [cardHovered] gates the trash button's visibility.
* Auto-saving note editor with two modes. In edit mode it is a multi-line field whose changes are
* debounced and pushed to [onPersist] (no explicit save), and flushed on focus loss. In view mode the
* note is rendered as Markdown; a double-click or the footer's edit action switches back to editing.
* Saved notes open in view mode; blank or [autoFocus]ed (draft) notes open in edit mode, and a blank
* note is always edited since there is nothing to render.
*
* The footer carries the last-edit stamp ([timestampMillis], when > 0) plus the hover-revealed
* ([cardHovered]) mode toggle and trash. [onDelete] removes the note (or the draft's created note);
* when [clearOnDelete] is true the field is also emptied so the draft editor stays in place.
*/
@OptIn(FlowPreview::class, ExperimentalFoundationApi::class)
@Composable
Expand All @@ -429,9 +439,18 @@ private fun NoteEditor(
val focusRequester = remember { FocusRequester() }
val currentOnPersist by rememberUpdatedState(onPersist)
var hadFocus by remember { mutableStateOf(false) }
var editing by remember { mutableStateOf(initialText.isBlank() || autoFocus) }
// Bumped to focus the field once it is (re)composed after leaving view mode.
var focusRequests by remember { mutableIntStateOf(0) }
val isBlank = state.text.isBlank()
val showField = editing || isBlank

if (autoFocus) {
LaunchedEffect(Unit) { focusRequester.requestFocus() }
}
LaunchedEffect(focusRequests) {
if (focusRequests > 0) focusRequester.requestFocus()
}
LaunchedEffect(Unit) {
snapshotFlow { state.text.toString() }
.drop(1) // skip the initial value; only react to edits
Expand All @@ -440,58 +459,136 @@ private fun NoteEditor(
.catch { }
.collect { currentOnPersist(it) }
}
Column(modifier = Modifier.fillMaxWidth()) {
PlainTextMenus {
TextArea(
state = state,
placeholder = { Text(stringResource(Res.string.note_body_placeholder)) },
// A bounded max height is required inside the LazyColumn (infinite incoming height).
modifier =
Modifier
.fillMaxWidth()
.heightIn(min = 64.dp, max = 220.dp)
.focusRequester(focusRequester)
// Persist immediately when the field loses focus (clicking outside it),
// instead of waiting for the debounce.
.onFocusChanged { focusState ->
if (hadFocus && !focusState.isFocused) {
currentOnPersist(state.text.toString())
}
hadFocus = focusState.isFocused
},
)
}
val startEditing: () -> Unit = {
editing = true
focusRequests++
}

// Fixed-height footer so revealing the trash on hover never reflows the card.
Row(
modifier = Modifier.fillMaxWidth().height(26.dp).padding(top = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
val stamp = timestampMillis?.takeIf { it > 0L }
if (stamp != null) {
Text(
text = formatNoteTime(stamp),
fontSize = 11.sp,
color =
JewelTheme.globalColors.text.info
.copy(alpha = 0.7f),
modifier = Modifier.weight(1f),
Column(modifier = Modifier.fillMaxWidth()) {
if (showField) {
PlainTextMenus {
TextArea(
state = state,
placeholder = { Text(stringResource(Res.string.note_body_placeholder)) },
// A bounded max height is required inside the LazyColumn (infinite incoming height).
modifier =
Modifier
.fillMaxWidth()
.heightIn(min = 64.dp, max = 220.dp)
.focusRequester(focusRequester)
// Persist immediately when the field loses focus (clicking outside it),
// instead of waiting for the debounce, then show the rendered note.
.onFocusChanged { focusState ->
if (hadFocus && !focusState.isFocused) {
currentOnPersist(state.text.toString())
if (state.text.isNotBlank()) editing = false
}
hadFocus = focusState.isFocused
},
)
} else {
Spacer(modifier = Modifier.weight(1f))
}
} else {
NoteMarkdownView(markdown = state.text.toString(), onDoubleClick = startEditing)
}

NoteFooter(
timestampMillis = timestampMillis,
showActions = cardHovered && !isBlank,
editing = showField,
// Explicit targets rather than a toggle: pressing the button may first blur the field,
// which already switches to view mode on its own. Leaving edit mode flushes the text too.
onToggleMode =
if (showField) {
{
currentOnPersist(state.text.toString())
editing = false
}
} else {
startEditing
},
onDelete = {
if (clearOnDelete) state.clearText()
onDelete()
},
)
}
}

val canDelete = state.text.isNotBlank()
if (cardHovered && canDelete) {
/**
* Read-only Markdown rendering of a note, sized like the edit field's text. A double-click asks to
* edit; a single tap clears focus like a tap anywhere else in the pane (this detector consumes it).
*/
@Composable
private fun NoteMarkdownView(
markdown: String,
onDoubleClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val focusManager = LocalFocusManager.current
val currentOnDoubleClick by rememberUpdatedState(onDoubleClick)
AccentMarkdown(
markdown = markdown,
onUrlClick = UrlOpener::open,
fontSize = 13.sp,
lineHeight = 20.sp,
modifier =
modifier
.fillMaxWidth()
.pointerInput(Unit) {
detectTapGestures(
onTap = { focusManager.clearFocus() },
onDoubleTap = { currentOnDoubleClick() },
)
}.padding(horizontal = 6.dp, vertical = 4.dp),
)
}

/**
* Fixed-height note footer: the last-edit stamp, then (while [showActions]) the edit/preview toggle
* and the trash. The height never changes, so revealing the actions on hover never reflows the card.
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun NoteFooter(
timestampMillis: Long?,
showActions: Boolean,
editing: Boolean,
onToggleMode: () -> Unit,
onDelete: () -> Unit,
modifier: Modifier = Modifier,
) {
Row(
modifier = modifier.fillMaxWidth().height(26.dp).padding(top = 2.dp),
verticalAlignment = Alignment.CenterVertically,
) {
val stamp = timestampMillis?.takeIf { it > 0L }
if (stamp != null) {
Text(
text = formatNoteTime(stamp),
fontSize = 11.sp,
color =
JewelTheme.globalColors.text.info
.copy(alpha = 0.7f),
modifier = Modifier.weight(1f),
)
} else {
Spacer(modifier = Modifier.weight(1f))
}

if (showActions) {
val modeLabel = stringResource(if (editing) Res.string.note_preview else Res.string.note_edit)
Tooltip({ Text(modeLabel) }) {
IconActionButton(
key = AllIconsKeys.General.Delete,
onClick = {
if (clearOnDelete) state.clearText()
onDelete()
},
contentDescription = stringResource(Res.string.delete_note),
key = if (editing) AllIconsKeys.Actions.Preview else AllIconsKeys.Actions.Edit,
onClick = onToggleMode,
contentDescription = modeLabel,
)
}
IconActionButton(
key = AllIconsKeys.General.Delete,
onClick = onDelete,
contentDescription = stringResource(Res.string.delete_note),
)
}
}
}
Loading