mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-21 17:41:25 -08:00
Add PMP shorthand editing in Settings (#1352)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> - Add PMP shorthand editing in Settings - Migrate from storing shorthands as regex in account data to `{ prefix?, suffix? }`. <img width="1394" height="520" alt="image" src="https://github.com/user-attachments/assets/3137f1ac-10d1-4510-b88f-dcdc52866fc7" /> Part of #1279 #### Type of change > [!NOTE] > This PR is a breaking change on an experimental feature, so I have considered it 'minor' instead of 'major'. Migrations have also been made so users should not expect issues. - [ ] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [x] 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 - [x] 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). - [ ] 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. -->
This commit is contained in:
8 files changed
+616
-62
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: minor
|
||||
---
|
||||
|
||||
# Add PMP shorthand editing in Settings
|
||||
@@ -100,7 +100,7 @@ export function PersonaPicker({
|
||||
setSelectedGlobalPersona(syncedGlobalProfile ?? null);
|
||||
};
|
||||
syncProfile();
|
||||
}, [mx, roomId]);
|
||||
}, [mx, roomId, profiles]);
|
||||
|
||||
const fetchProfiles = async (mx_: MatrixClient) => {
|
||||
const fetchedProfiles = await getAllPerMessageProfiles(mx_);
|
||||
@@ -112,20 +112,23 @@ export function PersonaPicker({
|
||||
fetchProfiles(mx);
|
||||
}, [mx]);
|
||||
|
||||
const filter = (e: FormEvent) => {
|
||||
const term = (e.target as HTMLInputElement).value.toLocaleLowerCase();
|
||||
const filter = useCallback(
|
||||
(e: FormEvent) => {
|
||||
const term = (e.target as HTMLInputElement).value.toLocaleLowerCase();
|
||||
|
||||
const filtered = term
|
||||
? profiles?.filter((profile) =>
|
||||
searchInputRef.current
|
||||
? profile.name.toLocaleLowerCase().includes(searchInputRef.current?.value) ||
|
||||
profile.id.toLocaleLowerCase().includes(searchInputRef.current?.value)
|
||||
: true
|
||||
)
|
||||
: profiles;
|
||||
const filtered = term
|
||||
? profiles?.filter((profile) =>
|
||||
searchInputRef.current
|
||||
? profile.name.toLocaleLowerCase().includes(searchInputRef.current?.value) ||
|
||||
profile.id.toLocaleLowerCase().includes(searchInputRef.current?.value)
|
||||
: true
|
||||
)
|
||||
: profiles;
|
||||
|
||||
setFilteredProfiles(filtered);
|
||||
};
|
||||
setFilteredProfiles(filtered);
|
||||
},
|
||||
[profiles]
|
||||
);
|
||||
|
||||
const avatarUrl = useCallback(
|
||||
(profile: PerMessageProfile) => {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { SequenceCard, SequenceCardStyle } from '$components/sequence-card';
|
||||
import { Box, Button, Text, Avatar, config, IconButton, Input } from 'folds';
|
||||
import { menuIcon, X } from '$components/icons/phosphor';
|
||||
import { Box, Button, Text, Avatar, config, IconButton, Input, toRem, Spinner, color } from 'folds';
|
||||
import { menuIcon, Trash, X } from '$components/icons/phosphor';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { nameInitials } from '$utils/common';
|
||||
import { mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useFilePicker } from '$hooks/useFilePicker';
|
||||
@@ -13,12 +13,302 @@ import { UserAvatar } from '$components/user-avatar';
|
||||
import { CompactUploadCardRenderer } from '$components/upload-card';
|
||||
import {
|
||||
addOrUpdatePerMessageProfile,
|
||||
associateProxyWithProfile,
|
||||
createProxyKey,
|
||||
deletePerMessageProfile,
|
||||
dropProxyAssociationForPMP,
|
||||
getAllPerMessageProfileProxies,
|
||||
getAllProxiesForPMP,
|
||||
getPerMessageProfileById,
|
||||
type PerMessageProfileProxyAssociationV2,
|
||||
renamePerMessageProfile,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import type { PronounSet } from '$utils/pronouns';
|
||||
import { parsePronounsStringToPronounsSetArray } from '$utils/pronouns';
|
||||
import { generateShortId } from '$utils/shortIdGen';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { type AsyncState, AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
|
||||
const constructProxyString = (s: Shorthand) => {
|
||||
return `${s.prefix ?? ''}text${s.suffix ?? ''}`;
|
||||
};
|
||||
|
||||
type Shorthand = { id: string; prefix?: string; suffix?: string };
|
||||
type ShorthandRow = Shorthand & { rowId: string };
|
||||
|
||||
type ShorthandListItemProps = Shorthand & {
|
||||
onDelete: (shorthandId: string) => void;
|
||||
onSave: (shorthandId: string, shorthand: Shorthand) => void;
|
||||
deleteState: AsyncState<void>;
|
||||
saveState: AsyncState<void>;
|
||||
};
|
||||
function ShorthandListItem({
|
||||
id,
|
||||
prefix,
|
||||
suffix,
|
||||
onDelete,
|
||||
onSave,
|
||||
deleteState,
|
||||
saveState,
|
||||
}: ShorthandListItemProps) {
|
||||
const [currentPrefix] = useState(prefix);
|
||||
const [currentSuffix] = useState(suffix);
|
||||
const [newPrefix, setNewPrefix] = useState(prefix);
|
||||
const [newSuffix, setNewSuffix] = useState(suffix);
|
||||
|
||||
const [prefixWarn, setPrefixWarn] = useState(false);
|
||||
const [suffixWarn, setSuffixWarn] = useState(false);
|
||||
|
||||
const handlePrefixChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setNewPrefix(e.target.value);
|
||||
}, []);
|
||||
const handleSuffixChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setNewSuffix(e.target.value);
|
||||
}, []);
|
||||
|
||||
const hasChanges = useMemo(
|
||||
() =>
|
||||
(newPrefix ?? '') !== (currentPrefix ?? '') || (newSuffix ?? '') !== (currentSuffix ?? ''),
|
||||
[newPrefix, newSuffix, currentPrefix, currentSuffix]
|
||||
);
|
||||
const isBlank = useMemo(() => !newPrefix && !newSuffix, [newPrefix, newSuffix]);
|
||||
|
||||
useEffect(() => {
|
||||
setPrefixWarn((newPrefix ?? '').endsWith(' '));
|
||||
setSuffixWarn((newSuffix ?? '').startsWith(' '));
|
||||
}, [newPrefix, newSuffix]);
|
||||
|
||||
const handleSave = () =>
|
||||
onSave(id, {
|
||||
id: createProxyKey(newPrefix, newSuffix),
|
||||
prefix: newPrefix?.trimStart(),
|
||||
suffix: newSuffix?.trimEnd(),
|
||||
});
|
||||
|
||||
return (
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="Surface"
|
||||
style={{ padding: toRem(8) }}
|
||||
gap="100"
|
||||
>
|
||||
<Box
|
||||
direction="Column"
|
||||
style={{ width: '100%' }} /* sorry, complex layout, idk what's happening */
|
||||
>
|
||||
{(prefixWarn || suffixWarn) && (
|
||||
<Text size="T200" style={{ color: color.Warning.Main }}>
|
||||
Whitespace inside of a shorthand will require whitespace{' '}
|
||||
{prefixWarn && suffixWarn
|
||||
? 'before/after'
|
||||
: prefixWarn
|
||||
? 'before'
|
||||
: suffixWarn
|
||||
? 'after'
|
||||
: 'before/after'}{' '}
|
||||
text to match.
|
||||
</Text>
|
||||
)}
|
||||
<Box direction="Row" gap="100">
|
||||
<Input
|
||||
value={newPrefix}
|
||||
style={{ flexGrow: 1, height: '2rem' }}
|
||||
placeholder="Prefix..."
|
||||
variant={prefixWarn ? 'Warning' : 'Secondary'}
|
||||
radii="300"
|
||||
onChange={handlePrefixChange}
|
||||
/>
|
||||
<Input
|
||||
value={newSuffix}
|
||||
style={{ flexGrow: 1, height: '2rem' }}
|
||||
placeholder="Suffix..."
|
||||
variant={suffixWarn ? 'Warning' : 'Secondary'}
|
||||
radii="300"
|
||||
onChange={handleSuffixChange}
|
||||
/>
|
||||
<Box gap="100" style={{ marginLeft: toRem(6) }}>
|
||||
<Button
|
||||
onClick={() => onDelete(id)}
|
||||
size="300"
|
||||
variant="Critical"
|
||||
disabled={isBlank}
|
||||
fill="Soft"
|
||||
outlined
|
||||
radii="300"
|
||||
aria-label="Delete shorthand"
|
||||
>
|
||||
{deleteState.status === AsyncStatus.Loading ? (
|
||||
<Spinner size="100" variant="Primary" fill="Solid" />
|
||||
) : (
|
||||
menuIcon(Trash)
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
size="300"
|
||||
variant="Primary"
|
||||
disabled={!hasChanges}
|
||||
fill="Soft"
|
||||
outlined
|
||||
radii="300"
|
||||
aria-label="Update shorthand"
|
||||
>
|
||||
{saveState.status === AsyncStatus.Loading ? (
|
||||
<Spinner size="100" variant="Primary" fill="Solid" />
|
||||
) : (
|
||||
<Text size="B300">Save</Text>
|
||||
)}
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
</SequenceCard>
|
||||
);
|
||||
}
|
||||
|
||||
type ShorthandEditorProps = {
|
||||
mx: MatrixClient;
|
||||
profileId: string;
|
||||
};
|
||||
function ShorthandEditor({ mx, profileId }: ShorthandEditorProps) {
|
||||
const [shorthands, setShorthands] = useState<ShorthandRow[]>();
|
||||
|
||||
const containsBlankShorthand = useMemo(
|
||||
() => shorthands && shorthands.some((shorthand) => !shorthand.prefix && !shorthand.suffix),
|
||||
[shorthands]
|
||||
);
|
||||
|
||||
const handleAddShorthand = () => {
|
||||
if (shorthands !== undefined) {
|
||||
setShorthands([...shorthands, { id: 'blank', rowId: generateShortId(16) }]);
|
||||
}
|
||||
};
|
||||
|
||||
const [deleteShorthandState, handleDeleteShorthand] = useAsyncCallback(
|
||||
useCallback(
|
||||
async (id: string) => {
|
||||
if (shorthands === undefined) return;
|
||||
|
||||
const shorthandToDelete = shorthands.find((shorthand) => shorthand.id === id);
|
||||
if (!shorthandToDelete) return;
|
||||
|
||||
const proxy = constructProxyString(shorthandToDelete);
|
||||
|
||||
await dropProxyAssociationForPMP(mx, proxy);
|
||||
|
||||
setShorthands((s) => s?.filter((shorthand) => shorthand.id !== id));
|
||||
},
|
||||
[mx, shorthands]
|
||||
)
|
||||
);
|
||||
|
||||
const [saveShorthandState, handleSaveShorthand] = useAsyncCallback<
|
||||
void,
|
||||
Error,
|
||||
[string, Shorthand]
|
||||
>(
|
||||
useCallback(
|
||||
async (oldId: string, shorthand: Shorthand) => {
|
||||
if (shorthands === undefined) return;
|
||||
|
||||
const shorthandAssociation = (await getAllPerMessageProfileProxies(mx)).find(
|
||||
(association) => createProxyKey(association.prefix, association.suffix) === shorthand.id
|
||||
);
|
||||
const shorthandAssociatedProfile = shorthandAssociation
|
||||
? await getPerMessageProfileById(mx, shorthandAssociation.profileId)
|
||||
: undefined;
|
||||
if (shorthandAssociatedProfile) {
|
||||
throw new Error(
|
||||
`Shorthand is already associated with profile ${shorthandAssociatedProfile.name} (${shorthandAssociatedProfile.id})`
|
||||
);
|
||||
}
|
||||
|
||||
if (oldId !== 'blank') {
|
||||
await dropProxyAssociationForPMP(mx, oldId);
|
||||
}
|
||||
await associateProxyWithProfile(mx, profileId, shorthand.prefix, shorthand.suffix, false);
|
||||
|
||||
setShorthands((currentShorthands) => {
|
||||
if (currentShorthands === undefined) return currentShorthands;
|
||||
|
||||
const oldShorthandIdx = currentShorthands.findIndex((s) => s.id === oldId);
|
||||
if (oldShorthandIdx < 0) return currentShorthands;
|
||||
const oldShorthand = currentShorthands[oldShorthandIdx];
|
||||
if (oldShorthand === undefined) return currentShorthands;
|
||||
|
||||
return currentShorthands.with(oldShorthandIdx, {
|
||||
...shorthand,
|
||||
rowId: oldShorthand.rowId,
|
||||
});
|
||||
});
|
||||
},
|
||||
[mx, shorthands, profileId]
|
||||
)
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchShorthands = async () => {
|
||||
const fetchedShorthands: PerMessageProfileProxyAssociationV2[] = await getAllProxiesForPMP(
|
||||
mx,
|
||||
profileId
|
||||
);
|
||||
const enumeratedShorthands: ShorthandRow[] = fetchedShorthands.map((v) => {
|
||||
return { id: createProxyKey(v.prefix, v.suffix), rowId: generateShortId(16), ...v };
|
||||
});
|
||||
setShorthands(enumeratedShorthands);
|
||||
};
|
||||
fetchShorthands();
|
||||
}, [mx, profileId]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Shorthands"
|
||||
description="Use this persona for a single message using a prefix or suffix."
|
||||
focusId={`shorthandsInput-${profileId}`}
|
||||
>
|
||||
{saveShorthandState.status === AsyncStatus.Error && (
|
||||
<Text size="T200" style={{ color: color.Critical.Main }}>
|
||||
{saveShorthandState.error.toString()}
|
||||
</Text>
|
||||
)}
|
||||
{shorthands === undefined ? (
|
||||
<Spinner size="400" />
|
||||
) : (
|
||||
shorthands.map((shorthand: ShorthandRow) => (
|
||||
<ShorthandListItem
|
||||
key={shorthand.rowId}
|
||||
id={shorthand.id}
|
||||
prefix={shorthand.prefix}
|
||||
suffix={shorthand.suffix}
|
||||
onDelete={handleDeleteShorthand}
|
||||
onSave={handleSaveShorthand}
|
||||
deleteState={deleteShorthandState}
|
||||
saveState={saveShorthandState}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
<Button
|
||||
onClick={handleAddShorthand}
|
||||
size="400"
|
||||
radii="300"
|
||||
variant="Primary"
|
||||
disabled={containsBlankShorthand}
|
||||
/* add aria label and title pls */
|
||||
>
|
||||
<Text size="B300">Add new shorthand</Text>
|
||||
</Button>
|
||||
</SettingTile>
|
||||
</SequenceCard>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* the props we use for the per-message profile editor, which is used to edit a per-message profile. This is used in the settings page when the user wants to edit a profile.
|
||||
@@ -29,6 +319,7 @@ type PerMessageProfileEditorProps = {
|
||||
avatarMxcUrl?: string;
|
||||
displayName?: string;
|
||||
pronouns?: PronounSet[];
|
||||
shorthands?: Shorthand[];
|
||||
onDelete?: (profileId: string) => void;
|
||||
};
|
||||
|
||||
@@ -371,7 +662,7 @@ export function PerMessageProfileEditor({
|
||||
aria-label={`Delete profile ${profileId}`}
|
||||
title={`Delete profile ${profileId}`}
|
||||
>
|
||||
<Text size="B300">Delete</Text>
|
||||
<Text size="B300">Delete persona</Text>
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
@@ -386,6 +677,9 @@ export function PerMessageProfileEditor({
|
||||
<Text size="B300">Save</Text>
|
||||
</Button>
|
||||
</Box>
|
||||
|
||||
<Text size="L400">Shorthands</Text>
|
||||
<ShorthandEditor mx={mx} profileId={profileId} />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,110 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { parsePerMessageProfileProxyAssociation } from './usePerMessageProfile';
|
||||
import {
|
||||
extractCircumfixProxyTagsFromKey,
|
||||
parsePerMessageProfileProxyAssociation,
|
||||
migratePmpProxyAssociation,
|
||||
type PerMessageProfileProxyAssociationV2,
|
||||
type PerMessageProfileProxyAssociationV1,
|
||||
proxyNeedsMigration,
|
||||
createProxyKey,
|
||||
} from './usePerMessageProfile';
|
||||
|
||||
describe('migratePerMessageProfileProxyAssociation', () => {
|
||||
it('turns a key into a prefix', () => {
|
||||
const key = 'j;text';
|
||||
const migrated = extractCircumfixProxyTagsFromKey(key);
|
||||
|
||||
expect(migrated).toStrictEqual({ prefix: 'j;', suffix: undefined });
|
||||
});
|
||||
it('turns a key into a suffix', () => {
|
||||
const key = 'text-J';
|
||||
const migrated = extractCircumfixProxyTagsFromKey(key);
|
||||
|
||||
expect(migrated).toStrictEqual({ prefix: undefined, suffix: '-J' });
|
||||
});
|
||||
it('turns a key into a circumfix', () => {
|
||||
const key = '[text]';
|
||||
const migrated = extractCircumfixProxyTagsFromKey(key);
|
||||
|
||||
expect(migrated).toStrictEqual({ prefix: '[', suffix: ']' });
|
||||
});
|
||||
it('testing whitespace in proxy tags', () => {
|
||||
const key = 'J: text -J';
|
||||
const migrated = extractCircumfixProxyTagsFromKey(key);
|
||||
|
||||
expect(migrated).toStrictEqual({ prefix: 'J: ', suffix: ' -J' });
|
||||
});
|
||||
it('atypical proxy tag format 1', () => {
|
||||
const key = '_text -j';
|
||||
const migrated = extractCircumfixProxyTagsFromKey(key);
|
||||
|
||||
expect(migrated).toStrictEqual({ prefix: '_', suffix: ' -j' });
|
||||
});
|
||||
|
||||
it('noop migration', () => {
|
||||
const v2: PerMessageProfileProxyAssociationV2 = {
|
||||
profileId: 'foo',
|
||||
prefix: '[',
|
||||
suffix: ']',
|
||||
};
|
||||
const migrated = migratePmpProxyAssociation('[text]', v2);
|
||||
|
||||
expect(migrated).toStrictEqual(v2);
|
||||
});
|
||||
|
||||
it('simple migration', () => {
|
||||
const v1: PerMessageProfileProxyAssociationV1 = {
|
||||
profileId: 'foo',
|
||||
regexString: 'bar',
|
||||
};
|
||||
const migrated = migratePmpProxyAssociation('[text]', v1);
|
||||
|
||||
expect(migrated).toStrictEqual({
|
||||
profileId: 'foo',
|
||||
prefix: '[',
|
||||
suffix: ']',
|
||||
});
|
||||
});
|
||||
|
||||
it('needsMigration positive test', () => {
|
||||
const v1: PerMessageProfileProxyAssociationV1 = {
|
||||
profileId: 'foo',
|
||||
regexString: 'bar',
|
||||
};
|
||||
const checked = proxyNeedsMigration(v1);
|
||||
|
||||
expect(checked).toBe(true);
|
||||
});
|
||||
|
||||
it('needsMigration negative test', () => {
|
||||
const v2: PerMessageProfileProxyAssociationV2 = {
|
||||
profileId: 'foo',
|
||||
prefix: '[',
|
||||
suffix: ']',
|
||||
};
|
||||
const checked = proxyNeedsMigration(v2);
|
||||
|
||||
expect(checked).toBe(false);
|
||||
});
|
||||
|
||||
it('create prefix proxy key', () => {
|
||||
const key = createProxyKey('j;', undefined);
|
||||
expect(key).toBe('j;text');
|
||||
});
|
||||
it('create suffix proxy key', () => {
|
||||
const key = createProxyKey(undefined, '-J');
|
||||
expect(key).toBe('text-J');
|
||||
});
|
||||
it('create circumfix proxy key', () => {
|
||||
const key = createProxyKey('[', ']');
|
||||
expect(key).toBe('[text]');
|
||||
});
|
||||
it('check proxy key does not do falsy stuff', () => {
|
||||
const key = createProxyKey('false', '0');
|
||||
expect(key).toBe('falsetext0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('parsePerMessageProfileProxyAssociation', () => {
|
||||
it('parses a regex string with flags (RegExp#toString form)', () => {
|
||||
|
||||
@@ -121,25 +121,49 @@ type PerMessageProfileRoomAssociation = {
|
||||
validUntil?: number;
|
||||
};
|
||||
|
||||
type ProxyVariation =
|
||||
| { prefix: string; suffix: undefined }
|
||||
| { prefix: undefined; suffix: string }
|
||||
| { prefix: string; suffix: string };
|
||||
|
||||
/**
|
||||
* associating a profile by proxy
|
||||
* @author Rye
|
||||
* Deprecated in favor of {@link PerMessageProfileProxyAssociationV2}, kept for migration purposes
|
||||
*/
|
||||
export type PerMessageProfileProxyAssociation = {
|
||||
export type PerMessageProfileProxyAssociationV1 = {
|
||||
profileId: string;
|
||||
/**
|
||||
* @deprecated regex (string representation of it) to handle the proxy
|
||||
*/
|
||||
regexString: string;
|
||||
setAt?: number;
|
||||
};
|
||||
|
||||
export type PerMessageProfileProxyAssociationV2 = {
|
||||
/**
|
||||
* the profile associated with the proxy
|
||||
*/
|
||||
profileId: string;
|
||||
/**
|
||||
* regex (string representation of it) to handle the proxy
|
||||
*/
|
||||
regexString: string;
|
||||
|
||||
/**
|
||||
* optional parameter to save when the proxy was added
|
||||
*/
|
||||
setAt?: number;
|
||||
|
||||
prefix: string | undefined;
|
||||
suffix: string | undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* associating a profile by proxy
|
||||
* @author Rye
|
||||
*/
|
||||
export type PerMessageProfileProxyAssociation =
|
||||
| PerMessageProfileProxyAssociationV1
|
||||
| PerMessageProfileProxyAssociationV2;
|
||||
|
||||
/**
|
||||
* @deprecated in favor of {@link PerMessageProfileProxyAssociationV2}
|
||||
*/
|
||||
export type InternalPerMessageProfileProxyAssociation = {
|
||||
/**
|
||||
* the profile associated with the proxy
|
||||
@@ -155,8 +179,59 @@ export type InternalPerMessageProfileProxyAssociation = {
|
||||
setAt?: number;
|
||||
};
|
||||
|
||||
export function parsePerMessageProfileProxyAssociation(
|
||||
/**
|
||||
* Used to migrate old format proxy tags to new format.
|
||||
* @author Josie F0rest
|
||||
*/
|
||||
export function extractCircumfixProxyTagsFromKey(proxyId: string): ProxyVariation | null {
|
||||
const [prefix, suffix] = proxyId.split('text');
|
||||
|
||||
/*
|
||||
i tried to do this a smart unpacking way but tsc did not like it. sorry for if-else spam.
|
||||
feel free to clean this up if you can pass tsc
|
||||
*/
|
||||
if (!prefix && !suffix) {
|
||||
return null;
|
||||
} else if (prefix && !suffix) {
|
||||
return { prefix, suffix: undefined };
|
||||
} else if (!prefix && suffix) {
|
||||
return { prefix: undefined, suffix };
|
||||
} else {
|
||||
return { prefix: prefix!, suffix: suffix! };
|
||||
}
|
||||
}
|
||||
|
||||
export function createProxyKey(prefix: string | undefined, suffix: string | undefined) {
|
||||
return `${prefix || ''}text${suffix || ''}`;
|
||||
}
|
||||
|
||||
export function proxyNeedsMigration(assoc: PerMessageProfileProxyAssociation) {
|
||||
return (assoc as PerMessageProfileProxyAssociationV1).regexString !== undefined;
|
||||
}
|
||||
|
||||
export function migratePmpProxyAssociation(
|
||||
proxyId: string,
|
||||
assoc: PerMessageProfileProxyAssociation
|
||||
): PerMessageProfileProxyAssociationV2 | null {
|
||||
/* detect old proxy association */
|
||||
if ((assoc as PerMessageProfileProxyAssociationV1).regexString) {
|
||||
const fixes = extractCircumfixProxyTagsFromKey(proxyId);
|
||||
if (!fixes) return null;
|
||||
return {
|
||||
profileId: assoc.profileId,
|
||||
...(assoc.setAt && { setAt: assoc.setAt! }),
|
||||
...fixes,
|
||||
};
|
||||
} else {
|
||||
return assoc as PerMessageProfileProxyAssociationV2;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated in favor of {@link PerMessageProfileProxyAssociationV2}
|
||||
*/
|
||||
export function parsePerMessageProfileProxyAssociation(
|
||||
assoc: PerMessageProfileProxyAssociationV1
|
||||
): InternalPerMessageProfileProxyAssociation {
|
||||
const m = assoc.regexString.match(/^\/([\s\S]*)\/([gimsuy]*)$/);
|
||||
const source = m?.[1] ?? assoc.regexString;
|
||||
@@ -292,7 +367,7 @@ export async function getAllPerMessageProfiles(mx: MatrixClient): Promise<PerMes
|
||||
* @param profile the profile to add/update
|
||||
* @returns void
|
||||
*/
|
||||
export function addOrUpdatePerMessageProfile(mx: MatrixClient, profile: PerMessageProfile) {
|
||||
export async function addOrUpdatePerMessageProfile(mx: MatrixClient, profile: PerMessageProfile) {
|
||||
const profileListIndex = mx.getAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.index` as Parameters<typeof mx.getAccountData>[0]
|
||||
);
|
||||
@@ -304,13 +379,13 @@ export function addOrUpdatePerMessageProfile(mx: MatrixClient, profile: PerMessa
|
||||
} satisfies AccountDataCompatVersion,
|
||||
} satisfies PerMessageProfile;
|
||||
if (profileListIndex?.getContent()?.profileIds.includes(profile.id)) {
|
||||
return mx.setAccountData(
|
||||
return await mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.${profile.id}` as Parameters<typeof mx.setAccountData>[0],
|
||||
profileWithCompat as Parameters<typeof mx.setAccountData>[1]
|
||||
);
|
||||
}
|
||||
const newProfileIds = [...(profileListIndex?.getContent()?.profileIds || []), profile.id];
|
||||
return Promise.all([
|
||||
return await Promise.all([
|
||||
mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.index` as Parameters<typeof mx.setAccountData>[0],
|
||||
{ profileIds: newProfileIds } as Parameters<typeof mx.setAccountData>[1]
|
||||
@@ -437,10 +512,12 @@ export async function setCurrentlyUsedPerMessageProfileIdForAccount(
|
||||
export async function associateProxyWithProfile(
|
||||
mx: MatrixClient,
|
||||
profileId: string | undefined,
|
||||
proxy: string,
|
||||
proxyRegExp: RegExp,
|
||||
prefix: string | undefined,
|
||||
suffix: string | undefined,
|
||||
reset: boolean
|
||||
) {
|
||||
if (!(prefix || suffix)) throw new Error('Proxy must have either a prefix, suffix, or both.');
|
||||
|
||||
const associations = getProxyAssociationMap(
|
||||
mx
|
||||
.getAccountData(
|
||||
@@ -449,15 +526,18 @@ export async function associateProxyWithProfile(
|
||||
?.getContent()
|
||||
);
|
||||
|
||||
const proxy = createProxyKey(prefix, suffix);
|
||||
|
||||
if (reset) associations.delete(proxy);
|
||||
|
||||
if (!profileId) throw new Error('profileId might not be undefined');
|
||||
if (profileId)
|
||||
associations.set(proxy, {
|
||||
profileId,
|
||||
regexString: proxyRegExp.toString(),
|
||||
} satisfies PerMessageProfileProxyAssociation);
|
||||
mx.setAccountData(
|
||||
prefix,
|
||||
suffix,
|
||||
} satisfies PerMessageProfileProxyAssociationV2);
|
||||
await mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters<typeof mx.setAccountData>[0],
|
||||
{ associations: proxyAssociationsMapToObject(associations) } as Parameters<
|
||||
typeof mx.setAccountData
|
||||
@@ -474,7 +554,7 @@ export async function associateProxyWithProfile(
|
||||
*/
|
||||
export async function getAllPerMessageProfileProxies(
|
||||
mx: MatrixClient
|
||||
): Promise<PerMessageProfileProxyAssociation[]> {
|
||||
): Promise<PerMessageProfileProxyAssociationV2[]> {
|
||||
const cont: PerMessageProfileProxyAssociationWrapper | undefined = mx
|
||||
.getAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters<typeof mx.getAccountData>[0]
|
||||
@@ -482,8 +562,50 @@ export async function getAllPerMessageProfileProxies(
|
||||
?.getContent();
|
||||
if (!cont) return [];
|
||||
const pmap = getProxyAssociationMap(cont);
|
||||
const parr = new Array<PerMessageProfileProxyAssociation>();
|
||||
pmap.values().forEach((v) => parr.push(v));
|
||||
const parr = new Array<PerMessageProfileProxyAssociationV2>();
|
||||
let needsMigration = false;
|
||||
pmap.entries().forEach(([k, v]) => {
|
||||
if (proxyNeedsMigration(v)) {
|
||||
needsMigration = true;
|
||||
v = migratePmpProxyAssociation(k, v) ?? v;
|
||||
}
|
||||
return parr.push(v as PerMessageProfileProxyAssociationV2);
|
||||
});
|
||||
|
||||
if (needsMigration) {
|
||||
const newPmap = new Map(
|
||||
pmap.entries().map(([k, v]) => [k, migratePmpProxyAssociation(k, v) ?? v])
|
||||
);
|
||||
|
||||
await mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters<typeof mx.setAccountData>[0],
|
||||
{ associations: proxyAssociationsMapToObject(newPmap) } as Parameters<
|
||||
typeof mx.setAccountData
|
||||
>[1]
|
||||
);
|
||||
}
|
||||
|
||||
return parr;
|
||||
}
|
||||
|
||||
export async function getAllProxiesForPMP(
|
||||
mx: MatrixClient,
|
||||
profileId: string
|
||||
): Promise<PerMessageProfileProxyAssociationV2[]> {
|
||||
const cont: PerMessageProfileProxyAssociationWrapper | undefined = mx
|
||||
.getAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters<typeof mx.getAccountData>[0]
|
||||
)
|
||||
?.getContent();
|
||||
if (!cont) return [];
|
||||
|
||||
const pmap = getProxyAssociationMap(cont);
|
||||
const parr = new Array<PerMessageProfileProxyAssociationV2>();
|
||||
pmap
|
||||
.entries()
|
||||
/* oxlint-disable no-unused-vars */
|
||||
.filter(([_k, v]) => v.profileId === profileId)
|
||||
.forEach(([k, v]) => parr.push(migratePmpProxyAssociation(k, v)!));
|
||||
return parr;
|
||||
}
|
||||
|
||||
@@ -497,7 +619,7 @@ export async function dropProxyAssociationForPMP(mx: MatrixClient, proxy: string
|
||||
);
|
||||
if (!associations) return;
|
||||
associations.delete(proxy);
|
||||
mx.setAccountData(
|
||||
await mx.setAccountData(
|
||||
`${ACCOUNT_DATA_PREFIX}.proxyassociation` as Parameters<typeof mx.setAccountData>[0],
|
||||
{ associations: proxyAssociationsMapToObject(associations) } as Parameters<
|
||||
typeof mx.setAccountData
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { PerMessageProfile } from '$hooks/usePerMessageProfile';
|
||||
import type {
|
||||
PerMessageProfile,
|
||||
PerMessageProfileProxyAssociationV2,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import {
|
||||
addOrUpdatePerMessageProfile,
|
||||
associateProxyWithProfile,
|
||||
dropProxyAssociationForPMP,
|
||||
extractCircumfixProxyTagsFromKey,
|
||||
getAllPerMessageProfiles,
|
||||
getPerMessageProfileById,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
@@ -27,22 +31,42 @@ function regexEscapeFallBackFunc(template: string): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated
|
||||
* build a regex to recognize proxies
|
||||
* a template can be for example `[text]` or `f:text`
|
||||
*
|
||||
* @param {string} template
|
||||
* @return {*} {RegExp}
|
||||
*/
|
||||
function buildRegex(template: string): RegExp {
|
||||
const [before = '', after = ''] = template.split('text');
|
||||
export function buildProxyRegex({ prefix, suffix }: PerMessageProfileProxyAssociationV2): RegExp {
|
||||
const escape = (s: string) =>
|
||||
// @ts-ignore TS2339 - RegExp.escape is a new/proposed method
|
||||
typeof RegExp.escape === 'function' ? RegExp.escape(s) : regexEscapeFallBackFunc(s);
|
||||
|
||||
const pattern = `${escape(before)}(.+)${escape(after)}`;
|
||||
const pattern = `${escape(prefix ?? '')}(.+)${escape(suffix ?? '')}`;
|
||||
return new RegExp(`^${pattern}$`);
|
||||
}
|
||||
|
||||
export function testProxy(
|
||||
{ prefix, suffix }: PerMessageProfileProxyAssociationV2,
|
||||
input: string
|
||||
): boolean {
|
||||
const matchesPrefix = prefix ? input.startsWith(prefix) : true;
|
||||
const matchesSuffix = suffix ? input.endsWith(suffix) : true;
|
||||
|
||||
return matchesPrefix && matchesSuffix;
|
||||
}
|
||||
export function stripProxy(
|
||||
{ prefix, suffix }: PerMessageProfileProxyAssociationV2,
|
||||
input: string
|
||||
): string {
|
||||
let message = input;
|
||||
if (prefix) message = message.slice(prefix.length);
|
||||
if (suffix) message = message.slice(0, message.length - suffix.length);
|
||||
|
||||
return message;
|
||||
}
|
||||
|
||||
/**
|
||||
* a class to use as PluralKit command message handler
|
||||
*
|
||||
@@ -229,8 +253,17 @@ export class PKitCommandMessageHandler {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const matchAgainstRegExp = buildRegex(matchAgainst);
|
||||
await associateProxyWithProfile(this.mx, pmpId, matchAgainst, matchAgainstRegExp, false);
|
||||
const proxyTags = extractCircumfixProxyTagsFromKey(matchAgainst);
|
||||
|
||||
if (!proxyTags) {
|
||||
sendFeedback(
|
||||
`malformed input: could not find a prefix and/or suffix, ${helpTextPkMemberNewProxy}`,
|
||||
this.room,
|
||||
this.mx.getSafeUserId()
|
||||
);
|
||||
return;
|
||||
}
|
||||
await associateProxyWithProfile(this.mx, pmpId, proxyTags.prefix, proxyTags.suffix, false);
|
||||
sendFeedback(
|
||||
`Persona with ${this.useIdInsteadOfNameWherePossible ? 'id' : 'name'} "${name}" (${pmpId}) is now associated with ${matchAgainst}`,
|
||||
this.room,
|
||||
|
||||
@@ -24,15 +24,9 @@ describe('PKitProxyMessageHandler', () => {
|
||||
});
|
||||
|
||||
it('matches a proxied message, returns pmp, and strips content', async () => {
|
||||
const proxyRegex = /^\[(.+)\]$/;
|
||||
|
||||
(mocked.getAllPerMessageProfileProxies as unknown as Mock).mockResolvedValueOnce([
|
||||
{ profileId: 'p1', regexString: proxyRegex.toString() },
|
||||
{ profileId: 'p1', prefix: '[', suffix: ']' },
|
||||
]);
|
||||
(mocked.parsePerMessageProfileProxyAssociation as unknown as Mock).mockReturnValueOnce({
|
||||
profileId: 'p1',
|
||||
regex: proxyRegex,
|
||||
});
|
||||
(mocked.getPerMessageProfileById as unknown as Mock).mockResolvedValueOnce({
|
||||
id: 'p1',
|
||||
name: 'Test',
|
||||
@@ -46,5 +40,8 @@ describe('PKitProxyMessageHandler', () => {
|
||||
// getPmpBasedOnMessage refreshes/init() so we should be inited now
|
||||
expect(handler.isAProxiedMessage('[hello]')).toBe(true);
|
||||
expect(handler.stripProxyFromMessage('[hello]')).toBe('hello');
|
||||
|
||||
expect(handler.isAProxiedMessage('[hello\nworld]')).toBe(true);
|
||||
expect(handler.stripProxyFromMessage('[hello\nworld]')).toBe('hello\nworld');
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,13 @@
|
||||
import type {
|
||||
InternalPerMessageProfileProxyAssociation,
|
||||
PerMessageProfile,
|
||||
PerMessageProfileProxyAssociationV2,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import {
|
||||
getAllPerMessageProfileProxies,
|
||||
getPerMessageProfileById,
|
||||
parsePerMessageProfileProxyAssociation,
|
||||
} from '$hooks/usePerMessageProfile';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { stripProxy, testProxy } from './PKitCommandMessageHandler';
|
||||
|
||||
/**
|
||||
* proxy message handler
|
||||
@@ -29,7 +29,7 @@ export class PKitProxyMessageHandler {
|
||||
* @type {PerMessageProfileProxyAssociation[]}
|
||||
* @memberof PKitProxyMessageHandler
|
||||
*/
|
||||
private proxiesAssocs: InternalPerMessageProfileProxyAssociation[];
|
||||
private proxiesAssocs: PerMessageProfileProxyAssociationV2[];
|
||||
|
||||
private succInit: boolean;
|
||||
|
||||
@@ -48,9 +48,7 @@ export class PKitProxyMessageHandler {
|
||||
*/
|
||||
public async init(): Promise<void> {
|
||||
try {
|
||||
this.proxiesAssocs = (await getAllPerMessageProfileProxies(this.mx)).map((p) =>
|
||||
parsePerMessageProfileProxyAssociation(p)
|
||||
);
|
||||
this.proxiesAssocs = await getAllPerMessageProfileProxies(this.mx);
|
||||
this.succInit = true;
|
||||
} catch (err) {
|
||||
this.succInit = false;
|
||||
@@ -66,7 +64,7 @@ export class PKitProxyMessageHandler {
|
||||
*/
|
||||
public isAProxiedMessage(message: string): boolean {
|
||||
if (!this.succInit) return false;
|
||||
return this.proxiesAssocs.some((assoc) => assoc.regex.test(message));
|
||||
return this.proxiesAssocs.some((assoc) => testProxy(assoc, message));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,8 +76,7 @@ export class PKitProxyMessageHandler {
|
||||
// Always refresh so newly-added proxies apply immediately.
|
||||
await this.init();
|
||||
// check if the message matches our formats
|
||||
// maybe a bit unsafe, as we are evaluating regex that aren't necessarily by us, could be _maybe_ manipulated
|
||||
const profileId = this.proxiesAssocs.find((assoc) => assoc.regex.test(message))?.profileId;
|
||||
const profileId = this.proxiesAssocs.find((assoc) => testProxy(assoc, message))?.profileId;
|
||||
if (!profileId) return undefined;
|
||||
return getPerMessageProfileById(this.mx, profileId);
|
||||
}
|
||||
@@ -95,8 +92,7 @@ export class PKitProxyMessageHandler {
|
||||
if (!this.succInit) return undefined;
|
||||
let m;
|
||||
this.proxiesAssocs.forEach((assoc) => {
|
||||
const match = assoc.regex.exec(message);
|
||||
if (match?.at(1)) m = match.at(1);
|
||||
if (testProxy(assoc, message)) m = stripProxy(assoc, message);
|
||||
});
|
||||
return m;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user