π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Improve Ensu chat text spacing and rendering
setalp428c2ccd8063
diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.ktindex 8f4aa97a1a..85ea477c5e 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/LaTeXView.kt@@ -12,6 +12,7 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.toArgbimport androidx.compose.ui.platform.LocalDensityimport androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.spimport androidx.compose.ui.viewinterop.AndroidViewimport com.agog.mathdisplay.MTMathViewimport io.ente.ensu.designsystem.EnsuColor@@ -22,7 +23,7 @@ fun LaTeXView(latex: String, modifier: Modifier = Modifier) {val isDark = isSystemInDarkTheme()val textColor = if (isDark) EnsuColor.textPrimaryDark else EnsuColor.textPrimaryLightval paddingPx = with(LocalDensity.current) { EnsuSpacing.cardPadding.dp.roundToPx() }- val fontSizePx = 16f * LocalDensity.current.density+ val fontSizePx = with(LocalDensity.current) { 16.sp.toPx() }AndroidView(factory = { context ->@@ -49,7 +50,7 @@ fun InlineLaTeXView() {val isDark = isSystemInDarkTheme()val textColor = if (isDark) EnsuColor.textPrimaryDark else EnsuColor.textPrimaryLight- val fontSizePx = fontSizeSp * LocalDensity.current.density+ val fontSizePx = with(LocalDensity.current) { fontSizeSp.sp.toPx() }val paddingPx = with(LocalDensity.current) { 2.dp.roundToPx() }AndroidView(diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.ktindex 5664c89aaa..8a49ee08e1 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/chat/MarkdownRenderer.kt@@ -92,7 +92,8 @@ fun MarkdownView(}}is MarkdownBlock.ListItems -> {- Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.xs.dp)) {+ // Separate list items like paragraphs; wrapped lines use message typography.+ Column(verticalArrangement = Arrangement.spacedBy(EnsuSpacing.md.dp)) {block.items.forEachIndexed { itemIndex, item ->key(itemIndex) {val itemCursor = appendCursor && itemIndex == block.items.lastIndex@@ -858,14 +859,15 @@ private object MarkdownParser {if (trimmed.startsWith("- ") || trimmed.startsWith("* ")) {flushParagraph()- listItems.add(trimmed.drop(2))+ // Marker padding must not indent only the first rendered line.+ listItems.add(trimmed.drop(2).trimStart())continue}val orderedMatch = Regex("^(\\d+)\\. ").find(trimmed)if (orderedMatch != null) {flushParagraph()- listItems.add(trimmed.substring(orderedMatch.value.length))+ listItems.add(trimmed.substring(orderedMatch.value.length).trimStart())continue}diff --git a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.ktindex 86afa453fd..ec7948a1d7 100644--- a/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt+++ b/android/apps/ensu/app/src/main/java/io/ente/ensu/designsystem/Theme.kt@@ -140,7 +140,7 @@ object EnsuTypography {val mini = TextStyle(fontFamily = uiFamily, fontSize = 12.sp, fontWeight = FontWeight.Medium, lineHeight = 15.sp)val tiny = TextStyle(fontFamily = uiFamily, fontSize = 10.sp, fontWeight = FontWeight.Medium, lineHeight = 12.sp)- val message = TextStyle(fontFamily = messageFamily, fontSize = 15.sp, fontWeight = FontWeight.Normal, lineHeight = 26.sp)+ val message = TextStyle(fontFamily = messageFamily, fontSize = 15.sp, fontWeight = FontWeight.Normal, lineHeight = 22.sp)val code = TextStyle(fontFamily = codeFamily, fontSize = 13.sp, fontWeight = FontWeight.Normal, lineHeight = 19.sp)val material = Typography(diff --git a/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swift b/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swiftindex a39f367ad0..f5f7380294 100644--- a/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swift+++ b/apple/apps/ensu/Ensu/Chat/MessageList/MessageListComponents.swift@@ -202,7 +202,7 @@ struct UserMessageBubbleView: View {Text(message.text).font(EnsuTypography.message).foregroundStyle(EnsuColor.userMessageText)- .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))+ .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 22.0 / 15)).multilineTextAlignment(.leading).textSelection(.enabled)}@@ -651,7 +651,7 @@ struct TodoListCardView: View {}VStack(alignment: .leading, spacing: 6) {- ForEach(items, id: \.self) { item in+ ForEach(Array(items.enumerated()), id: \.offset) { _, item inHStack(alignment: .top, spacing: EnsuSpacing.sm) {Circle().fill(EnsuColor.accent)@@ -679,6 +679,8 @@ struct MarkdownView: View {let blocks: [MarkdownBlock]var showCursor: Bool = false+ private let messageLineSpacing = EnsuLineHeight.spacing(fontSize: 15, lineHeight: 22.0 / 15)+var body: some View {let lastKind = blocks.last?.kindlet inlineCursorSupported = lastKind.map { kind in@@ -724,7 +726,7 @@ struct MarkdownView: View {markdownText(displayText).font(EnsuTypography.message).foregroundStyle(EnsuColor.textPrimary)- .lineSpacing(EnsuLineHeight.spacing(fontSize: 15, lineHeight: 1.7))+ .lineSpacing(messageLineSpacing)}case .blockquote(let text):let displayText = showCursor && isLast ? text + StreamingCursor.glyph : text@@ -740,8 +742,9 @@ struct MarkdownView: View {}: items- VStack(alignment: .leading, spacing: 6) {- ForEach(resolvedItems, id: \.self) { item in+ // Use paragraph spacing both between items and within wrapped item text.+ VStack(alignment: .leading, spacing: EnsuSpacing.md) {+ ForEach(Array(resolvedItems.enumerated()), id: \.offset) { _, item inHStack(alignment: .top, spacing: EnsuSpacing.sm) {Text("β’").font(EnsuTypography.message)@@ -756,6 +759,7 @@ struct MarkdownView: View {markdownText(item).font(EnsuTypography.message).foregroundStyle(EnsuColor.textPrimary)+ .lineSpacing(messageLineSpacing)}}}diff --git a/web/apps/ensu/src/components/MarkdownRenderer.tsx b/web/apps/ensu/src/components/MarkdownRenderer.tsxindex 379fde2660..330c955c2d 100644--- a/web/apps/ensu/src/components/MarkdownRenderer.tsx+++ b/web/apps/ensu/src/components/MarkdownRenderer.tsx@@ -1,8 +1,11 @@-import { isTauriRuntime } from "@/services/tauri-runtime";+import {+ handleExternalLinkClick,+ safeExternalUrl,+} from "@/services/external-links";import { Copy01Icon } from "@hugeicons/core-free-icons";import { HugeiconsIcon } from "@hugeicons/react";import { Box, IconButton } from "@mui/material";-import React, { useCallback } from "react";+import React, { useCallback, useState } from "react";import ReactMarkdown from "react-markdown";import rehypeKatex from "rehype-katex";import remarkGfm from "remark-gfm";@@ -33,19 +36,35 @@ const extractCodeText = (node: React.ReactNode): string => {};const CodeBlock = ({ children, node: _node, ...rest }: PreProps) => {+ // Markdown adds one display newline; retain any blank lines in the code itself.const codeText = extractCodeText(children).replace(/\n$/, "");-- const handleCopy = useCallback(- () => void navigator.clipboard.writeText(codeText),- [codeText],- );+ const [copyResult, setCopyResult] = useState<{+ text: string;+ message: string;+ }>();+ const copyStatus = copyResult?.text === codeText ? copyResult.message : "";+ const handleCopy = useCallback(() => {+ void navigator.clipboard.writeText(codeText).then(+ () => setCopyResult({ text: codeText, message: "Copied" }),+ () => setCopyResult({ text: codeText, message: "Could not copy" }),+ );+ }, [codeText]);return (- <Box className="markdown-code-block" sx={{ position: "relative" }}>- <Box component="pre" {...rest}>- {children}- </Box>- <Box sx={{ position: "absolute", right: 8, bottom: 8 }}>+ <Box className="markdown-code-block">+ <Box+ sx={{+ display: "flex",+ alignItems: "center",+ justifyContent: "flex-end",+ gap: 1,+ px: "8px",+ py: "4px",+ }}+ >+ <Box component="span" role="status" sx={{ fontSize: "12px" }}>+ {copyStatus}+ </Box><IconButtonaria-label="Copy code"onClick={handleCopy}@@ -66,41 +85,13 @@ const CodeBlock = ({ children, node: _node, ...rest }: PreProps) => {/></IconButton></Box>+ <Box component="pre" {...rest}>+ {children}+ </Box></Box>);};-const openExternalUrl = async (url: string) => {- if (isTauriRuntime()) {- try {- const { openUrl } = await import("@tauri-apps/plugin-opener");- await openUrl(url);- return;- } catch {- // Fall through to window.open.- }- }-- if (typeof window !== "undefined") {- const popup = window.open(url, "_blank", "noopener,noreferrer");- if (!popup) {- window.location.href = url;- }- }-};--const safeExternalUrl = (href: string | undefined) => {- if (!href) return undefined;- try {- const url = new URL(href);- return ["http:", "https:", "mailto:"].includes(url.protocol)- ? url.toString()- : undefined;- } catch {- return undefined;- }-};-type AnchorProps = React.ComponentPropsWithoutRef<"a"> & { node?: unknown };const ExternalLink = ({@@ -116,16 +107,28 @@ const ExternalLink = ({<a{...rest}href={safeHref}- onClick={(e) => {- e.preventDefault();- if (safeHref) void openExternalUrl(safeHref);- }}+ target="_blank"+ rel="noopener noreferrer"+ onClick={handleExternalLinkClick}>{children}</a>);};+type TableProps = React.ComponentPropsWithoutRef<"table"> & { node?: unknown };++const MarkdownTable = ({ node: _node, ...props }: TableProps) => (+ <div+ className="markdown-table"+ tabIndex={0}+ role="region"+ aria-label="Table"+ >+ <table {...props} />+ </div>+);+export const MarkdownRenderer = ({content,className,@@ -137,7 +140,11 @@ export const MarkdownRenderer = ({rehypePlugins={[[rehypeKatex, { strict: false, throwOnError: false }],]}- components={{ pre: CodeBlock, a: ExternalLink }}+ components={{+ pre: CodeBlock,+ a: ExternalLink,+ table: MarkdownTable,+ }}>{content}</ReactMarkdown>diff --git a/web/apps/ensu/src/components/chat/ChatMessageList.tsx b/web/apps/ensu/src/components/chat/ChatMessageList.tsxindex 65c060606f..43fd1a8cbd 100644--- a/web/apps/ensu/src/components/chat/ChatMessageList.tsx+++ b/web/apps/ensu/src/components/chat/ChatMessageList.tsx@@ -5,8 +5,11 @@ import {type BranchSwitcher,} from "@/services/chat/branching";import type { ChatAttachment, ChatMessage } from "@/services/chat/store";+import {+ handleExternalLinkClick,+ safeExternalUrl,+} from "@/services/external-links";import { noteSourceErrorMessage, openNoteDocument } from "@/services/notes";-import { isTauriRuntime } from "@/services/tauri-runtime";import {ArrowLeft01Icon,ArrowRight01Icon,@@ -45,23 +48,6 @@ interface IconProps {strokeWidth: number;}-const openExternalUrl = async (url: string) => {- if (isTauriRuntime()) {- const opened = await import("@tauri-apps/plugin-opener")- .then(async ({ openUrl }) => {- await openUrl(url);- return true;- })- .catch(() => false);- if (opened) return;- }-- if (typeof window !== "undefined") {- const popup = window.open(url, "_blank", "noopener,noreferrer");- if (!popup) window.location.href = url;- }-};-const sourceLinkSx = {border: 0,p: 0,@@ -260,21 +246,21 @@ const PackSourceCard = memo(</Typography><Stack direction="row" sx={{ gap: 2, flexWrap: "wrap" }}><Link- component="button"- type="button"+ href={safeExternalUrl(citation.sourceUrl)}+ target="_blank"+ rel="noopener noreferrer"underline="hover"- onClick={() => void openExternalUrl(citation.sourceUrl)}+ onClick={handleExternalLinkClick}sx={sourceLinkSx}>Open source β</Link><Link- component="button"- type="button"+ href={safeExternalUrl(citation.licenseUrl)}+ target="_blank"+ rel="noopener noreferrer"underline="hover"- onClick={() =>- void openExternalUrl(citation.licenseUrl)- }+ onClick={handleExternalLinkClick}sx={sourceLinkSx}>{citation.licenseLabel} βdiff --git a/web/apps/ensu/src/pages/chat.tsx b/web/apps/ensu/src/pages/chat.tsxindex e74ef5166a..7bee2fb625 100644--- a/web/apps/ensu/src/pages/chat.tsx+++ b/web/apps/ensu/src/pages/chat.tsx@@ -394,7 +394,7 @@ const Page: React.FC = () => {: "rgba(0, 0, 0, 0.04)";const messageTypographySx = {fontSize: "15px",- lineHeight: "26px",+ lineHeight: "22px",fontWeight: 400,fontFamily: messageFontFamily,} as const;@@ -414,6 +414,7 @@ const Page: React.FC = () => {wordBreak: "break-word",overflowWrap: "anywhere",} as const;+ const markdownParagraphSpacing = "12px";const assistantMarkdownSx = {...messageTypographySx,color: "text.base",@@ -432,22 +433,32 @@ const Page: React.FC = () => {marginLeft: "2px",animation: "ensu-blink 1s steps(1, end) infinite",},- "& p": { margin: 0 },- "& p + p": { marginTop: "12px" },- "& ul, & ol": { paddingLeft: "24px", margin: "12px 0 0" },- "& li": { marginBottom: "4px" },+ "& p, & ul, & ol, & blockquote, & pre, & h1, & h2, & h3, & h4, & h5, & h6, & hr":+ { margin: 0 },+ "& .markdown-content > * + *, & li > * + *, & blockquote > * + *": {+ marginTop: markdownParagraphSpacing,+ },+ "& ul, & ol": { paddingLeft: "24px" },+ // Tight lists can have plain text before nested blocks, not a sibling element.+ "& li > :is(ul, ol, .markdown-code-block, blockquote, h1, h2, h3, h4, h5, h6, hr)":+ { marginTop: markdownParagraphSpacing },+ "& li + li": { marginTop: markdownParagraphSpacing },"& code": { fontFamily: codeFontFamily, fontSize: "0.95em" },- "& .markdown-code-block": { position: "relative", margin: "12px 0 0" },+ "& .markdown-code-block": {+ borderRadius: "6px",+ backgroundColor: codeBlockBackground,+ overflow: "hidden",+ },"& .markdown-code-block pre": {margin: 0,padding: "12px",- borderRadius: 6,- backgroundColor: codeBlockBackground,overflowX: "auto",+ whiteSpace: "pre",+ overflowWrap: "normal",+ wordBreak: "normal",},"& .markdown-code-block pre code": { fontFamily: codeFontFamily },"& blockquote": {- margin: "12px 0 0",paddingLeft: "12px",borderLeft: "3px solid",borderLeftColor: "divider",@@ -461,6 +472,22 @@ const Page: React.FC = () => {overflowX: "auto",},"& .katex": { color: "text.base" },+ "& .markdown-table": { maxWidth: "100%", overflowX: "auto" },+ "& table": {+ borderCollapse: "collapse",+ width: "max-content",+ minWidth: "100%",+ },+ "& th, & td": {+ border: "1px solid",+ borderColor: "divider",+ padding: "8px 12px",+ minWidth: "100px",+ maxWidth: "320px",+ verticalAlign: "top",+ },+ "& th": { backgroundColor: codeBlockBackground },+ "& img": { maxWidth: "100%", height: "auto" },"& a": { color: "accent.main" },};const streamingMessageSx = { transition: "all 0.2s ease" } as const;diff --git a/web/apps/ensu/src/services/external-links.ts b/web/apps/ensu/src/services/external-links.tsnew file mode 100644index 0000000000..810a4efa5d--- /dev/null+++ b/web/apps/ensu/src/services/external-links.ts@@ -0,0 +1,30 @@+import { isTauriRuntime } from "@/services/tauri-runtime";+import type { MouseEvent } from "react";++export const safeExternalUrl = (href: string | undefined) => {+ if (!href) return undefined;+ try {+ const url = new URL(href);+ return ["http:", "https:", "mailto:"].includes(url.protocol)+ ? url.toString()+ : undefined;+ } catch {+ return undefined;+ }+};++/** Browsers keep native link behavior, including modifier and middle clicks. */+export const handleExternalLinkClick = (+ event: MouseEvent<HTMLAnchorElement>,+) => {+ if (!isTauriRuntime() || event.button !== 0) return;+ const href = safeExternalUrl(event.currentTarget.href);+ if (!href) return;+ event.preventDefault();+ void import("@tauri-apps/plugin-opener")+ .then(({ openUrl }) => openUrl(href))+ .catch(() => {+ // noopener returns null even on success; never navigate the chat away.+ window.open(href, "_blank", "noopener,noreferrer");+ });+};