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
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@
<string name="settings_spellcheck_language_same_as_app">Stejné jako jazyk aplikace</string>
<string name="no_spell_check">Bez kontroly pravopisu</string>
<string name="image_size_header">Velikost obrázku</string>
<string name="image_remove">Odebrat</string>
<string name="image_size_original">Původní velikost</string>
<string name="image_size_reset">Obnovit velikost</string>
<string name="export_pdf_context_menu_item">Exportovat do PDF</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@
<string name="settings_spellcheck_language_same_as_app">Wie die Sprache der App</string>
<string name="no_spell_check">Keine Rechtschreibprüfung</string>
<string name="image_size_header">Bildgröße</string>
<string name="image_remove">Entfernen</string>
<string name="image_size_original">Originalgröße</string>
<string name="image_size_reset">Größe zurücksetzen</string>
<string name="export_pdf_context_menu_item">Als PDF exportieren</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@
<string name="settings_spellcheck_language_same_as_app">Igual que el idioma de la aplicación</string>
<string name="no_spell_check">Sin corrector ortográfico</string>
<string name="image_size_header">Tamaño de la imagen</string>
<string name="image_remove">Quitar</string>
<string name="image_size_original">Tamaño original</string>
<string name="image_size_reset">Restablecer tamaño</string>
<string name="export_pdf_context_menu_item">Exportar a PDF</string>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@
<string name="settings_spellcheck_language_same_as_app">与应用语言相同</string>
<string name="no_spell_check">不检查拼写</string>
<string name="image_size_header">图片大小</string>
<string name="image_remove">移除</string>
<string name="image_size_original">原始大小</string>
<string name="image_size_reset">重置大小</string>
<string name="export_pdf_context_menu_item">导出为 PDF</string>
Expand Down
1 change: 1 addition & 0 deletions shared/src/commonMain/composeResources/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@
<string name="settings_spellcheck_language_label">Spell check language</string>
<string name="settings_spellcheck_language_same_as_app">Same as app language</string>
<string name="image_size_header">Image size</string>
<string name="image_remove">Remove</string>
<string name="image_size_original">Original size</string>
<string name="image_size_reset">Reset size</string>
<string name="export_pdf_context_menu_item">Export to PDF</string>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package dev.jotalac.core.ui.components

import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import androidx.compose.ui.input.pointer.PointerEventPass
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalFocusManager

/**
* Ends the editing of the note when something outside of the editor is pressed - the sidebar, the title bar.
* The open editor says how in [onOutsidePress]; without one the focus is just cleared.
*/
class EditorUnfocus {
var onOutsidePress: (() -> Unit)? = null
}

val LocalEditorUnfocus = staticCompositionLocalOf { EditorUnfocus() }

/** A press here takes the cursor out of the note. The press itself is left alone, it still does what it does. */
fun Modifier.unfocusEditorOnPress(): Modifier = composed {
val editorUnfocus = LocalEditorUnfocus.current
val focusManager = LocalFocusManager.current
pointerInput(editorUnfocus) {
awaitEachGesture {
awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial)
editorUnfocus.onOutsidePress?.invoke() ?: focusManager.clearFocus()
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package dev.jotalac.core.ui.window

import dev.jotalac.core.ui.components.unfocusEditorOnPress
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
Expand Down Expand Up @@ -27,7 +28,8 @@ internal fun WindowTitleBar(host: TitleBarHost) {
contentColor = MaterialTheme.colorScheme.onSurface,
modifier = Modifier
.fillMaxWidth()
.draggableWindow(),
.draggableWindow()
.unfocusEditorOnPress(),
) {
Column(modifier = Modifier.fillMaxWidth()) {
Row(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,13 @@ import androidx.compose.ui.input.key.*
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFocusManager
import dev.jotalac.core.ui.components.LocalEditorUnfocus
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import dev.jotalac.core.ui.components.AppVerticalScrollbar
import dev.jotalac.core.ui.components.unfocusEditorOnPress
import dev.jotalac.core.utils.isDesktopPlatform
import dev.jotalac.core.utils.onExternalImageDrop
import dev.jotalac.core.utils.requestFocusSafely
Expand Down Expand Up @@ -85,6 +88,26 @@ fun MarkdownEditor(
if (isDesktopPlatform) surfaceFocusRequester.requestFocusSafely()
}

// click outside the editor text field unfocuses the editor
val focusManager = LocalFocusManager.current
val editorUnfocus = LocalEditorUnfocus.current
DisposableEffect(editorUnfocus) {
val onOutsidePress = {
if (editorState.isFocused) {
if (isDesktopPlatform) surfaceFocusRequester.requestFocusSafely() else focusManager.clearFocus()
}
}
editorUnfocus.onOutsidePress = onOutsidePress
onDispose { if (editorUnfocus.onOutsidePress === onOutsidePress) editorUnfocus.onOutsidePress = null }
}

// on a phone, hiding the keyboard ends the editing too - no cursor without a keyboard
var wasKeyboardOpen by remember { mutableStateOf(false) }
LaunchedEffect(isKeyboardOpen) {
if (wasKeyboardOpen && !isKeyboardOpen && !isDesktopPlatform) focusManager.clearFocus()
wasKeyboardOpen = isKeyboardOpen
}

fun selectMatch(match: FindMatch?) {
match?.let { editorState.select(TextRange(it.start, it.end)) }
}
Expand Down Expand Up @@ -124,6 +147,7 @@ fun MarkdownEditor(
.fillMaxSize()
.padding(bottom = if (isToolbarShown) toolbarHeight else 0.dp)
.verticalScroll(scrollState)
.unfocusEditorOnPress()
.padding(top = if (findState.isOpen) 50.dp else 0.dp),
horizontalAlignment = Alignment.CenterHorizontally,
) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
package dev.jotalac.feature.editor.ui.components.markdown_rendering

import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.gestures.awaitLongPressOrCancellation
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
Expand All @@ -25,6 +33,8 @@ import dev.jotalac.core.ui.components.DesktopContextMenu
import dev.jotalac.core.ui.components.onContextMenuOpen
import dev.jotalac.core.utils.isDesktopPlatform
import git_writer.shared.generated.resources.Res
import git_writer.shared.generated.resources.delete
import git_writer.shared.generated.resources.image_remove
import git_writer.shared.generated.resources.image_size_header
import git_writer.shared.generated.resources.image_size_original
import org.intellij.markdown.MarkdownElementTypes
Expand All @@ -33,11 +43,8 @@ import org.jetbrains.compose.resources.stringResource
import kotlin.math.roundToInt

/**
* A markdown image - like the library's MarkdownImage, which has no way to set a size, plus the
* Obsidian style size in the alt text: `![photo|300](images/photo.png)`, see [ImageAlt].
*
* With [onTextChange] (the block can be edited) a right click on desktop offers sizes relative to the
* picture, and the block's text is changed to the chosen one.
* An image drawn in markdown note
* Using obsidian-like image sizes - ![alttext|WidthxHeight](source)
*/
@Composable
fun CustomImageComponent(
Expand All @@ -51,9 +58,16 @@ fun CustomImageComponent(
// the size of the loaded picture, unspecified until it has loaded
val pictureSize = imageTransformer.intrinsicSize(imageData.painter)

// the scales need the picture's size, known once it has loaded
val canResize = onTextChange != null && isDesktopPlatform && pictureSize.hasArea()
var menuPosition by remember { mutableStateOf<DpOffset?>(null) }
val haptic = LocalHapticFeedback.current
val menuModifier = when {
onTextChange == null -> Modifier
isDesktopPlatform -> Modifier.onContextMenuOpen { menuPosition = it }
else -> Modifier.onLongPress {
haptic.performHapticFeedback(HapticFeedbackType.LongPress)
menuPosition = DpOffset.Zero
}
}

Box {
Image(
Expand All @@ -62,7 +76,7 @@ fun CustomImageComponent(
modifier = imageData.modifier
.imageSize(alt, pictureSize)
.clip(RoundedCornerShape(8.dp))
.then(if (canResize) Modifier.onContextMenuOpen { menuPosition = it } else Modifier),
.then(menuModifier),
alignment = imageData.alignment,
contentScale = if (alt.isStretched) ContentScale.FillBounds else imageData.contentScale,
alpha = imageData.alpha,
Expand All @@ -72,34 +86,73 @@ fun CustomImageComponent(
menuPosition?.let { position ->
// anchored at the click, so the menu opens there however tall the image is
Box(Modifier.offset(position.x, position.y)) {
ImageSizeMenu(
ImageContextMenu(
onDismissRequest = { menuPosition = null },
onSizeSelected = { width ->
model.node.resizedIn(model.content, width)?.let { onTextChange?.invoke(it) }
},
pictureWidth = pictureSize.width,
onImageDeleted = { onTextChange?.invoke("") },
// the scales need the picture's size, known once it has loaded
pictureWidth = pictureSize.takeIf { it.hasArea() }?.width,
)
}
}
}
}

// a menu at the pointer on desktop, a sheet from the bottom on a phone
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ImageSizeMenu(
private fun ImageContextMenu(
onDismissRequest: () -> Unit,
onSizeSelected: (width: Int?) -> Unit,
pictureWidth: Float,
onImageDeleted: () -> Unit,
pictureWidth: Float?,
) {
DesktopContextMenu(expanded = true, onDismissRequest = onDismissRequest, offset = DpOffset.Zero) {
ContextMenuHeader(stringResource(Res.string.image_size_header))

IMAGE_SCALES.forEach { scale ->
ContextMenuItem(
text = scale.scaleLabel(),
onClick = { onSizeSelected(scaledImageWidth(pictureWidth, scale)) },
onDismissRequest = onDismissRequest,
val items: @Composable () -> Unit = {
if (pictureWidth != null) {
ContextMenuHeader(stringResource(Res.string.image_size_header))
IMAGE_SCALES.forEach { scale ->
ContextMenuItem(
text = scale.scaleLabel(),
onClick = { onSizeSelected(scaledImageWidth(pictureWidth, scale)) },
onDismissRequest = onDismissRequest,
)
}
HorizontalDivider(
color = MaterialTheme.colorScheme.outlineVariant,
modifier = Modifier.padding(horizontal = 3.dp, vertical = 4.dp),
)
}
ContextMenuItem(
text = stringResource(Res.string.image_remove),
iconPainter = Res.drawable.delete,
onClick = onImageDeleted,
onDismissRequest = onDismissRequest,
itemColor = MaterialTheme.colorScheme.error,
)
}

if (isDesktopPlatform) {
DesktopContextMenu(expanded = true, onDismissRequest = onDismissRequest, offset = DpOffset.Zero, content = items)
} else {
ModalBottomSheet(onDismissRequest = onDismissRequest) {
Column(modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp).padding(bottom = 24.dp)) { items() }
}
}
}

// a long press on image on phone
private fun Modifier.onLongPress(onLongPress: () -> Unit): Modifier = pointerInput(Unit) {
awaitEachGesture {
val down = awaitFirstDown(requireUnconsumed = false)
if (awaitLongPressOrCancellation(down.id) != null) {
onLongPress()
do {
val event = awaitPointerEvent()
event.changes.forEach { it.consume() }
} while (event.changes.any { it.pressed })
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,10 @@ private val HEADINGS = mapOf(
)

// i dont know if anybody actually uses this settext markdown syntax????
private val SETEXT_HEADINGS = mapOf(MarkdownElementTypes.SETEXT_1 to 1, MarkdownElementTypes.SETEXT_2 to 2)
// the hashes of a `# heading`, with the space after them
private val ATX_HASHES = Regex("(#{1,6})[ \\t]+(?=\\S)")
private val SETEXT_HEADINGS = setOf<IElementType>(MarkdownElementTypes.SETEXT_1, MarkdownElementTypes.SETEXT_2)

private val SETEXT_UNDERLINES = setOf<IElementType>(MarkdownTokenTypes.SETEXT_1, MarkdownTokenTypes.SETEXT_2)

private val LIST_MARKERS = setOf<IElementType>(MarkdownTokenTypes.LIST_BULLET, MarkdownTokenTypes.LIST_NUMBER)

Expand Down Expand Up @@ -90,7 +91,7 @@ private class DecorationCollector(private val text: String, private val selectio
private fun block(node: ASTNode, isTopLevel: Boolean, listDepth: Int) {
// if a block is heading
HEADINGS[node.type]?.let { return atxHeading(node, it) }
SETEXT_HEADINGS[node.type]?.let { return setextHeading(node, it) }
if (node.type in SETEXT_HEADINGS) return textWithUnderline(node, isTopLevel)

// get the block type and render it
when (node.type) {
Expand Down Expand Up @@ -142,22 +143,16 @@ private class DecorationCollector(private val text: String, private val selectio
val closing = node.children.lastOrNull { it.type == MarkdownTokenTypes.CODE_FENCE_END }
val codeEnd = closing?.let { it.startOffset - 1 } ?: node.endOffset
val hasCode = codeStart in 1..codeEnd
if (hasCode) {
val language = node.children.firstOrNull { it.type == MarkdownTokenTypes.FENCE_LANG }
?.let { text.substring(it.startOffset, it.endOffset).trim() }
add(CodeContent(codeStart, codeEnd, language))
}

if (isEdited(node) || !hasCode) {
add(CodeBackground(node.startOffset, node.endOffset))
node.children.filter { it.type in FENCE_SYNTAX }.forEach { look(it, TextLook.Syntax) }
} else {
// the fence lines with their line breaks

add(CodeBackground(codeStart, codeEnd))
add(Replacement(node.startOffset, codeStart, ""))
if (closing != null) add(Replacement(codeEnd, node.endOffset, ""))
}
val language = node.children.firstOrNull { it.type == MarkdownTokenTypes.FENCE_LANG }
?.let { text.substring(it.startOffset, it.endOffset).trim() }
if (hasCode) add(CodeContent(codeStart, codeEnd, language))

// the fence lines keep their place while the cursor is away, only what is written on them is not shown -
// the block is as tall as while it is edited, and the text around it does not move
val isShown = isEdited(node) || !hasCode
add(CodeBackground(node.startOffset, node.endOffset, label = language?.takeIf { !isShown && it.isNotEmpty() }))
node.children.filter { it.type in FENCE_SYNTAX }
.forEach { look(it, if (isShown) TextLook.Syntax else TextLook.Hidden) }
}

private fun atxHeading(node: ASTNode, level: Int) {
Expand All @@ -171,13 +166,24 @@ private class DecorationCollector(private val text: String, private val selectio
content?.let { inline(it.children) }
}

private fun setextHeading(node: ASTNode, level: Int) {
val underline = node.children.lastOrNull { it.type in SETEXT_UNDERLINES }
val contentEnd = underline?.let { text.lastIndexOf('\n', it.startOffset).coerceAtLeast(node.startOffset) }
?: node.endOffset
add(HeadingLine(node.startOffset, contentEnd, level))
underline?.let { look(it, TextLook.Syntax) }
node.children.filter { it.type == MarkdownTokenTypes.SETEXT_CONTENT }.forEach { inline(it.children) }
// text with a line of `---` or `===` under it is a heading in markdown - here the underline makes no heading:
// the text stays what it is without it, and a line of three or more dashes is the rule the user means by it
private fun textWithUnderline(node: ASTNode, isTopLevel: Boolean) {
val content = node.children.filter { it.type == MarkdownTokenTypes.SETEXT_CONTENT }
val hashes = content.singleOrNull()?.let { ATX_HASHES.matchAt(text, it.startOffset) }
if (hashes != null) {
// `# heading` with dashes under it - still the heading of its hashes
val heading = content.single()
add(HeadingLine(heading.startOffset, heading.endOffset, level = hashes.groupValues[1].length))
syntax(hashes.range.first, hashes.range.last + 1, heading)
}
content.forEach { inline(it.children) }

val dashes = node.children.lastOrNull { it.type == MarkdownTokenTypes.SETEXT_2 } ?: return
val isRule = text.substring(dashes.startOffset, dashes.endOffset).count { it == '-' } >= 3
if (isRule) {
if (isTopLevel && !isEdited(dashes)) addWidget(dashes, WidgetKind.Rule) else look(dashes, TextLook.Syntax)
}
}

private fun list(node: ASTNode, depth: Int) {
Expand Down Expand Up @@ -240,7 +246,7 @@ private class DecorationCollector(private val text: String, private val selectio
// the same length, so the text does not move when the cursor comes to it
private fun bullet(bullet: Int, depth: Int) {
if (isEdited(bullet, bullet + 1)) add(Look(bullet, bullet + 1, TextLook.Syntax))
else add(Replacement(bullet, bullet + 1, LIST_BULLETS[depth % LIST_BULLETS.size]))
else add(ListBullet(bullet, bullet + 1, depth))
}

// "- [ ] " - the bullet and the brackets become one box
Expand Down
Loading
Loading