diff --git a/.changeset/fix-blockquote-md.md b/.changeset/fix-blockquote-md.md new file mode 100644 index 000000000..ce041ffec --- /dev/null +++ b/.changeset/fix-blockquote-md.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fixed blockquotes needing a double backslash to escape and require a space after the `>` in order to form a blockquote. diff --git a/.changeset/fix-jump-to-events.md b/.changeset/fix-jump-to-events.md new file mode 100644 index 000000000..cde123efd --- /dev/null +++ b/.changeset/fix-jump-to-events.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fixed jumpting to arbitrary events (e.g. reactions, edits, pins, leaves/joins). diff --git a/.changeset/fix-latex-codeblock.md b/.changeset/fix-latex-codeblock.md new file mode 100644 index 000000000..60a5b01e2 --- /dev/null +++ b/.changeset/fix-latex-codeblock.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fix latex in codeblocks getting parsed. diff --git a/.changeset/fix-tweak-favoriting-behavior.md b/.changeset/fix-tweak-favoriting-behavior.md new file mode 100644 index 000000000..3431802e9 --- /dev/null +++ b/.changeset/fix-tweak-favoriting-behavior.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Fixed tweak automatic favoriting behavior when entering/leaving the catalog. diff --git a/.changeset/fix-underline-markdown.md b/.changeset/fix-underline-markdown.md new file mode 100644 index 000000000..7a3b3d3c6 --- /dev/null +++ b/.changeset/fix-underline-markdown.md @@ -0,0 +1,5 @@ +--- +default: patch +--- + +Added the ability to **underline** using `__underscores__`. diff --git a/src/app/components/message/Reply.tsx b/src/app/components/message/Reply.tsx index 46537cd4d..1c2fd8ddb 100644 --- a/src/app/components/message/Reply.tsx +++ b/src/app/components/message/Reply.tsx @@ -231,7 +231,7 @@ export const Reply = as<'div', ReplyProps>( {(pinsAdded?.length > 0 && `pinned ${pinsAdded.length} message${pinsAdded.length > 1 ? 's' : ''}`) || ''} - {(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && `and`) || ''} + {(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && ` and `) || ''} {(pinsRemoved?.length > 0 && `unpinned ${pinsRemoved.length} message${pinsRemoved.length > 1 ? 's' : ''}`) || ''} diff --git a/src/app/components/url-preview/TweakPreviewUrlCard.tsx b/src/app/components/url-preview/TweakPreviewUrlCard.tsx index ab3ce5e2c..c3c632745 100644 --- a/src/app/components/url-preview/TweakPreviewUrlCard.tsx +++ b/src/app/components/url-preview/TweakPreviewUrlCard.tsx @@ -198,7 +198,6 @@ export function TweakPreviewUrlCard({ url }: { url: string }) { const nextEnabled = enabledTweakFullUrls.filter((u) => u !== url); patchSettings({ themeRemoteEnabledTweakFullUrls: nextEnabled, - themeRemoteTweakFavorites: pruneTweakFavorites(tweakFavorites, nextEnabled), }); } }, diff --git a/src/app/features/room/RoomTimeline.tsx b/src/app/features/room/RoomTimeline.tsx index 8bc5d770c..812f2043c 100644 --- a/src/app/features/room/RoomTimeline.tsx +++ b/src/app/features/room/RoomTimeline.tsx @@ -45,6 +45,7 @@ import { factoryRenderLinkifyWithMention, } from '$plugins/react-custom-html-parser'; import { today, yesterday, timeDayMonthYear } from '$utils/time'; +import { unwrapRelationJumpTarget } from '$utils/room'; import { useMemberEventParser } from '$hooks/useMemberEventParser'; import { usePowerLevelsContext } from '$hooks/usePowerLevels'; import { useRoomCreators } from '$hooks/useRoomCreators'; @@ -77,8 +78,11 @@ import { } from '$utils/timeline'; import { useTimelineSync } from '$hooks/timeline/useTimelineSync'; import { useTimelineActions } from '$hooks/timeline/useTimelineActions'; -import type { ProcessedEvent } from '$hooks/timeline/useProcessedTimeline'; -import { useProcessedTimeline } from '$hooks/timeline/useProcessedTimeline'; +import { + useProcessedTimeline, + getProcessedRowIndexForRawTimelineIndex, + type ProcessedEvent, +} from '$hooks/timeline/useProcessedTimeline'; import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer'; import * as css from './RoomTimeline.css'; @@ -494,19 +498,40 @@ export function RoomTimeline({ setOpenThread: setOpenThread as unknown as (threadId: string | undefined) => void, handleEdit, handleOpenEvent: (id) => { - const evtTimeline = getEventTimeline(room, id); + const anchorId = unwrapRelationJumpTarget(room, id); + let evtTimeline = getEventTimeline(room, anchorId); + let resolvedForIndex = anchorId; + if (!evtTimeline && anchorId !== id) { + evtTimeline = getEventTimeline(room, id); + resolvedForIndex = id; + } const absoluteIndex = evtTimeline - ? getEventIdAbsoluteIndex(timelineSync.timeline.linkedTimelines, evtTimeline, id) + ? getEventIdAbsoluteIndex( + timelineSync.timeline.linkedTimelines, + evtTimeline, + resolvedForIndex + ) : undefined; if (typeof absoluteIndex === 'number') { - const processedIndex = getRawIndexToProcessedIndex(absoluteIndex); + let processedIndex = getRawIndexToProcessedIndex(absoluteIndex); + let focusRawIndex = absoluteIndex; + if (processedIndex === undefined) { + const nearest = getProcessedRowIndexForRawTimelineIndex( + processedEventsRef.current, + absoluteIndex + ); + if (nearest) { + processedIndex = nearest.rowIndex; + focusRawIndex = nearest.focusRawIndex; + } + } if (vListRef.current && processedIndex !== undefined) { vListRef.current.scrollToIndex(processedIndex, { align: 'center' }); } - timelineSync.setFocusItem({ index: absoluteIndex, scrollTo: false, highlight: true }); + timelineSync.setFocusItem({ index: focusRawIndex, scrollTo: false, highlight: true }); } else { - timelineSync.loadEventTimeline(id); + timelineSync.loadEventTimeline(anchorId); } }, }); diff --git a/src/app/features/room/ThreadDrawer.tsx b/src/app/features/room/ThreadDrawer.tsx index 3171e3ba4..39cc66728 100644 --- a/src/app/features/room/ThreadDrawer.tsx +++ b/src/app/features/room/ThreadDrawer.tsx @@ -23,7 +23,12 @@ import { makeMentionCustomProps, renderMatrixMention, } from '$plugins/react-custom-html-parser'; -import { getEditedEvent, getMemberDisplayName, reactionOrEditEvent } from '$utils/room'; +import { + getEditedEvent, + getMemberDisplayName, + reactionOrEditEvent, + unwrapRelationJumpTarget, +} from '$utils/room'; import { getMxIdLocalPart, toggleReaction } from '$utils/matrix'; import { useMatrixClient } from '$hooks/useMatrixClient'; import { useMediaAuthentication } from '$hooks/useMediaAuthentication'; @@ -49,8 +54,11 @@ import { useIgnoredUsers } from '$hooks/useIgnoredUsers'; import { useGetMemberPowerTag } from '$hooks/useMemberPowerTag'; import { useMemberEventParser } from '$hooks/useMemberEventParser'; import { useMessageEdit } from '$hooks/useMessageEdit'; -import type { ProcessedEvent } from '$hooks/timeline/useProcessedTimeline'; -import { useProcessedTimeline } from '$hooks/timeline/useProcessedTimeline'; +import { + useProcessedTimeline, + getProcessedRowIndexForRawTimelineIndex, + type ProcessedEvent, +} from '$hooks/timeline/useProcessedTimeline'; import { useTimelineEventRenderer } from '$hooks/timeline/useTimelineEventRenderer'; import { RoomInput } from './RoomInput'; import { RoomViewFollowing, RoomViewFollowingPlaceholder } from './RoomViewFollowing'; @@ -627,18 +635,32 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra (evt) => { const targetId = evt.currentTarget.getAttribute('data-event-id'); if (!targetId) return; - const isRoot = targetId === threadRootId; - const isInReplies = processedEventsRef.current.some((e) => e.id === targetId); + let anchorId = unwrapRelationJumpTarget(room, targetId); + const threadLive = thread?.timelineSet.getLiveTimeline(); + const threadEvents = threadLive?.getEvents(); + const rawIndex = threadEvents?.findIndex((e) => e.getId() === anchorId) ?? -1; + if (rawIndex >= 0) { + const nearest = getProcessedRowIndexForRawTimelineIndex( + processedEventsRef.current, + rawIndex + ); + if (nearest) { + const rowEv = processedEventsRef.current[nearest.rowIndex]; + if (rowEv) anchorId = rowEv.id; + } + } + const isRoot = anchorId === threadRootId; + const isInReplies = processedEventsRef.current.some((e) => e.id === anchorId); if (!isRoot && !isInReplies) return; - setJumpToEventId(targetId); + setJumpToEventId(anchorId); setTimeout(() => setJumpToEventId(undefined), 2500); const el = drawerRef.current; if (el) { - const target = el.querySelector(`[data-message-id="${targetId}"]`); + const target = el.querySelector(`[data-message-id="${anchorId}"]`); target?.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } }, - [threadRootId] + [threadRootId, room, thread] ); // Map jumpToEventId to a focusItem index for useTimelineEventRenderer highlighting diff --git a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx index 8653a88b8..e602c7dfc 100644 --- a/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx +++ b/src/app/features/settings/cosmetics/ThemeCatalogSettings.tsx @@ -1,4 +1,4 @@ -import { type ChangeEventHandler, useCallback, useEffect, useMemo, useState } from 'react'; +import { type ChangeEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useTimeoutToggle } from '$hooks/useTimeoutToggle'; import { copyToClipboard, downloadTextFile } from '$utils/dom'; import { useQuery, useQueryClient } from '@tanstack/react-query'; @@ -214,6 +214,9 @@ export function ThemeCatalogSettings({ const [browseOpen, setBrowseOpen] = useState(false); const [importModalOpen, setImportModalOpen] = useState(false); + const appearanceCatalogBrowseWasOpenRef = useRef(false); + const tweakFavoritesSnapshotAtAppearanceCatalogOpenRef = useRef>(new Set()); + useEffect(() => { if (isAppearanceMode) { onBrowseOpenChange?.(browseOpen); @@ -248,6 +251,19 @@ export function ThemeCatalogSettings({ 'themeChatAutoPreviewAnyUrl' ); + useEffect(() => { + if (!isAppearanceMode) { + appearanceCatalogBrowseWasOpenRef.current = false; + return; + } + if (browseOpen && !appearanceCatalogBrowseWasOpenRef.current) { + tweakFavoritesSnapshotAtAppearanceCatalogOpenRef.current = new Set( + tweakFavorites.map((f) => f.fullUrl.trim()).filter(Boolean) + ); + } + appearanceCatalogBrowseWasOpenRef.current = browseOpen; + }, [browseOpen, isAppearanceMode, tweakFavorites]); + const [themeSearch, setThemeSearch] = useState(''); const [tweakSearch, setTweakSearch] = useState(''); const [kindFilter, setKindFilter] = useState<'all' | 'light' | 'dark'>('all'); @@ -779,7 +795,15 @@ export function ThemeCatalogSettings({ }, [patchSettings]); const setTweakApplied = useCallback( - async (fullUrl: string, apply: boolean, hint?: { displayName?: string; basename?: string }) => { + async ( + fullUrl: string, + apply: boolean, + hint?: { + displayName?: string; + basename?: string; + pruneUnpinnedFavoriteOnDisable?: boolean; + } + ) => { const trimmed = fullUrl.trim(); if (!trimmed) return; @@ -811,10 +835,25 @@ export function ThemeCatalogSettings({ }); } else { const nextEnabled = enabledTweakFullUrls.filter((u) => u !== trimmed); - patchSettings({ - themeRemoteEnabledTweakFullUrls: nextEnabled, - themeRemoteTweakFavorites: pruneTweakFavorites(tweakFavorites, nextEnabled), - }); + if (hint?.pruneUnpinnedFavoriteOnDisable) { + const enabledSet = new Set(nextEnabled); + const inLibraryBeforeThisCatalogVisit = + tweakFavoritesSnapshotAtAppearanceCatalogOpenRef.current; + const nextTweakFavs = tweakFavorites.filter( + (f) => + f.pinned === true || + enabledSet.has(f.fullUrl) || + inLibraryBeforeThisCatalogVisit.has(f.fullUrl.trim()) + ); + patchSettings({ + themeRemoteEnabledTweakFullUrls: nextEnabled, + themeRemoteTweakFavorites: nextTweakFavs, + }); + } else { + patchSettings({ + themeRemoteEnabledTweakFullUrls: nextEnabled, + }); + } } }, [enabledTweakFullUrls, patchSettings, prefetchFull, pruneTweakFavorites, tweakFavorites] @@ -1468,6 +1507,7 @@ export function ThemeCatalogSettings({ setTweakApplied(row.fullUrl, v, { displayName: row.displayName, basename: row.basename, + pruneUnpinnedFavoriteOnDisable: true, }) } /> diff --git a/src/app/hooks/timeline/useProcessedTimeline.ts b/src/app/hooks/timeline/useProcessedTimeline.ts index 1dd6d11c5..56f7145f2 100644 --- a/src/app/hooks/timeline/useProcessedTimeline.ts +++ b/src/app/hooks/timeline/useProcessedTimeline.ts @@ -39,6 +39,19 @@ export interface ProcessedEvent { willRenderDayDivider: boolean; } +/** Raw timeline indices for skipped events (reactions, edits, …) have no row; walk backward to a visible one. */ +export function getProcessedRowIndexForRawTimelineIndex( + processedEvents: ProcessedEvent[], + startRawIndex: number +): { rowIndex: number; focusRawIndex: number } | undefined { + if (startRawIndex < 0) return undefined; + for (let i = startRawIndex; i >= 0; i -= 1) { + const rowIndex = processedEvents.findIndex((e) => e.itemIndex === i); + if (rowIndex >= 0) return { rowIndex, focusRawIndex: i }; + } + return undefined; +} + const MESSAGE_EVENT_TYPES = new Set([ 'm.room.message', 'm.room.message.encrypted', diff --git a/src/app/hooks/timeline/useTimelineEventRenderer.tsx b/src/app/hooks/timeline/useTimelineEventRenderer.tsx index 3ceba3c9f..131f7f457 100644 --- a/src/app/hooks/timeline/useTimelineEventRenderer.tsx +++ b/src/app/hooks/timeline/useTimelineEventRenderer.tsx @@ -1074,7 +1074,7 @@ export function useTimelineEventRenderer({ {(pinsAdded?.length > 0 && `pinned ${pinsAdded.length} message${pinsAdded.length > 1 ? 's' : ''}`) || ''} - {(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && ` and`) || ''} + {(pinsAdded?.length > 0 && pinsRemoved?.length > 0 && ` and `) || ''} {(pinsRemoved?.length > 0 && `unpinned ${pinsRemoved.length} message${pinsRemoved.length > 1 ? 's' : ''}`) || ''} diff --git a/src/app/plugins/markdown/bidirectional.test.ts b/src/app/plugins/markdown/bidirectional.test.ts index a7767cf0a..216ad9d05 100644 --- a/src/app/plugins/markdown/bidirectional.test.ts +++ b/src/app/plugins/markdown/bidirectional.test.ts @@ -29,6 +29,14 @@ describe('bidirectional round-trip', () => { expect(result).toContain('*italic text*'); }); + it('round-trips underline', () => { + const markdown = '__underlined__'; + const html = markdownToHtml(markdown); + const injected = injectDataMd(html); + const result = htmlToMarkdown(injected); + expect(result).toContain('__underlined__'); + }); + it('round-trips inline code', () => { const markdown = '`inline code`'; const html = markdownToHtml(markdown); diff --git a/src/app/plugins/markdown/extensions/matrix-math.ts b/src/app/plugins/markdown/extensions/matrix-math.ts index 590d84b55..7ceece744 100644 --- a/src/app/plugins/markdown/extensions/matrix-math.ts +++ b/src/app/plugins/markdown/extensions/matrix-math.ts @@ -1,5 +1,160 @@ import type { TokenizerExtension, RendererExtension } from 'marked'; +/** Private-use char so math extensions do not match `$` / `$$` inside code spans. Not U+E000–U+E002 (emoticon placeholders). */ +export const MATH_CODE_DOLLAR_MASK = '\uE020'; + +function findSameLineFenceClose(md: string, from: number, tick: string, minLen: number): number { + let j = from; + while (j < md.length && md[j] !== '\n') { + if (md[j] === tick) { + let run = 0; + while (j + run < md.length && md[j + run] === tick) run++; + if (run >= minLen) return j; + j += run; + } else { + j++; + } + } + return -1; +} + +function findMultilineFenceEnd( + md: string, + contentStart: number, + tick: string, + minLen: number +): { blockEnd: number; contentEnd: number } | null { + let p = contentStart; + while (p <= md.length) { + const nl = md.indexOf('\n', p); + const lineStart = p; + const lineEnd = nl === -1 ? md.length : nl; + const line = md.slice(lineStart, lineEnd); + const m = tick === '`' ? /^ {0,3}(`{3,})\s*$/.exec(line) : /^ {0,3}(~{3,})\s*$/.exec(line); + const fenceRun = m?.[1]; + if (fenceRun && fenceRun.length >= minLen && fenceRun[0] === tick) { + return { + blockEnd: nl === -1 ? md.length : nl + 1, + contentEnd: lineStart, + }; + } + if (nl === -1) return null; + p = nl + 1; + } + return null; +} + +function tryConsumeFence(md: string, i: number): { text: string; end: number } | null { + const atLineStart = i === 0 || md[i - 1] === '\n'; + if (!atLineStart) return null; + + const rest = md.slice(i); + const open = /^(\s{0,3})(`{3,}|~{3,})/.exec(rest); + if (!open?.[2]) return null; + + const fenceStr = open[2]; + const tick = fenceStr.charAt(0); + const openLen = fenceStr.length; + const afterOpen = i + open[0].length; + + if (afterOpen < md.length && md[afterOpen] === '\n') { + const contentStart = afterOpen + 1; + const close = findMultilineFenceEnd(md, contentStart, tick, openLen); + if (!close) { + const inner = md.slice(contentStart, md.length); + const masked = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK); + return { text: md.slice(i, contentStart) + masked, end: md.length }; + } + const inner = md.slice(contentStart, close.contentEnd); + const maskedInner = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK); + return { + text: md.slice(i, contentStart) + maskedInner + md.slice(close.contentEnd, close.blockEnd), + end: close.blockEnd, + }; + } + + const closeIdx = findSameLineFenceClose(md, afterOpen, tick, openLen); + if (closeIdx < 0) return null; + + let closeRun = 0; + while (closeIdx + closeRun < md.length && md[closeIdx + closeRun] === tick) closeRun++; + + const inner = md.slice(afterOpen, closeIdx); + const maskedInner = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK); + return { + text: md.slice(i, afterOpen) + maskedInner + md.slice(closeIdx, closeIdx + closeRun), + end: closeIdx + closeRun, + }; +} + +function tryConsumeInlineCode(md: string, i: number): { text: string; end: number } | null { + if (md[i] !== '`') return null; + let run = 0; + while (i + run < md.length && md[i + run] === '`') run++; + const contentStart = i + run; + let j = contentStart; + while (j < md.length) { + if (md[j] === '`') { + let cr = 0; + while (j + cr < md.length && md[j + cr] === '`') cr++; + if (cr === run) { + const inner = md.slice(contentStart, j); + const maskedInner = inner.replace(/\$/g, MATH_CODE_DOLLAR_MASK); + return { + text: md.slice(i, contentStart) + maskedInner + md.slice(j, j + run), + end: j + run, + }; + } + j += cr; + } else { + j++; + } + } + return null; +} + +/** + * Replaces `$` inside fenced and inline code so Matrix math extensions do not run on code literals. + * {@link unmaskMathCodeDollarPlaceholders} must be applied to the final HTML. + */ +export function maskDollarSignsInsideMarkdownCode(markdown: string): string { + const md = markdown.replace(/\r\n/g, '\n'); + let out = ''; + let i = 0; + const n = md.length; + + while (i < n) { + const atLineStart = i === 0 || md[i - 1] === '\n'; + + if (atLineStart) { + const fence = tryConsumeFence(md, i); + if (fence) { + out += fence.text; + i = fence.end; + continue; + } + } + + if (md[i] === '`') { + const span = tryConsumeInlineCode(md, i); + if (span) { + out += span.text; + i = span.end; + continue; + } + } + + out += md[i]; + i++; + } + + return out; +} + +export function unmaskMathCodeDollarPlaceholders(html: string): string { + return html.replaceAll(MATH_CODE_DOLLAR_MASK, '$'); +} + function escapeHtml(text: string): string { return text .replace(/&/g, '&') diff --git a/src/app/plugins/markdown/extensions/matrix-underline.ts b/src/app/plugins/markdown/extensions/matrix-underline.ts new file mode 100644 index 000000000..8f7a0b2ed --- /dev/null +++ b/src/app/plugins/markdown/extensions/matrix-underline.ts @@ -0,0 +1,38 @@ +import type { TokenizerExtension, RendererExtension, Tokens } from 'marked'; + +// Underline extension: __text__ +export const matrixUnderlineExtension = { + name: 'matrixUnderline', + level: 'inline', + start(src: string) { + return src.indexOf('__'); + }, + tokenizer( + this: { + lexer: { inlineTokens: (t: string, tokens: Tokens.Generic[]) => void }; + }, + src: string + ) { + if (!src.startsWith('__')) return undefined; + const rule = /^__(.+?)__/; + const match = rule.exec(src); + if (match) { + const token = { + type: 'matrixUnderline', + raw: match[0], + text: match[1], + tokens: [] as Tokens.Generic[], + }; + this.lexer.inlineTokens(token.text!, token.tokens); + return token; + } + return undefined; + }, + renderer( + this: { parser: { parseInline: (tokens: Tokens.Generic[]) => string } }, + token: Tokens.Generic + ) { + const tokens = (token as { tokens: Tokens.Generic[] }).tokens || []; + return `${this.parser.parseInline(tokens)}`; + }, +} satisfies TokenizerExtension & RendererExtension; diff --git a/src/app/plugins/markdown/htmlToMarkdown.ts b/src/app/plugins/markdown/htmlToMarkdown.ts index ceda1d3a7..94c7381bf 100644 --- a/src/app/plugins/markdown/htmlToMarkdown.ts +++ b/src/app/plugins/markdown/htmlToMarkdown.ts @@ -117,8 +117,10 @@ function processNode(node: ChildNode, listDepth: number = 0, insideCode: boolean case 'i': return processInlineWrapper(node, '*', listDepth, insideCode); - case 'u': - return processInlineWrapper(node, '_', listDepth, insideCode); + case 'u': { + const md = node.attribs['data-md']; + return processInlineWrapper(node, md ?? '__'); + } case 's': case 'del': diff --git a/src/app/plugins/markdown/injectDataMd.test.ts b/src/app/plugins/markdown/injectDataMd.test.ts index 2572c9e20..c29f30196 100644 --- a/src/app/plugins/markdown/injectDataMd.test.ts +++ b/src/app/plugins/markdown/injectDataMd.test.ts @@ -56,7 +56,7 @@ describe('injectDataMd', () => { it('injects data-md into u tags', () => { const result = injectDataMd('underline'); - expect(result).toContain('data-md="_"'); + expect(result).toContain('data-md="__"'); }); it('injects data-md into s tags', () => { diff --git a/src/app/plugins/markdown/injectDataMd.ts b/src/app/plugins/markdown/injectDataMd.ts index e27cfdb7b..ca1403650 100644 --- a/src/app/plugins/markdown/injectDataMd.ts +++ b/src/app/plugins/markdown/injectDataMd.ts @@ -75,7 +75,7 @@ export function injectDataMd(html: string): string { // Inject inline markdown markers for underline html = html.replace(/]*)>([^<]*)<\/u>/g, (_, attrs, content) => { if (attrs.includes('data-md')) return `${content}`; - return `${content}`; + return `${content}`; }); // Inject inline markdown markers for strikethrough diff --git a/src/app/plugins/markdown/markdownToHtml.test.ts b/src/app/plugins/markdown/markdownToHtml.test.ts index 61acb9f5c..93fc71321 100644 --- a/src/app/plugins/markdown/markdownToHtml.test.ts +++ b/src/app/plugins/markdown/markdownToHtml.test.ts @@ -13,6 +13,14 @@ describe('markdownToHtml', () => { expect(result).toContain('bold'); }); + it('converts __ to underline, not bold', () => { + const result = markdownToHtml('__underlined__'); + expect(result).toContain('underlined<'); + expect(result).not.toContain('underlined'); + }); + it('converts italic text', () => { const result = markdownToHtml('*italic*'); expect(result).toContain('italic'); @@ -40,6 +48,27 @@ describe('markdownToHtml', () => { expect(result).toContain('E = mc^2'); }); + it('does not parse dollars inside fenced code as math', () => { + expect(markdownToHtml('```\n$$test$$\n```')).not.toContain('data-mx-maths'); + expect(markdownToHtml('```\n$$test$$\n```')).toContain('$$test$$'); + }); + + it('does not parse dollars inside single-line fenced code as math', () => { + expect(markdownToHtml('```$$test$$```')).not.toContain('data-mx-maths'); + expect(markdownToHtml('```$$test$$```')).toContain('$$test$$'); + }); + + it('does not parse dollars inside inline code as math', () => { + expect(markdownToHtml('`$$test$$`')).not.toContain('data-mx-maths'); + expect(markdownToHtml('`$$test$$`')).toContain('$$test$$'); + }); + + it('does not parse inline math when dollars are only inside backticks in a sentence', () => { + const result = markdownToHtml('See `$$test$$` here.'); + expect(result).not.toContain('data-mx-maths'); + expect(result).toContain('$$test$$'); + }); + it('converts block math syntax', () => { const result = markdownToHtml('$$\\frac{a}{b}$$'); expect(result).toContain('data-mx-maths'); @@ -81,6 +110,24 @@ describe('markdownToHtml', () => { expect(result).toContain('\\*x\\*'); }); + it('does not treat >:3 as a block quote (requires space after >)', () => { + const result = markdownToHtml('>:3'); + expect(result).not.toContain('
'); + expect(result).toContain(':3'); + }); + + it('treats > followed by space as block quote', () => { + const result = markdownToHtml('> quoted'); + expect(result).toContain('
'); + expect(result).toContain('quoted'); + }); + + it('escapes block quote with a single backslash before >', () => { + const result = markdownToHtml('\\>:3'); + expect(result).not.toContain('
'); + expect(result).toContain(':3'); + }); + it('preserves img[data-mx-emoticon] tags with valid mxc URLs', () => { const html = ':blobcat:'; diff --git a/src/app/plugins/markdown/markdownToHtml.ts b/src/app/plugins/markdown/markdownToHtml.ts index aa76b8839..970814d99 100644 --- a/src/app/plugins/markdown/markdownToHtml.ts +++ b/src/app/plugins/markdown/markdownToHtml.ts @@ -1,18 +1,26 @@ import { marked } from 'marked'; import DOMPurify from 'dompurify'; import { matrixSpoilerExtension } from './extensions/matrix-spoiler'; -import { matrixMathExtension, matrixMathBlockExtension } from './extensions/matrix-math'; +import { + matrixMathExtension, + matrixMathBlockExtension, + maskDollarSignsInsideMarkdownCode, + unmaskMathCodeDollarPlaceholders, +} from './extensions/matrix-math'; import { matrixSubscriptExtension } from './extensions/matrix-subscript'; import { matrixEmoticonExtension, preprocessEmoticon } from './extensions/matrix-emoticon'; +import { matrixUnderlineExtension } from './extensions/matrix-underline'; import { - unescapeMarkdownBlockSequences, + escapeLineStartBlockquoteWithoutFollowingSpace, unescapeMarkdownInlineSequencesExceptInCodeHtml, + unescapeMarkdownInlineSequences, } from './utils'; // Configure marked with Matrix extensions const processor = marked.use({ breaks: true, extensions: [ + matrixUnderlineExtension, matrixSpoilerExtension, matrixMathExtension, matrixMathBlockExtension, @@ -53,13 +61,15 @@ export function markdownToHtml(markdown: string): string { // (e.g., < becomes < for link URLs) const decoded = decodeHtmlEntities(markdown); - // First unescape any block-level escape sequences (e.g., \>, \#) - const unescapedBlocks = unescapeMarkdownBlockSequences(decoded, (text) => text); + // Only treat `> ` as block quote, escape bare `>` at line start (e.g. `>:3`) + const blockquotePrefixed = escapeLineStartBlockquoteWithoutFollowingSpace(decoded); - const preprocessed = preprocessEmoticon(unescapedBlocks); + const preprocessed = preprocessEmoticon(blockquotePrefixed); + + const mathInput = maskDollarSignsInsideMarkdownCode(preprocessed); // Parse markdown to HTML using marked with our Matrix extensions - const html = processor.parse(preprocessed) as string; + const html = processor.parse(mathInput) as string; // Unescape inline sequences (e.g., \*, \_) after parsing, but not inside
/
   const unescapedInline = unescapeMarkdownInlineSequencesExceptInCodeHtml(html);
@@ -139,5 +149,8 @@ export function markdownToHtml(markdown: string): string {
 
   DOMPurify.removeHook('afterSanitizeAttributes');
 
-  return sanitized.replace(/
  • (

    <\/p>)?<\/li>/gi, '


  • '); + return unmaskMathCodeDollarPlaceholders(sanitized).replace( + /
  • (

    <\/p>)?<\/li>/gi, + '


  • ' + ); } diff --git a/src/app/plugins/markdown/utils.ts b/src/app/plugins/markdown/utils.ts index e32a85f23..822a1e5a1 100644 --- a/src/app/plugins/markdown/utils.ts +++ b/src/app/plugins/markdown/utils.ts @@ -1,10 +1,5 @@ import { findAndReplace } from '$utils/findAndReplace'; -// Regex patterns for block-level markdown escape sequences -// These match escaped markdown characters like \>, \#, \`, etc. -const ESC_BLOCK_SEQ = /^\\(\\*[#>[ `])/; -const UN_ESC_BLOCK_SEQ = /^\*[#>[ `]/; - // URL-aware pattern for inline sequences const URL_NEG_LB = '(? { }; /** - * Removes escape sequences from markdown block elements in the given plain-text. - * This function unescapes characters that are escaped with backslashes (e.g., `\>`, `\#`) - * in markdown syntax, returning the original plain-text with markdown characters in effect. - * - * @param {string} text - The input markdown plain-text containing escape characters (e.g., `\> block quote`). - * @param {function} processPart - It takes the plain-text as input and returns a modified version of it. - * @returns {string} The plain-text with markdown escape sequences removed and markdown formatting applied. + * CommonMark treats `>` at line start as a block quote marker even when not followed by + * space. We only start a block quote when `>` is followed by horizontal whitespace. + * Lines like `>:3` get a backslash so the `>` is literal. */ -export const unescapeMarkdownBlockSequences = ( - text: string, - processPart: (text: string) => string -): string => { - const match = text.match(ESC_BLOCK_SEQ); - - if (!match) return processPart(text); - - const [, g1] = match; - return text.replace(ESC_BLOCK_SEQ, g1 ?? ''); -}; - -/** - * Escapes markdown block elements by adding backslashes before markdown characters - * (e.g., `\>`, `\#`) that are normally interpreted as markdown syntax. - * - * @param {string} text - The input markdown plain-text that may contain markdown elements (e.g., `> block quote`). - * @param {function} processPart - It takes the plain-text as input and returns a modified version of it. - * @returns {string} The plain-text with markdown escape sequences added, preventing markdown formatting. - */ -export const escapeMarkdownBlockSequences = ( - text: string, - processPart: (text: string) => string -): string => { - const match = text.match(UN_ESC_BLOCK_SEQ); - - if (!match) return processPart(text); - - const [, g1] = match; - return text.replace(UN_ESC_BLOCK_SEQ, `\\${g1}`); -}; +export const escapeLineStartBlockquoteWithoutFollowingSpace = (markdown: string): string => + markdown.replace(/^(\s*)>(?![ \t])/gm, '$1\\>'); diff --git a/src/app/utils/consolePasteScamWarning.ts b/src/app/utils/consolePasteScamWarning.ts new file mode 100644 index 000000000..72d750e28 --- /dev/null +++ b/src/app/utils/consolePasteScamWarning.ts @@ -0,0 +1,58 @@ +// This is probably not very accurate, but doesn't really matter I suppose +function isDockedDevtoolsLikely(): boolean { + const gapW = window.outerWidth - window.innerWidth; + const gapH = window.outerHeight - window.innerHeight; + const threshold = 160; + return gapW >= threshold || gapH >= threshold; +} + +export function installConsolePasteScamWarning(): void { + const BANNER_STYLE = + 'font-size:56px;font-weight:900;color:#ff0033;background:#1a0006;padding:16px 24px;border:6px solid #ff0033;line-height:1.1;'; + const BODY_STYLE = + 'font-size:22px;font-weight:700;color:#ffb3c1;background:#120008;padding:14px 20px;line-height:1.35;max-width:920px;'; + const CONTRIBUTE_STYLE = + 'font-size:18px;font-weight:600;color:#a8d4ff;background:#0a1520;padding:12px 20px;line-height:1.35;max-width:920px;'; + + const spamWarnings = () => { + const repeat = 15; + const betweenPairsMs = 300; + + const emitPair = (index: number) => { + console.warn('%cSTOP', BANNER_STYLE); + console.warn( + '%cIf anyone told you to paste code or text here, you are being scammed. Close this window, do not paste anything, and report their account.', + BODY_STYLE + ); + if (index + 1 < repeat) { + window.setTimeout(() => { + emitPair(index + 1); + }, betweenPairsMs); + } else { + window.setTimeout(() => { + console.warn( + "%cIf you know what you're doing, check out our GitHub and contribute: https://github.com/SableClient/Sable", + CONTRIBUTE_STYLE + ); + }, betweenPairsMs); + } + }; + + emitPair(0); + }; + + let devtoolsWasOpen = false; + + const check = () => { + const devtoolsLikelyOpen = isDockedDevtoolsLikely(); + if (devtoolsLikelyOpen && !devtoolsWasOpen) { + spamWarnings(); + } + devtoolsWasOpen = devtoolsLikelyOpen; + }; + + window.setInterval(check, 1500); + window.addEventListener('resize', () => queueMicrotask(check)); + + queueMicrotask(check); +} diff --git a/src/app/utils/room.ts b/src/app/utils/room.ts index ffa0528ff..f252d95b5 100644 --- a/src/app/utils/room.ts +++ b/src/app/utils/room.ts @@ -679,6 +679,24 @@ export const reactionOrEditEvent = (mEvent: MatrixEvent): boolean => { return false; }; +/** + * Timeline rows skip reactions, edits, and other relation-only events. When jumping + * to a reply target, unwrap to the event that is actually rendered (root of an + * edit chain, message for a reaction annotation, etc.). + */ +export const unwrapRelationJumpTarget = (room: Room, eventId: string, maxHops = 24): string => { + let current = eventId; + for (let hop = 0; hop < maxHops; hop += 1) { + const ev = room.findEventById(current); + if (!ev) return current; + if (!reactionOrEditEvent(ev)) return current; + const related = ev.getRelation()?.event_id; + if (typeof related !== 'string' || related === current) return current; + current = related; + } + return current; +}; + export const getMentionContent = (userIds: string[], room: boolean): IMentions => { const mMentions: IMentions = {}; if (userIds.length > 0) { diff --git a/src/index.tsx b/src/index.tsx index 4f6dfb004..1721755d5 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -22,8 +22,10 @@ import type { Sessions } from './app/state/sessions'; import { getFallbackSession, MATRIX_SESSIONS_KEY, ACTIVE_SESSION_KEY } from './app/state/sessions'; import { createLogger } from './app/utils/debug'; import { getLocalStorageItem } from './app/state/utils/atomWithLocalStorage'; +import { installConsolePasteScamWarning } from './app/utils/consolePasteScamWarning'; enableMapSet(); +installConsolePasteScamWarning(); const log = createLogger('index'); document.body.classList.add(configClass, varsClass);