Merge commit '46108ecfe18f53e8a989aa36e9397914f6bc0108' into glitch-soc/merge-4.6

This commit is contained in:
Claire committed 2026-06-24 17:27:19 +02:00
commit 3083fdad1f
20 files changed
+603 -159

No files matched your search

@@ -24,7 +24,6 @@ import {
import {
Article,
ItemList,
Scrollable,
} from 'mastodon/components/scrollable_list/components';
import { useAccount } from 'mastodon/hooks/useAccount';
import { useSearchAccounts } from 'mastodon/hooks/useSearchAccounts';
@@ -417,43 +416,42 @@ export const CollectionAccounts: React.FC<{
</AccountsHeadingElement>
)}
<Scrollable className={classes.scrollableWrapper}>
<ItemList
emptyMessage={
<EmptyState
title={
<FormattedMessage
id='collections.accounts.empty_editor_title'
defaultMessage='No one is in this collection yet'
/>
}
message={
<FormattedMessage
id='collections.accounts.empty_description'
defaultMessage='Add up to {count} accounts'
values={{
count: MAX_COLLECTION_ACCOUNT_COUNT,
}}
/>
}
/>
}
>
{editorItems.map(({ account_id, state }, index) => (
<Article
key={account_id}
aria-posinset={index}
aria-setsize={editorItems.length}
>
<AddedAccountItem
accountId={account_id}
pending={state === 'pending'}
onRemove={handleRemoveAccountItem}
<ItemList
className={classes.accountList}
emptyMessage={
<EmptyState
title={
<FormattedMessage
id='collections.accounts.empty_editor_title'
defaultMessage='No one is in this collection yet'
/>
</Article>
))}
</ItemList>
</Scrollable>
}
message={
<FormattedMessage
id='collections.accounts.empty_description'
defaultMessage='Add up to {count} accounts'
values={{
count: MAX_COLLECTION_ACCOUNT_COUNT,
}}
/>
}
/>
}
>
{editorItems.map(({ account_id, state }, index) => (
<Article
key={account_id}
aria-posinset={index}
aria-setsize={editorItems.length}
>
<AddedAccountItem
accountId={account_id}
pending={state === 'pending'}
onRemove={handleRemoveAccountItem}
/>
</Article>
))}
</ItemList>
</div>
</FormStack>
{!isEditMode && hasItems && (
@@ -55,7 +55,7 @@
gap: 16px;
}
.scrollableWrapper {
.accountList {
margin-inline: -16px;
}
@@ -26,8 +26,8 @@ export const EMOJI_TYPE_UNICODE = 'unicode';
export const EMOJI_TYPE_CUSTOM = 'custom';
export const EMOJI_DB_NAME_SHORTCODES = 'shortcodes';
export const EMOJI_DB_SHORTCODE_TEST = '2122'; // 2122 is the trademark sign, which we know has shortcodes in all datasets.
export const EMOJI_DB_RELOAD_EVENT = 'emojiDbReload';
export const EMOJIS_WITH_DARK_BORDER = [
'🎱', // 1F3B1
@@ -2,6 +2,7 @@ import { SUPPORTED_LOCALES } from 'emojibase';
import type { CompactEmoji, Locale, ShortcodesDataset } from 'emojibase';
import type { ApiCustomEmojiJSON } from '@/mastodon/api_types/custom_emoji';
import { onceAsync } from '@/mastodon/utils/promises';
import { openEmojiDB } from './db-schema';
import type { Database } from './db-schema';
@@ -22,8 +23,6 @@ const log = emojiLogger('database');
// Loads the database in a way that ensures it's only loaded once.
const loadDB = (() => {
let dbPromise: Promise<Database> | null = null;
// Actually load the DB.
async function initDB() {
const db = await openEmojiDB();
@@ -32,17 +31,14 @@ const loadDB = (() => {
return db;
}
let dbPromise = onceAsync(initDB);
// Loads the database, or returns the existing promise if it hasn't resolved yet.
const loadPromise = async (): Promise<Database> => {
if (dbPromise) {
return dbPromise;
}
dbPromise = initDB();
return dbPromise;
};
const loadPromise = () => dbPromise();
// Special way to reset the database, used for unit testing.
loadPromise.reset = () => {
dbPromise = null;
dbPromise = onceAsync(initDB);
};
return loadPromise;
})();
@@ -335,13 +331,6 @@ export async function clearCache(key: CacheKey) {
log('Cleared cache for %s', key);
}
export async function resetDatabase() {
const db = await loadDB();
const storeNames = [...db.objectStoreNames];
await Promise.all(storeNames.map((storeName) => db.clear(storeName)));
log(storeNames, 'Reset emoji database stores:');
}
export async function loadEmojiByHexcode(
hexcode: string,
localeString: string,
@@ -0,0 +1,67 @@
import { IDBFactory } from 'fake-indexeddb';
import { EMOJI_DB_RELOAD_EVENT } from './constants';
import { openEmojiDB } from './db-schema';
describe('openEmojiDB', () => {
afterEach(() => {
indexedDB = new IDBFactory();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe('versionchange handler', () => {
test('dispatches reload event in main thread context', async () => {
const dispatchSpy = vi.fn();
window.addEventListener(EMOJI_DB_RELOAD_EVENT, dispatchSpy);
await openEmojiDB();
// Opening a higher version on the same IDBFactory triggers versionchange
// on all existing connections to that database.
indexedDB.open('mastodon-emoji', 9999);
await vi.waitFor(() => {
expect(dispatchSpy).toHaveBeenCalledOnce();
});
window.removeEventListener(EMOJI_DB_RELOAD_EVENT, dispatchSpy);
});
test('posts db-blocked message in worker context', async () => {
const postMessageSpy = vi.fn();
vi.stubGlobal('window', undefined);
vi.stubGlobal('self', { postMessage: postMessageSpy });
await openEmojiDB();
indexedDB.open('mastodon-emoji', 9999);
await vi.waitFor(() => {
expect(postMessageSpy).toHaveBeenCalledWith({ type: 'db-blocked' });
});
});
test('closes all open connections when versionchange fires', async () => {
const dispatchSpy = vi.fn();
window.addEventListener(EMOJI_DB_RELOAD_EVENT, dispatchSpy);
const db1 = await openEmojiDB();
const db2 = await openEmojiDB();
// Opening a higher version on the same IDBFactory triggers versionchange
// on all existing connections to that database.
indexedDB.open('mastodon-emoji', 9999);
await vi.waitFor(() => {
expect(dispatchSpy).toHaveBeenCalledTimes(2);
});
window.removeEventListener(EMOJI_DB_RELOAD_EVENT, dispatchSpy);
// Both connections should now be closed.
expect(() => db1.transaction('etags', 'readonly')).toThrow();
expect(() => db2.transaction('etags', 'readonly')).toThrow();
});
});
});
@@ -1,6 +1,6 @@
import { SUPPORTED_LOCALES } from 'emojibase';
import type { Locale } from 'emojibase';
import { openDB } from 'idb';
import { deleteDB, openDB } from 'idb';
import type {
DBSchema,
IDBPDatabase,
@@ -10,8 +10,13 @@ import type {
StoreNames,
} from 'idb';
import { resetDatabase } from './database';
import type { CustomEmojiData, CacheKey, UnicodeEmojiData } from './types';
import { EMOJI_DB_RELOAD_EVENT } from './constants';
import type {
CustomEmojiData,
CacheKey,
UnicodeEmojiData,
EmojiWorkerMessage,
} from './types';
import { emojiLogger } from './utils';
const log = emojiLogger('database');
@@ -58,72 +63,95 @@ type Transaction<Mode extends IDBTransactionMode = 'versionchange'> =
export type Database = IDBPDatabase<EmojiDB>;
const DATABASE_NAME = 'mastodon-emoji';
const SCHEMA_VERSION = 4;
export async function openEmojiDB() {
const db = await openDB<EmojiDB>('mastodon-emoji', SCHEMA_VERSION, {
upgrade(database, oldVersion, newVersion, trx) {
if (!database.objectStoreNames.contains('custom')) {
database.createObjectStore('custom', {
keyPath: 'shortcode',
autoIncrement: false,
});
}
maybeAddIndex({ trx, storeName: 'custom', indexName: 'category' });
maybeAddIndex({
trx,
storeName: 'custom',
indexName: 'tokens',
options: { multiEntry: true },
});
if (!database.objectStoreNames.contains('etags')) {
database.createObjectStore('etags');
}
SUPPORTED_LOCALES.forEach((locale) => {
createLocaleTable(locale, database, trx);
});
const shortcodeTable = database.objectStoreNames.contains('shortcodes')
? trx.objectStore('shortcodes')
: database.createObjectStore('shortcodes', {
keyPath: 'hexcode',
try {
const db = await openDB<EmojiDB>(DATABASE_NAME, SCHEMA_VERSION, {
upgrade(database, oldVersion, newVersion, trx) {
if (!database.objectStoreNames.contains('custom')) {
database.createObjectStore('custom', {
keyPath: 'shortcode',
autoIncrement: false,
});
maybeAddIndex({
trx,
storeName: 'shortcodes',
indexName: 'shortcodes',
options: { multiEntry: true },
});
deleteOldIndexes(shortcodeTable, ['hexcode']);
}
maybeAddIndex({ trx, storeName: 'custom', indexName: 'category' });
maybeAddIndex({
trx,
storeName: 'custom',
indexName: 'tokens',
options: { multiEntry: true },
});
void resetDatabase();
if (!database.objectStoreNames.contains('etags')) {
database.createObjectStore('etags');
}
log(
'Upgraded emoji database from version %d to %d',
oldVersion,
newVersion,
);
},
blocked(currentVersion, blockedVersion) {
log(
'Emoji database upgrade from version %d to %d is blocked',
currentVersion,
blockedVersion,
);
},
blocking(currentVersion, blockedVersion) {
log(
'Emoji database upgrade from version %d is blocking upgrade to %d',
currentVersion,
blockedVersion,
);
},
});
SUPPORTED_LOCALES.forEach((locale) => {
createLocaleTable(locale, database, trx);
});
return db;
const shortcodeTable = database.objectStoreNames.contains('shortcodes')
? trx.objectStore('shortcodes')
: database.createObjectStore('shortcodes', {
keyPath: 'hexcode',
autoIncrement: false,
});
maybeAddIndex({
trx,
storeName: 'shortcodes',
indexName: 'shortcodes',
options: { multiEntry: true },
});
deleteOldIndexes(shortcodeTable, ['hexcode']);
// Reset all database stores.
for (const storeName of database.objectStoreNames) {
void trx.objectStore(storeName).clear();
}
log(
'Upgraded emoji database from version %d to %d',
oldVersion,
newVersion,
);
},
blocked(currentVersion, blockedVersion) {
log(
'Emoji database upgrade from version %d to %d is blocked',
currentVersion,
blockedVersion,
);
},
blocking(currentVersion, blockedVersion) {
log(
'Emoji database upgrade from version %d is blocking upgrade to %d, closing connection',
currentVersion,
blockedVersion,
);
// Close the database connection immediately.
db.close();
if (typeof window !== 'undefined') {
window.dispatchEvent(new Event(EMOJI_DB_RELOAD_EVENT));
} else {
self.postMessage({ type: 'db-blocked' } satisfies EmojiWorkerMessage);
}
},
});
return db;
} catch (error) {
if (error instanceof DOMException && error.name === 'VersionError') {
log(
'Emoji database version is newer than expected, deleting and recreating',
);
await deleteDB(DATABASE_NAME);
return openEmojiDB();
}
throw error;
}
}
function maybeAddIndex<StoreName extends StoreNames<EmojiDB>>({
@@ -1,5 +1,6 @@
import { initialState } from '@/mastodon/initial_state';
import { EMOJI_DB_RELOAD_EVENT } from './constants';
import { toSupportedLocale } from './locale';
import type { EmojiWorkerMessage } from './types';
import { emojiLogger } from './utils';
@@ -14,6 +15,12 @@ const workerLog = emojiLogger('worker');
// This is too short, but better to fallback quickly than wait.
const WORKER_TIMEOUT = 2_000;
// Handle reload events
window.addEventListener(
EMOJI_DB_RELOAD_EVENT,
() => void handleEmojiDbReload(),
);
export async function initializeEmoji() {
log('initializing emojis');
@@ -51,6 +58,8 @@ export async function initializeEmoji() {
workerLog(message.message);
} else if (type === 'done' && message.storeName === 'custom') {
void loadEmojisToStore();
} else if (type === 'db-blocked') {
window.dispatchEvent(new Event(EMOJI_DB_RELOAD_EVENT));
}
if (type !== 'ready') {
@@ -131,3 +140,10 @@ async function loadEmojisToStore() {
log('loaded emoji data into store');
}
async function handleEmojiDbReload() {
log('Emoji database reload needed, triggering warning');
const { store } = await import('@/mastodon/store');
const { needsReload } = await import('@/mastodon/actions/app');
store.dispatch(needsReload());
}
@@ -1,6 +1,8 @@
import { joinShortcodes } from 'emojibase';
import type { CompactEmoji, Locale, ShortcodesDataset } from 'emojibase';
import { onceAsyncByArgs } from '@/mastodon/utils/promises';
import {
putEmojiData,
putCustomEmojiData,
@@ -17,6 +19,12 @@ const log = emojiLogger('loader');
export async function importEmojiData(localeString: string, shortcodes = true) {
const locale = toSupportedLocale(localeString);
return importEmojiDataOnce(locale, shortcodes);
}
const importEmojiDataOnce = onceAsyncByArgs(importEmojiDataImpl);
async function importEmojiDataImpl(locale: Locale, shortcodes: boolean) {
log(
'importing emoji data for locale %s%s',
locale,
@@ -171,9 +179,7 @@ async function fetchAndCheckEtag({
// Use location.origin as this script may be loaded from a CDN domain.
const url = new URL(path, location.origin);
const response = await fetch(url, {
headers,
});
const response = await fetch(url, { headers });
// If not modified, return null
if (response.status === 304) {
@@ -82,6 +82,7 @@ export type ExtraCustomEmojiMap = Record<
export type EmojiWorkerMessage =
| { type: 'ready' }
| { type: 'db-blocked' }
| {
type: 'load';
storeName: string;
@@ -47,11 +47,9 @@ interface MediaModalProps {
}
const MIN_SWIPE_DISTANCE = 400;
const isLtrDir = getComputedStyle(document.body).direction !== 'rtl';
export const MediaModal: FC<MediaModalProps> = forwardRef<
HTMLDivElement,
MediaModalProps
>(
export const MediaModal = forwardRef<HTMLDivElement, MediaModalProps>(
(
{
media,
@@ -64,15 +62,16 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
statusId,
onChangeBackgroundColor,
},
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- _ref is required to keep the ref forwarding working
_ref,
) => {
const [index, setIndex] = useState(startIndex);
const [zoomedIn, setZoomedIn] = useState(false);
const currentMedia = media.get(index);
const sign = isLtrDir ? '-' : '';
const [wrapperStyles, api] = useSpring(() => ({
x: `-${index * 100}%`,
x: `${sign}${index * 100}%`,
}));
const handleChangeIndex = useCallback(
@@ -85,10 +84,12 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
setIndex(newIndex);
setZoomedIn(false);
if (animate) {
void api.start({ x: `calc(-${newIndex * 100}% + 0px)` });
void api.start({
x: `calc(${sign}${newIndex * 100}% + 0px)`,
});
}
},
[api, media.size],
[api, media.size, sign],
);
const handlePrevClick = useCallback(() => {
handleChangeIndex(index - 1, true);
@@ -99,11 +100,14 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
const handleKeyDown = useCallback(
(event: KeyboardEvent) => {
if (event.key === 'ArrowLeft') {
const prevKey = isLtrDir ? 'ArrowLeft' : 'ArrowRight';
const nextKey = isLtrDir ? 'ArrowRight' : 'ArrowLeft';
if (event.key === prevKey) {
handlePrevClick();
event.preventDefault();
event.stopPropagation();
} else if (event.key === 'ArrowRight') {
} else if (event.key === nextKey) {
handleNextClick();
event.preventDefault();
event.stopPropagation();
@@ -124,13 +128,14 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
active &&
Math.abs(mx) > Math.min(window.innerWidth / 4, MIN_SWIPE_DISTANCE)
) {
handleChangeIndex(index - xDir);
handleChangeIndex(isLtrDir ? index - xDir : index + xDir);
cancel();
}
// Set the x position via calc to ensure proper centering regardless of screen size.
const x = active ? mx : 0;
const operator = isLtrDir ? '+' : '-';
void api.start({
x: `calc(-${index * 100}% + ${x}px)`,
x: `calc(${sign}${index * 100}% ${operator} ${x}px)`,
});
},
{ pointer: { capture: false } },
@@ -161,14 +166,23 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
width: number;
height: number;
}>({ width: 0, height: 0 });
const handleRef: RefCallback<HTMLDivElement> = useCallback((ele) => {
if (ele?.clientWidth && ele.clientHeight) {
setViewportDimensions({
width: ele.clientWidth,
height: ele.clientHeight,
});
}
}, []);
const handleRef: RefCallback<HTMLDivElement> = useCallback(
(ele) => {
if (typeof _ref === 'function') {
_ref(ele);
} else if (_ref) {
_ref.current = ele;
}
if (ele?.clientWidth && ele.clientHeight) {
setViewportDimensions({
width: ele.clientWidth,
height: ele.clientHeight,
});
}
},
[_ref],
);
const zoomable =
currentMedia?.get('type') === 'image' &&
@@ -268,9 +282,8 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
const intl = useIntl();
const leftNav = media.size > 1 && (
const prevNav = media.size > 1 && (
<button
tabIndex={0}
className='media-modal__nav media-modal__nav--prev'
onClick={handlePrevClick}
aria-label={intl.formatMessage(messages.previous)}
@@ -279,9 +292,8 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
<Icon id='chevron-left' icon={ChevronLeftIcon} />
</button>
);
const rightNav = media.size > 1 && (
const nextNav = media.size > 1 && (
<button
tabIndex={0}
className='media-modal__nav media-modal__nav--next'
onClick={handleNextClick}
aria-label={intl.formatMessage(messages.next)}
@@ -330,8 +342,8 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
/>
</div>
{leftNav}
{rightNav}
{prevNav}
{nextNav}
<div className='media-modal__overlay'>
<MediaPagination