feat: room abbreviations with hover tooltips and space inheritance (#514)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description Adds a room abbreviations feature: moderators can define term/definition pairs in room settings. Defined terms are highlighted with a dotted underline in messages and show a tooltip on hover (tap-to-pin on mobile). Abbreviations defined in a parent space are inherited by child rooms and nested spaces, with overrides allowed at each level. The settings UI shows a flat list of inherited and locally-defined entries. Fixes # #### Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [x] My code follows the style guidelines of this project - [x] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [X] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. --> The code adds changes that allow for setting and viewing room abbreviations, with an on-hover tooltip (or press on mobile - semi-persistent). It stores these in the room state under a new key, and recursively fetches abbreviations from the space level. This also adds regex so that abbreviations correctly work at word boundaries. Also adds the needed hooks to `room.ts` and `slidingSync.ts`
This commit is contained in:
16 files changed
+861
-67
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
Add room abbreviations with hover tooltips: moderators define term/definition pairs in room settings; matching terms are highlighted in messages.
|
||||
@@ -1,10 +1,94 @@
|
||||
import { MouseEventHandler, useEffect, useState } from 'react';
|
||||
import parse, { HTMLReactParserOptions } from 'html-react-parser';
|
||||
import Linkify from 'linkify-react';
|
||||
import { Opts } from 'linkifyjs';
|
||||
import { PopOut, RectCords, Text, Tooltip, TooltipProvider, toRem } from 'folds';
|
||||
import { sanitizeCustomHtml } from '$utils/sanitize';
|
||||
import { highlightText, scaleSystemEmoji } from '$plugins/react-custom-html-parser';
|
||||
import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations';
|
||||
import { splitByAbbreviations } from '$utils/abbreviations';
|
||||
import { MessageEmptyContent } from './content';
|
||||
|
||||
type AbbreviationTermProps = {
|
||||
text: string;
|
||||
definition: string;
|
||||
};
|
||||
function AbbreviationTerm({ text, definition }: AbbreviationTermProps) {
|
||||
const [anchor, setAnchor] = useState<RectCords | undefined>();
|
||||
|
||||
const handleClick: MouseEventHandler<HTMLElement> = (e) => {
|
||||
e.stopPropagation();
|
||||
setAnchor((prev) => (prev ? undefined : e.currentTarget.getBoundingClientRect()));
|
||||
};
|
||||
|
||||
// On mobile, tapping an abbreviation pins the tooltip open.
|
||||
// Tapping anywhere else (outside the abbr) dismisses it.
|
||||
useEffect(() => {
|
||||
if (!anchor) return undefined;
|
||||
const dismiss = () => setAnchor(undefined);
|
||||
document.addEventListener('click', dismiss, { once: true });
|
||||
return () => document.removeEventListener('click', dismiss);
|
||||
}, [anchor]);
|
||||
|
||||
const tooltipContent = (
|
||||
<Tooltip style={{ maxWidth: toRem(250) }}>
|
||||
<Text size="T200">{definition}</Text>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<TooltipProvider position="Top" tooltip={tooltipContent}>
|
||||
{(triggerRef) => (
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions
|
||||
<abbr
|
||||
ref={triggerRef as React.Ref<HTMLElement>}
|
||||
onClick={handleClick}
|
||||
style={{ textDecoration: 'underline dotted', cursor: 'help' }}
|
||||
>
|
||||
{text}
|
||||
</abbr>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
{anchor && (
|
||||
<PopOut anchor={anchor} position="Top" align="Center" content={tooltipContent}>
|
||||
{null}
|
||||
</PopOut>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a `replaceTextNode` callback for use with {@link getReactCustomHtmlParser}.
|
||||
* Returns `undefined` when there are no abbreviations to apply (avoids creating
|
||||
* extra closures in the common case).
|
||||
*/
|
||||
export function buildAbbrReplaceTextNode(
|
||||
abbrMap: Map<string, string>
|
||||
): ((text: string) => JSX.Element | undefined) | undefined {
|
||||
if (abbrMap.size === 0) return undefined;
|
||||
return function replaceTextNode(text: string) {
|
||||
const segments = splitByAbbreviations(text, abbrMap);
|
||||
if (!segments.some((s) => s.termKey !== undefined)) return undefined;
|
||||
return (
|
||||
<>
|
||||
{segments.map((seg) =>
|
||||
seg.termKey !== undefined ? (
|
||||
<AbbreviationTerm
|
||||
key={seg.id}
|
||||
text={seg.text}
|
||||
definition={abbrMap.get(seg.termKey) ?? ''}
|
||||
/>
|
||||
) : (
|
||||
seg.text
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
type RenderBodyProps = {
|
||||
body: string;
|
||||
customBody?: string;
|
||||
@@ -20,12 +104,37 @@ export function RenderBody({
|
||||
htmlReactParserOptions,
|
||||
linkifyOpts,
|
||||
}: Readonly<RenderBodyProps>) {
|
||||
const abbrMap = useRoomAbbreviationsContext();
|
||||
|
||||
if (customBody) {
|
||||
if (customBody === '') return <MessageEmptyContent />;
|
||||
return parse(sanitizeCustomHtml(customBody), htmlReactParserOptions);
|
||||
}
|
||||
if (body === '') return <MessageEmptyContent />;
|
||||
|
||||
if (abbrMap.size > 0) {
|
||||
const segments = splitByAbbreviations(body, abbrMap);
|
||||
if (segments.some((s) => s.termKey !== undefined)) {
|
||||
return (
|
||||
<>
|
||||
{segments.map((seg) => {
|
||||
if (seg.termKey !== undefined) {
|
||||
const definition = abbrMap.get(seg.termKey) ?? '';
|
||||
return <AbbreviationTerm key={seg.id} text={seg.text} definition={definition} />;
|
||||
}
|
||||
return (
|
||||
<Linkify key={seg.id} options={linkifyOpts}>
|
||||
{highlightRegex
|
||||
? highlightText(highlightRegex, scaleSystemEmoji(seg.text))
|
||||
: scaleSystemEmoji(seg.text)}
|
||||
</Linkify>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Linkify options={linkifyOpts}>
|
||||
{highlightRegex
|
||||
|
||||
@@ -19,6 +19,7 @@ import { DeveloperTools } from '$features/common-settings/developer-tools';
|
||||
import { Cosmetics } from '$features/common-settings/cosmetics/Cosmetics';
|
||||
import { Permissions } from './permissions';
|
||||
import { General } from './general';
|
||||
import { RoomAbbreviations } from './abbreviations/RoomAbbreviations';
|
||||
|
||||
type RoomSettingsMenuItem = {
|
||||
page: RoomSettingsPage;
|
||||
@@ -51,6 +52,11 @@ const useRoomSettingsMenuItems = (): RoomSettingsMenuItem[] =>
|
||||
icon: Icons.Alphabet,
|
||||
activeIcon: Icons.AlphabetUnderline,
|
||||
},
|
||||
{
|
||||
page: RoomSettingsPage.AbbreviationsPage,
|
||||
name: 'Abbreviations',
|
||||
icon: Icons.Info,
|
||||
},
|
||||
{
|
||||
page: RoomSettingsPage.EmojisStickersPage,
|
||||
name: 'Emojis & Stickers',
|
||||
@@ -196,6 +202,9 @@ export function RoomSettings({ initialPage, requestClose }: RoomSettingsProps) {
|
||||
{activePage === RoomSettingsPage.DeveloperToolsPage && (
|
||||
<DeveloperTools requestClose={handlePageRequestClose} />
|
||||
)}
|
||||
{activePage === RoomSettingsPage.AbbreviationsPage && (
|
||||
<RoomAbbreviations requestClose={handlePageRequestClose} />
|
||||
)}
|
||||
</PageRoot>
|
||||
</SwipeableOverlayWrapper>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
import { FormEventHandler, useCallback, useMemo } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Chip,
|
||||
Icon,
|
||||
IconButton,
|
||||
Icons,
|
||||
Input,
|
||||
Scroll,
|
||||
Spinner,
|
||||
Text,
|
||||
config,
|
||||
} from 'folds';
|
||||
import { Page, PageContent, PageHeader } from '$components/page';
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { useRoom } from '$hooks/useRoom';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { usePowerLevels } from '$hooks/usePowerLevels';
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { useStateEvent } from '$hooks/useStateEvent';
|
||||
import { useStateEventCallback } from '$hooks/useStateEventCallback';
|
||||
import { useForceUpdate } from '$hooks/useForceUpdate';
|
||||
import { StateEvent } from '$types/matrix/room';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { MatrixError } from '$types/matrix-sdk';
|
||||
import { AbbreviationEntry, RoomAbbreviationsContent } from '$utils/abbreviations';
|
||||
import { getAllParents, getStateEvent } from '$utils/room';
|
||||
import { roomToParentsAtom } from '$state/room/roomToParents';
|
||||
import { SequenceCardStyle } from '$features/common-settings/styles.css';
|
||||
|
||||
type AbbreviationsProps = {
|
||||
requestClose: () => void;
|
||||
isSpace?: boolean;
|
||||
};
|
||||
|
||||
export function RoomAbbreviations({ requestClose, isSpace }: AbbreviationsProps) {
|
||||
const room = useRoom();
|
||||
const mx = useMatrixClient();
|
||||
const powerLevels = usePowerLevels(room);
|
||||
const creators = useRoomCreators(room);
|
||||
const permissions = useRoomPermissions(creators, powerLevels);
|
||||
const userId = mx.getUserId() ?? '';
|
||||
|
||||
const stateEvent = useStateEvent(room, StateEvent.RoomAbbreviations);
|
||||
const content = stateEvent?.getContent<RoomAbbreviationsContent>();
|
||||
const entries: AbbreviationEntry[] = Array.isArray(content?.entries) ? content.entries : [];
|
||||
|
||||
// Ancestor space abbreviations (read-only, inherited) — full multi-level support
|
||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
||||
const [ancestorUpdateCount, forceAncestorUpdate] = useForceUpdate();
|
||||
|
||||
useStateEventCallback(
|
||||
mx,
|
||||
useCallback(
|
||||
(event) => {
|
||||
if (event.getType() !== StateEvent.RoomAbbreviations) return;
|
||||
const eventRoomId = event.getRoomId();
|
||||
if (eventRoomId && getAllParents(roomToParents, room.roomId).has(eventRoomId)) {
|
||||
forceAncestorUpdate();
|
||||
}
|
||||
},
|
||||
[room.roomId, roomToParents, forceAncestorUpdate]
|
||||
)
|
||||
);
|
||||
|
||||
type SpaceEntryGroup = { spaceId: string; spaceName: string; entries: AbbreviationEntry[] };
|
||||
const ancestorGroups = useMemo(
|
||||
(): SpaceEntryGroup[] =>
|
||||
Array.from(getAllParents(roomToParents, room.roomId)).reduce<SpaceEntryGroup[]>(
|
||||
(groups, parentId) => {
|
||||
const parentRoom = mx.getRoom(parentId);
|
||||
if (!parentRoom) return groups;
|
||||
const ev = getStateEvent(parentRoom, StateEvent.RoomAbbreviations);
|
||||
const c = ev?.getContent<RoomAbbreviationsContent>();
|
||||
const parentEntries: AbbreviationEntry[] = Array.isArray(c?.entries) ? c.entries : [];
|
||||
if (parentEntries.length > 0) {
|
||||
groups.push({ spaceId: parentId, spaceName: parentRoom.name, entries: parentEntries });
|
||||
}
|
||||
return groups;
|
||||
},
|
||||
[]
|
||||
),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[mx, roomToParents, room.roomId, ancestorUpdateCount]
|
||||
);
|
||||
const allAncestorEntries = useMemo(
|
||||
() => ancestorGroups.flatMap((g) => g.entries),
|
||||
[ancestorGroups]
|
||||
);
|
||||
|
||||
const canEdit = permissions.stateEvent(StateEvent.RoomAbbreviations, userId);
|
||||
|
||||
const [saveState, saveAbbreviations] = useAsyncCallback<void, MatrixError, [AbbreviationEntry[]]>(
|
||||
useCallback(
|
||||
async (newEntries) => {
|
||||
const newContent: RoomAbbreviationsContent = { entries: newEntries };
|
||||
await mx.sendStateEvent(room.roomId, StateEvent.RoomAbbreviations as any, newContent, '');
|
||||
},
|
||||
[mx, room.roomId]
|
||||
)
|
||||
);
|
||||
|
||||
const saving = saveState.status === AsyncStatus.Loading;
|
||||
|
||||
const handleAdd: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||
evt.preventDefault();
|
||||
if (saving || !canEdit) return;
|
||||
const form = evt.target as HTMLFormElement;
|
||||
const termInput = form.elements.namedItem('term') as HTMLInputElement | null;
|
||||
const definitionInput = form.elements.namedItem('definition') as HTMLInputElement | null;
|
||||
if (!termInput || !definitionInput) return;
|
||||
const term = termInput.value.trim();
|
||||
const definition = definitionInput.value.trim();
|
||||
if (!term || !definition) return;
|
||||
|
||||
const alreadyExists =
|
||||
entries.some((e) => e.term.toLowerCase() === term.toLowerCase()) ||
|
||||
allAncestorEntries.some((e) => e.term.toLowerCase() === term.toLowerCase());
|
||||
if (alreadyExists) {
|
||||
termInput.setCustomValidity('This term already exists.');
|
||||
termInput.reportValidity();
|
||||
return;
|
||||
}
|
||||
termInput.setCustomValidity('');
|
||||
|
||||
const newEntries = [...entries, { term, definition }];
|
||||
saveAbbreviations(newEntries).then(() => {
|
||||
form.reset();
|
||||
});
|
||||
};
|
||||
|
||||
const handleRemove = (index: number) => {
|
||||
if (saving || !canEdit) return;
|
||||
const newEntries = entries.filter((_, i) => i !== index);
|
||||
saveAbbreviations(newEntries);
|
||||
};
|
||||
|
||||
return (
|
||||
<Page>
|
||||
<PageHeader outlined={false}>
|
||||
<Box grow="Yes" gap="200">
|
||||
<Box grow="Yes" alignItems="Center" gap="200">
|
||||
<Text size="H3" truncate>
|
||||
Abbreviations
|
||||
</Text>
|
||||
</Box>
|
||||
<Box shrink="No">
|
||||
<IconButton onClick={requestClose} variant="Surface">
|
||||
<Icon src={Icons.Cross} />
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
</PageHeader>
|
||||
<Box grow="Yes">
|
||||
<Scroll hideTrack visibility="Hover">
|
||||
<PageContent>
|
||||
<Box direction="Column" gap="700">
|
||||
{canEdit && (
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Add Abbreviation</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="New Entry"
|
||||
description="Define a term that members can hover over to see its meaning."
|
||||
>
|
||||
<Box
|
||||
style={{ marginTop: config.space.S200 }}
|
||||
as="form"
|
||||
onSubmit={handleAdd}
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Term</Text>
|
||||
<Input
|
||||
name="term"
|
||||
required
|
||||
size="400"
|
||||
variant="Secondary"
|
||||
radii="300"
|
||||
placeholder="e.g. FOSS"
|
||||
readOnly={saving}
|
||||
onChange={(e) => e.currentTarget.setCustomValidity('')}
|
||||
/>
|
||||
</Box>
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Definition</Text>
|
||||
<Input
|
||||
name="definition"
|
||||
required
|
||||
size="400"
|
||||
variant="Secondary"
|
||||
radii="300"
|
||||
placeholder="e.g. Free and Open Source Software"
|
||||
readOnly={saving}
|
||||
/>
|
||||
</Box>
|
||||
{saveState.status === AsyncStatus.Error && (
|
||||
<Text size="T200" style={{ color: 'var(--mx-danger)' }}>
|
||||
{saveState.error.message}
|
||||
</Text>
|
||||
)}
|
||||
<Box gap="200">
|
||||
<Button
|
||||
type="submit"
|
||||
size="300"
|
||||
variant="Primary"
|
||||
radii="300"
|
||||
disabled={saving}
|
||||
before={saving ? <Spinner size="100" variant="Primary" /> : undefined}
|
||||
>
|
||||
<Text size="B300">{saving ? 'Saving…' : 'Add'}</Text>
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</SettingTile>
|
||||
</SequenceCard>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Box direction="Column" gap="100">
|
||||
{(() => {
|
||||
const totalCount = entries.length + (isSpace ? 0 : allAncestorEntries.length);
|
||||
const label = isSpace ? 'Space' : 'Room';
|
||||
return (
|
||||
<>
|
||||
<Text size="L400">
|
||||
{totalCount > 0
|
||||
? `${label} Abbreviations (${totalCount})`
|
||||
: `${label} Abbreviations`}
|
||||
</Text>
|
||||
{totalCount === 0 ? (
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
>
|
||||
<Text size="T300" style={{ color: 'var(--mx-surface-variant-on)' }}>
|
||||
No {isSpace ? 'space' : 'room'}-level abbreviations defined yet.
|
||||
{canEdit && ' Use the form above to add some.'}
|
||||
</Text>
|
||||
</SequenceCard>
|
||||
) : (
|
||||
<>
|
||||
{entries.map((entry, index) => (
|
||||
<SequenceCard
|
||||
key={entry.term}
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Row"
|
||||
gap="400"
|
||||
alignItems="Center"
|
||||
>
|
||||
<Box grow="Yes" direction="Column" gap="100">
|
||||
<Text size="T300">
|
||||
<b>{entry.term}</b>
|
||||
</Text>
|
||||
<Text size="T200" style={{ opacity: 0.7 }}>
|
||||
{entry.definition}
|
||||
</Text>
|
||||
</Box>
|
||||
{canEdit && (
|
||||
<Box shrink="No">
|
||||
<IconButton
|
||||
onClick={() => handleRemove(index)}
|
||||
variant="Background"
|
||||
size="300"
|
||||
radii="300"
|
||||
disabled={saving}
|
||||
aria-label={`Remove abbreviation ${entry.term}`}
|
||||
>
|
||||
<Icon src={Icons.Delete} size="100" />
|
||||
</IconButton>
|
||||
</Box>
|
||||
)}
|
||||
</SequenceCard>
|
||||
))}
|
||||
{!isSpace &&
|
||||
ancestorGroups.flatMap(({ spaceId, spaceName, entries: spEntries }) =>
|
||||
spEntries.map((entry) => (
|
||||
<SequenceCard
|
||||
key={`${spaceId}-${entry.term}`}
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Row"
|
||||
gap="400"
|
||||
alignItems="Center"
|
||||
>
|
||||
<Box grow="Yes" direction="Column" gap="100">
|
||||
<Box gap="200" alignItems="Center">
|
||||
<Text size="T300">
|
||||
<b>{entry.term}</b>
|
||||
</Text>
|
||||
<Chip variant="Primary" radii="Pill" size="400">
|
||||
<Text size="T200">Space - {spaceName}</Text>
|
||||
</Chip>
|
||||
</Box>
|
||||
<Text size="T200" style={{ opacity: 0.7 }}>
|
||||
{entry.definition}
|
||||
</Text>
|
||||
</Box>
|
||||
</SequenceCard>
|
||||
))
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
</Box>
|
||||
</Box>
|
||||
</PageContent>
|
||||
</Scroll>
|
||||
</Box>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import { callChatAtom } from '$state/callEmbed';
|
||||
import { roomIdToOpenThreadAtomFamily } from '$state/room/roomToOpenThread';
|
||||
import { roomIdToThreadBrowserAtomFamily } from '$state/room/roomToThreadBrowser';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
import { useMergedAbbreviations, RoomAbbreviationsContext } from '$hooks/useRoomAbbreviations';
|
||||
import { RoomViewHeader } from './RoomViewHeader';
|
||||
import { MembersDrawer } from './MembersDrawer';
|
||||
import { RoomView } from './RoomView';
|
||||
@@ -97,6 +98,7 @@ export function Room() {
|
||||
);
|
||||
|
||||
const callView = room.isCallRoom();
|
||||
const abbreviations = useMergedAbbreviations(room);
|
||||
|
||||
// Log call view state
|
||||
useEffect(() => {
|
||||
@@ -105,58 +107,80 @@ export function Room() {
|
||||
|
||||
return (
|
||||
<PowerLevelsContextProvider value={powerLevels}>
|
||||
<Box grow="Yes" style={{ position: 'relative' }}>
|
||||
{callView && (screenSize === ScreenSize.Desktop || !chat) && (
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomViewHeader callView />
|
||||
<Box grow="Yes">
|
||||
<CallView />
|
||||
<RoomAbbreviationsContext.Provider value={abbreviations}>
|
||||
<Box grow="Yes" style={{ position: 'relative' }}>
|
||||
{callView && (screenSize === ScreenSize.Desktop || !chat) && (
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomViewHeader callView />
|
||||
<Box grow="Yes">
|
||||
<CallView />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
{!callView && (
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomViewHeader />
|
||||
<Box grow="Yes">
|
||||
<RoomView eventId={eventId} />
|
||||
)}
|
||||
{!callView && (
|
||||
<Box grow="Yes" direction="Column">
|
||||
<RoomViewHeader />
|
||||
<Box grow="Yes">
|
||||
<RoomView eventId={eventId} />
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
)}
|
||||
|
||||
{callView && chat && (
|
||||
<>
|
||||
{screenSize === ScreenSize.Desktop && (
|
||||
{callView && chat && (
|
||||
<>
|
||||
{screenSize === ScreenSize.Desktop && (
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
)}
|
||||
<CallChatView />
|
||||
</>
|
||||
)}
|
||||
{!callView && screenSize === ScreenSize.Desktop && isDrawer && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
)}
|
||||
<CallChatView />
|
||||
</>
|
||||
)}
|
||||
{!callView && screenSize === ScreenSize.Desktop && isDrawer && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
<MembersDrawer key={room.roomId} room={room} members={members} />
|
||||
</>
|
||||
)}
|
||||
{screenSize === ScreenSize.Desktop && isWidgetDrawerOpen && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
<WidgetsDrawer key={`widgets-${room.roomId}`} room={room} />
|
||||
</>
|
||||
)}
|
||||
{screenSize === ScreenSize.Desktop && openThreadId && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
<MembersDrawer key={room.roomId} room={room} members={members} />
|
||||
</>
|
||||
)}
|
||||
{screenSize === ScreenSize.Desktop && isWidgetDrawerOpen && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
<WidgetsDrawer key={`widgets-${room.roomId}`} room={room} />
|
||||
</>
|
||||
)}
|
||||
{screenSize === ScreenSize.Desktop && openThreadId && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
<ThreadDrawer
|
||||
key={`thread-${room.roomId}-${openThreadId}`}
|
||||
room={room}
|
||||
threadRootId={openThreadId}
|
||||
onClose={() => setOpenThread(undefined)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{screenSize === ScreenSize.Desktop && threadBrowserOpen && !openThreadId && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
<ThreadBrowser
|
||||
key={`thread-browser-${room.roomId}`}
|
||||
room={room}
|
||||
onOpenThread={(id) => {
|
||||
setOpenThread(id);
|
||||
setThreadBrowserOpen(false);
|
||||
}}
|
||||
onClose={() => setThreadBrowserOpen(false)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{screenSize !== ScreenSize.Desktop && openThreadId && (
|
||||
<ThreadDrawer
|
||||
key={`thread-${room.roomId}-${openThreadId}`}
|
||||
room={room}
|
||||
threadRootId={openThreadId}
|
||||
onClose={() => setOpenThread(undefined)}
|
||||
overlay
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{screenSize === ScreenSize.Desktop && threadBrowserOpen && !openThreadId && (
|
||||
<>
|
||||
<Line variant="Background" direction="Vertical" size="300" />
|
||||
)}
|
||||
{screenSize !== ScreenSize.Desktop && threadBrowserOpen && !openThreadId && (
|
||||
<ThreadBrowser
|
||||
key={`thread-browser-${room.roomId}`}
|
||||
room={room}
|
||||
@@ -165,31 +189,11 @@ export function Room() {
|
||||
setThreadBrowserOpen(false);
|
||||
}}
|
||||
onClose={() => setThreadBrowserOpen(false)}
|
||||
overlay
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{screenSize !== ScreenSize.Desktop && openThreadId && (
|
||||
<ThreadDrawer
|
||||
key={`thread-${room.roomId}-${openThreadId}`}
|
||||
room={room}
|
||||
threadRootId={openThreadId}
|
||||
onClose={() => setOpenThread(undefined)}
|
||||
overlay
|
||||
/>
|
||||
)}
|
||||
{screenSize !== ScreenSize.Desktop && threadBrowserOpen && !openThreadId && (
|
||||
<ThreadBrowser
|
||||
key={`thread-browser-${room.roomId}`}
|
||||
room={room}
|
||||
onOpenThread={(id) => {
|
||||
setOpenThread(id);
|
||||
setThreadBrowserOpen(false);
|
||||
}}
|
||||
onClose={() => setThreadBrowserOpen(false)}
|
||||
overlay
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</RoomAbbreviationsContext.Provider>
|
||||
</PowerLevelsContextProvider>
|
||||
);
|
||||
}
|
||||
@@ -58,6 +58,8 @@ import { useImagePackRooms } from '$hooks/useImagePackRooms';
|
||||
import { settingsAtom, MessageLayout } from '$state/settings';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations';
|
||||
import { buildAbbrReplaceTextNode } from '$components/message/RenderBody';
|
||||
import { profilesCacheAtom } from '$state/userRoomProfile';
|
||||
import { roomToParentsAtom } from '$state/room/roomToParents';
|
||||
import { roomIdToReplyDraftAtomFamily } from '$state/room/roomInputDrafts';
|
||||
@@ -451,6 +453,8 @@ export function RoomTimeline({
|
||||
[mx, room.roomId, mentionClickHandler, nicknames]
|
||||
);
|
||||
|
||||
const abbrMap = useRoomAbbreviationsContext();
|
||||
|
||||
const htmlReactParserOptions = useMemo(
|
||||
() =>
|
||||
getReactCustomHtmlParser(mx, room.roomId, {
|
||||
@@ -460,6 +464,7 @@ export function RoomTimeline({
|
||||
handleMentionClick: mentionClickHandler,
|
||||
nicknames,
|
||||
autoplayEmojis,
|
||||
replaceTextNode: buildAbbrReplaceTextNode(abbrMap),
|
||||
}),
|
||||
[
|
||||
mx,
|
||||
@@ -470,6 +475,7 @@ export function RoomTimeline({
|
||||
nicknames,
|
||||
mediaAuthentication,
|
||||
spoilerClickHandler,
|
||||
abbrMap,
|
||||
]
|
||||
);
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { nicknamesAtom } from '$state/nicknames';
|
||||
import { MessageLayout, MessageSpacing, settingsAtom } from '$state/settings';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { useRoomAbbreviationsContext } from '$hooks/useRoomAbbreviations';
|
||||
import { buildAbbrReplaceTextNode } from '$components/message/RenderBody';
|
||||
import { createMentionElement, moveCursor, useEditor } from '$components/editor';
|
||||
import { useMentionClickHandler } from '$hooks/useMentionClickHandler';
|
||||
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
|
||||
@@ -394,6 +396,8 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
[mx, room, mentionClickHandler, nicknames]
|
||||
);
|
||||
|
||||
const abbrMap = useRoomAbbreviationsContext();
|
||||
|
||||
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
|
||||
() =>
|
||||
getReactCustomHtmlParser(mx, room.roomId, {
|
||||
@@ -402,8 +406,18 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
|
||||
handleSpoilerClick: spoilerClickHandler,
|
||||
handleMentionClick: mentionClickHandler,
|
||||
nicknames,
|
||||
replaceTextNode: buildAbbrReplaceTextNode(abbrMap),
|
||||
}),
|
||||
[mx, room, linkifyOpts, spoilerClickHandler, mentionClickHandler, useAuthentication, nicknames]
|
||||
[
|
||||
mx,
|
||||
room,
|
||||
linkifyOpts,
|
||||
spoilerClickHandler,
|
||||
mentionClickHandler,
|
||||
useAuthentication,
|
||||
nicknames,
|
||||
abbrMap,
|
||||
]
|
||||
);
|
||||
|
||||
// Power levels & permissions
|
||||
|
||||
@@ -16,6 +16,7 @@ import { EmojisStickers } from '$features/common-settings/emojis-stickers';
|
||||
import { Members } from '$features/common-settings/members';
|
||||
import { DeveloperTools } from '$features/common-settings/developer-tools';
|
||||
import { Cosmetics } from '$features/common-settings/cosmetics/Cosmetics';
|
||||
import { RoomAbbreviations } from '$features/room-settings/abbreviations/RoomAbbreviations';
|
||||
import { General } from './general';
|
||||
import { Permissions } from './permissions';
|
||||
|
||||
@@ -50,6 +51,11 @@ const useSpaceSettingsMenuItems = (): SpaceSettingsMenuItem[] =>
|
||||
icon: Icons.Alphabet,
|
||||
activeIcon: Icons.AlphabetUnderline,
|
||||
},
|
||||
{
|
||||
page: SpaceSettingsPage.AbbreviationsPage,
|
||||
name: 'Abbreviations',
|
||||
icon: Icons.Info,
|
||||
},
|
||||
{
|
||||
page: SpaceSettingsPage.EmojisStickersPage,
|
||||
name: 'Emojis & Stickers',
|
||||
@@ -187,6 +193,9 @@ export function SpaceSettings({ initialPage, requestClose }: SpaceSettingsProps)
|
||||
{activePage === SpaceSettingsPage.DeveloperToolsPage && (
|
||||
<DeveloperTools requestClose={handlePageRequestClose} />
|
||||
)}
|
||||
{activePage === SpaceSettingsPage.AbbreviationsPage && (
|
||||
<RoomAbbreviations isSpace requestClose={handlePageRequestClose} />
|
||||
)}
|
||||
</PageRoot>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { createContext, useContext, useCallback, useMemo } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { Room } from '$types/matrix-sdk';
|
||||
import { StateEvent } from '$types/matrix/room';
|
||||
import { buildAbbreviationsMap, RoomAbbreviationsContent } from '$utils/abbreviations';
|
||||
import { getAllParents, getStateEvent } from '$utils/room';
|
||||
import { roomToParentsAtom } from '$state/room/roomToParents';
|
||||
import { useMatrixClient } from './useMatrixClient';
|
||||
import { useStateEvent } from './useStateEvent';
|
||||
import { useStateEventCallback } from './useStateEventCallback';
|
||||
import { useForceUpdate } from './useForceUpdate';
|
||||
|
||||
const EMPTY_MAP: Map<string, string> = new Map();
|
||||
|
||||
export const RoomAbbreviationsContext = createContext<Map<string, string>>(EMPTY_MAP);
|
||||
|
||||
export const useRoomAbbreviationsContext = () => useContext(RoomAbbreviationsContext);
|
||||
|
||||
/** Read the room's abbreviations state event and return a term→definition map. */
|
||||
export const useRoomAbbreviations = (room: Room): Map<string, string> => {
|
||||
const stateEvent = useStateEvent(room, StateEvent.RoomAbbreviations);
|
||||
if (!stateEvent) return EMPTY_MAP;
|
||||
const content = stateEvent.getContent<RoomAbbreviationsContent>();
|
||||
if (!Array.isArray(content?.entries) || content.entries.length === 0) return EMPTY_MAP;
|
||||
return buildAbbreviationsMap(content.entries);
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a merged map of abbreviations from ALL ancestor spaces and the room.
|
||||
* Nearest ancestor entries override farther ancestor entries; room entries override everything.
|
||||
* Subscribes to abbreviation state changes across the full space hierarchy.
|
||||
*/
|
||||
export const useMergedAbbreviations = (room: Room): Map<string, string> => {
|
||||
const mx = useMatrixClient();
|
||||
const roomToParents = useAtomValue(roomToParentsAtom);
|
||||
const [updateCount, forceUpdate] = useForceUpdate();
|
||||
|
||||
useStateEventCallback(
|
||||
mx,
|
||||
useCallback(
|
||||
(event) => {
|
||||
if (event.getType() !== StateEvent.RoomAbbreviations) return;
|
||||
const eventRoomId = event.getRoomId();
|
||||
if (!eventRoomId) return;
|
||||
if (
|
||||
eventRoomId === room.roomId ||
|
||||
getAllParents(roomToParents, room.roomId).has(eventRoomId)
|
||||
) {
|
||||
forceUpdate();
|
||||
}
|
||||
},
|
||||
[room.roomId, roomToParents, forceUpdate]
|
||||
)
|
||||
);
|
||||
|
||||
return useMemo(() => {
|
||||
const allParentIds = Array.from(getAllParents(roomToParents, room.roomId));
|
||||
const ancestorEntries = allParentIds.flatMap((parentId) => {
|
||||
const parentRoom = mx.getRoom(parentId);
|
||||
if (!parentRoom) return [];
|
||||
const content = getStateEvent(
|
||||
parentRoom,
|
||||
StateEvent.RoomAbbreviations
|
||||
)?.getContent<RoomAbbreviationsContent>();
|
||||
return Array.isArray(content?.entries) ? content.entries : [];
|
||||
});
|
||||
|
||||
const roomContent = getStateEvent(
|
||||
room,
|
||||
StateEvent.RoomAbbreviations
|
||||
)?.getContent<RoomAbbreviationsContent>();
|
||||
const roomEntries = Array.isArray(roomContent?.entries) ? roomContent.entries : [];
|
||||
|
||||
if (ancestorEntries.length === 0 && roomEntries.length === 0) return EMPTY_MAP;
|
||||
// Ancestor entries first; room entries appended so they override duplicates.
|
||||
return buildAbbreviationsMap([...ancestorEntries, ...roomEntries]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [mx, roomToParents, room, updateCount]);
|
||||
};
|
||||
@@ -351,10 +351,15 @@ export const getReactCustomHtmlParser = (
|
||||
useAuthentication?: boolean;
|
||||
nicknames?: Nicknames;
|
||||
autoplayEmojis?: boolean;
|
||||
replaceTextNode?: (text: string) => JSX.Element | undefined;
|
||||
}
|
||||
): HTMLReactParserOptions => {
|
||||
const { replaceTextNode } = params;
|
||||
const opts: HTMLReactParserOptions = {
|
||||
replace: (domNode) => {
|
||||
if (replaceTextNode && domNode instanceof DOMText) {
|
||||
return replaceTextNode(domNode.data) ?? undefined;
|
||||
}
|
||||
if (domNode instanceof Element && 'name' in domNode) {
|
||||
const { name, attribs, children, parent } = domNode;
|
||||
const renderChildren = () => domToReact(children as any, opts);
|
||||
|
||||
@@ -8,6 +8,7 @@ export enum RoomSettingsPage {
|
||||
DeveloperToolsPage,
|
||||
// Sable pages
|
||||
CosmeticsPage,
|
||||
AbbreviationsPage,
|
||||
}
|
||||
|
||||
export type RoomSettingsState = {
|
||||
|
||||
@@ -8,6 +8,7 @@ export enum SpaceSettingsPage {
|
||||
DeveloperToolsPage,
|
||||
// Sable pages
|
||||
CosmeticsPage,
|
||||
AbbreviationsPage,
|
||||
}
|
||||
|
||||
export type SpaceSettingsState = {
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { buildAbbreviationsMap, splitByAbbreviations } from './abbreviations';
|
||||
|
||||
describe('buildAbbreviationsMap', () => {
|
||||
it('returns an empty map for empty entries', () => {
|
||||
expect(buildAbbreviationsMap([])).toEqual(new Map());
|
||||
});
|
||||
|
||||
it('stores the key as lowercase regardless of input casing', () => {
|
||||
const map = buildAbbreviationsMap([
|
||||
{ term: 'FOSS', definition: 'Free and Open Source Software' },
|
||||
]);
|
||||
expect(map.get('foss')).toBe('Free and Open Source Software');
|
||||
expect(map.get('FOSS')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('trims surrounding whitespace from terms', () => {
|
||||
const map = buildAbbreviationsMap([
|
||||
{ term: ' FOSS ', definition: 'Free and Open Source Software' },
|
||||
]);
|
||||
expect(map.get('foss')).toBe('Free and Open Source Software');
|
||||
expect(map.size).toBe(1);
|
||||
});
|
||||
|
||||
it('skips empty and whitespace-only terms', () => {
|
||||
const map = buildAbbreviationsMap([
|
||||
{ term: '', definition: 'ignored' },
|
||||
{ term: ' ', definition: 'also ignored' },
|
||||
]);
|
||||
expect(map.size).toBe(0);
|
||||
});
|
||||
|
||||
it('deduplicates different-cased variants of the same term (last entry wins)', () => {
|
||||
const map = buildAbbreviationsMap([
|
||||
{ term: 'OSS', definition: 'Open Source Software' },
|
||||
{ term: 'oss', definition: 'open source software' },
|
||||
]);
|
||||
expect(map.size).toBe(1);
|
||||
expect(map.get('oss')).toBe('open source software');
|
||||
});
|
||||
|
||||
it('stores multiple distinct entries', () => {
|
||||
const map = buildAbbreviationsMap([
|
||||
{ term: 'FOSS', definition: 'Free and Open Source Software' },
|
||||
{ term: 'RTFM', definition: 'Read The Fine Manual' },
|
||||
]);
|
||||
expect(map.size).toBe(2);
|
||||
expect(map.get('foss')).toBe('Free and Open Source Software');
|
||||
expect(map.get('rtfm')).toBe('Read The Fine Manual');
|
||||
});
|
||||
});
|
||||
|
||||
describe('splitByAbbreviations', () => {
|
||||
const map = buildAbbreviationsMap([
|
||||
{ term: 'FOSS', definition: 'Free and Open Source Software' },
|
||||
{ term: 'RTFM', definition: 'Read The Fine Manual' },
|
||||
{ term: 'OSS', definition: 'Open Source Software' },
|
||||
]);
|
||||
|
||||
it('returns a single plain segment when the map is empty', () => {
|
||||
expect(splitByAbbreviations('hello FOSS world', new Map())).toEqual([
|
||||
{ id: 'txt-0', text: 'hello FOSS world' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns a single plain segment when there are no matches', () => {
|
||||
expect(splitByAbbreviations('hello world', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'hello world' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns a single plain segment for an empty string', () => {
|
||||
expect(splitByAbbreviations('', map)).toEqual([{ id: 'txt-0', text: '' }]);
|
||||
});
|
||||
|
||||
it('splits a term match in the middle of a string', () => {
|
||||
expect(splitByAbbreviations('Use FOSS software', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'Use ' },
|
||||
{ id: 'txt-1', text: 'FOSS', termKey: 'foss' },
|
||||
{ id: 'txt-2', text: ' software' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('splits a term match at the start of a string', () => {
|
||||
expect(splitByAbbreviations('FOSS is great', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'FOSS', termKey: 'foss' },
|
||||
{ id: 'txt-1', text: ' is great' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('splits a term match at the end of a string', () => {
|
||||
expect(splitByAbbreviations('I love FOSS', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'I love ' },
|
||||
{ id: 'txt-1', text: 'FOSS', termKey: 'foss' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('handles multiple terms in the same string', () => {
|
||||
expect(splitByAbbreviations('FOSS and RTFM', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'FOSS', termKey: 'foss' },
|
||||
{ id: 'txt-1', text: ' and ' },
|
||||
{ id: 'txt-2', text: 'RTFM', termKey: 'rtfm' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches case-insensitively (termKey is always lowercase)', () => {
|
||||
expect(splitByAbbreviations('I like foss and Foss', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'I like ' },
|
||||
{ id: 'txt-1', text: 'foss', termKey: 'foss' },
|
||||
{ id: 'txt-2', text: ' and ' },
|
||||
{ id: 'txt-3', text: 'Foss', termKey: 'foss' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not match a term that is a prefix of a longer word (word boundary)', () => {
|
||||
// OSS is in the map, but should not match inside FOSS because the F provides no boundary
|
||||
const ossOnlyMap = buildAbbreviationsMap([{ term: 'OSS', definition: 'Open Source Software' }]);
|
||||
expect(splitByAbbreviations('FOSS rocks', ossOnlyMap)).toEqual([
|
||||
{ id: 'txt-0', text: 'FOSS rocks' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not match a term embedded inside a longer word', () => {
|
||||
// OSS should not match inside CROSS or GLOSS
|
||||
const ossOnlyMap = buildAbbreviationsMap([{ term: 'OSS', definition: 'Open Source Software' }]);
|
||||
expect(splitByAbbreviations('CROSS the GLOSS', ossOnlyMap)).toEqual([
|
||||
{ id: 'txt-0', text: 'CROSS the GLOSS' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('matches a shorter term standalone when the longer overlapping term is also defined', () => {
|
||||
// OSS is a suffix of FOSS; when standalone it should still match
|
||||
expect(splitByAbbreviations('OSS is related to FOSS', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'OSS', termKey: 'oss' },
|
||||
{ id: 'txt-1', text: ' is related to ' },
|
||||
{ id: 'txt-2', text: 'FOSS', termKey: 'foss' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('prefers the longer term when a shorter one is a suffix of it', () => {
|
||||
// FOSS contains OSS; FOSS should win and OSS should not be matched separately
|
||||
expect(splitByAbbreviations('Use FOSS today', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'Use ' },
|
||||
{ id: 'txt-1', text: 'FOSS', termKey: 'foss' },
|
||||
{ id: 'txt-2', text: ' today' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('preserves plain text between two consecutive matches', () => {
|
||||
expect(splitByAbbreviations('FOSS, RTFM, OSS', map)).toEqual([
|
||||
{ id: 'txt-0', text: 'FOSS', termKey: 'foss' },
|
||||
{ id: 'txt-1', text: ', ' },
|
||||
{ id: 'txt-2', text: 'RTFM', termKey: 'rtfm' },
|
||||
{ id: 'txt-3', text: ', ' },
|
||||
{ id: 'txt-4', text: 'OSS', termKey: 'oss' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
export type AbbreviationEntry = {
|
||||
term: string;
|
||||
definition: string;
|
||||
};
|
||||
|
||||
export type RoomAbbreviationsContent = {
|
||||
entries: AbbreviationEntry[];
|
||||
};
|
||||
|
||||
/** Build a map of lowercase term → definition for O(1) lookup. */
|
||||
export const buildAbbreviationsMap = (entries: AbbreviationEntry[]): Map<string, string> => {
|
||||
const map = new Map<string, string>();
|
||||
entries.forEach(({ term, definition }) => {
|
||||
const t = term.trim();
|
||||
if (t) map.set(t.toLowerCase(), definition);
|
||||
});
|
||||
return map;
|
||||
};
|
||||
|
||||
/**
|
||||
* Split a plain-text string into alternating [plain, term, plain, term, …] segments.
|
||||
* Matched terms preserve their original casing from the source string.
|
||||
* Matching is whole-word and case-insensitive.
|
||||
*
|
||||
* Returns an array of `{ text, termKey }` objects where `termKey` is undefined for
|
||||
* plain segments and is the lowercase lookup key for abbreviation segments.
|
||||
*/
|
||||
export type TextSegment = {
|
||||
id: string;
|
||||
text: string;
|
||||
/** Undefined for plain text; the lowercase map key for an abbreviation. */
|
||||
termKey?: string;
|
||||
};
|
||||
|
||||
export const splitByAbbreviations = (text: string, abbrMap: Map<string, string>): TextSegment[] => {
|
||||
if (abbrMap.size === 0) return [{ id: 'txt-0', text }];
|
||||
|
||||
// Build a regex that matches any of the terms at word boundaries.
|
||||
// Sort longest first so "HTTP/2" matches before "HTTP".
|
||||
const terms = [...abbrMap.keys()].sort((a, b) => b.length - a.length);
|
||||
const escaped = terms.map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
|
||||
const pattern = new RegExp(`\\b(${escaped.join('|')})\\b`, 'gi');
|
||||
|
||||
const segments: TextSegment[] = [];
|
||||
let lastIndex = 0;
|
||||
|
||||
Array.from(text.matchAll(pattern)).forEach((match) => {
|
||||
const matchIndex = match.index;
|
||||
if (matchIndex > lastIndex) {
|
||||
segments.push({ id: `txt-${segments.length}`, text: text.slice(lastIndex, matchIndex) });
|
||||
}
|
||||
segments.push({
|
||||
id: `txt-${segments.length}`,
|
||||
text: match[0],
|
||||
termKey: match[0].toLowerCase(),
|
||||
});
|
||||
lastIndex = matchIndex + match[0].length;
|
||||
});
|
||||
|
||||
if (lastIndex < text.length) {
|
||||
segments.push({ id: `txt-${segments.length}`, text: text.slice(lastIndex) });
|
||||
}
|
||||
|
||||
return segments.length > 0 ? segments : [{ id: 'txt-0', text }];
|
||||
};
|
||||
@@ -123,6 +123,7 @@ const buildListRequiredState = (): MSC3575RoomSubscription['required_state'] =>
|
||||
[EventType.RoomMember, MSC3575_STATE_KEY_ME],
|
||||
['m.space.child', MSC3575_WILDCARD],
|
||||
['im.ponies.room_emotes', MSC3575_WILDCARD],
|
||||
['moe.sable.room.abbreviations', ''],
|
||||
];
|
||||
|
||||
// For an active encrypted room: fetch everything so the client can decrypt all events.
|
||||
|
||||
@@ -49,6 +49,7 @@ export enum StateEvent {
|
||||
RoomCosmeticsColor = 'moe.sable.room.cosmetics.color',
|
||||
RoomCosmeticsFont = 'moe.sable.room.cosmetics.font',
|
||||
RoomCosmeticsPronouns = 'moe.sable.room.cosmetics.pronouns',
|
||||
RoomAbbreviations = 'moe.sable.room.abbreviations',
|
||||
}
|
||||
|
||||
export enum MessageEvent {
|
||||
|
||||
Reference in new issue
Block a user