Refactor set/get current account ID

And add fallback for standalone mode where session storage is not enough
pull/501/head
Lim Chee Aun 2024-04-13 00:06:34 +08:00
rodzic aefda31c2a
commit e782cc0dde
13 zmienionych plików z 57 dodań i 27 usunięć

Wyświetl plik

@ -53,7 +53,7 @@ import { getAccessToken } from './utils/auth';
import focusDeck from './utils/focus-deck'; import focusDeck from './utils/focus-deck';
import states, { initStates, statusKey } from './utils/states'; import states, { initStates, statusKey } from './utils/states';
import store from './utils/store'; import store from './utils/store';
import { getCurrentAccount } from './utils/store-utils'; import { getCurrentAccount, setCurrentAccountID } from './utils/store-utils';
import './utils/toast-alert'; import './utils/toast-alert';
window.__STATES__ = states; window.__STATES__ = states;
@ -338,7 +338,7 @@ function App() {
window.__IGNORE_GET_ACCOUNT_ERROR__ = true; window.__IGNORE_GET_ACCOUNT_ERROR__ = true;
const account = getCurrentAccount(); const account = getCurrentAccount();
if (account) { if (account) {
store.session.set('currentAccount', account.info.id); setCurrentAccountID(account.info.id);
const { client } = api({ account }); const { client } = api({ account });
const { instance } = client; const { instance } = client;
// console.log('masto', masto); // console.log('masto', masto);

Wyświetl plik

@ -22,7 +22,7 @@ import shortenNumber from '../utils/shorten-number';
import showToast from '../utils/show-toast'; import showToast from '../utils/show-toast';
import states, { hideAllModals } from '../utils/states'; import states, { hideAllModals } from '../utils/states';
import store from '../utils/store'; import store from '../utils/store';
import { updateAccount } from '../utils/store-utils'; import { getCurrentAccountID, updateAccount } from '../utils/store-utils';
import AccountBlock from './account-block'; import AccountBlock from './account-block';
import Avatar from './avatar'; import Avatar from './avatar';
@ -198,10 +198,7 @@ function AccountInfo({
} }
} }
const isSelf = useMemo( const isSelf = useMemo(() => id === getCurrentAccountID(), [id]);
() => id === store.session.get('currentAccount'),
[id],
);
useEffect(() => { useEffect(() => {
const infoHasEssentials = !!( const infoHasEssentials = !!(
@ -920,7 +917,7 @@ function RelatedActions({
useEffect(() => { useEffect(() => {
if (info) { if (info) {
const currentAccount = store.session.get('currentAccount'); const currentAccount = getCurrentAccountID();
let currentID; let currentID;
(async () => { (async () => {
if (sameInstance && authenticated) { if (sameInstance && authenticated) {

Wyświetl plik

@ -8,6 +8,7 @@ import FilterContext from '../utils/filter-context';
import { isFiltered } from '../utils/filters'; import { isFiltered } from '../utils/filters';
import states, { statusKey } from '../utils/states'; import states, { statusKey } from '../utils/states';
import store from '../utils/store'; import store from '../utils/store';
import { getCurrentAccountID } from '../utils/store-utils';
import Media from './media'; import Media from './media';
@ -88,7 +89,7 @@ function MediaPost({
}; };
const currentAccount = useMemo(() => { const currentAccount = useMemo(() => {
return store.session.get('currentAccount'); return getCurrentAccountID();
}, []); }, []);
const isSelf = useMemo(() => { const isSelf = useMemo(() => {
return currentAccount && currentAccount === accountId; return currentAccount && currentAccount === accountId;

Wyświetl plik

@ -11,6 +11,7 @@ import { getLists } from '../utils/lists';
import safeBoundingBoxPadding from '../utils/safe-bounding-box-padding'; import safeBoundingBoxPadding from '../utils/safe-bounding-box-padding';
import states from '../utils/states'; import states from '../utils/states';
import store from '../utils/store'; import store from '../utils/store';
import { getCurrentAccountID } from '../utils/store-utils';
import Avatar from './avatar'; import Avatar from './avatar';
import Icon from './icon'; import Icon from './icon';
@ -24,9 +25,8 @@ function NavMenu(props) {
const [currentAccount, moreThanOneAccount] = useMemo(() => { const [currentAccount, moreThanOneAccount] = useMemo(() => {
const accounts = store.local.getJSON('accounts') || []; const accounts = store.local.getJSON('accounts') || [];
const acc = const acc =
accounts.find( accounts.find((account) => account.info.id === getCurrentAccountID()) ||
(account) => account.info.id === store.session.get('currentAccount'), accounts[0];
) || accounts[0];
return [acc, accounts.length > 1]; return [acc, accounts.length > 1];
}, []); }, []);

Wyświetl plik

@ -4,6 +4,7 @@ import { memo } from 'preact/compat';
import shortenNumber from '../utils/shorten-number'; import shortenNumber from '../utils/shorten-number';
import states, { statusKey } from '../utils/states'; import states, { statusKey } from '../utils/states';
import store from '../utils/store'; import store from '../utils/store';
import { getCurrentAccountID } from '../utils/store-utils';
import useTruncated from '../utils/useTruncated'; import useTruncated from '../utils/useTruncated';
import Avatar from './avatar'; import Avatar from './avatar';
@ -132,7 +133,7 @@ function Notification({
const actualStatus = status?.reblog || status; const actualStatus = status?.reblog || status;
const actualStatusID = actualStatus?.id; const actualStatusID = actualStatus?.id;
const currentAccount = store.session.get('currentAccount'); const currentAccount = getCurrentAccountID();
const isSelf = currentAccount === account?.id; const isSelf = currentAccount === account?.id;
const isVoted = status?.poll?.voted; const isVoted = status?.poll?.voted;
const isReplyToOthers = const isReplyToOthers =

Wyświetl plik

@ -19,6 +19,7 @@ import pmem from '../utils/pmem';
import showToast from '../utils/show-toast'; import showToast from '../utils/show-toast';
import states from '../utils/states'; import states from '../utils/states';
import store from '../utils/store'; import store from '../utils/store';
import { getCurrentAccountID } from '../utils/store-utils';
import AsyncText from './AsyncText'; import AsyncText from './AsyncText';
import Icon from './icon'; import Icon from './icon';
@ -787,7 +788,7 @@ function ImportExport({ shortcuts, onClose }) {
disabled={importUIState === 'cloud-downloading'} disabled={importUIState === 'cloud-downloading'}
onClick={async () => { onClick={async () => {
setImportUIState('cloud-downloading'); setImportUIState('cloud-downloading');
const currentAccount = store.session.get('currentAccount'); const currentAccount = getCurrentAccountID();
showToast( showToast(
'Downloading saved shortcuts from instance server…', 'Downloading saved shortcuts from instance server…',
); );
@ -1043,7 +1044,7 @@ function ImportExport({ shortcuts, onClose }) {
disabled={importUIState === 'cloud-uploading'} disabled={importUIState === 'cloud-uploading'}
onClick={async () => { onClick={async () => {
setImportUIState('cloud-uploading'); setImportUIState('cloud-uploading');
const currentAccount = store.session.get('currentAccount'); const currentAccount = getCurrentAccountID();
try { try {
const relationships = const relationships =
await masto.v1.accounts.relationships.fetch({ await masto.v1.accounts.relationships.fetch({

Wyświetl plik

@ -54,6 +54,7 @@ import { speak, supportsTTS } from '../utils/speech';
import states, { getStatus, saveStatus, statusKey } from '../utils/states'; import states, { getStatus, saveStatus, statusKey } from '../utils/states';
import statusPeek from '../utils/status-peek'; import statusPeek from '../utils/status-peek';
import store from '../utils/store'; import store from '../utils/store';
import { getCurrentAccountID } from '../utils/store-utils';
import unfurlMastodonLink from '../utils/unfurl-link'; import unfurlMastodonLink from '../utils/unfurl-link';
import useHotkeys from '../utils/useHotkeys'; import useHotkeys from '../utils/useHotkeys';
import useTruncated from '../utils/useTruncated'; import useTruncated from '../utils/useTruncated';
@ -256,7 +257,7 @@ function Status({
if (mediaFirst && hasMediaAttachments) size = 's'; if (mediaFirst && hasMediaAttachments) size = 's';
const currentAccount = useMemo(() => { const currentAccount = useMemo(() => {
return store.session.get('currentAccount'); return getCurrentAccountID();
}, []); }, []);
const isSelf = useMemo(() => { const isSelf = useMemo(() => {
return currentAccount && currentAccount === accountId; return currentAccount && currentAccount === accountId;

Wyświetl plik

@ -13,12 +13,13 @@ import NameText from '../components/name-text';
import { api } from '../utils/api'; import { api } from '../utils/api';
import states from '../utils/states'; import states from '../utils/states';
import store from '../utils/store'; import store from '../utils/store';
import { getCurrentAccountID, setCurrentAccountID } from '../utils/store-utils';
function Accounts({ onClose }) { function Accounts({ onClose }) {
const { masto } = api(); const { masto } = api();
// Accounts // Accounts
const accounts = store.local.getJSON('accounts'); const accounts = store.local.getJSON('accounts');
const currentAccount = store.session.get('currentAccount'); const currentAccount = getCurrentAccountID();
const moreThanOneAccount = accounts.length > 1; const moreThanOneAccount = accounts.length > 1;
const [_, reload] = useReducer((x) => x + 1, 0); const [_, reload] = useReducer((x) => x + 1, 0);
@ -81,7 +82,7 @@ function Accounts({ onClose }) {
if (isCurrent) { if (isCurrent) {
states.showAccount = `${account.info.username}@${account.instanceURL}`; states.showAccount = `${account.info.username}@${account.instanceURL}`;
} else { } else {
store.session.set('currentAccount', account.info.id); setCurrentAccountID(account.info.id);
location.reload(); location.reload();
} }
}} }}

Wyświetl plik

@ -39,7 +39,7 @@ import showToast from '../utils/show-toast';
import states, { statusKey } from '../utils/states'; import states, { statusKey } from '../utils/states';
import statusPeek from '../utils/status-peek'; import statusPeek from '../utils/status-peek';
import store from '../utils/store'; import store from '../utils/store';
import { getCurrentAccountNS } from '../utils/store-utils'; import { getCurrentAccountID, getCurrentAccountNS } from '../utils/store-utils';
import { assignFollowedTags } from '../utils/timeline-utils'; import { assignFollowedTags } from '../utils/timeline-utils';
import useHotkeys from '../utils/useHotkeys'; import useHotkeys from '../utils/useHotkeys';
import useTitle from '../utils/useTitle'; import useTitle from '../utils/useTitle';
@ -112,7 +112,7 @@ function Catchup() {
const [showTopLinks, setShowTopLinks] = useState(false); const [showTopLinks, setShowTopLinks] = useState(false);
const currentAccount = useMemo(() => { const currentAccount = useMemo(() => {
return store.session.get('currentAccount'); return getCurrentAccountID();
}, []); }, []);
const isSelf = (accountID) => accountID === currentAccount; const isSelf = (accountID) => accountID === currentAccount;

Wyświetl plik

@ -7,6 +7,7 @@ import {
getAccountByInstance, getAccountByInstance,
getCurrentAccount, getCurrentAccount,
saveAccount, saveAccount,
setCurrentAccountID,
} from './store-utils'; } from './store-utils';
// Default *fallback* instance // Default *fallback* instance
@ -118,7 +119,7 @@ export async function initAccount(client, instance, accessToken, vapidKey) {
const mastoAccount = await masto.v1.accounts.verifyCredentials(); const mastoAccount = await masto.v1.accounts.verifyCredentials();
console.log('CURRENTACCOUNT SET', mastoAccount.id); console.log('CURRENTACCOUNT SET', mastoAccount.id);
store.session.set('currentAccount', mastoAccount.id); setCurrentAccountID(mastoAccount.id);
saveAccount({ saveAccount({
info: mastoAccount, info: mastoAccount,

Wyświetl plik

@ -1,5 +1,5 @@
import mem from './mem'; import mem from './mem';
import store from './store'; import { getCurrentAccountID } from './store-utils';
function _isFiltered(filtered, filterContext) { function _isFiltered(filtered, filterContext) {
if (!filtered?.length) return false; if (!filtered?.length) return false;
@ -43,7 +43,7 @@ export function filteredItem(item, filterContext, currentAccountID) {
export function filteredItems(items, filterContext) { export function filteredItems(items, filterContext) {
if (!items?.length) return []; if (!items?.length) return [];
if (!filterContext) return items; if (!filterContext) return items;
const currentAccountID = store.session.get('currentAccount'); const currentAccountID = getCurrentAccountID();
return items.filter((item) => return items.filter((item) =>
filteredItem(item, filterContext, currentAccountID), filteredItem(item, filterContext, currentAccountID),
); );

Wyświetl plik

@ -1,11 +1,11 @@
import { api } from './api'; import { api } from './api';
import store from './store'; import { getCurrentAccountID } from './store-utils';
export async function fetchRelationships(accounts, relationshipsMap = {}) { export async function fetchRelationships(accounts, relationshipsMap = {}) {
if (!accounts?.length) return; if (!accounts?.length) return;
const { masto } = api(); const { masto } = api();
const currentAccount = store.session.get('currentAccount'); const currentAccount = getCurrentAccountID();
const uniqueAccountIds = accounts.reduce((acc, a) => { const uniqueAccountIds = accounts.reduce((acc, a) => {
// 1. Ignore duplicate accounts // 1. Ignore duplicate accounts
// 2. Ignore accounts that are already inside relationshipsMap // 2. Ignore accounts that are already inside relationshipsMap

Wyświetl plik

@ -16,13 +16,40 @@ export function getAccountByInstance(instance) {
return accounts.find((a) => a.instanceURL === instance); return accounts.find((a) => a.instanceURL === instance);
} }
const standaloneMQ = window.matchMedia('(display-mode: standalone)');
export function getCurrentAccountID() {
try {
const id = store.session.get('currentAccount');
if (id) return id;
} catch (e) {}
if (standaloneMQ.matches) {
try {
const id = store.local.get('currentAccount');
if (id) return id;
} catch (e) {}
}
return null;
}
export function setCurrentAccountID(id) {
try {
store.session.set('currentAccount', id);
} catch (e) {}
if (standaloneMQ.matches) {
try {
store.local.set('currentAccount', id);
} catch (e) {}
}
}
export function getCurrentAccount() { export function getCurrentAccount() {
if (!window.__IGNORE_GET_ACCOUNT_ERROR__) { if (!window.__IGNORE_GET_ACCOUNT_ERROR__) {
// Track down getCurrentAccount() calls before account-based states are initialized // Track down getCurrentAccount() calls before account-based states are initialized
console.error('getCurrentAccount() called before states are initialized'); console.error('getCurrentAccount() called before states are initialized');
if (import.meta.env.DEV) console.trace(); if (import.meta.env.DEV) console.trace();
} }
const currentAccount = store.session.get('currentAccount'); const currentAccount = getCurrentAccountID();
const account = getAccount(currentAccount); const account = getAccount(currentAccount);
return account; return account;
} }
@ -48,7 +75,7 @@ export function saveAccount(account) {
accounts.push(account); accounts.push(account);
} }
store.local.setJSON('accounts', accounts); store.local.setJSON('accounts', accounts);
store.session.set('currentAccount', account.info.id); setCurrentAccountID(account.info.id);
} }
export function updateAccount(accountInfo) { export function updateAccount(accountInfo) {