diff --git a/SeforimApp/src/commonMain/composeResources/values/strings.xml b/SeforimApp/src/commonMain/composeResources/values/strings.xml index 23968ba45..c7be1a2f7 100644 --- a/SeforimApp/src/commonMain/composeResources/values/strings.xml +++ b/SeforimApp/src/commonMain/composeResources/values/strings.xml @@ -212,6 +212,8 @@ אין הערות על השורות שנבחרו. בחר טקסט ולחץ "הוסף הערה". אין צורך לכתוב הערה על השורה כולה: ניתן לסמן מילים מסוימות, ללחוץ לחיצה ימנית ולבחור "הוסף הערה" כדי לכתוב הערה על קטע מדויק בלבד. מחק הערה + עריכה + תצוגה כלים diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/AppNativeMenuBar.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/AppNativeMenuBar.kt index 5b5fc3b59..78fbdc811 100644 --- a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/AppNativeMenuBar.kt +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/AppNativeMenuBar.kt @@ -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 @@ -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)) diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/NotesPopup.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/NotesPopup.kt index b0ea6e99e..d75ecaf4b 100644 --- a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/NotesPopup.kt +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/components/NotesPopup.kt @@ -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 @@ -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)) diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/text/MarkdownText.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/text/MarkdownText.kt new file mode 100644 index 000000000..e670d5b84 --- /dev/null +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/text/MarkdownText.kt @@ -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("""(? 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 @@ -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 @@ -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), + ) } } } diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/home/widgets/library/LibraryWidgets.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/home/widgets/library/LibraryWidgets.kt index d8658d6c4..89af58d88 100644 --- a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/home/widgets/library/LibraryWidgets.kt +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/home/widgets/library/LibraryWidgets.kt @@ -41,6 +41,7 @@ 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.history.destination +import io.github.kdroidfilter.seforimapp.core.presentation.text.markdownToPlainText import io.github.kdroidfilter.seforimapp.features.home.widgets.CellSpan import io.github.kdroidfilter.seforimapp.features.home.widgets.FitColumn import io.github.kdroidfilter.seforimapp.features.home.widgets.HomeWidget @@ -254,7 +255,12 @@ internal object NotesWidget : HomeWidget { ) { VectorIcon(NotebookPen, Modifier.padding(top = 1.dp), accent) Column(Modifier.weight(1f)) { - Text(bookNote.note.note, fontSize = 13.sp, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text( + markdownToPlainText(bookNote.note.note), + fontSize = 13.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) Text( listOf(bookNote.note.quote, bookTitle).filter { it.isNotBlank() }.joinToString(" · "), fontSize = 11.sp, diff --git a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/notes/NotesScreen.kt b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/notes/NotesScreen.kt index 57cd9379e..82342808b 100644 --- a/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/notes/NotesScreen.kt +++ b/SeforimApp/src/jvmMain/kotlin/io/github/kdroidfilter/seforimapp/features/notes/NotesScreen.kt @@ -24,6 +24,7 @@ import io.github.kdroidfilter.seforimapp.core.presentation.components.ListRow import io.github.kdroidfilter.seforimapp.core.presentation.components.PageHeader import io.github.kdroidfilter.seforimapp.core.presentation.components.PageSearchField import io.github.kdroidfilter.seforimapp.core.presentation.components.SectionHeader +import io.github.kdroidfilter.seforimapp.core.presentation.text.markdownToPlainText import io.github.kdroidfilter.seforimapp.framework.desktop.LocalOpenWindow import io.github.kdroidfilter.seforimapp.framework.di.LocalAppGraph import io.github.kdroidfilter.seforimapp.icons.NotebookPen @@ -111,7 +112,7 @@ private fun BookNotesCard( notes.forEachIndexed { index, bookNote -> val note = bookNote.note ListRow( - title = note.note, + title = markdownToPlainText(note.note), subtitle = listOf( note.quote, diff --git a/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/text/MarkdownTextTest.kt b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/text/MarkdownTextTest.kt new file mode 100644 index 000000000..c6c087712 --- /dev/null +++ b/SeforimApp/src/jvmTest/kotlin/io/github/kdroidfilter/seforimapp/core/presentation/text/MarkdownTextTest.kt @@ -0,0 +1,82 @@ +package io.github.kdroidfilter.seforimapp.core.presentation.text + +import kotlin.test.Test +import kotlin.test.assertEquals + +class MarkdownTextTest { + @Test + fun plain_text_is_unchanged() { + assertEquals("הערה פשוטה", markdownToPlainText("הערה פשוטה")) + } + + @Test + fun blank_input_gives_empty_string() { + assertEquals("", markdownToPlainText(" \n\n ")) + } + + @Test + fun headings_lose_their_hashes() { + assertEquals("כותרת", markdownToPlainText("## כותרת")) + assertEquals("Title", markdownToPlainText("# Title #")) + assertEquals("#hashtag", markdownToPlainText("#hashtag")) + } + + @Test + fun emphasis_markers_are_removed() { + assertEquals("bold and italic and both", markdownToPlainText("**bold** and *italic* and ***both***")) + assertEquals("strong and em", markdownToPlainText("__strong__ and _em_")) + assertEquals("gone", markdownToPlainText("~~gone~~")) + } + + @Test + fun underscores_inside_words_are_kept() { + assertEquals("snake_case_name", markdownToPlainText("snake_case_name")) + } + + @Test + fun lone_asterisks_are_kept() { + assertEquals("2 * 3 * 4", markdownToPlainText("2 * 3 * 4")) + } + + @Test + fun inline_code_keeps_its_literal_content() { + assertEquals("run a*b*c now", markdownToPlainText("run `a*b*c` now")) + assertEquals("x `y` z", markdownToPlainText("x `` `y` `` z")) + } + + @Test + fun links_and_images_keep_their_text() { + assertEquals("see the site", markdownToPlainText("see [the site](https://example.com)")) + assertEquals("logo here", markdownToPlainText("![logo](a.png) here")) + assertEquals("https://example.com", markdownToPlainText("")) + } + + @Test + fun list_markers_and_task_boxes_are_removed() { + assertEquals("one two three done", markdownToPlainText("- one\n* two\n1. three\n- [x] done")) + } + + @Test + fun blockquotes_are_removed() { + assertEquals("quoted nested item", markdownToPlainText("> quoted\n> > nested\n> - item")) + } + + @Test + fun fences_and_rules_are_dropped_and_lines_joined() { + assertEquals("before code after", markdownToPlainText("before\n```kotlin\ncode\n```\n---\nafter")) + } + + @Test + fun escapes_resolve_to_literal_characters() { + assertEquals("*not italic* and # not heading", markdownToPlainText("\\*not italic\\* and \\# not heading")) + assertEquals("a\\b", markdownToPlainText("a\\\\b")) + } + + @Test + fun hebrew_markdown_is_flattened() { + assertEquals( + "עיין רש\"י שם וראה גם תוספות", + markdownToPlainText("### עיין **רש\"י** שם\n\n- וראה גם [תוספות](https://example.com)"), + ) + } +}