update to unstable key

Signed-off-by: Shea <[email protected]>
This commit is contained in:
Shea committed 2026-07-31 09:01:54 +03:00
commit 05f2ce4291
18 files changed
+351 -154

No files matched your search

@@ -37,9 +37,11 @@ import { useCapabilities } from '$hooks/useCapabilities';
import { NameColorEditor } from '$features/settings/account/NameColorEditor';
import { PronounEditor } from '$features/settings/account/PronounEditor';
import type { PronounSet } from '$utils/pronouns';
import { EventType } from '$types/matrix-sdk';
import { EventTimeline, EventType } from '$types/matrix-sdk';
import { CustomStateEvent } from '$types/matrix/room';
import { AvatarUploadTile } from '$components/avatar-upload-tile/AvatarUploadTile';
import type { CustomRoomMemberEventContent } from '$unstable/CustomRoomMemberEventContent';
import * as prefix from '$unstable/prefixes';
const log = createLogger('Cosmetics');
@@ -250,6 +252,20 @@ export function Cosmetics({ requestBack, requestClose }: CosmeticsProps) {
const powerLevels = usePowerLevels(room);
const isSpace = room.isSpaceRoom();
const mEvent = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(EventType.RoomMember, mx.getSafeUserId());
const oldColorState = room.getLiveTimeline().getState(EventTimeline.FORWARDS);
const oldColorEvent = oldColorState?.getStateEvents(CustomStateEvent.RoomCosmeticsColor, userId);
const localColorOld = (
Array.isArray(oldColorEvent) ? oldColorEvent[0] : oldColorEvent
)?.getContent()?.color;
const content = mEvent?.getContent<CustomRoomMemberEventContent>();
const colorOnDark = content?.[prefix.MATRIX_UNSTABLE_COLORS]?.on_dark ?? localColorOld;
const colorOnLight = content?.[prefix.MATRIX_UNSTABLE_COLORS]?.on_light ?? localColorOld;
const permissions = useRoomPermissions(creators, powerLevels);
const canEditPermissions = permissions.stateEvent(EventType.RoomPowerLevels, mx.getSafeUserId());
@@ -257,7 +273,6 @@ export function Cosmetics({ requestBack, requestClose }: CosmeticsProps) {
const getLevel = (eventType: string) => (powerLevels.events ?? {})?.[eventType] ?? 50;
const canHaveRoomColor = getLevel(CustomStateEvent.RoomCosmeticsColor) === 0;
const canHaveRoomPronouns = getLevel(CustomStateEvent.RoomCosmeticsPronouns) === 0;
const canHaveRoomFont = getLevel(CustomStateEvent.RoomCosmeticsFont) === 0;
@@ -331,11 +346,27 @@ export function Cosmetics({ requestBack, requestClose }: CosmeticsProps) {
gap="400"
>
<NameColorEditor
title={isSpace ? 'Space Name Color' : 'Room Name Color'}
current={roomProfile.resolvedColor}
disabled={!(canHaveRoomColor || canEditPermissions)}
title={
isSpace
? 'Space Dark theme Global Name Color'
: 'Room Dark theme Global Name Color'
}
current={colorOnDark}
description="Your name's color for a dark theme user."
onSave={(color) =>
commands[isSpace ? Command.SColor : Command.Color].exe(color ?? 'clear')
commands[isSpace ? Command.SColor : Command.Color].exe(
color ? `dark ${color}` : 'dark reset'
)
}
/>
<NameColorEditor
title={isSpace ? 'Space Light theme Name Color' : 'Room Light theme Name Color'}
current={colorOnLight}
description="Your name's color for a light theme user."
onSave={(color) =>
commands[isSpace ? Command.SColor : Command.Color].exe(
color ? `light ${color}` : 'light reset'
)
}
/>
</SequenceCard>
@@ -381,22 +412,7 @@ export function Cosmetics({ requestBack, requestClose }: CosmeticsProps) {
variant="SurfaceVariant"
direction="Column"
gap="400"
>
<SettingTile
title={isSpace ? 'Space-Wide Colors' : 'Room Colors'}
description={`Allow everyone to set a color that applies in ${isSpace ? "all the space's rooms" : 'this room'}.`}
after={
<Switch
variant="Primary"
value={canHaveRoomColor}
onChange={(enabled) =>
handleToggle(CustomStateEvent.RoomCosmeticsColor, enabled)
}
disabled={!canEditPermissions}
/>
}
/>
</SequenceCard>
></SequenceCard>
<SequenceCard
className={SequenceCardStyle}
variant="SurfaceVariant"
+2 -2
View File
@@ -456,8 +456,8 @@ function MessageInternal(
const pmpNameColor = useMemo(() => {
if (!renderPersonaColors) return undefined;
const pmpNameColorLight = parsedPMPContent?.nameColorLightTheme;
const pmpNameColorDark = parsedPMPContent?.nameColorDarkTheme;
const pmpNameColorLight = parsedPMPContent?.colors?.on_light;
const pmpNameColorDark = parsedPMPContent?.colors?.on_dark;
return activeTheme.kind === ThemeKind.Dark ? pmpNameColorDark : pmpNameColorLight;
}, [parsedPMPContent, activeTheme, renderPersonaColors]);
@@ -79,9 +79,7 @@ export function PersonaPicker({
const nameColor = useCallback(
(persona: PerMessageProfile) =>
activeTheme.kind === ThemeKind.Dark
? persona.nameColorDarkTheme
: persona.nameColorLightTheme,
activeTheme.kind === ThemeKind.Dark ? persona.colors?.on_dark : persona.colors?.on_light,
[activeTheme]
);
@@ -115,6 +113,7 @@ export function PersonaPicker({
const fetchProfiles = async (mx_: MatrixClient) => {
const fetchedProfiles = await getAllPerMessageProfiles(mx_);
setProfiles(fetchedProfiles);
console.log(fetchedProfiles);
setFilteredProfiles(fetchedProfiles);
};
@@ -266,7 +265,7 @@ export function PersonaPicker({
<UserAvatar
userId={profile.id}
src={avatarUrl(profile)}
fallbackColor={profile.nameColorLightTheme ?? undefined}
fallbackColor={profile.colors?.on_light ?? undefined}
renderFallback={() => (
<Text as="span" size="H4" aria-label="Avatar fallback">
{nameInitials(profile.name)}
@@ -450,8 +450,10 @@ export function PerMessageProfileEditor({
name: newDisplayName,
avatarUrl: avatarMxc,
pronouns: newPronouns,
nameColorLightTheme: newNameColorLight ?? undefined,
nameColorDarkTheme: newNameColorDark ?? undefined,
colors: {
on_light: newNameColorLight ?? undefined,
on_dark: newNameColorDark ?? undefined,
},
});
setCurrentDisplayName(newDisplayName);
@@ -96,8 +96,8 @@ export function PerMessageProfileOverview({
avatarMxcUrl={profile.avatarUrl}
displayName={profile.name}
pronouns={profile.pronouns}
nameColorLight={profile.nameColorLightTheme}
nameColorDark={profile.nameColorDarkTheme}
nameColorLight={profile.colors?.on_light}
nameColorDark={profile.colors?.on_dark}
onOpenEditor={handleEdit}
/>
</SequenceCard>
@@ -29,8 +29,8 @@ export function PerMessageProfilePage({ requestBack, requestClose }: PerMessageP
avatarMxcUrl={editingProfile.avatarUrl}
displayName={editingProfile.name}
pronouns={editingProfile.pronouns}
nameColorLightTheme={editingProfile.nameColorLightTheme}
nameColorDarkTheme={editingProfile.nameColorDarkTheme}
nameColorLightTheme={editingProfile.colors?.on_light}
nameColorDarkTheme={editingProfile.colors?.on_dark}
requestClose={handleEditorClose}
/>
);
@@ -4,6 +4,7 @@ import { menuIcon, X } from '$components/icons/phosphor';
import { HexColorPicker } from 'react-colorful';
import { SettingTile } from '$components/setting-tile';
import { HexColorPickerPopOut } from '$components/HexColorPickerPopOut';
import { isValidHex } from '$hooks/useUserProfile';
type NameColorEditorProps = {
title: string;
@@ -20,7 +21,6 @@ const stripQuotes = (str?: string) => {
// to solve the silly tuwunel
return str.replaceAll(/^["']|["']$/g, '');
};
const colorPattern = /^#[0-9A-F]{6}$/i;
export function NameColorEditor({
title,
@@ -44,9 +44,10 @@ export function NameColorEditor({
// It's disruptive to the user to immediately present their input as an error.
// We should only present an error if they fail the regex test :)
// (Also this change makes the fallback "undefined" instead of #fff so this is required)
// oxlint-disable-next-line unicorn/consistent-function-scoping
const validInput = (testColor: string | undefined) => {
if (!testColor) return true;
return colorPattern.test(testColor);
return isValidHex(testColor);
};
const handleUpdate = (newColor: string) => {
@@ -58,7 +59,7 @@ export function NameColorEditor({
};
const handleSave = () => {
if (!!onSave && !!tempColor && colorPattern.test(tempColor)) {
if (!!onSave && !!tempColor && isValidHex(tempColor)) {
onSave(tempColor);
setHasChanged(false);
}
@@ -72,7 +73,7 @@ export function NameColorEditor({
};
useEffect(() => {
const validColor = tempColor !== undefined && colorPattern.test(tempColor);
const validColor = tempColor !== undefined && isValidHex(tempColor);
if (onChange) onChange(validColor ? tempColor : null);
}, [onChange, tempColor]);
@@ -100,7 +101,7 @@ export function NameColorEditor({
size="300"
radii="Pill"
onClick={handleSave}
disabled={!tempColor || !colorPattern.test(tempColor)}
disabled={!tempColor || !isValidHex(tempColor)}
>
<Text size="B300">Save</Text>
</Button>
+31 -29
View File
@@ -8,7 +8,7 @@ import type { SettingMenuOption } from '$components/setting-menu-selector';
import { SettingMenuSelector } from '$components/setting-menu-selector';
import { SettingTile } from '$components/setting-tile';
import { useMatrixClient } from '$hooks/useMatrixClient';
import type { UserProfile, MSC4440Bio } from '$hooks/useUserProfile';
import type { UserProfile, MSC4440Bio, ColorSet } from '$hooks/useUserProfile';
import { useUserProfile } from '$hooks/useUserProfile';
import { getMxIdLocalPart, mxcUrlToHttp } from '$utils/matrix';
import { UserAvatar } from '$components/user-avatar';
@@ -393,6 +393,7 @@ function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
const EXCLUDED_KEYS = new Set([
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME,
prefix.MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_HAS_CAT_PROPERTY_NAME,
prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME,
]);
// Unknown fields / unimplemented non-matrix-spec fields
@@ -425,6 +426,25 @@ function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
[mx, presence]
);
const color_on_dark =
profile.nameColors?.on_dark ??
(profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined)?.on_dark;
const color_on_light =
profile.nameColors?.on_light ??
(profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined)?.on_light;
// Deletes the depricated key, the color specific ones should be depricated too at a later date
if (profile.nameColor || (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as string)) {
const fallback =
profile.nameColor ?? (profile.extended?.[prefix.MATRIX_UNSTABLE_COLORS] as string);
if (!color_on_light || !color_on_dark)
handleSaveField(prefix.MATRIX_UNSTABLE_COLORS, {
on_dark: color_on_dark ?? fallback,
on_light: color_on_light ?? fallback,
});
handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME, null);
}
return (
<Box direction="Column" gap="100">
<Text size="L400">Extended Profile</Text>
@@ -442,46 +462,28 @@ function ProfileExtended({ profile, userId }: Readonly<ProfileProps>) {
direction="Column"
gap="400"
>
<NameColorEditor
title="General Global Name Color"
description="Custom name color everywhere names have color!"
focusId="name-color"
current={
profile.nameColor ||
(profile.extended?.[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME] as
| string
| undefined)
}
onSave={(color) =>
handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME, color)
}
/>
<NameColorEditor
title="Dark theme Global Name Color"
description="Your name's color for a dark theme user."
focusId="name-color-dark-theme"
current={
profile.nameColorDark ||
(profile.extended?.[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME] as
| string
| undefined)
}
current={color_on_dark}
onSave={(color) =>
handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME, color)
handleSaveField(prefix.MATRIX_UNSTABLE_COLORS, {
on_dark: color,
on_light: color_on_light,
})
}
/>
<NameColorEditor
title="Light theme Global Name Color"
description="Your name's color for a light theme user."
focusId="name-color-light-theme"
current={
profile.nameColorLight ||
(profile.extended?.[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME] as
| string
| undefined)
}
current={color_on_light}
onSave={(color) =>
handleSaveField(prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME, color)
handleSaveField(prefix.MATRIX_UNSTABLE_COLORS, {
on_dark: color_on_dark,
on_light: color,
})
}
/>
</SequenceCard>
+129 -55
View File
@@ -1,4 +1,3 @@
import type { RoomMemberEventContent } from '$types/matrix-sdk';
import { EventTimeline, EventType, MatrixError } from '$types/matrix-sdk';
import { setOwnRoomMemberProfile } from '$utils/roomMemberProfile';
import { parsePronounsInput } from '$utils/pronouns';
@@ -7,6 +6,9 @@ import { CustomStateEvent } from '$types/matrix/room';
import { ErrorCode } from '../../cs-errorcode';
import type { CommandContext, CommandRecord } from './types';
import { Command } from './types';
import { isValidHex } from '$hooks/useUserProfile';
import * as prefix from '$unstable/prefixes';
import type { CustomRoomMemberEventContent } from '$unstable/CustomRoomMemberEventContent';
export const createProfileCommands = (ctx: CommandContext): Partial<CommandRecord> => {
const { mx, room, profileDisplayName } = ctx;
@@ -21,10 +23,12 @@ export const createProfileCommands = (ctx: CommandContext): Partial<CommandRecor
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(EventType.RoomMember, mx.getSafeUserId());
const content = mEvent?.getContent<RoomMemberEventContent>();
const content = mEvent?.getContent<CustomRoomMemberEventContent>();
if (!content) return;
const updatedContent: RoomMemberEventContent = { ...content };
const withDisplay = updatedContent as RoomMemberEventContent & { displayname?: string };
const updatedContent: CustomRoomMemberEventContent = { ...content };
const withDisplay = updatedContent as CustomRoomMemberEventContent & {
displayname?: string;
};
if (nick == null || nick === '') {
delete withDisplay.displayname;
} else {
@@ -43,65 +47,95 @@ export const createProfileCommands = (ctx: CommandContext): Partial<CommandRecor
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(EventType.RoomMember, mx.getSafeUserId());
const content = mEvent?.getContent<RoomMemberEventContent>();
const content = mEvent?.getContent<CustomRoomMemberEventContent>();
if (!content) return;
const updatedContent: RoomMemberEventContent = { ...content };
const updatedContent: CustomRoomMemberEventContent = { ...content };
if (isRemove) {
// Reset to global avatar
const globalAvatar = mx.getUser(mx.getSafeUserId())?.avatarUrl ?? undefined;
(updatedContent as RoomMemberEventContent & { avatar_url?: string }).avatar_url =
(updatedContent as CustomRoomMemberEventContent & { avatar_url?: string }).avatar_url =
globalAvatar;
} else {
if (!trimmed.match(/^mxc:\/\/\S+$/)) {
// bad mxc
return;
}
(updatedContent as RoomMemberEventContent & { avatar_url?: string }).avatar_url = trimmed;
(updatedContent as CustomRoomMemberEventContent & { avatar_url?: string }).avatar_url =
trimmed;
}
await setOwnRoomMemberProfile(mx, room, updatedContent);
},
},
[Command.Color]: {
name: Command.Color,
description: 'Set a room-specific color. Example: /color #ff00ff | /color reset',
description: 'Set a room-specific color. Example: /color light #ff00ff | /color reset',
exe: async (payload) => {
const input = payload.trim().toLowerCase();
const input = payload.trim().toLowerCase().split(' ');
const userId = mx.getSafeUserId();
const completeClear = input.length >= 0 && (input[0] === 'reset' || input[0] === 'clear');
const isLight =
input.length === 2 &&
(input[0] === 'light' || input[0] === 'on_light' || input[0] === 'both');
const isDark =
input.length === 2 &&
(input[0] === 'dark' || input[0] === 'on_dark' || input[0] === 'both');
const color =
input[1] === 'reset' || input[1] === 'clear'
? undefined
: input[1]?.length
? input[1]
: '';
try {
if (input === 'reset' || input === 'clear') {
await mx.sendStateEvent(room.roomId, CustomStateEvent.RoomCosmeticsColor, {}, userId);
sendFeedback('Room color has been reset.', room, userId);
return;
}
if (!color || isValidHex(color) || completeClear) {
const mEvent = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(EventType.RoomMember, mx.getSafeUserId());
const content = mEvent?.getContent<CustomRoomMemberEventContent>();
if (!content) return;
const updatedContent: CustomRoomMemberEventContent = { ...content };
if (completeClear) {
// Reset
updatedContent[prefix.MATRIX_UNSTABLE_COLORS] = undefined;
if (/^#[0-9A-F]{6}$/i.test(input)) {
await mx.sendStateEvent(
room.roomId,
CustomStateEvent.RoomCosmeticsColor,
{ color: input },
userId
);
sendFeedback(`Room color set to ${input}.`, room, userId);
} else {
sendFeedback('Invalid format. Use #RRGGBB.', room, userId);
}
} catch (e: unknown) {
if (e instanceof MatrixError && e.errcode === ErrorCode.M_FORBIDDEN) {
await mx.sendStateEvent(room.roomId, CustomStateEvent.RoomCosmeticsColor, {}, userId);
} else {
if (color && !isValidHex(color)) {
return;
}
updatedContent[prefix.MATRIX_UNSTABLE_COLORS] = {
on_dark: isDark ? color : content[prefix.MATRIX_UNSTABLE_COLORS]?.on_dark,
on_light: isLight ? color : content[prefix.MATRIX_UNSTABLE_COLORS]?.on_light,
};
}
await setOwnRoomMemberProfile(mx, room, updatedContent);
sendFeedback(
'Permission Denied. An admin must enable "Room Colors" in Settings > Cosmetics in app.sable.moe or another supported client.',
`Room color set to:\nOver dark themes ${updatedContent[prefix.MATRIX_UNSTABLE_COLORS]?.on_dark},\nOver light themes ${updatedContent[prefix.MATRIX_UNSTABLE_COLORS]?.on_light}.`,
room,
userId
);
await mx.sendStateEvent(room.roomId, CustomStateEvent.RoomCosmeticsColor, {}, userId);
} else {
sendFeedback(
'Invalid format. Use #RRGGBB for colors and specify which color.',
room,
userId
);
}
} catch (e: unknown) {
if (e instanceof MatrixError && e.errcode === ErrorCode.M_FORBIDDEN) {
sendFeedback('Permission Denied.', room, userId);
}
}
},
},
[Command.SColor]: {
name: Command.SColor,
description: 'Set your color for the current Space. Example: /scolor #ff00ff | /scolor reset',
description:
'Set your color for the current Space. Example: /scolor light #ff00ff | /scolor reset',
exe: async (payload) => {
const input = payload.trim().toLowerCase();
const input = payload.trim().toLowerCase().split(' ');
const userId = mx.getSafeUserId();
const parents = room
@@ -111,38 +145,78 @@ export const createProfileCommands = (ctx: CommandContext): Partial<CommandRecor
const targetSpaceId =
parents && parents.length > 0 ? parents[0]!.getStateKey() : room.roomId;
const targetRoom = mx.getRoom(targetSpaceId);
const completeClear = input.length >= 0 && (input[0] === 'reset' || input[0] === 'clear');
const isLight =
input.length === 2 &&
(input[0] === 'light' || input[0] === 'on_light' || input[0] === 'both');
const isDark =
input.length === 2 &&
(input[0] === 'dark' || input[0] === 'on_dark' || input[0] === 'both');
const color =
input[1] === 'reset' || input[1] === 'clear'
? undefined
: input[1]?.length
? input[1]
: '';
try {
if (input === 'reset' || input === 'clear') {
await mx.sendStateEvent(
targetSpaceId as string,
CustomStateEvent.RoomCosmeticsColor,
{},
userId
);
sendFeedback('Global space color reset.', room, userId);
return;
}
if (/^#[0-9A-F]{6}$/i.test(input)) {
await mx.sendStateEvent(
targetSpaceId as string,
CustomStateEvent.RoomCosmeticsColor,
{ color: input },
userId
);
sendFeedback(`Global space color set to ${input}.`, room, userId);
if (!color || isValidHex(color) || completeClear) {
const mEvent = room
.getLiveTimeline()
.getState(EventTimeline.FORWARDS)
?.getStateEvents(EventType.RoomMember, mx.getSafeUserId());
const content = mEvent?.getContent<CustomRoomMemberEventContent>();
if (!content) return;
const updatedContent: CustomRoomMemberEventContent = { ...content };
if (completeClear) {
// Reset
updatedContent[prefix.MATRIX_UNSTABLE_COLORS] = undefined;
//This may be ignored since it is to delete the old key when updated
try {
await mx.sendStateEvent(
room.roomId,
CustomStateEvent.RoomCosmeticsColor,
{},
userId
);
} catch {}
} else {
if (color && !isValidHex(color)) {
return;
}
updatedContent[prefix.MATRIX_UNSTABLE_COLORS] = {
on_dark: isDark ? color : content[prefix.MATRIX_UNSTABLE_COLORS]?.on_dark,
on_light: isLight ? color : content[prefix.MATRIX_UNSTABLE_COLORS]?.on_light,
};
}
if (targetRoom) {
await setOwnRoomMemberProfile(mx, targetRoom, updatedContent);
sendFeedback(
`Room color set to:\nOver dark themes ${updatedContent[prefix.MATRIX_UNSTABLE_COLORS]?.on_dark},\nOver light themes ${updatedContent[prefix.MATRIX_UNSTABLE_COLORS]?.on_light}.`,
room,
userId
);
try {
await mx.sendStateEvent(
room.roomId,
CustomStateEvent.RoomCosmeticsColor,
{},
userId
);
} catch {}
}
} else {
sendFeedback('Invalid format. Use #RRGGBB.', room, userId);
}
} catch (e: unknown) {
if (e instanceof MatrixError && e.errcode === ErrorCode.M_FORBIDDEN) {
sendFeedback(
'Permission Denied. An admin must enable "Space-Wide Colors" in Settings > Cosmetics in app.sable.moe or another supported client.',
'Invalid format. Use #RRGGBB for colors and specify which color (on_light|on_dark).',
room,
userId
);
}
} catch (e: unknown) {
if (e instanceof MatrixError && e.errcode === ErrorCode.M_FORBIDDEN) {
sendFeedback('Permission Denied.', room, userId);
}
}
},
},
+41 -3
View File
@@ -2,10 +2,10 @@ import type { MouseEventHandler, ReactNode } from 'react';
import { useCallback } from 'react';
import { Text } from 'folds';
import type { MatrixEvent, Room } from '$types/matrix-sdk';
import type { IMemberContent } from '$types/matrix/room';
import {
At,
EnvelopeSimple,
PaintBrush,
SignIn,
SignOut,
timelineIcon,
@@ -20,6 +20,8 @@ import { useOpenUserRoomProfile } from '$state/hooks/userRoomProfile';
import { useSableCosmetics } from './useSableCosmetics';
import { useMatrixClient } from './useMatrixClient';
import { KnownMembership } from '$types/matrix-sdk';
import type { CustomRoomMemberEventContent } from '$unstable/CustomRoomMemberEventContent';
import { MATRIX_UNSTABLE_COLORS } from '$unstable/prefixes';
type DecoratedUserProps = {
roomId: string;
@@ -57,8 +59,8 @@ export type ParsedResult = {
export type MemberEventParser = (mEvent: MatrixEvent) => ParsedResult;
const parseMemberEvent: MemberEventParser = (mEvent) => {
const content = mEvent.getContent<IMemberContent>();
const prevContent = mEvent.getPrevContent() as IMemberContent;
const content = mEvent.getContent<CustomRoomMemberEventContent>();
const prevContent = mEvent.getPrevContent() as CustomRoomMemberEventContent;
const senderId = mEvent.getSender();
const userId = mEvent.getStateKey();
const roomId = mEvent.getRoomId();
@@ -266,6 +268,42 @@ const parseMemberEvent: MemberEventParser = (mEvent) => {
),
};
}
if (content[MATRIX_UNSTABLE_COLORS]?.on_dark !== prevContent[MATRIX_UNSTABLE_COLORS]?.on_dark) {
return {
icon: timelineIcon(PaintBrush),
body:
content[MATRIX_UNSTABLE_COLORS]?.on_dark &&
typeof content[MATRIX_UNSTABLE_COLORS]?.on_dark === 'string' ? (
<>
<DecoratedUser roomId={roomId ?? ''} userId={userId} userName={userName} />
<Text>{' changed one of their room name colors'}</Text>
</>
) : (
<>
<DecoratedUser roomId={roomId ?? ''} userId={userId} userName={userName} />
<Text>{' removed one of their room name colors '}</Text>
</>
),
};
}
if (content[MATRIX_UNSTABLE_COLORS]?.on_light !== prevContent[MATRIX_UNSTABLE_COLORS]?.on_light) {
return {
icon: timelineIcon(PaintBrush),
body:
content[MATRIX_UNSTABLE_COLORS]?.on_light &&
typeof content[MATRIX_UNSTABLE_COLORS]?.on_light === 'string' ? (
<>
<DecoratedUser roomId={roomId ?? ''} userId={userId} userName={userName} />
<Text>{' changed one of their room name colors'}</Text>
</>
) : (
<>
<DecoratedUser roomId={roomId ?? ''} userId={userId} userName={userName} />
<Text>{' removed one of their room name colors '}</Text>
</>
),
};
}
return {
icon: timelineIcon(User),
+7 -15
View File
@@ -3,10 +3,9 @@ import type { AccountDataCompatVersion } from '$types/matrix/accountData';
import type { PronounSet } from '$utils/pronouns';
import type { MatrixClient } from '$types/matrix-sdk';
import { CustomAccountDataEvent } from '$types/matrix/accountData';
import {
MATRIX_UNSTABLE_PROFILE_NAME_COLOR_PROPERTY_NAME,
MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME,
} from '$unstable/prefixes';
import { MATRIX_UNSTABLE_COLORS } from '$unstable/prefixes';
import { MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME } from '$unstable/prefixes';
import type { ColorSet } from './useUserProfile';
const ACCOUNT_DATA_PREFIX = CustomAccountDataEvent.SablePerProfileMessageProfiles;
@@ -34,10 +33,7 @@ export type PerMessageProfile = {
*/
pronouns?: PronounSet[];
compat?: AccountDataCompatVersion;
/* name colors */
nameColorLightTheme?: string;
nameColorDarkTheme?: string;
colors?: ColorSet;
};
/**
@@ -63,7 +59,7 @@ export type PerMessageProfileBeeperFormat = {
*/
[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]?: PronounSet[];
[MATRIX_UNSTABLE_PROFILE_NAME_COLOR_PROPERTY_NAME]?: { light?: string; dark?: string };
[MATRIX_UNSTABLE_COLORS]?: ColorSet;
has_fallback?: boolean;
};
@@ -83,10 +79,7 @@ export function convertPerMessageProfileToBeeperFormat(
displayname: profile.name,
avatar_url: profile.avatarUrl,
[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME]: profile.pronouns,
[MATRIX_UNSTABLE_PROFILE_NAME_COLOR_PROPERTY_NAME]: {
light: profile.nameColorLightTheme,
dark: profile.nameColorDarkTheme,
},
[MATRIX_UNSTABLE_COLORS]: profile.colors,
has_fallback,
};
// delete empty fields
@@ -115,8 +108,7 @@ export function convertBeeperFormatToOurPerMessageProfile(
name: beeperProfile.displayname ?? '',
avatarUrl: beeperProfile.avatar_url,
pronouns: beeperProfile[MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME],
nameColorLightTheme: beeperProfile[MATRIX_UNSTABLE_PROFILE_NAME_COLOR_PROPERTY_NAME]?.light,
nameColorDarkTheme: beeperProfile[MATRIX_UNSTABLE_PROFILE_NAME_COLOR_PROPERTY_NAME]?.dark,
colors: beeperProfile[MATRIX_UNSTABLE_COLORS],
};
}
+35 -6
View File
@@ -25,6 +25,11 @@ const inFlightProfiles = new WeakMap<MatrixClient, Map<string, Promise<Record<st
const activeProfileRequests = new WeakMap<MatrixClient, number>();
const profileRequestQueues = new WeakMap<MatrixClient, Array<() => void>>();
export type ColorSet = {
on_light?: string;
on_dark?: string;
};
const scheduleProfileRequest = (
mx: MatrixClient,
task: () => Promise<Record<string, unknown>>
@@ -66,6 +71,7 @@ export type UserProfile = {
nameColor?: string;
nameColorDark?: string;
nameColorLight?: string;
nameColors?: ColorSet;
heroColorScheme?: Record<string, string>;
isCat?: boolean;
hasCats?: boolean;
@@ -92,6 +98,7 @@ const normalizeInfo = (info: Record<string, unknown>): UserProfile => {
prefix.MATRIX_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME,
prefix.MATRIX_UNSTABLE_PROFILE_BANNER_PROPERTY_NAME,
prefix.MATRIX_COMMET_UNSTABLE_PROFILE_STATUS_PROPERTY_NAME,
prefix.MATRIX_UNSTABLE_COLORS,
prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME,
prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME,
prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME,
@@ -131,6 +138,7 @@ const normalizeInfo = (info: Record<string, unknown>): UserProfile => {
nameColorLight: info[prefix.MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME] as
| string
| undefined,
nameColors: info[prefix.MATRIX_UNSTABLE_COLORS] as ColorSet | undefined,
heroColorScheme: info[prefix.MATRIX_COMMET_UNSTABLE_PROFILE_COLOR_SCHEME_PROPERTY_NAME] as
| Record<string, string>
| undefined,
@@ -153,7 +161,7 @@ const normalizeInfo = (info: Record<string, unknown>): UserProfile => {
};
};
const isValidHex = (c: unknown): string | undefined => {
export const isValidHex = (c: unknown): string | undefined => {
if (typeof c !== 'string') return undefined;
// silly tuwunel smh
const cleaned = c.replaceAll(/["']/g, '').trim();
@@ -272,8 +280,17 @@ export const useUserProfile = (
const state = room.getLiveTimeline().getState(EventTimeline.FORWARDS);
if (renderRoomColors) {
const roomMemberEvent = state?.getStateEvents(EventType.RoomMember, userId);
const roomColorContent = (
Array.isArray(roomMemberEvent) ? roomMemberEvent[0] : roomMemberEvent
)?.getContent();
const roomColorObject = roomColorContent?.[prefix.MATRIX_UNSTABLE_COLORS];
const roomColorNew =
themeKind === ThemeKind.Light ? roomColorObject?.on_light : roomColorObject?.on_dark;
const localEvent = state?.getStateEvents(CustomStateEvent.RoomCosmeticsColor, userId);
localColor = (Array.isArray(localEvent) ? localEvent[0] : localEvent)?.getContent()?.color;
const localColorOld = (Array.isArray(localEvent) ? localEvent[0] : localEvent)?.getContent()
?.color;
localColor = roomColorNew ?? localColorOld;
}
if (renderRoomFonts) {
@@ -297,9 +314,18 @@ export const useUserProfile = (
const pState = parentSpace?.getLiveTimeline().getState(EventTimeline.FORWARDS);
if (renderRoomColors) {
const spaceMemberEvent = pState?.getStateEvents(EventType.RoomMember, userId);
const spaceColorContent = (
Array.isArray(spaceMemberEvent) ? spaceMemberEvent[0] : spaceMemberEvent
)?.getContent();
const spaceColorObject = spaceColorContent?.[prefix.MATRIX_UNSTABLE_COLORS];
const spaceColorNew =
themeKind === ThemeKind.Light ? spaceColorObject?.on_light : spaceColorObject?.on_dark;
const spaceEvent = pState?.getStateEvents(CustomStateEvent.RoomCosmeticsColor, userId);
spaceColor = (Array.isArray(spaceEvent) ? spaceEvent[0] : spaceEvent)?.getContent()
?.color;
const spaceColorOld = (
Array.isArray(spaceEvent) ? spaceEvent[0] : spaceEvent
)?.getContent()?.color;
spaceColor = spaceColorNew ?? spaceColorOld;
}
if (renderRoomFonts) {
@@ -319,9 +345,12 @@ export const useUserProfile = (
}
}
const colorArray = data.nameColors;
const validGlobalVal = isValidHex(data?.nameColor);
const validGlobalValDark = isValidHex(data?.nameColorDark);
const validGlobalValLight = isValidHex(data?.nameColorLight);
const validGlobalValDark = isValidHex(colorArray?.on_dark) ?? isValidHex(data?.nameColorDark);
const validGlobalValLight =
isValidHex(colorArray?.on_light) ?? isValidHex(data?.nameColorLight);
const validGlobalGeneral =
(renderGlobalColors || userId === mx.getUserId()) && !!validGlobalVal
+3 -2
View File
@@ -1,11 +1,12 @@
import type { MatrixClient, Room, RoomMemberEventContent } from '$types/matrix-sdk';
import type { MatrixClient, Room } from '$types/matrix-sdk';
import { EventType, MatrixEvent } from '$types/matrix-sdk';
import type { CustomRoomMemberEventContent } from '$unstable/CustomRoomMemberEventContent';
/** Send an own-membership profile update and immediately reflect the accepted state locally. */
export async function setOwnRoomMemberProfile(
mx: MatrixClient,
room: Room,
content: RoomMemberEventContent
content: CustomRoomMemberEventContent
): Promise<void> {
const userId = mx.getSafeUserId();
const response = await mx.sendStateEvent(room.roomId, EventType.RoomMember, content, userId);
+6
View File
@@ -1,5 +1,6 @@
import type { IImageInfo } from './common';
import * as prefix from '$unstable/prefixes';
import type { ColorSet } from '$hooks/useUserProfile';
export type IMemberContent = {
avatar_url?: string;
@@ -71,3 +72,8 @@ export type MemberPowerTag = {
color?: string;
icon?: MemberPowerTagIcon;
};
export type MemberPowerStyle = {
name: string;
color?: ColorSet;
};
@@ -0,0 +1,22 @@
import type { ColorSet } from '$hooks/useUserProfile';
import type * as prefix from '$unstable/prefixes';
import type { KnownMembership } from 'matrix-js-sdk';
// moving the type here as the sdk is not updated to permit the changes and will not be for a very long while
export interface CustomRoomMemberEventContent {
avatar_url?: string;
displayname?: string;
is_direct?: boolean;
[prefix.MATRIX_UNSTABLE_COLORS]?: ColorSet;
join_authorised_via_users_server?: string;
membership: KnownMembership;
reason?: string;
third_party_invite?: {
display_name: string;
signed: {
mxid: string;
token: string;
ts: number;
};
};
}
+6 -5
View File
@@ -6,11 +6,6 @@
*/
export const MATRIX_UNSTABLE_PROFILE_PRONOUNS_PROPERTY_NAME = 'io.fsky.nyx.pronouns';
/**
* unstable prefix for profile name colors
*/
export const MATRIX_UNSTABLE_PROFILE_NAME_COLOR_PROPERTY_NAME = 'net.f0rest.name_color';
/**
* unstable prefix for profile biography
* defined in MSC4440 https://github.com/matrix-org/matrix-spec-proposals/pull/4440
@@ -25,3 +20,9 @@ export const MATRIX_STABLE_PROFILE_TIMEZONE_PROPERTY_NAME = 'm.tz';
*/
export const MATRIX_UNSTABLE_MSC4466_FEATURE = 'computer.gingershaped.msc4466';
export const MATRIX_UNSTABLE_MSC4466_PROPAGATE_TO = 'computer.gingershaped.msc4466.propagate_to';
/**
* Unstable prefix for username colors. defined in https://github.com/matrix-org/matrix-spec-proposals/pull/4522
*/
export const MATRIX_UNSTABLE_COLORS = 'eu.she-a.colors';
@@ -8,3 +8,5 @@ export const MATRIX_UNSTABLE_STATE_ROOM_EMOTES_PROPERTY_NAME = 'im.ponies.room_e
* defined in MSC3401 https://github.com/matrix-org/matrix-spec-proposals/pull/3401
*/
export const MATRIX_UNSTABLE_ROOM_TYPE_CALL_PROPERTY_NAME = 'org.matrix.msc3401.call';
export const MATRIX_UNSTABLE_ROOM_STYLING = 'eu.she-a.powerlevels_style';
+12
View File
@@ -5,9 +5,21 @@
* @deprecated in favor of MSC4440
*/
export const MATRIX_SABLE_UNSTABLE_PROFILE_BIOGRAPHY_PROPERTY_NAME = 'moe.sable.app.bio';
/**
* @deprecated in favor of MSC4522
*/
export const MATRIX_SABLE_UNSTABLE_NAME_COLOR_PROPERTY_NAME = 'moe.sable.app.name_color';
/**
* @deprecated in favor of MSC4522
*/
export const MATRIX_SABLE_UNSTABLE_NAME_COLOR_DARK_PROPERTY_NAME =
'moe.sable.app.name_color_dark_theme';
/**
* @deprecated in favor of MSC4522
*/
export const MATRIX_SABLE_UNSTABLE_NAME_COLOR_LIGHT_PROPERTY_NAME =
'moe.sable.app.name_color_light_theme';
export const MATRIX_SABLE_UNSTABLE_ANIMAL_IDENTITY_IS_CAT_PROPERTY_NAME = 'kitty.meow.is_cat';