| 20 | // the feed. Off: every link out of the app goes to the system browser, |
| 21 | // never the wrapper's own browser view. |
| 22 | export const useInAppLinks = (): void => { |
| 23 | const router = useRouter(); |
| 24 | const isPhone = useIsPhone(); |
| 25 | const { value: isOptedOut, set: setOptedOut } = useSettingsBooleanFlag( |
| 26 | 'openLinksInAppOptOut', |
| 27 | ); |
| 28 | const { loadedSettings } = useSettingsContext(); |
| 29 | const setOptedOutRef = useRef(setOptedOut); |
| 30 | setOptedOutRef.current = setOptedOut; |
| 31 | |
| 32 | // The wrapper mirrors the choice into the system Settings and reports a |
| 33 | // change made there when the app comes back; both sides say what they |
| 34 | // know, and only a difference writes. |
| 35 | useEffect(() => { |
| 36 | if (!loadedSettings || !supportsReading()) { |
| 37 | return undefined; |
| 38 | } |
| 39 | postReading(ReadingAction.Preference, { inApp: !isOptedOut }); |
| 40 | const onPreference = (event: Event) => { |
| 41 | const { inApp } = |
| 42 | (event as CustomEvent<{ inApp?: boolean }>).detail ?? {}; |
| 43 | if (typeof inApp === 'boolean' && inApp === isOptedOut) { |
| 44 | setOptedOutRef.current(!inApp); |
| 45 | } |
| 46 | }; |
| 47 | window.addEventListener(ReadingEvent.Preference, onPreference); |
| 48 | return () => |
| 49 | window.removeEventListener(ReadingEvent.Preference, onPreference); |
| 50 | }, [isOptedOut, loadedSettings]); |
| 51 | |
| 52 | useEffect(() => { |
| 53 | if (!isPhone || !supportsReading()) { |
| 54 | return undefined; |
| 55 | } |
| 56 | if (isOptedOut) { |
| 57 | const onClick = (event: MouseEvent) => { |
| 58 | const anchor = (event.target as Element | null)?.closest?.('a[href]'); |
| 59 | if (!(anchor instanceof HTMLAnchorElement) || !isOutsideLink(anchor)) { |
| 60 | return; |
| 61 | } |
| 62 | event.preventDefault(); |
| 63 | openInSystemBrowser(anchor.href); |
| 64 | }; |
| 65 | document.addEventListener('click', onClick, true); |
| 66 | return () => document.removeEventListener('click', onClick, true); |
| 67 | } |
| 68 | // The drawer puts the page where it belongs on arrival; the router's |
| 69 | // own scroll to the top would land after it. |
| 70 | setFeedReadingOpener((post, url) => { |
| 71 | queueReadingOpen(post, url); |
| 72 | router.push(getPostPath(post), undefined, { scroll: false }); |
| 73 | }); |
| 74 | return () => setFeedReadingOpener(null); |
| 75 | }, [isPhone, isOptedOut, router]); |
| 76 | }; |