merge upstream

Signed-off-by: Shea <[email protected]>
This commit is contained in:
Shea committed 2026-06-11 19:11:45 +03:00
commit 63e60be3aa
28 files changed
+422 -47

No files matched your search

@@ -0,0 +1,5 @@
---
default: minor
---
Added configurable max pronoun pill count and max pill length rendering settings.
+5
View File
@@ -0,0 +1,5 @@
---
default: minor
---
Adds the ability to hover/tap over `...` to see the rest of someone's pronouns.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Change image rendering to allow enabling anti-aliasing in the image viewer
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fixed lists rendering `p` html tags on new lines.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix math parsing inside of color blocks not being parsed properly.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fixed nested lists having wrong indentation levels when editing.
+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Fix missing filename breaking edits, and missing a fallback, and codeblock titles overflowing
+10 -4
View File
@@ -1,3 +1,4 @@
import type { CSSProperties } from 'react';
import { memo, useMemo, useCallback } from 'react';
import type { IPreviewUrlResponse, MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
import { MsgType } from '$types/matrix-sdk';
@@ -47,6 +48,7 @@ import { ClientSideHoverFreeze } from './ClientSideHoverFreeze';
import { CuteEventType, MCuteEvent } from './message/MCuteEvent';
import { PollEvent } from './message/PollEvent';
import { M_TEXT } from 'matrix-js-sdk';
import type { IImageInfo } from '$types/matrix/common';
type RenderMessageContentProps = {
displayName: string;
@@ -80,7 +82,8 @@ const isSableChatEmbedCandidate = (url: string): boolean =>
/^https:\/\//i.test(url) &&
(/\.preview\.sable\.css(\?|#|$)/i.test(url) || isHttpsFullSableCssUrl(url));
const CAPTION_STYLE = { marginTop: config.space.S200 };
const CAPTION_STYLE: CSSProperties = { marginTop: config.space.S200, maxWidth: '100%' };
const TEXT_STYLE: CSSProperties = { maxWidth: '100%' };
function RenderMessageContentInternal({
displayName,
@@ -224,6 +227,7 @@ function RenderMessageContentInternal({
<Box
style={{
padding: config.space.S200,
paddingRight: config.space.S0,
wordBreak: 'break-word',
maxWidth: '100%',
display: 'flex',
@@ -238,6 +242,7 @@ function RenderMessageContentInternal({
renderBody={renderBody}
renderUrlsPreview={messageUrlsPreview}
renderBundledPreviews={messageBundlePreview}
style={TEXT_STYLE}
/>
</Box>
);
@@ -301,6 +306,7 @@ function RenderMessageContentInternal({
renderBody={renderBody}
renderUrlsPreview={messageUrlsPreview}
renderBundledPreviews={messageBundlePreview}
style={TEXT_STYLE}
/>
);
}
@@ -342,7 +348,7 @@ function RenderMessageContentInternal({
}
if (msgType === (MsgType.Image as string)) {
const info = (content as { info?: { mimetype?: string } }).info;
const { info } = content as { info?: IImageInfo };
const isGif =
info?.mimetype === 'image/gif' ||
info?.mimetype === 'image/apng' ||
@@ -366,11 +372,11 @@ function RenderMessageContentInternal({
if (isGif && !autoplayGifs && p.src) {
return (
<ClientSideHoverFreeze src={p.src}>
<Image {...p} loading="lazy" />
<Image info={info} {...p} loading="lazy" />
</ClientSideHoverFreeze>
);
}
return <Image {...p} loading="lazy" />;
return <Image info={info} {...p} loading="lazy" />;
}}
renderViewer={(p) => <ImageViewer {...p} />}
/>
@@ -4,24 +4,30 @@ import classNames from 'classnames';
import { Box, Chip, Header, Icon, IconButton, Icons, Text, as } from 'folds';
import { useImageGestures } from '$hooks/useImageGestures';
import { useSetting } from '$state/hooks/settings';
import { isPixelatedViewerRendering, settingsAtom } from '$state/settings';
import { isPixelatedRendering, settingsAtom } from '$state/settings';
import { downloadMedia } from '$utils/matrix';
import * as css from './ImageViewer.css';
import type { IImageInfo } from '$types/matrix/common';
import { CheckerboardIcon } from '@phosphor-icons/react';
export type ImageViewerProps = {
alt: string;
src: string;
requestClose: () => void;
info?: IImageInfo;
};
export const ImageViewer = as<'div', ImageViewerProps>(
({ className, alt, src, requestClose, ...props }, ref) => {
({ className, alt, src, requestClose, info, ...props }, ref) => {
const zoomInputRef = useRef<HTMLInputElement>(null);
const [pixelatedImageRendering] = useSetting(settingsAtom, 'pixelatedImageRendering');
const [isImageReady, setIsImageReady] = useState(false);
const [isEditingZoom, setIsEditingZoom] = useState(false);
const [zoomInput, setZoomInput] = useState('100');
const [isPixelated, setIsPixelated] = useState(
isPixelatedRendering(pixelatedImageRendering, info)
);
const {
transforms,
@@ -84,6 +90,16 @@ export const ImageViewer = as<'div', ImageViewerProps>(
</Text>
</Box>
<Box shrink="No" alignItems="Center" gap="200">
<IconButton
variant="Surface"
size="300"
radii="Pill"
onClick={() => setIsPixelated(!isPixelated)}
aria-label="Toggle Pixelation"
title={`Turn ${isPixelated ? 'Anti-aliasing' : 'Pixelation'} on`}
>
<CheckerboardIcon size={20} weight={isPixelated ? 'duotone' : 'fill'} />
</IconButton>
<IconButton
variant="Surface"
style={{
@@ -225,10 +241,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
onPointerDown={onPointerDown}
>
<img
className={classNames(
css.ImageViewerImg,
isPixelatedViewerRendering(pixelatedImageRendering) && css.ImageViewerImgPixelated
)}
className={classNames(css.ImageViewerImg, isPixelated && css.ImageViewerImgPixelated)}
draggable={false}
data-gestures="ignore"
style={{
+7 -4
View File
@@ -2,18 +2,21 @@ import type { ImgHTMLAttributes } from 'react';
import { forwardRef } from 'react';
import classNames from 'classnames';
import { useSetting } from '$state/hooks/settings';
import { isPixelatedChatRendering, settingsAtom } from '$state/settings';
import { isPixelatedRendering, settingsAtom } from '$state/settings';
import * as css from './media.css';
import type { IImageInfo } from '$types/matrix/common';
export const Image = forwardRef<HTMLImageElement, ImgHTMLAttributes<HTMLImageElement>>(
({ className, alt, ...props }, ref) => {
type ImageProps = ImgHTMLAttributes<HTMLImageElement> & { info?: IImageInfo };
export const Image = forwardRef<HTMLImageElement, ImageProps>(
({ className, alt, info, ...props }, ref) => {
const [pixelatedImageRendering] = useSetting(settingsAtom, 'pixelatedImageRendering');
return (
<img
className={classNames(
css.Image,
isPixelatedChatRendering(pixelatedImageRendering) && css.ImagePixelated,
isPixelatedRendering(pixelatedImageRendering, info) && css.ImagePixelated,
className
)}
alt={alt}
@@ -426,7 +426,7 @@ export function MImage({ content, renderImageContent, outlined }: MImageProps) {
}}
>
{renderImageContent({
body: content.filename || 'Image',
body: content.filename || content.body || 'Image',
info: imgInfo,
mimeType: imgInfo?.mimetype,
url: mxcUrl,
@@ -59,6 +59,7 @@ type RenderViewerProps = {
src: string;
alt: string;
requestClose: () => void;
info?: IImageInfo;
};
type RenderImageProps = {
alt: string;
@@ -242,6 +243,7 @@ export const ImageContent = as<'div', ImageContentProps>(
src: viewerFullSrc ?? srcState.data,
alt: body,
requestClose: () => setViewer(false),
info: info,
})}
</Modal>
</FocusTrap>
@@ -305,6 +305,7 @@ export const UrlPreviewCard = as<
renderViewer={(p) => <ImageViewer {...p} />}
renderImage={(p) => (
<Image
info={ogImageInfo}
{...p}
style={{
display: 'block',
+81 -4
View File
@@ -11,10 +11,13 @@ import {
MenuItem,
PopOut,
Text,
Tooltip,
TooltipProvider,
as,
config,
toRem,
} from 'folds';
import type { MouseEventHandler, MouseEvent, ReactNode } from 'react';
import type { KeyboardEventHandler, MouseEventHandler, MouseEvent, ReactNode } from 'react';
import { memo, useCallback, useRef, useState, useEffect, useMemo } from 'react';
import FocusTrap from 'focus-trap-react';
import { useHover, useFocusWithin } from 'react-aria';
@@ -275,6 +278,73 @@ function useMobileDoubleTap(callback: () => void, delay = 300) {
const clamp = (str: string, len: number) => (str.length > len ? `${str.slice(0, len)}...` : str);
type MorePronounsPillProps = {
pronouns: PronounSet[];
tagColor: string;
maxPillLength: number;
};
function MorePronounsPill({ pronouns, tagColor, maxPillLength }: MorePronounsPillProps) {
const [anchor, setAnchor] = useState<RectCords | undefined>();
const toggleAnchor = (target: HTMLElement) => {
setAnchor((prev) => (prev ? undefined : target.getBoundingClientRect()));
};
const handleClick: MouseEventHandler<HTMLElement> = (e) => {
e.stopPropagation();
toggleAnchor(e.currentTarget);
};
const handleKeyDown: KeyboardEventHandler<HTMLElement> = (e) => {
if (e.key !== 'Enter' && e.key !== ' ') return;
e.preventDefault();
e.stopPropagation();
toggleAnchor(e.currentTarget);
};
// On mobile, tapping the pill pins the tooltip open.
// Tapping anywhere else dismisses it.
useEffect(() => {
if (!anchor) return undefined;
const dismiss = () => setAnchor(undefined);
document.addEventListener('click', dismiss, { once: true });
return () => document.removeEventListener('click', dismiss);
}, [anchor]);
const tooltipText = pronouns.map((p) => clamp(p.summary, maxPillLength)).join(', ');
const tooltipContent = (
<Tooltip style={{ maxWidth: toRem(250) }}>
<Text size="T200">{tooltipText}</Text>
</Tooltip>
);
return (
<>
<TooltipProvider position="Top" tooltip={tooltipContent}>
{(triggerRef) => (
<PronounPill
ref={triggerRef as React.Ref<HTMLSpanElement>}
style={{ color: tagColor, cursor: 'help' }}
onClick={handleClick}
onKeyDown={handleKeyDown}
role="button"
tabIndex={0}
>
...
</PronounPill>
)}
</TooltipProvider>
{anchor && (
<PopOut anchor={anchor} position="Top" align="Center" content={tooltipContent}>
{null}
</PopOut>
)}
</>
);
}
/**
* Component to render pronouns in the chat timeline.
* It also filters them.
@@ -307,7 +377,8 @@ const Pronouns = as<
selectedLanguages
);
const limit = mobileOrTablet() ? 1 : 3;
const limit = getSettings().pronounPillMaxCount ?? 3;
const maxPillLength = getSettings().pronounPillMaxLength ?? 16;
// if language specific pronouns can't be found matching the filter return unfiltered
if (visiblePronouns.length === 0) {
@@ -318,10 +389,16 @@ const Pronouns = as<
<AsPronouns {...props} ref={ref}>
{visiblePronouns.slice(0, limit).map((p) => (
<PronounPill key={p.summary} style={{ color: tagColor }}>
{clamp(p.summary, 16)}
{clamp(p.summary, maxPillLength)}
</PronounPill>
))}
{visiblePronouns.length > limit && <PronounPill style={{ color: tagColor }}>...</PronounPill>}
{visiblePronouns.length > limit && (
<MorePronounsPill
pronouns={visiblePronouns.slice(limit)}
tagColor={tagColor}
maxPillLength={maxPillLength}
/>
)}
</AsPronouns>
);
});
@@ -292,9 +292,10 @@ export const MessageEditor = as<'div', MessageEditorProps>(
content.format = contentBody.format;
content.formatted_body = contentBody.formatted_body;
content['m.new_content'] = newContent;
if (oldContent.info !== undefined && oldContent.filename?.length > 0) {
content.filename = oldContent.filename;
content['m.new_content'].filename = oldContent.filename;
if (oldContent.info !== undefined && oldContent.msgtype !== 'm.text') {
content.filename = 'filename' in oldContent ? oldContent.filename : oldContent.body;
content['m.new_content'].filename =
'filename' in oldContent ? oldContent.filename : oldContent.body;
content.info = oldContent.info;
content['m.new_content'].info = oldContent.info;
@@ -3,6 +3,7 @@ import { DefaultReset, config, toRem } from 'folds';
export const MessageBase = style({
position: 'relative',
maxWidth: '100%',
});
export const MessageBaseBubbleCollapsed = style({
paddingTop: 0,
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState } from 'react';
import type { MouseEventHandler } from 'react';
import type { ChangeEventHandler, KeyboardEventHandler, MouseEventHandler } from 'react';
import type { RectCords } from 'folds';
import {
Box,
@@ -7,13 +7,16 @@ import {
config,
Icon,
Icons,
Input,
Menu,
MenuItem,
PopOut,
Scroll,
Switch,
Text,
toRem,
} from 'folds';
import { isKeyHotkey } from 'is-hotkey';
import FocusTrap from 'focus-trap-react';
import { PageContent } from '$components/page';
import { SequenceCard } from '$components/sequence-card';
@@ -27,6 +30,94 @@ import { SettingsSectionPage } from '../SettingsSectionPage';
import { Appearance } from './Themes';
import { LanguageSpecificPronouns } from './LanguageSpecificPronouns';
function PronounPillMaxCountInput({ disabled }: { disabled: boolean }) {
const [maxCount, setMaxCount] = useSetting(settingsAtom, 'pronounPillMaxCount');
const [inputValue, setInputValue] = useState(maxCount.toString());
const handleChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
const val = evt.target.value;
setInputValue(val);
const parsed = Number.parseInt(val, 10);
if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 10) {
setMaxCount(parsed);
}
};
const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (evt) => {
if (isKeyHotkey('escape', evt)) {
evt.stopPropagation();
setInputValue(maxCount.toString());
(evt.target as HTMLInputElement).blur();
}
if (isKeyHotkey('enter', evt)) {
(evt.target as HTMLInputElement).blur();
}
};
return (
<Input
style={{ width: toRem(80) }}
variant={Number.parseInt(inputValue, 10) === maxCount ? 'Secondary' : 'Success'}
size="300"
radii="300"
type="number"
min="1"
max="10"
value={inputValue}
onChange={handleChange}
onKeyDown={handleKeyDown}
disabled={disabled}
outlined
/>
);
}
function PronounPillMaxLengthInput({ disabled }: { disabled: boolean }) {
const [maxLength, setMaxLength] = useSetting(settingsAtom, 'pronounPillMaxLength');
const [inputValue, setInputValue] = useState(maxLength.toString());
const handleChange: ChangeEventHandler<HTMLInputElement> = (evt) => {
const val = evt.target.value;
setInputValue(val);
const parsed = Number.parseInt(val, 10);
if (!Number.isNaN(parsed) && parsed >= 1 && parsed <= 64) {
setMaxLength(parsed);
}
};
const handleKeyDown: KeyboardEventHandler<HTMLInputElement> = (evt) => {
if (isKeyHotkey('escape', evt)) {
evt.stopPropagation();
setInputValue(maxLength.toString());
(evt.target as HTMLInputElement).blur();
}
if (isKeyHotkey('enter', evt)) {
(evt.target as HTMLInputElement).blur();
}
};
return (
<Input
style={{ width: toRem(80) }}
variant={Number.parseInt(inputValue, 10) === maxLength ? 'Secondary' : 'Success'}
size="300"
radii="300"
type="number"
min="1"
max="64"
value={inputValue}
onChange={handleChange}
onKeyDown={handleKeyDown}
disabled={disabled}
outlined
/>
);
}
const emojiSizeItems = [
{ id: 'none', name: 'None (Same size as text)' },
{ id: 'extraSmall', name: 'Extra Small' },
@@ -282,6 +373,32 @@ function IdentityCosmetics() {
after={<Switch variant="Primary" value={showPronouns} onChange={setShowPronouns} />}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
style={{ opacity: showPronouns ? 1 : 0.5 }}
>
<SettingTile
title="Max Pronoun Pills"
focusId="pronoun-pill-max-count"
description="Maximum number of pronoun pills shown per user in the timeline. Additional pronouns appear behind the ... pill."
after={<PronounPillMaxCountInput disabled={!showPronouns} />}
/>
</SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
style={{ opacity: showPronouns ? 1 : 0.5 }}
>
<SettingTile
title="Max Pronoun Pill Length"
focusId="pronoun-pill-max-length"
description="Maximum characters shown in each pronoun pill before truncation."
after={<PronounPillMaxLengthInput disabled={!showPronouns} />}
/>
</SequenceCard>
<SequenceCard className={SequenceCardStyle} variant="SurfaceVariant" direction="Column">
<SettingTile
title="Pronoun Pills for All"
@@ -222,10 +222,9 @@ function ThemeVisualPreferences() {
'pixelatedImageRendering'
);
const pixelatedImageRenderingOptions: SettingMenuOption<PixelatedImageRenderingMode>[] = [
{ value: 'both', label: 'Both' },
{ value: 'chat', label: 'Chat' },
{ value: 'viewer', label: 'Image viewer' },
{ value: 'none', label: 'Neither' },
{ value: 'always', label: 'Always' },
{ value: 'smart', label: 'Smart' },
{ value: 'never', label: 'never' },
];
const [incomingInlineImagesDefaultHeight, setIncomingInlineImagesDefaultHeight] = useSetting(
settingsAtom,
@@ -110,6 +110,8 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
'theme-chat-auto-any',
'theme-import-open',
'theme-local-sync-system',
'pronoun-pill-max-count',
'pronoun-pill-max-length',
'pronoun-pills-for-all',
'reduced-motion',
'render-global-username-colors',
@@ -103,6 +103,26 @@ describe('bidirectional round-trip', () => {
expect(result).toContain('2. Second');
});
it('round-trips nested sublists with four-space indent', () => {
const markdown = '1. parent\n - child';
const html = markdownToHtml(markdown);
expect(html).toMatch(/<li>[\s\S]*<ul/i);
const injected = injectDataMd(html);
const result = htmlToMarkdown(injected);
expect(result).toContain('1. parent');
expect(result).toContain(' - child');
});
it('round-trips nested sublists written with two-space indent', () => {
const markdown = '1. parent\n - child';
const html = markdownToHtml(markdown);
expect(html).toMatch(/<li>[\s\S]*<ul/i);
const injected = injectDataMd(html);
const result = htmlToMarkdown(injected);
expect(result).toContain('1. parent');
expect(result).toContain('- child');
});
it('round-trips spoiler syntax', () => {
const markdown = '||hidden message||';
const html = markdownToHtml(markdown);
@@ -15,6 +15,24 @@ describe('expandBlockBoundariesAfterSingleNewlines', () => {
it('still expands when a blockquote ends', () => {
expect(expandBlockBoundariesAfterSingleNewlines('> quote\nplain')).toBe('> quote\n\nplain');
});
it('does not expand between consecutive ordered list items', () => {
expect(expandBlockBoundariesAfterSingleNewlines('1. one\n2. two')).toBe('1. one\n2. two');
});
it('does not expand before a 2-space nested sublist', () => {
expect(expandBlockBoundariesAfterSingleNewlines('1. test\n - sub')).toBe('1. test\n - sub');
});
it('does not expand before a 4-space nested sublist', () => {
expect(expandBlockBoundariesAfterSingleNewlines('1. test\n - sub')).toBe(
'1. test\n - sub'
);
});
it('still expands before the first top-level list item after prose', () => {
expect(expandBlockBoundariesAfterSingleNewlines('intro\n- item')).toBe('intro\n\n- item');
});
});
describe('consecutive blockquotes', () => {
@@ -135,11 +135,41 @@ function nextLineIsBlockStarter(md: string, newlineIdx: number): boolean {
return looksLikeBlockStart(effective);
}
function leadingSpaces(line: string): number {
let k = 0;
while (k < line.length && line[k] === ' ') k++;
return k;
}
function lineLooksLikeListItem(line: string): boolean {
const effective = effectiveContentAfterEscapes(line);
if (effective === null) return false;
return /^\d{1,9}\.\s/.test(effective) || /^[-*+]\s/.test(effective);
}
function nextLineIsNestedListItem(md: string, newlineIdx: number): boolean {
const prevLine = lineAtNewline(md, newlineIdx);
const nextLine = lineAfterNewline(md, newlineIdx);
if (!lineLooksLikeListItem(nextLine)) return false;
return leadingSpaces(nextLine) > leadingSpaces(prevLine);
}
function nextLineIsSiblingListItem(md: string, newlineIdx: number): boolean {
const prevLine = lineAtNewline(md, newlineIdx);
const nextLine = lineAfterNewline(md, newlineIdx);
if (!lineLooksLikeListItem(prevLine) || !lineLooksLikeListItem(nextLine)) return false;
return leadingSpaces(prevLine) === leadingSpaces(nextLine);
}
function shouldExpandSingleNewline(md: string, newlineIdx: number): boolean {
// Consecutive `>` lines belong to one blockquote, keep the single `\n` between them.
if (prevLineIsBlockquote(md, newlineIdx) && nextLineContinuesBlockquote(md, newlineIdx)) {
return false;
}
// Keep single `\n` between list items (siblings) and before nested sublists (2- or 4-space indent).
if (nextLineIsSiblingListItem(md, newlineIdx) || nextLineIsNestedListItem(md, newlineIdx)) {
return false;
}
if (nextLineIsBlockStarter(md, newlineIdx)) return true;
// CommonMark lazy continuation keeps non-`>` lines inside blockquotes, close on single `\n`.
if (prevLineIsBlockquote(md, newlineIdx) && !nextLineContinuesBlockquote(md, newlineIdx)) {
@@ -221,12 +221,18 @@ function isIgnorableMathContent(latex: string): boolean {
* - the closing `$` is not preceded by whitespace, and
* - the closing `$` is not immediately followed by an ASCII digit.
*/
/** Opening `$[fg.color=…]` / `$[bg.color=…]` */
const MFM_COLOR_FN_OPEN = /^\$\[(?:fg|bg)\.color=/;
function tryTokenizeInlineMath(
src: string
): { type: 'math'; raw: string; latex: string } | undefined {
if (!src.startsWith('$')) {
return undefined;
}
if (MFM_COLOR_FN_OPEN.test(src)) {
return undefined;
}
if (src.startsWith('$$') && (src.length < 3 || src.charAt(2) !== '$')) {
return undefined;
}
@@ -256,7 +262,7 @@ export const matrixMathExtension = {
name: 'math',
level: 'inline',
start(src: string) {
if (/^\$\[(?:fg|bg)\.color=/.test(src)) return -1;
if (MFM_COLOR_FN_OPEN.test(src)) return -1;
return src.indexOf('$');
},
tokenizer(src: string) {
@@ -4,9 +4,12 @@ import {
MX_EMOTICON_MD_SEP,
MX_EMOTICON_MD_START,
} from './extensions/matrix-emoticon';
import { toMatrixCustomHTML, trimCustomHtml } from '$components/editor/output';
import { plainToEditorInput } from '$components/editor/input';
import { BlockType } from '$components/editor/types';
import { injectDataMd } from './injectDataMd';
import { htmlToMarkdown } from './htmlToMarkdown';
import { markdownToHtml } from './markdownToHtml';
describe('htmlToMarkdown', () => {
it('converts headings', () => {
@@ -125,6 +128,20 @@ describe('htmlToMarkdown', () => {
expect(result).toContain('Item 1');
});
it('indents nested sublists with four spaces per level', () => {
const html = '<ol><li><p>parent</p><ul><li><p>child</p></li></ul></li></ol>';
expect(htmlToMarkdown(html)).toContain('1. parent');
expect(htmlToMarkdown(html)).toContain(' - child');
});
it('edit-load and save round-trip keeps nested sublist', () => {
const md = '1. test\n - sub\n';
const loaded = htmlToMarkdown(injectDataMd(markdownToHtml(md)));
expect(loaded).toContain(' - sub');
const html = trimCustomHtml(toMatrixCustomHTML(plainToEditorInput(loaded), {}));
expect(html).toMatch(/<li>[\s\S]*<ul/i);
});
it('preserves data-md attributes for round-trip', () => {
const result = htmlToMarkdown('<strong data-md="**">bold</strong>');
expect(result).toContain('**bold**');
+5 -2
View File
@@ -11,6 +11,9 @@ import { isAllowedHtmlTag } from './allowedHtmlTags';
import { formatMfmColorDataMd } from './extensions/matrix-mfm-color';
import { isMatrixHexColor } from '$utils/matrixHtml';
/** CommonMark list nesting indent (four spaces per level). */
const LIST_MARKDOWN_INDENT = ' ';
/**
* Converts Matrix-compatible HTML back to markdown for round-trip editing.
* Preserves original markdown syntax via data-md attributes and converts
@@ -419,7 +422,7 @@ function processUnorderedList(
insideCode: boolean = false
): string {
const mdSequence = node.attribs['data-md'] || '-';
const indent = ' '.repeat(depth);
const indent = LIST_MARKDOWN_INDENT.repeat(depth);
const items = node.children
.filter((c): c is Element => isTag(c) && c.name === 'li')
.map((li) => {
@@ -439,7 +442,7 @@ function processOrderedList(node: Element, depth: number = 0, insideCode: boolea
? mdSequence
: `${mdSequence}.`;
const indent = ' '.repeat(depth);
const indent = LIST_MARKDOWN_INDENT.repeat(depth);
const items = node.children
.filter((c): c is Element => isTag(c) && c.name === 'li')
.map((li, index) => {
@@ -446,4 +446,15 @@ describe('react custom html parser', () => {
expect(screen.queryByText('&lt;test&gt;')).not.toBeInTheDocument();
}
);
it('unwraps paragraph tags inside list items instead of rendering block breaks', () => {
const { container } = renderMessage(
'<ol><li><p>one</p></li><li><p>two</p></li></ol><ul><li><p>bullet</p></li></ul>'
);
expect(container.querySelector('p')).toBeNull();
expect(container.textContent).toContain('one');
expect(container.textContent).toContain('two');
expect(container.textContent).toContain('bullet');
});
});
+5 -2
View File
@@ -111,7 +111,7 @@ function KatexRenderer({
useEffect(() => {
let mounted = true;
Promise.all([import('katex'), import('katex/dist/katex.min.css')]).then(([katex]) => {
void Promise.all([import('katex'), import('katex/dist/katex.min.css')]).then(([katex]) => {
if (mounted) {
setHtml(katex.default.renderToString(math, { throwOnError: false, displayMode }));
}
@@ -430,7 +430,7 @@ export function CodeBlock({
const [copied, setCopied] = useTimeoutToggle();
const handleCopy = () => {
copyToClipboard(extractTextFromChildren(children));
void copyToClipboard(extractTextFromChildren(children));
setCopied();
};
@@ -631,6 +631,9 @@ export const getReactCustomHtmlParser = (
}
if (name === 'p') {
if (parent instanceof Element && parent.name === 'li') {
return <>{renderChildren()}</>;
}
return (
<Text {...props} className={classNames(css.Paragraph, css.MarginSpaced)} size="Inherit">
{renderChildren()}
+25 -15
View File
@@ -1,6 +1,7 @@
import { atom, type WritableAtom } from 'jotai';
import type { Store } from 'jotai/vanilla/store';
import { mobileOrTablet } from '$utils/user-agent';
import type { IImageInfo } from '$types/matrix/common';
const STORAGE_KEY = 'settings';
export type DateFormat = 'D MMM YYYY' | 'DD/MM/YYYY' | 'MM/DD/YYYY' | 'YYYY/MM/DD' | '';
@@ -56,14 +57,14 @@ export type ThemeRemoteTweakFavorite = {
export type RenderUserCardsMode = 'both' | 'light' | 'dark' | 'none';
/** Where to use crisp nearest-neighbor (pixelated) image scaling. */
export type PixelatedImageRenderingMode = 'both' | 'chat' | 'viewer' | 'none';
export type PixelatedImageRenderingMode = 'always' | 'smart' | 'never';
export function isPixelatedChatRendering(mode: PixelatedImageRenderingMode): boolean {
return mode === 'both' || mode === 'chat';
}
export function isPixelatedViewerRendering(mode: PixelatedImageRenderingMode): boolean {
return mode === 'both' || mode === 'viewer';
export function isPixelatedRendering(
mode: PixelatedImageRenderingMode,
info?: IImageInfo
): boolean {
if (mode === 'smart') return !!info && !!info.w && !!info.h && (info.w < 192 || info.h < 192);
return mode === 'always';
}
export function shouldApplyUserHeroCards(
@@ -138,6 +139,8 @@ export interface Settings {
privacyBlurEmotes: boolean;
showPronouns: boolean;
parsePronouns: boolean;
pronounPillMaxCount: number;
pronounPillMaxLength: number;
renderGlobalNameColors: boolean;
renderUserCards: RenderUserCardsMode;
filterPronounsBasedOnLanguage?: boolean;
@@ -276,6 +279,8 @@ export const defaultSettings: Settings = {
privacyBlurEmotes: false,
showPronouns: true,
parsePronouns: true,
pronounPillMaxCount: 3,
pronounPillMaxLength: 16,
renderGlobalNameColors: true,
renderUserCards: 'both',
renderRoomColors: true,
@@ -300,7 +305,7 @@ export const defaultSettings: Settings = {
autoplayGifs: true,
autoplayStickers: true,
autoplayEmojis: true,
pixelatedImageRendering: 'viewer',
pixelatedImageRendering: 'smart',
incomingInlineImagesDefaultHeight: 32,
incomingInlineImagesMaxHeight: 64,
linkPreviewImageMaxHeight: 640,
@@ -380,10 +385,9 @@ function migrateParsedLocalStorage(parsed: Record<string, unknown>): void {
if (typeof parsed.pixelatedImageRendering === 'boolean') {
parsed.pixelatedImageRendering = parsed.pixelatedImageRendering ? 'both' : 'none';
} else if (
parsed.pixelatedImageRendering !== 'both' &&
parsed.pixelatedImageRendering !== 'chat' &&
parsed.pixelatedImageRendering !== 'viewer' &&
parsed.pixelatedImageRendering !== 'none'
parsed.pixelatedImageRendering !== 'always' &&
parsed.pixelatedImageRendering !== 'smart' &&
parsed.pixelatedImageRendering !== 'never'
) {
delete parsed.pixelatedImageRendering;
}
@@ -512,13 +516,19 @@ function sanitizeSettingsKey(key: keyof Settings, val: unknown): unknown {
? val
: undefined;
case 'pixelatedImageRendering':
return val === 'both' || val === 'chat' || val === 'viewer' || val === 'none'
? val
: undefined;
return val === 'always' || val === 'smart' || val === 'never' ? val : undefined;
case 'jumboEmojiSize':
return typeof val === 'string' && JUMBO_EMOJI_VALUES.has(val as JumboEmojiSize)
? val
: undefined;
case 'pronounPillMaxCount':
return typeof val === 'number' && Number.isInteger(val) && val >= 1 && val <= 10
? val
: undefined;
case 'pronounPillMaxLength':
return typeof val === 'number' && Number.isInteger(val) && val >= 1 && val <= 64
? val
: undefined;
case 'themeRemoteManualKind':
case 'themeRemoteLightKind':
case 'themeRemoteDarkKind':