Merge commit '46108ecfe18f53e8a989aa36e9397914f6bc0108' into glitch-soc/merge-4.6
This commit is contained in:
commit
3083fdad1f
29
CHANGELOG.md
29
CHANGELOG.md
@ -2,6 +2,35 @@
|
|||||||
|
|
||||||
All notable changes to this project will be documented in this file.
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
## [4.6.1] - 2026-06-24
|
||||||
|
|
||||||
|
### Security
|
||||||
|
|
||||||
|
- Update dependencies
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Add `avatar_description` and `header_description` to `/api/v1/accounts/update_credentials` (#39547 and #39574 by @ClearlyClaire and @mkljczk)
|
||||||
|
- This is available starting from Mastodon API version `11` and intended to provide an easier implementation path for clients implementing a similar feature in forks.
|
||||||
|
- The new `/api/v1/profile` API remains the recommended API for setting avatar and header description as well as other profile values.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- Fix combobox menu not closing after a selection (#39595 by @diondiondion)
|
||||||
|
- Fix Emoji IndexedDB upgrades when multiple tabs are open (#39576 by @ChaosExAnima)
|
||||||
|
- Fix combobox listbox not scrolling up when new suggestions have loaded (#39588 by @diondiondion)
|
||||||
|
- Fix media modal navigation in RTL languages (#39587 by @diondiondion)
|
||||||
|
- Fix accounts not visible in collection editor in advanced web interface (#39586 by @diondiondion)
|
||||||
|
- Fix error on login with certain LDAP configurations (#39571 by @oneiros)
|
||||||
|
- Fix simplified layout applying to other pages in web UI (#39570 by @Gargron)
|
||||||
|
- Fix emoji database loading in web worker (#39558 and #39562 by @ChaosExAnima)
|
||||||
|
- Fix display name length limit being incorrectly enforced in web UI (#39499 by @shleeable)
|
||||||
|
- Fix advanced UI columns not using mobile styles (#39528 by @diondiondion)
|
||||||
|
- Fix "private mention" post heading overlapping thread line (#39521 and #39554 by @diondiondion)
|
||||||
|
- Fix misattribution of remote featured collections in some cases (#39523, #39525, and #39550 by @oneiros)
|
||||||
|
- Fix custom profile field overflow (#39513 by @diondiondion)
|
||||||
|
- Fix fetching unknown key when it's not the actor's first, and add error handling for unavailable keys (#39512 by @ClearlyClaire)
|
||||||
|
|
||||||
## [4.6.0] - 2026-06-17
|
## [4.6.0] - 2026-06-17
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|||||||
@ -10,3 +10,5 @@ interface ChangeLayoutPayload {
|
|||||||
}
|
}
|
||||||
export const changeLayout =
|
export const changeLayout =
|
||||||
createAction<ChangeLayoutPayload>('APP_LAYOUT_CHANGE');
|
createAction<ChangeLayoutPayload>('APP_LAYOUT_CHANGE');
|
||||||
|
|
||||||
|
export const needsReload = createAction('APP_NEED_RELOAD');
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { useState, useEffect } from 'react';
|
import { useState, useEffect } from 'react';
|
||||||
|
|
||||||
import { useIntl } from 'react-intl';
|
import { defineMessage, useIntl } from 'react-intl';
|
||||||
import type { IntlShape } from 'react-intl';
|
import type { IntlShape } from 'react-intl';
|
||||||
|
|
||||||
import { dismissAlert } from 'mastodon/actions/alerts';
|
import { dismissAlert } from 'mastodon/actions/alerts';
|
||||||
@ -75,6 +75,9 @@ const TimedAlert: React.FC<{
|
|||||||
|
|
||||||
export const AlertsController: React.FC = () => {
|
export const AlertsController: React.FC = () => {
|
||||||
const alerts = useAppSelector((state) => state.alerts);
|
const alerts = useAppSelector((state) => state.alerts);
|
||||||
|
const needsReload = useAppSelector(
|
||||||
|
(state) => !!state.meta.get('needsReload'),
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<A11yLiveRegion className='notification-list'>
|
<A11yLiveRegion className='notification-list'>
|
||||||
@ -85,6 +88,18 @@ export const AlertsController: React.FC = () => {
|
|||||||
dismissAfter={5000 + idx * 1000}
|
dismissAfter={5000 + idx * 1000}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
|
{needsReload && <ReloadAlert />}
|
||||||
</A11yLiveRegion>
|
</A11yLiveRegion>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const reloadMessage = defineMessage({
|
||||||
|
id: 'alert.need_reload.message',
|
||||||
|
defaultMessage:
|
||||||
|
'Mastodon has been updated. Some things may not work correctly until you reload the page.',
|
||||||
|
});
|
||||||
|
|
||||||
|
const ReloadAlert: React.FC = () => {
|
||||||
|
const intl = useIntl();
|
||||||
|
return <Alert isActive message={intl.formatMessage(reloadMessage)} />;
|
||||||
|
};
|
||||||
|
|||||||
@ -3,6 +3,7 @@ import {
|
|||||||
forwardRef,
|
forwardRef,
|
||||||
useCallback,
|
useCallback,
|
||||||
useContext,
|
useContext,
|
||||||
|
useEffect,
|
||||||
useId,
|
useId,
|
||||||
useMemo,
|
useMemo,
|
||||||
useRef,
|
useRef,
|
||||||
@ -238,6 +239,11 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
|
|||||||
const inputRef = useRef<HTMLInputElement | null>();
|
const inputRef = useRef<HTMLInputElement | null>();
|
||||||
const popoverRef = useRef<HTMLDivElement>(null);
|
const popoverRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// This ref tracks whether the menu was just closed following a
|
||||||
|
// selection, and prevents the menu from re-opening again
|
||||||
|
// when focus is returned to the input.
|
||||||
|
const wasMenuJustClosedRef = useRef(false);
|
||||||
|
|
||||||
const [highlightedItemId, setHighlightedItemId] = useState<string | null>(
|
const [highlightedItemId, setHighlightedItemId] = useState<string | null>(
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
@ -276,12 +282,6 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
|
|||||||
setShouldMenuOpen(false);
|
setShouldMenuOpen(false);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const resetHighlight = useCallback(() => {
|
|
||||||
const firstItem = flatItems[0];
|
|
||||||
const firstItemId = firstItem ? getItemId(firstItem) : null;
|
|
||||||
setHighlightedItemId(firstItemId);
|
|
||||||
}, [getItemId, flatItems]);
|
|
||||||
|
|
||||||
const highlightItem = useCallback((id: string | null) => {
|
const highlightItem = useCallback((id: string | null) => {
|
||||||
setHighlightedItemId(id);
|
setHighlightedItemId(id);
|
||||||
if (id) {
|
if (id) {
|
||||||
@ -294,9 +294,22 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
|
|||||||
}
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const resetHighlight = useCallback(() => {
|
||||||
|
const firstItem = flatItems[0];
|
||||||
|
const firstItemId = firstItem ? getItemId(firstItem) : null;
|
||||||
|
highlightItem(firstItemId);
|
||||||
|
}, [flatItems, getItemId, highlightItem]);
|
||||||
|
|
||||||
|
// Reset scroll & highlight when menu items change
|
||||||
|
useEffect(() => {
|
||||||
|
if (flatItems.length) {
|
||||||
|
resetHighlight();
|
||||||
|
}
|
||||||
|
}, [flatItems, resetHighlight]);
|
||||||
|
|
||||||
const handleFocus: React.FocusEventHandler<HTMLInputElement> = useCallback(
|
const handleFocus: React.FocusEventHandler<HTMLInputElement> = useCallback(
|
||||||
(e) => {
|
(e) => {
|
||||||
if (openOnFocus) {
|
if (openOnFocus && !wasMenuJustClosedRef.current) {
|
||||||
setShouldMenuOpen(true);
|
setShouldMenuOpen(true);
|
||||||
}
|
}
|
||||||
onFocus?.(e);
|
onFocus?.(e);
|
||||||
@ -333,6 +346,10 @@ const ComboboxWithRef = <Item extends ComboboxItem, GroupKey extends string>(
|
|||||||
|
|
||||||
if (closeOnSelect) {
|
if (closeOnSelect) {
|
||||||
closeMenu();
|
closeMenu();
|
||||||
|
wasMenuJustClosedRef.current = true;
|
||||||
|
setTimeout(() => {
|
||||||
|
wasMenuJustClosedRef.current = false;
|
||||||
|
}, 50);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -24,7 +24,6 @@ import {
|
|||||||
import {
|
import {
|
||||||
Article,
|
Article,
|
||||||
ItemList,
|
ItemList,
|
||||||
Scrollable,
|
|
||||||
} from 'mastodon/components/scrollable_list/components';
|
} from 'mastodon/components/scrollable_list/components';
|
||||||
import { useAccount } from 'mastodon/hooks/useAccount';
|
import { useAccount } from 'mastodon/hooks/useAccount';
|
||||||
import { useSearchAccounts } from 'mastodon/hooks/useSearchAccounts';
|
import { useSearchAccounts } from 'mastodon/hooks/useSearchAccounts';
|
||||||
@ -417,43 +416,42 @@ export const CollectionAccounts: React.FC<{
|
|||||||
</AccountsHeadingElement>
|
</AccountsHeadingElement>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<Scrollable className={classes.scrollableWrapper}>
|
<ItemList
|
||||||
<ItemList
|
className={classes.accountList}
|
||||||
emptyMessage={
|
emptyMessage={
|
||||||
<EmptyState
|
<EmptyState
|
||||||
title={
|
title={
|
||||||
<FormattedMessage
|
<FormattedMessage
|
||||||
id='collections.accounts.empty_editor_title'
|
id='collections.accounts.empty_editor_title'
|
||||||
defaultMessage='No one is in this collection yet'
|
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}
|
|
||||||
/>
|
/>
|
||||||
</Article>
|
}
|
||||||
))}
|
message={
|
||||||
</ItemList>
|
<FormattedMessage
|
||||||
</Scrollable>
|
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>
|
</div>
|
||||||
</FormStack>
|
</FormStack>
|
||||||
{!isEditMode && hasItems && (
|
{!isEditMode && hasItems && (
|
||||||
|
|||||||
@ -55,7 +55,7 @@
|
|||||||
gap: 16px;
|
gap: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.scrollableWrapper {
|
.accountList {
|
||||||
margin-inline: -16px;
|
margin-inline: -16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -26,8 +26,8 @@ export const EMOJI_TYPE_UNICODE = 'unicode';
|
|||||||
export const EMOJI_TYPE_CUSTOM = 'custom';
|
export const EMOJI_TYPE_CUSTOM = 'custom';
|
||||||
|
|
||||||
export const EMOJI_DB_NAME_SHORTCODES = 'shortcodes';
|
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_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 = [
|
export const EMOJIS_WITH_DARK_BORDER = [
|
||||||
'🎱', // 1F3B1
|
'🎱', // 1F3B1
|
||||||
|
|||||||
@ -2,6 +2,7 @@ import { SUPPORTED_LOCALES } from 'emojibase';
|
|||||||
import type { CompactEmoji, Locale, ShortcodesDataset } from 'emojibase';
|
import type { CompactEmoji, Locale, ShortcodesDataset } from 'emojibase';
|
||||||
|
|
||||||
import type { ApiCustomEmojiJSON } from '@/mastodon/api_types/custom_emoji';
|
import type { ApiCustomEmojiJSON } from '@/mastodon/api_types/custom_emoji';
|
||||||
|
import { onceAsync } from '@/mastodon/utils/promises';
|
||||||
|
|
||||||
import { openEmojiDB } from './db-schema';
|
import { openEmojiDB } from './db-schema';
|
||||||
import type { Database } 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.
|
// Loads the database in a way that ensures it's only loaded once.
|
||||||
const loadDB = (() => {
|
const loadDB = (() => {
|
||||||
let dbPromise: Promise<Database> | null = null;
|
|
||||||
|
|
||||||
// Actually load the DB.
|
// Actually load the DB.
|
||||||
async function initDB() {
|
async function initDB() {
|
||||||
const db = await openEmojiDB();
|
const db = await openEmojiDB();
|
||||||
@ -32,17 +31,14 @@ const loadDB = (() => {
|
|||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let dbPromise = onceAsync(initDB);
|
||||||
|
|
||||||
// Loads the database, or returns the existing promise if it hasn't resolved yet.
|
// Loads the database, or returns the existing promise if it hasn't resolved yet.
|
||||||
const loadPromise = async (): Promise<Database> => {
|
const loadPromise = () => dbPromise();
|
||||||
if (dbPromise) {
|
|
||||||
return dbPromise;
|
|
||||||
}
|
|
||||||
dbPromise = initDB();
|
|
||||||
return dbPromise;
|
|
||||||
};
|
|
||||||
// Special way to reset the database, used for unit testing.
|
// Special way to reset the database, used for unit testing.
|
||||||
loadPromise.reset = () => {
|
loadPromise.reset = () => {
|
||||||
dbPromise = null;
|
dbPromise = onceAsync(initDB);
|
||||||
};
|
};
|
||||||
return loadPromise;
|
return loadPromise;
|
||||||
})();
|
})();
|
||||||
@ -335,13 +331,6 @@ export async function clearCache(key: CacheKey) {
|
|||||||
log('Cleared cache for %s', key);
|
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(
|
export async function loadEmojiByHexcode(
|
||||||
hexcode: string,
|
hexcode: string,
|
||||||
localeString: string,
|
localeString: string,
|
||||||
|
|||||||
67
app/javascript/mastodon/features/emoji/db-schema.test.ts
Normal file
67
app/javascript/mastodon/features/emoji/db-schema.test.ts
Normal file
@ -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 { SUPPORTED_LOCALES } from 'emojibase';
|
||||||
import type { Locale } from 'emojibase';
|
import type { Locale } from 'emojibase';
|
||||||
import { openDB } from 'idb';
|
import { deleteDB, openDB } from 'idb';
|
||||||
import type {
|
import type {
|
||||||
DBSchema,
|
DBSchema,
|
||||||
IDBPDatabase,
|
IDBPDatabase,
|
||||||
@ -10,8 +10,13 @@ import type {
|
|||||||
StoreNames,
|
StoreNames,
|
||||||
} from 'idb';
|
} from 'idb';
|
||||||
|
|
||||||
import { resetDatabase } from './database';
|
import { EMOJI_DB_RELOAD_EVENT } from './constants';
|
||||||
import type { CustomEmojiData, CacheKey, UnicodeEmojiData } from './types';
|
import type {
|
||||||
|
CustomEmojiData,
|
||||||
|
CacheKey,
|
||||||
|
UnicodeEmojiData,
|
||||||
|
EmojiWorkerMessage,
|
||||||
|
} from './types';
|
||||||
import { emojiLogger } from './utils';
|
import { emojiLogger } from './utils';
|
||||||
|
|
||||||
const log = emojiLogger('database');
|
const log = emojiLogger('database');
|
||||||
@ -58,72 +63,95 @@ type Transaction<Mode extends IDBTransactionMode = 'versionchange'> =
|
|||||||
|
|
||||||
export type Database = IDBPDatabase<EmojiDB>;
|
export type Database = IDBPDatabase<EmojiDB>;
|
||||||
|
|
||||||
|
const DATABASE_NAME = 'mastodon-emoji';
|
||||||
const SCHEMA_VERSION = 4;
|
const SCHEMA_VERSION = 4;
|
||||||
|
|
||||||
export async function openEmojiDB() {
|
export async function openEmojiDB() {
|
||||||
const db = await openDB<EmojiDB>('mastodon-emoji', SCHEMA_VERSION, {
|
try {
|
||||||
upgrade(database, oldVersion, newVersion, trx) {
|
const db = await openDB<EmojiDB>(DATABASE_NAME, SCHEMA_VERSION, {
|
||||||
if (!database.objectStoreNames.contains('custom')) {
|
upgrade(database, oldVersion, newVersion, trx) {
|
||||||
database.createObjectStore('custom', {
|
if (!database.objectStoreNames.contains('custom')) {
|
||||||
keyPath: 'shortcode',
|
database.createObjectStore('custom', {
|
||||||
autoIncrement: false,
|
keyPath: 'shortcode',
|
||||||
});
|
|
||||||
}
|
|
||||||
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',
|
|
||||||
autoIncrement: false,
|
autoIncrement: false,
|
||||||
});
|
});
|
||||||
maybeAddIndex({
|
}
|
||||||
trx,
|
maybeAddIndex({ trx, storeName: 'custom', indexName: 'category' });
|
||||||
storeName: 'shortcodes',
|
maybeAddIndex({
|
||||||
indexName: 'shortcodes',
|
trx,
|
||||||
options: { multiEntry: true },
|
storeName: 'custom',
|
||||||
});
|
indexName: 'tokens',
|
||||||
deleteOldIndexes(shortcodeTable, ['hexcode']);
|
options: { multiEntry: true },
|
||||||
|
});
|
||||||
|
|
||||||
void resetDatabase();
|
if (!database.objectStoreNames.contains('etags')) {
|
||||||
|
database.createObjectStore('etags');
|
||||||
|
}
|
||||||
|
|
||||||
log(
|
SUPPORTED_LOCALES.forEach((locale) => {
|
||||||
'Upgraded emoji database from version %d to %d',
|
createLocaleTable(locale, database, trx);
|
||||||
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,
|
|
||||||
);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
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>>({
|
function maybeAddIndex<StoreName extends StoreNames<EmojiDB>>({
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
import { initialState } from '@/mastodon/initial_state';
|
import { initialState } from '@/mastodon/initial_state';
|
||||||
|
|
||||||
|
import { EMOJI_DB_RELOAD_EVENT } from './constants';
|
||||||
import { toSupportedLocale } from './locale';
|
import { toSupportedLocale } from './locale';
|
||||||
import type { EmojiWorkerMessage } from './types';
|
import type { EmojiWorkerMessage } from './types';
|
||||||
import { emojiLogger } from './utils';
|
import { emojiLogger } from './utils';
|
||||||
@ -14,6 +15,12 @@ const workerLog = emojiLogger('worker');
|
|||||||
// This is too short, but better to fallback quickly than wait.
|
// This is too short, but better to fallback quickly than wait.
|
||||||
const WORKER_TIMEOUT = 2_000;
|
const WORKER_TIMEOUT = 2_000;
|
||||||
|
|
||||||
|
// Handle reload events
|
||||||
|
window.addEventListener(
|
||||||
|
EMOJI_DB_RELOAD_EVENT,
|
||||||
|
() => void handleEmojiDbReload(),
|
||||||
|
);
|
||||||
|
|
||||||
export async function initializeEmoji() {
|
export async function initializeEmoji() {
|
||||||
log('initializing emojis');
|
log('initializing emojis');
|
||||||
|
|
||||||
@ -51,6 +58,8 @@ export async function initializeEmoji() {
|
|||||||
workerLog(message.message);
|
workerLog(message.message);
|
||||||
} else if (type === 'done' && message.storeName === 'custom') {
|
} else if (type === 'done' && message.storeName === 'custom') {
|
||||||
void loadEmojisToStore();
|
void loadEmojisToStore();
|
||||||
|
} else if (type === 'db-blocked') {
|
||||||
|
window.dispatchEvent(new Event(EMOJI_DB_RELOAD_EVENT));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (type !== 'ready') {
|
if (type !== 'ready') {
|
||||||
@ -131,3 +140,10 @@ async function loadEmojisToStore() {
|
|||||||
|
|
||||||
log('loaded emoji data into store');
|
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 { joinShortcodes } from 'emojibase';
|
||||||
import type { CompactEmoji, Locale, ShortcodesDataset } from 'emojibase';
|
import type { CompactEmoji, Locale, ShortcodesDataset } from 'emojibase';
|
||||||
|
|
||||||
|
import { onceAsyncByArgs } from '@/mastodon/utils/promises';
|
||||||
|
|
||||||
import {
|
import {
|
||||||
putEmojiData,
|
putEmojiData,
|
||||||
putCustomEmojiData,
|
putCustomEmojiData,
|
||||||
@ -17,6 +19,12 @@ const log = emojiLogger('loader');
|
|||||||
export async function importEmojiData(localeString: string, shortcodes = true) {
|
export async function importEmojiData(localeString: string, shortcodes = true) {
|
||||||
const locale = toSupportedLocale(localeString);
|
const locale = toSupportedLocale(localeString);
|
||||||
|
|
||||||
|
return importEmojiDataOnce(locale, shortcodes);
|
||||||
|
}
|
||||||
|
|
||||||
|
const importEmojiDataOnce = onceAsyncByArgs(importEmojiDataImpl);
|
||||||
|
|
||||||
|
async function importEmojiDataImpl(locale: Locale, shortcodes: boolean) {
|
||||||
log(
|
log(
|
||||||
'importing emoji data for locale %s%s',
|
'importing emoji data for locale %s%s',
|
||||||
locale,
|
locale,
|
||||||
@ -171,9 +179,7 @@ async function fetchAndCheckEtag({
|
|||||||
|
|
||||||
// Use location.origin as this script may be loaded from a CDN domain.
|
// Use location.origin as this script may be loaded from a CDN domain.
|
||||||
const url = new URL(path, location.origin);
|
const url = new URL(path, location.origin);
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, { headers });
|
||||||
headers,
|
|
||||||
});
|
|
||||||
|
|
||||||
// If not modified, return null
|
// If not modified, return null
|
||||||
if (response.status === 304) {
|
if (response.status === 304) {
|
||||||
|
|||||||
@ -82,6 +82,7 @@ export type ExtraCustomEmojiMap = Record<
|
|||||||
|
|
||||||
export type EmojiWorkerMessage =
|
export type EmojiWorkerMessage =
|
||||||
| { type: 'ready' }
|
| { type: 'ready' }
|
||||||
|
| { type: 'db-blocked' }
|
||||||
| {
|
| {
|
||||||
type: 'load';
|
type: 'load';
|
||||||
storeName: string;
|
storeName: string;
|
||||||
|
|||||||
@ -47,11 +47,9 @@ interface MediaModalProps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const MIN_SWIPE_DISTANCE = 400;
|
const MIN_SWIPE_DISTANCE = 400;
|
||||||
|
const isLtrDir = getComputedStyle(document.body).direction !== 'rtl';
|
||||||
|
|
||||||
export const MediaModal: FC<MediaModalProps> = forwardRef<
|
export const MediaModal = forwardRef<HTMLDivElement, MediaModalProps>(
|
||||||
HTMLDivElement,
|
|
||||||
MediaModalProps
|
|
||||||
>(
|
|
||||||
(
|
(
|
||||||
{
|
{
|
||||||
media,
|
media,
|
||||||
@ -64,15 +62,16 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
statusId,
|
statusId,
|
||||||
onChangeBackgroundColor,
|
onChangeBackgroundColor,
|
||||||
},
|
},
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- _ref is required to keep the ref forwarding working
|
|
||||||
_ref,
|
_ref,
|
||||||
) => {
|
) => {
|
||||||
const [index, setIndex] = useState(startIndex);
|
const [index, setIndex] = useState(startIndex);
|
||||||
const [zoomedIn, setZoomedIn] = useState(false);
|
const [zoomedIn, setZoomedIn] = useState(false);
|
||||||
const currentMedia = media.get(index);
|
const currentMedia = media.get(index);
|
||||||
|
|
||||||
|
const sign = isLtrDir ? '-' : '';
|
||||||
|
|
||||||
const [wrapperStyles, api] = useSpring(() => ({
|
const [wrapperStyles, api] = useSpring(() => ({
|
||||||
x: `-${index * 100}%`,
|
x: `${sign}${index * 100}%`,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const handleChangeIndex = useCallback(
|
const handleChangeIndex = useCallback(
|
||||||
@ -85,10 +84,12 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
setIndex(newIndex);
|
setIndex(newIndex);
|
||||||
setZoomedIn(false);
|
setZoomedIn(false);
|
||||||
if (animate) {
|
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(() => {
|
const handlePrevClick = useCallback(() => {
|
||||||
handleChangeIndex(index - 1, true);
|
handleChangeIndex(index - 1, true);
|
||||||
@ -99,11 +100,14 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
|
|
||||||
const handleKeyDown = useCallback(
|
const handleKeyDown = useCallback(
|
||||||
(event: KeyboardEvent) => {
|
(event: KeyboardEvent) => {
|
||||||
if (event.key === 'ArrowLeft') {
|
const prevKey = isLtrDir ? 'ArrowLeft' : 'ArrowRight';
|
||||||
|
const nextKey = isLtrDir ? 'ArrowRight' : 'ArrowLeft';
|
||||||
|
|
||||||
|
if (event.key === prevKey) {
|
||||||
handlePrevClick();
|
handlePrevClick();
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
} else if (event.key === 'ArrowRight') {
|
} else if (event.key === nextKey) {
|
||||||
handleNextClick();
|
handleNextClick();
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
@ -124,13 +128,14 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
active &&
|
active &&
|
||||||
Math.abs(mx) > Math.min(window.innerWidth / 4, MIN_SWIPE_DISTANCE)
|
Math.abs(mx) > Math.min(window.innerWidth / 4, MIN_SWIPE_DISTANCE)
|
||||||
) {
|
) {
|
||||||
handleChangeIndex(index - xDir);
|
handleChangeIndex(isLtrDir ? index - xDir : index + xDir);
|
||||||
cancel();
|
cancel();
|
||||||
}
|
}
|
||||||
// Set the x position via calc to ensure proper centering regardless of screen size.
|
// Set the x position via calc to ensure proper centering regardless of screen size.
|
||||||
const x = active ? mx : 0;
|
const x = active ? mx : 0;
|
||||||
|
const operator = isLtrDir ? '+' : '-';
|
||||||
void api.start({
|
void api.start({
|
||||||
x: `calc(-${index * 100}% + ${x}px)`,
|
x: `calc(${sign}${index * 100}% ${operator} ${x}px)`,
|
||||||
});
|
});
|
||||||
},
|
},
|
||||||
{ pointer: { capture: false } },
|
{ pointer: { capture: false } },
|
||||||
@ -161,14 +166,23 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
width: number;
|
width: number;
|
||||||
height: number;
|
height: number;
|
||||||
}>({ width: 0, height: 0 });
|
}>({ width: 0, height: 0 });
|
||||||
const handleRef: RefCallback<HTMLDivElement> = useCallback((ele) => {
|
const handleRef: RefCallback<HTMLDivElement> = useCallback(
|
||||||
if (ele?.clientWidth && ele.clientHeight) {
|
(ele) => {
|
||||||
setViewportDimensions({
|
if (typeof _ref === 'function') {
|
||||||
width: ele.clientWidth,
|
_ref(ele);
|
||||||
height: ele.clientHeight,
|
} else if (_ref) {
|
||||||
});
|
_ref.current = ele;
|
||||||
}
|
}
|
||||||
}, []);
|
|
||||||
|
if (ele?.clientWidth && ele.clientHeight) {
|
||||||
|
setViewportDimensions({
|
||||||
|
width: ele.clientWidth,
|
||||||
|
height: ele.clientHeight,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[_ref],
|
||||||
|
);
|
||||||
|
|
||||||
const zoomable =
|
const zoomable =
|
||||||
currentMedia?.get('type') === 'image' &&
|
currentMedia?.get('type') === 'image' &&
|
||||||
@ -268,9 +282,8 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
|
|
||||||
const intl = useIntl();
|
const intl = useIntl();
|
||||||
|
|
||||||
const leftNav = media.size > 1 && (
|
const prevNav = media.size > 1 && (
|
||||||
<button
|
<button
|
||||||
tabIndex={0}
|
|
||||||
className='media-modal__nav media-modal__nav--prev'
|
className='media-modal__nav media-modal__nav--prev'
|
||||||
onClick={handlePrevClick}
|
onClick={handlePrevClick}
|
||||||
aria-label={intl.formatMessage(messages.previous)}
|
aria-label={intl.formatMessage(messages.previous)}
|
||||||
@ -279,9 +292,8 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
<Icon id='chevron-left' icon={ChevronLeftIcon} />
|
<Icon id='chevron-left' icon={ChevronLeftIcon} />
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
const rightNav = media.size > 1 && (
|
const nextNav = media.size > 1 && (
|
||||||
<button
|
<button
|
||||||
tabIndex={0}
|
|
||||||
className='media-modal__nav media-modal__nav--next'
|
className='media-modal__nav media-modal__nav--next'
|
||||||
onClick={handleNextClick}
|
onClick={handleNextClick}
|
||||||
aria-label={intl.formatMessage(messages.next)}
|
aria-label={intl.formatMessage(messages.next)}
|
||||||
@ -330,8 +342,8 @@ export const MediaModal: FC<MediaModalProps> = forwardRef<
|
|||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{leftNav}
|
{prevNav}
|
||||||
{rightNav}
|
{nextNav}
|
||||||
|
|
||||||
<div className='media-modal__overlay'>
|
<div className='media-modal__overlay'>
|
||||||
<MediaPagination
|
<MediaPagination
|
||||||
|
|||||||
@ -267,6 +267,7 @@
|
|||||||
"admin.impact_report.instance_followers": "Followers our users would lose",
|
"admin.impact_report.instance_followers": "Followers our users would lose",
|
||||||
"admin.impact_report.instance_follows": "Followers their users would lose",
|
"admin.impact_report.instance_follows": "Followers their users would lose",
|
||||||
"admin.impact_report.title": "Impact summary",
|
"admin.impact_report.title": "Impact summary",
|
||||||
|
"alert.need_reload.message": "Mastodon has been updated. Some things may not work correctly until you reload the page.",
|
||||||
"alert.rate_limited.message": "Please retry after {retry_time, time, medium}.",
|
"alert.rate_limited.message": "Please retry after {retry_time, time, medium}.",
|
||||||
"alert.rate_limited.title": "Rate limited",
|
"alert.rate_limited.title": "Rate limited",
|
||||||
"alert.unexpected.message": "An unexpected error occurred.",
|
"alert.unexpected.message": "An unexpected error occurred.",
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
import { Map as ImmutableMap } from 'immutable';
|
import { Map as ImmutableMap } from 'immutable';
|
||||||
|
|
||||||
import { changeLayout } from 'mastodon/actions/app';
|
import { changeLayout, needsReload } from 'mastodon/actions/app';
|
||||||
import { STORE_HYDRATE } from 'mastodon/actions/store';
|
import { STORE_HYDRATE } from 'mastodon/actions/store';
|
||||||
import { layoutFromWindow } from 'mastodon/is_mobile';
|
import { layoutFromWindow } from 'mastodon/is_mobile';
|
||||||
|
|
||||||
@ -8,6 +8,7 @@ const initialState = ImmutableMap({
|
|||||||
streaming_api_base_url: null,
|
streaming_api_base_url: null,
|
||||||
layout: layoutFromWindow(),
|
layout: layoutFromWindow(),
|
||||||
permissions: '0',
|
permissions: '0',
|
||||||
|
needsReload: false,
|
||||||
});
|
});
|
||||||
|
|
||||||
export default function meta(state = initialState, action) {
|
export default function meta(state = initialState, action) {
|
||||||
@ -17,6 +18,8 @@ export default function meta(state = initialState, action) {
|
|||||||
return state.merge(action.state.get('meta')).delete('access_token').set('permissions', action.state.getIn(['role', 'permissions']));
|
return state.merge(action.state.get('meta')).delete('access_token').set('permissions', action.state.getIn(['role', 'permissions']));
|
||||||
case changeLayout.type:
|
case changeLayout.type:
|
||||||
return state.set('layout', action.payload.layout);
|
return state.set('layout', action.payload.layout);
|
||||||
|
case needsReload.type:
|
||||||
|
return state.set('needsReload', true);
|
||||||
default:
|
default:
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|||||||
203
app/javascript/mastodon/utils/promises.test.ts
Normal file
203
app/javascript/mastodon/utils/promises.test.ts
Normal file
@ -0,0 +1,203 @@
|
|||||||
|
import { onceAsync, onceAsyncByArgs } from './promises';
|
||||||
|
|
||||||
|
describe('onceAsync', () => {
|
||||||
|
test('calls async callback once for concurrent calls', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
let resolveValue!: (value: string) => void;
|
||||||
|
|
||||||
|
const wrapped = onceAsync(async () => {
|
||||||
|
callCount += 1;
|
||||||
|
return new Promise<string>((resolve) => {
|
||||||
|
resolveValue = resolve;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const first = wrapped();
|
||||||
|
const second = wrapped();
|
||||||
|
|
||||||
|
expect(callCount).toBe(1);
|
||||||
|
expect(first).toBe(second);
|
||||||
|
|
||||||
|
resolveValue('ok');
|
||||||
|
|
||||||
|
await expect(first).resolves.toBe('ok');
|
||||||
|
await expect(second).resolves.toBe('ok');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns cached response for later calls without re-running callback', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
const wrapped = onceAsync(() => {
|
||||||
|
callCount += 1;
|
||||||
|
return Promise.resolve('cached');
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(wrapped()).resolves.toBe('cached');
|
||||||
|
await expect(wrapped()).resolves.toBe('cached');
|
||||||
|
|
||||||
|
expect(callCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('keeps the same rejection promise and does not re-run callback', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
const error = new Error('boom');
|
||||||
|
|
||||||
|
const wrapped = onceAsync(() => {
|
||||||
|
callCount += 1;
|
||||||
|
return Promise.reject(error);
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(wrapped()).rejects.toThrow('boom');
|
||||||
|
await expect(wrapped()).rejects.toThrow('boom');
|
||||||
|
|
||||||
|
expect(callCount).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('onceAsyncByArgs', () => {
|
||||||
|
test('shares one in-flight callback for the same argument key', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
let resolveValue!: (value: string) => void;
|
||||||
|
|
||||||
|
const wrapped = onceAsyncByArgs((arg: string, bool: boolean) => {
|
||||||
|
callCount += 1;
|
||||||
|
return new Promise<string>((resolve) => {
|
||||||
|
resolveValue = (value: string) => {
|
||||||
|
resolve(`${arg}:${bool}:${value}`);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const first = wrapped('test', true);
|
||||||
|
const second = wrapped('test', true);
|
||||||
|
|
||||||
|
expect(callCount).toBe(1);
|
||||||
|
expect(first).toBe(second);
|
||||||
|
|
||||||
|
resolveValue('done');
|
||||||
|
|
||||||
|
await expect(first).resolves.toBe('test:true:done');
|
||||||
|
await expect(second).resolves.toBe('test:true:done');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('runs separate callbacks for different argument keys', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
|
||||||
|
const wrapped = onceAsyncByArgs((arg: string, bool: boolean) => {
|
||||||
|
callCount += 1;
|
||||||
|
return Promise.resolve(`${arg}:${bool}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(wrapped('test', false)).resolves.toBe('test:false');
|
||||||
|
await expect(wrapped('test', true)).resolves.toBe('test:true');
|
||||||
|
|
||||||
|
expect(callCount).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('allows the same key to run again after previous promise settles', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
|
||||||
|
const wrapped = onceAsyncByArgs((arg: string) => {
|
||||||
|
callCount += 1;
|
||||||
|
return Promise.resolve(arg);
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(wrapped('test')).resolves.toBe('test');
|
||||||
|
await expect(wrapped('test')).resolves.toBe('test');
|
||||||
|
|
||||||
|
expect(callCount).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('returns resolved promise again if deleteOnComplete is false', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
|
||||||
|
const wrapped = onceAsyncByArgs(
|
||||||
|
(arg: string) => {
|
||||||
|
callCount += 1;
|
||||||
|
return Promise.resolve(arg);
|
||||||
|
},
|
||||||
|
{ deleteOnComplete: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
const first = wrapped('test');
|
||||||
|
await expect(first).resolves.toBe('test');
|
||||||
|
|
||||||
|
const second = wrapped('test');
|
||||||
|
await expect(second).resolves.toBe('test');
|
||||||
|
|
||||||
|
expect(first).toBe(second);
|
||||||
|
expect(callCount).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('calls log function when provided', async () => {
|
||||||
|
let resolveValue!: (value: string) => void;
|
||||||
|
const log = vi.fn<(format: string, ...args: unknown[]) => void>();
|
||||||
|
|
||||||
|
const wrapped = onceAsyncByArgs(
|
||||||
|
(arg: string) =>
|
||||||
|
new Promise<string>((resolve) => {
|
||||||
|
resolveValue = (value: string) => {
|
||||||
|
resolve(`${arg}:${value}`);
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
{ log },
|
||||||
|
);
|
||||||
|
|
||||||
|
const first = wrapped('test');
|
||||||
|
const second = wrapped('test');
|
||||||
|
expect(first).toBe(second);
|
||||||
|
|
||||||
|
resolveValue('done');
|
||||||
|
await expect(first).resolves.toBe('test:done');
|
||||||
|
|
||||||
|
expect(log).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('added promise with key'),
|
||||||
|
);
|
||||||
|
expect(log).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('already have in-flight promise with key'),
|
||||||
|
);
|
||||||
|
expect(log).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('deleted completed promise with key'),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('re-runs callback for same key after rejection with default deleteOnComplete', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
const wrapped = onceAsyncByArgs((arg: string) => {
|
||||||
|
callCount += 1;
|
||||||
|
return Promise.reject(new Error(`boom:${arg}`));
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(wrapped('test')).rejects.toThrow('boom');
|
||||||
|
await expect(wrapped('test')).rejects.toThrow('boom');
|
||||||
|
|
||||||
|
expect(callCount).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('uses keyFromArgs to dedupe by custom key', async () => {
|
||||||
|
let callCount = 0;
|
||||||
|
let resolveValue!: (value: string) => void;
|
||||||
|
|
||||||
|
const wrapped = onceAsyncByArgs(
|
||||||
|
({ id }: { id: string; payload: string }) => {
|
||||||
|
callCount += 1;
|
||||||
|
return new Promise<string>((resolve) => {
|
||||||
|
resolveValue = (value: string) => {
|
||||||
|
resolve(`${id}:${value}`);
|
||||||
|
};
|
||||||
|
});
|
||||||
|
},
|
||||||
|
{
|
||||||
|
keyFromArgs: ({ id }) => id,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const first = wrapped({ id: '1', payload: 'a' });
|
||||||
|
const second = wrapped({ id: '1', payload: 'b' });
|
||||||
|
|
||||||
|
expect(first).toBe(second);
|
||||||
|
expect(callCount).toBe(1);
|
||||||
|
|
||||||
|
resolveValue('ok');
|
||||||
|
await expect(first).resolves.toBe('1:ok');
|
||||||
|
});
|
||||||
|
});
|
||||||
57
app/javascript/mastodon/utils/promises.ts
Normal file
57
app/javascript/mastodon/utils/promises.ts
Normal file
@ -0,0 +1,57 @@
|
|||||||
|
/**
|
||||||
|
* Wraps a function that returns a promise so that it only executes once, and subsequent calls return the same promise.
|
||||||
|
*/
|
||||||
|
export function onceAsync<TArgs extends unknown[], TResult>(
|
||||||
|
callback: (...args: TArgs) => Promise<TResult>,
|
||||||
|
): (...args: TArgs) => Promise<TResult> {
|
||||||
|
let promise: Promise<TResult> | null = null;
|
||||||
|
|
||||||
|
return (...args: TArgs) => {
|
||||||
|
promise ??= callback(...args);
|
||||||
|
return promise;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
interface OnceAsyncByArgs<TArgs extends unknown[]> {
|
||||||
|
/** Callback to derive a string key from arguments. Defaults to JSON.stringify. */
|
||||||
|
keyFromArgs?: (...args: TArgs) => string;
|
||||||
|
/** Whether to remove a promise from the cache once it resolves. Defaults to true. */
|
||||||
|
deleteOnComplete?: boolean;
|
||||||
|
/** Optional callback to log promise changes. */
|
||||||
|
log?: (format: string, ...args: unknown[]) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps an async function so that only one in-flight call exists per argument key.
|
||||||
|
* Concurrent calls with the same key share one promise.
|
||||||
|
*/
|
||||||
|
export function onceAsyncByArgs<TArgs extends unknown[], TResult>(
|
||||||
|
callback: (...args: TArgs) => Promise<TResult>,
|
||||||
|
{
|
||||||
|
keyFromArgs = (...args) => JSON.stringify(args),
|
||||||
|
deleteOnComplete = true,
|
||||||
|
log,
|
||||||
|
}: OnceAsyncByArgs<TArgs> = {},
|
||||||
|
): (...args: TArgs) => Promise<TResult> {
|
||||||
|
const inFlight = new Map<string, Promise<TResult>>();
|
||||||
|
|
||||||
|
return (...args: TArgs) => {
|
||||||
|
const key = keyFromArgs(...args);
|
||||||
|
const existingPromise = inFlight.get(key);
|
||||||
|
|
||||||
|
if (existingPromise) {
|
||||||
|
log?.(`already have in-flight promise with key ${key}`);
|
||||||
|
return existingPromise;
|
||||||
|
}
|
||||||
|
|
||||||
|
const promise = callback(...args).finally(() => {
|
||||||
|
if (deleteOnComplete) {
|
||||||
|
log?.(`deleted completed promise with key ${key}`);
|
||||||
|
inFlight.delete(key);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
log?.(`added promise with key ${key}`);
|
||||||
|
inFlight.set(key, promise);
|
||||||
|
return promise;
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -60,7 +60,7 @@ services:
|
|||||||
web:
|
web:
|
||||||
# You can uncomment the following line if you want to not use the prebuilt image, for example if you have local code changes
|
# You can uncomment the following line if you want to not use the prebuilt image, for example if you have local code changes
|
||||||
# build: .
|
# build: .
|
||||||
image: ghcr.io/glitch-soc/mastodon:v4.6.0
|
image: ghcr.io/glitch-soc/mastodon:v4.6.1
|
||||||
restart: always
|
restart: always
|
||||||
env_file: .env.production
|
env_file: .env.production
|
||||||
command: bundle exec puma -C config/puma.rb
|
command: bundle exec puma -C config/puma.rb
|
||||||
@ -84,7 +84,7 @@ services:
|
|||||||
# build:
|
# build:
|
||||||
# dockerfile: ./streaming/Dockerfile
|
# dockerfile: ./streaming/Dockerfile
|
||||||
# context: .
|
# context: .
|
||||||
image: ghcr.io/glitch-soc/mastodon-streaming:v4.6.0
|
image: ghcr.io/glitch-soc/mastodon-streaming:v4.6.1
|
||||||
restart: always
|
restart: always
|
||||||
env_file: .env.production
|
env_file: .env.production
|
||||||
command: node ./streaming/index.js
|
command: node ./streaming/index.js
|
||||||
@ -103,7 +103,7 @@ services:
|
|||||||
sidekiq:
|
sidekiq:
|
||||||
# You can uncomment the following line if you want to not use the prebuilt image, for example if you have local code changes
|
# You can uncomment the following line if you want to not use the prebuilt image, for example if you have local code changes
|
||||||
# build: .
|
# build: .
|
||||||
image: ghcr.io/glitch-soc/mastodon:v4.6.0
|
image: ghcr.io/glitch-soc/mastodon:v4.6.1
|
||||||
restart: always
|
restart: always
|
||||||
env_file: .env.production
|
env_file: .env.production
|
||||||
command: bundle exec sidekiq
|
command: bundle exec sidekiq
|
||||||
|
|||||||
@ -13,7 +13,7 @@ module Mastodon
|
|||||||
end
|
end
|
||||||
|
|
||||||
def patch
|
def patch
|
||||||
0
|
1
|
||||||
end
|
end
|
||||||
|
|
||||||
def default_prerelease
|
def default_prerelease
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user