Merge pull request #154 from dozro/feat-honor-language-of-pronouns

Add option to filter user pronouns based on the pronouns language
This commit is contained in:
7w1 authored and GitHub committed 2026-03-05 15:10:59 -06:00
commit 82a079a985
9 files changed
+222 -25

No files matched your search

@@ -0,0 +1,5 @@
---
sable: minor
---
Add option to filter user pronouns based on the pronouns language
@@ -31,6 +31,8 @@ import {
} from '$plugins/react-custom-html-parser';
import { useSpoilerClickHandler } from '$hooks/useSpoilerClickHandler';
import { RenderBody } from '$components/message';
import { getSettings } from '$state/settings';
import { filterPronounsByLanguage } from '$utils/pronouns';
import { CreatorChip } from './CreatorChip';
import { UserInviteAlert, UserBanAlert, UserModeration, UserKickAlert } from './UserModeration';
import { PowerChip } from './PowerChip';
@@ -74,7 +76,16 @@ function UserExtendedSection({
return String(val);
};
const pronouns = profile.pronouns?.map((p: any) => clamp(p.summary, 16)).join(', ');
const languageFilterEnabled = getSettings().filterPronounsBasedOnLanguage ?? false;
const languagesToFilterFor = getSettings().filterPronounsLanguages ?? ['en'];
const pronouns = filterPronounsByLanguage(
profile.pronouns!,
languageFilterEnabled,
languagesToFilterFor
)
.map((p) => p.summary)
.join(', ');
const localTime = useMemo(() => {
if (!profile.timezone) return null;
+21 -3
View File
@@ -50,7 +50,7 @@ import {
} from '$components/message';
import { canEditEvent, getMemberAvatarMxc } from '$utils/room';
import { mxcUrlToHttp } from '$utils/matrix';
import { MessageLayout, MessageSpacing, settingsAtom } from '$state/settings';
import { getSettings, MessageLayout, MessageSpacing, settingsAtom } from '$state/settings';
import { nicknamesAtom, setNicknameAtom } from '$state/nicknames';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useRecentEmoji } from '$hooks/useRecentEmoji';
@@ -76,6 +76,7 @@ import { MessageReadReceiptItem } from '$components/message/modals/MessageReadRe
import { MessageSourceCodeItem } from '$components/message/modals/MessageSource';
import { MessageDeleteItem } from '$components/message/modals/MessageDelete';
import { MessageReportItem } from '$components/message/modals/MessageReport';
import { filterPronounsByLanguage } from '$utils/pronouns';
import { MessageEditor } from './MessageEditor';
import * as css from './styles.css';
@@ -261,17 +262,34 @@ const Pronouns = as<
>(({ as: AsPronouns = 'span', pronouns, tagColor, ...props }, ref) => {
if (!pronouns || pronouns.length === 0) return null;
const languageFilterEnabled = Boolean(getSettings().filterPronounsBasedOnLanguage ?? false);
// if no language is given use english
const selectedLanguages = (getSettings().filterPronounsLanguages ?? ['en'])
.map((lang) => lang.trim().toLowerCase())
.filter(Boolean);
const visiblePronouns = filterPronounsByLanguage(
pronouns,
languageFilterEnabled,
selectedLanguages
);
const clamp = (str: string, len: number) => (str.length > len ? `${str.slice(0, len)}...` : str);
const limit = mobileOrTablet() ? 1 : 3;
// if language specific pronouns can't be found matching the filter return unfiltered
if (visiblePronouns.length === 0) {
visiblePronouns.push(...pronouns);
}
return (
<AsPronouns {...props} ref={ref}>
{pronouns.slice(0, limit).map((p) => (
{visiblePronouns.slice(0, limit).map((p) => (
<PronounPill key={p.summary} style={{ color: tagColor }}>
{clamp(p.summary, 16)}
</PronounPill>
))}
{pronouns.length > limit && <PronounPill style={{ color: tagColor }}>...</PronounPill>}
{visiblePronouns.length > limit && <PronounPill style={{ color: tagColor }}>...</PronounPill>}
</AsPronouns>
);
});
@@ -1,6 +1,7 @@
import { useState, useEffect, ChangeEvent } from 'react';
import { Input } from 'folds';
import { SettingTile } from '$components/setting-tile';
import { parsePronounsInput } from '$utils/pronouns';
type PronounSet = {
summary: string;
@@ -14,7 +15,9 @@ type PronounEditorProps = {
};
export function PronounEditor({ current, onSave }: PronounEditorProps) {
const initialString = current.map((p) => p.summary).join(', ');
const initialString = current
.map((p) => `${p.language ? `${p.language}:` : ''}${p.summary}`)
.join(', ');
const [val, setVal] = useState(initialString);
useEffect(() => setVal(initialString), [initialString]);
@@ -22,11 +25,7 @@ export function PronounEditor({ current, onSave }: PronounEditorProps) {
const handleSave = () => {
if (val === initialString) return;
const safeVal = val.slice(0, 128);
const next = safeVal
.split(',')
.map((s) => s.trim())
.filter(Boolean)
.map((s) => ({ summary: s.slice(0, 16), language: 'en' }));
const next = parsePronounsInput(safeVal);
onSave(next);
};
@@ -37,7 +36,9 @@ export function PronounEditor({ current, onSave }: PronounEditorProps) {
return (
<SettingTile
title="Pronouns"
description="Separate sets with commas (e.g. 'they/them, it/its')."
// let people specify multiple sets of pronouns for different languages
// the input is a comma separated list of pronoun sets, each set can have an optional language tag (e.g. "en:they/them, de:sie/ihr")
description="Separate sets with commas (e.g. 'en:they/them, en:it/its, de:sie/ihr')."
after={
<Input
value={val}
@@ -0,0 +1,112 @@
import { Box, Input, Switch, Text } from 'folds';
import { SettingTile } from '$components/setting-tile';
import { SequenceCard } from '$components/sequence-card';
import { useEffect, useState } from 'react';
import { getSettings, setSettings } from '$state/settings';
import { SequenceCardStyle } from '../styles.css';
export type LanguageSpecificPronounsConfig = {
enabled?: boolean | string;
languages?: string[];
};
export const resolveLanguageSpecificPronounsEnabled = (
enabled: LanguageSpecificPronounsConfig['enabled']
): boolean => {
if (enabled === undefined) return false;
if (typeof enabled === 'boolean') return enabled;
const normalized = String(enabled).trim().toLowerCase();
if (normalized === 'false' || normalized === '0' || normalized === 'off' || normalized === 'no')
return false;
if (normalized === 'true' || normalized === '1' || normalized === 'on' || normalized === 'yes')
return true;
return false;
};
// utility function to split a comma separated list of languages and trim whitespace
function splitAndTrimLanguages(languages: string): string[] {
return languages
.split(',')
.map((lang) => lang.trim())
.filter((lang) => lang.length > 0);
}
// MSC4247 allows users to set pronouns in different languages
export function LanguageSpecificPronouns() {
const [useLanguageSpecificPronouns, setEnabled] = useState(false);
const [languageList, setLanguageList] = useState('');
// common handler for saving changes to the language specific pronouns settings
const handleSave = (enabled: boolean, languages: string) => {
const currentSettings = getSettings();
setSettings({
...currentSettings,
filterPronounsBasedOnLanguage: enabled,
filterPronounsLanguages: splitAndTrimLanguages(languages),
});
};
// handler for when the language list input changes
const handleLanguageListChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val = e.target.value.trim();
setLanguageList(val);
// save the new language list to the client config, keeping the enabled state unchanged
handleSave(getSettings().filterPronounsBasedOnLanguage ?? false, val);
};
useEffect(() => {
setEnabled(
resolveLanguageSpecificPronounsEnabled(getSettings().filterPronounsBasedOnLanguage ?? false)
);
setLanguageList(getSettings().filterPronounsLanguages?.join(',') || '');
}, []);
// handler for toggling the enabled state of language specific pronouns
const handleSetEnabled = (enabled: boolean) => {
handleSave(enabled, getSettings().filterPronounsLanguages?.join(',') || '');
setEnabled(enabled);
};
return (
<Box direction="Column" gap="100">
<Text size="L400">Language Specific Pronouns</Text>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
direction="Column"
gap="100"
>
<SettingTile
title="Show pronouns only in selected language"
description="If enabled, pronouns are only shown when they match your selected language. This helps if your contacts set pronouns in different languages. It doesn't affect how your pronouns are shared with others."
after={
<Switch
variant="Primary"
value={useLanguageSpecificPronouns}
onChange={handleSetEnabled}
/>
}
/>
{useLanguageSpecificPronouns && (
<SettingTile
title="Selected language for pronouns"
description="The language to show pronouns for when the above setting is enabled."
after={
<Input
value={languageList}
size="300"
radii="300"
variant="Secondary"
// input should be a comma separated list of language codes, e.g. "en", "de", "en,de"
placeholder="Language code (e.g. 'en', 'de', 'en,de')"
disabled={!useLanguageSpecificPronouns}
onChange={handleLanguageListChange}
style={{ width: '232px' }}
/>
}
/>
)}
</SequenceCard>
</Box>
);
}
@@ -1,6 +1,7 @@
import { Box, Text, IconButton, Icon, Icons, Scroll } from 'folds';
import { Page, PageContent, PageHeader } from '$components/page';
import { InfoCard } from '$components/info-card';
import { LanguageSpecificPronouns } from '../cosmetics/LanguageSpecificPronouns';
import { Sync } from '../general';
type ExperimentalProps = {
@@ -42,6 +43,9 @@ export function Experimental({ requestClose }: ExperimentalProps) {
<Box direction="Column" gap="700">
<Sync />
</Box>
<Box direction="Column" gap="700">
<LanguageSpecificPronouns />
</Box>
</PageContent>
</Scroll>
</Box>
+17 -14
View File
@@ -30,6 +30,7 @@ import { splitWithSpace } from '$utils/common';
import { useSetting } from '$state/hooks/settings';
import { settingsAtom } from '$state/settings';
import { createRoomEncryptionState } from '$components/create-room';
import { parsePronounsInput } from '$utils/pronouns';
import { useRoomNavigate } from './useRoomNavigate';
import { enrichWidgetUrl } from './useRoomWidgets';
@@ -888,7 +889,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
[Command.Pronoun]: {
name: Command.Pronoun,
description:
'Set your pronouns for this room. Example: /pronoun "they/them, it/its" | /pronoun reset',
'Set your pronouns for this room. Example: /pronoun "en:they/them, de:sie/ihr" | /pronoun reset',
exe: async (payload) => {
const match = payload.trim().match(/^"(.*)"$/);
const rawInput = match ? match[1].trim() : payload.trim();
@@ -917,11 +918,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
return;
}
const pronounsArray = rawInput
.split(',')
.map((p) => p.trim())
.filter((p) => p.length > 0)
.map((p) => ({ summary: p }));
const pronounsArray = parsePronounsInput(rawInput);
await mx.sendStateEvent(
room.roomId,
@@ -929,7 +926,12 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
{ pronouns: pronounsArray },
userId
);
sendFeedback(`Room pronouns set: ${rawInput}`);
const feedbackString = pronounsArray
.map((p) => (p.language ? `for ${p.language} "${p.summary}" was set` : p.summary))
.join(', ');
sendFeedback(`Room pronouns set: ${feedbackString}`);
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback('Permission Denied. Could not update room pronouns.');
@@ -940,7 +942,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
[Command.GPronoun]: {
name: Command.GPronoun,
description:
'Set your global pronouns for this space. Example: /gpronoun "they/them, it/its" | /gpronoun reset',
'Set your global pronouns for this space. Example: /gpronoun "en:they/them, de:sie/ihr" | /gpronoun reset',
exe: async (payload) => {
const match = payload.trim().match(/^"(.*)"$/);
const rawInput = match ? match[1].trim() : payload.trim();
@@ -977,11 +979,7 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
return;
}
const pronounsArray = rawInput
.split(',')
.map((p) => p.trim())
.filter((p) => p.length > 0)
.map((p) => ({ summary: p }));
const pronounsArray = parsePronounsInput(rawInput);
await mx.sendStateEvent(
targetSpaceId as any,
@@ -989,7 +987,12 @@ export const useCommands = (mx: MatrixClient, room: Room): CommandRecord => {
{ pronouns: pronounsArray },
userId
);
sendFeedback(`Global space pronouns set: ${rawInput}`);
const feedbackString = pronounsArray
.map((p) => (p.language ? `for ${p.language} "${p.summary}" was set` : p.summary))
.join(', ');
sendFeedback(`Global space pronouns set: ${feedbackString}`);
} catch (e: any) {
if (e.errcode === 'M_FORBIDDEN') {
sendFeedback('Permission Denied. Could not update space pronouns.');
+2
View File
@@ -61,6 +61,8 @@ export interface Settings {
privacyBlurEmotes: boolean;
showPronouns: boolean;
renderGlobalNameColors: boolean;
filterPronounsBasedOnLanguage?: boolean;
filterPronounsLanguages?: string[];
renderRoomColors: boolean;
renderRoomFonts: boolean;
+41
View File
@@ -0,0 +1,41 @@
// helper function to convert a comma-separated pronouns string into an array of objects with summary and optional language
export function parsePronounsInput(pronouns: string): { summary: string; language?: string }[] {
return pronouns
.split(',')
.map((s) => s.trim())
.filter(Boolean)
.map((s) => {
const parts = s.split(':');
if (parts.length === 1) {
return {
summary: parts[0].slice(0, 16),
language: 'en',
};
}
const [language, summary] = parts;
return {
language: language || 'en',
summary: summary.slice(0, 16),
};
});
}
// helper function to filter a list of pronouns based on the user's language settings
export function filterPronounsByLanguage(
pronouns: { summary: string; language?: string }[],
enabled: boolean,
languages: string[]
): { summary: string; language?: string }[] {
if (!enabled) return pronouns;
const normalizedLanguages = languages.map((lang) => lang.trim().toLowerCase());
const filteredPronouns = pronouns.filter((p) =>
normalizedLanguages.includes((p.language || 'en').trim().toLowerCase())
);
if (filteredPronouns.length === 0) {
return pronouns;
}
return filteredPronouns;
}