[Glitch] Manage focus on navigation

Port bcb8553e01 to glitch-soc

Signed-off-by: Claire <claire.github-309c@sitedethib.com>
This commit is contained in:
diondiondion authored and Claire committed 2026-06-10 19:04:58 +02:00
1 parent 5893554a3a
commit 4cb1bf73c9
21 files changed
+254 -33

No files matched your search

@@ -19,6 +19,7 @@ import { useIdentity } from 'flavours/glitch/identity_context';
import { useColumnIndexContext } from '../features/ui/components/columns_area';
import { getColumnSkipLinkId } from '../features/ui/components/skip_links';
import { NavigationFocusTarget } from './navigation_focus_target';
import { useAppHistory } from './router';
export const messages = defineMessages({
@@ -285,7 +286,10 @@ export const ColumnHeader: React.FC<Props> = ({
<div className={headingClassName}>
{backButton}
{hasTitle && (
<h1 className='column-header__title-wrapper'>
<NavigationFocusTarget
as='h1'
className='column-header__title-wrapper'
>
{onClick ? (
<button
onClick={handleTitleClick}
@@ -304,7 +308,7 @@ export const ColumnHeader: React.FC<Props> = ({
{titleContents}
</span>
)}
</h1>
</NavigationFocusTarget>
)}
<div className='column-header__buttons'>
@@ -7,6 +7,7 @@ import { multiply } from 'color-blend';
import { createBrowserHistory } from 'history';
import { WithOptionalRouterPropTypes, withOptionalRouter } from 'flavours/glitch/utils/react_router';
import { IGNORE_FOCUS_ON_OPEN } from '../reducers/modal';
class ModalRoot extends PureComponent {
@@ -22,7 +23,10 @@ class ModalRoot extends PureComponent {
}),
]),
noEsc: PropTypes.bool,
ignoreFocus: PropTypes.bool,
ignoreFocus: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string, // 'on-open', see IGNORE_FOCUS_ON_OPEN
]),
...WithOptionalRouterPropTypes,
};
@@ -123,7 +127,11 @@ class ModalRoot extends PureComponent {
_ensureHistoryBuffer () {
const { pathname, search, hash, state } = this.history.location;
if (!state || state.mastodonModalKey !== this._modalHistoryKey) {
this.history.push({ pathname, search, hash }, { ...state, mastodonModalKey: this._modalHistoryKey });
this.history.push({ pathname, search, hash }, {
...state,
focusTarget: this.props.ignoreFocus !== IGNORE_FOCUS_ON_OPEN,
mastodonModalKey: this._modalHistoryKey,
});
}
}
@@ -0,0 +1,145 @@
import {
createContext,
useContext,
useRef,
useLayoutEffect,
useCallback,
} from 'react';
import { useLocation } from 'react-router-dom';
import { polymorphicForwardRef } from '@/types/polymorphic';
import type { MastodonLocation } from '../router';
export const FOCUS_TARGET = {
POST: 'detailed-status',
} as const;
export type FocusTarget =
| boolean
| (typeof FOCUS_TARGET)[keyof typeof FOCUS_TARGET];
const FocusTargetContext =
createContext<React.MutableRefObject<FocusTarget> | null>(null);
/**
* `FocusTargetProvider` keeps track of whether focus should be
* set after a navigation. By default, any navigation will set the
* current value of `focusTargetRef` to `true`, which will cause
* the `NavigationFocusTarget` component to focus itself when it mounts.
*
* To disable this behaviour for a navigation, the focus target can be
* set to `false` using location state, for example:
* ```
* location.push(url, { focusTarget: false });
* ```
*
* If the target page contains multiple `NavigationFocusTarget` components
* (e.g. a main heading and a post that should be focused), give the more
* specific `NavigationFocusTarget` instance a name, and pass the same name
* via location state:
* ```
* location.push(url, { focusTarget: 'detailed-status' });
* ```
*/
export const FocusTargetProvider: React.FC<{
children: React.ReactNode;
}> = ({ children }) => {
const focusTargetRef = useRef<FocusTarget>(false);
const previousLocationRef = useRef<
| (Pick<MastodonLocation, 'pathname' | 'search'> & {
focusTarget?: FocusTarget;
})
| null
>(null);
const {
pathname,
search,
state = {},
} = useLocation<{ focusTarget?: FocusTarget } | undefined>();
const { focusTarget } = state;
useLayoutEffect(() => {
// We never want to set focus on page load, so we keep
// track of whether a manual navigation has occurred by comparing
// our current with the previous location:
const previous = previousLocationRef.current;
// Bail out on the first render, populate previousLocationRef
if (previous === null) {
previousLocationRef.current = { pathname, search, focusTarget };
return;
}
// Bail out if location hasn't changed
if (
previous.pathname === pathname &&
previous.search === search &&
previous.focusTarget === focusTarget
) {
return;
}
// Location has changed:
// - Set focusTarget
// – Store current location as previous
// (We store `focusTarget` as `false` to allow overriding it.)
previousLocationRef.current = { pathname, search, focusTarget: false };
focusTargetRef.current = focusTarget ?? true;
}, [pathname, search, focusTarget]);
return (
<FocusTargetContext.Provider value={focusTargetRef}>
{children}
</FocusTargetContext.Provider>
);
};
export function useFocusOnNavigation(targetName?: string) {
const focusTargetRef = useContext(FocusTargetContext);
if (focusTargetRef === null) {
throw Error(
'useFocusTargetContext must be used inside of a FocusTargetProvider',
);
}
return useCallback(
(element: HTMLElement | null) => {
const focusTarget = focusTargetRef.current;
// Bail out if focusTarget was set to `false`
if (!element || !focusTarget) {
return;
}
if (focusTarget === true || focusTarget === targetName) {
setTimeout(() => {
element.focus({ preventScroll: true });
}, 0);
}
},
[focusTargetRef, targetName],
);
}
interface FocusTargetElementProps extends React.ComponentPropsWithoutRef<'h1'> {
focusTargetName?: string;
}
export const NavigationFocusTarget = polymorphicForwardRef<
'h1',
FocusTargetElementProps
>(({ as: Component = 'h1', focusTargetName, children, ...otherProps }) => {
const focusOnNavigation = useFocusOnNavigation(focusTargetName);
return (
<Component ref={focusOnNavigation} tabIndex={-1} {...otherProps}>
{children}
</Component>
);
});
@@ -14,9 +14,14 @@ import { createBrowserHistory } from 'history';
import { layoutFromWindow } from 'flavours/glitch/is_mobile';
import { isDevelopment } from 'flavours/glitch/utils/environment';
import type { FocusTarget } from './navigation_focus_target';
interface MastodonLocationState {
fromMastodon?: boolean;
mastodonModalKey?: string;
// Controls which element is focused after a navigation.
// Set to `false` to prevent navigation focus.
focusTarget?: FocusTarget;
// Prevent the rightmost column in advanced UI from scrolling
// into view on location changes
preventMultiColumnAutoScroll?: string;
@@ -32,6 +32,7 @@ import StatusIcons from './status_icons';
import StatusPrepend from './status_prepend';
import { CollectionPreviewCard } from '../features/collections/components/collection_preview_card';
import { compareUrls } from '../utils/compare_urls';
import { FOCUS_TARGET } from './navigation_focus_target';
const domParser = new DOMParser();
@@ -392,9 +393,9 @@ class Status extends ImmutablePureComponent {
window.open(path, '_blank', 'noopener');
} else {
if (history.location.pathname.replace('/deck/', '/') === path) {
history.replace(path);
history.replace(path, {focusTarget: FOCUS_TARGET.POST});
} else {
history.push(path);
history.push(path, {focusTarget: FOCUS_TARGET.POST});
}
}
};