Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/shared/src/components/shell/readingStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { Post } from '../../graphql/posts';
import { WebKitMessageHandlers } from '../../lib/ios';
import { hasNativeHandler, postNativeMessage } from '../../lib/nativeBridge';
import { getAbsoluteWebappUrl } from '../../lib/links';
import { publicApiUrl } from '../../lib/config';

// The article the wrapper shows behind the post while the post page is the
// reading drawer. The wrapper reports the page's state as it changes.
Expand Down Expand Up @@ -98,6 +99,15 @@ const appHosts = (): string[] =>
export const isOutsideLink = (anchor: HTMLAnchorElement): boolean =>
/^https?:$/.test(anchor.protocol) && !appHosts().includes(anchor.host);

// The post behind a redirect link (`api.daily.dev/r/<id>`): the redirect only
// counts the read when it can tell who is reading.
export const getRedirectPostId = (anchor: HTMLAnchorElement): string | null => {
if (!publicApiUrl || anchor.host !== new URL(publicApiUrl).host) {
return null;
}
return anchor.pathname.match(/^\/r\/([^/]+)\/?$/)?.[1] ?? null;
};

const shareIntents =
/^(?:[a-z0-9-]+\.)?(?:twitter\.com|x\.com|facebook\.com|linkedin\.com|reddit\.com|wa\.me|whatsapp\.com|t\.me|telegram\.me)$/;

Expand Down
43 changes: 43 additions & 0 deletions packages/shared/src/hooks/useInAppLinks.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ jest.mock('../contexts/SettingsContext', () => ({
useSettingsContext: () => ({ loadedSettings: mockLoadedSettings }),
}));

const mockViewPost = jest.fn(() => Promise.resolve());

jest.mock('./post/useViewPost', () => ({
useViewPost: () => mockViewPost,
}));

let mockUser: { id: string } | undefined = { id: 'u1' };

jest.mock('../contexts/AuthContext', () => ({
useAuthContext: () => ({ user: mockUser }),
}));

type BridgeGlobal = typeof globalThis & { webkit?: unknown };

const postMessage = jest.fn();
Expand All @@ -43,6 +55,7 @@ const Page = () => {
<>
<a href="https://blog.example.com/post">Outside</a>
<a href="/posts/p1">Inside</a>
<a href={`${process.env.NEXT_PUBLIC_API_URL}/r/p1`}>Read</a>
</>
);
};
Expand All @@ -51,6 +64,8 @@ beforeEach(() => {
postMessage.mockClear();
mockPush.mockClear();
mockSetOptedOut.mockClear();
mockViewPost.mockClear();
mockUser = { id: 'u1' };
mockLoadedSettings = true;
(globalThis as BridgeGlobal).webkit = {
messageHandlers: { reading: { postMessage } },
Expand Down Expand Up @@ -140,4 +155,32 @@ describe('useInAppLinks', () => {
openReadingFromFeed({ id: 'p1' } as Post, 'https://api.daily.dev/r/p1'),
).toBe(false);
});

it('counts the read of a post it hands to the system browser', () => {
mockOptedOut = true;
render(<Page />);

fireEvent.click(screen.getByText('Outside'));
expect(mockViewPost).not.toHaveBeenCalled();

fireEvent.click(screen.getByText('Read'));
expect(mockViewPost).toHaveBeenCalledWith('p1');
expect(postMessage).toHaveBeenCalledWith({
action: 'external',
url: `${process.env.NEXT_PUBLIC_API_URL}/r/p1`,
});
});

it('counts no read for a logged-out reader', () => {
mockOptedOut = true;
mockUser = undefined;
render(<Page />);

fireEvent.click(screen.getByText('Read'));
expect(mockViewPost).not.toHaveBeenCalled();
expect(postMessage).toHaveBeenCalledWith({
action: 'external',
url: `${process.env.NEXT_PUBLIC_API_URL}/r/p1`,
});
});
});
15 changes: 15 additions & 0 deletions packages/shared/src/hooks/useInAppLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ import { useRouter } from 'next/router';
import { useIsPhone } from './useViewSize';
import { useSettingsBooleanFlag } from './useSettingsBooleanFlag';
import { useSettingsContext } from '../contexts/SettingsContext';
import { useAuthContext } from '../contexts/AuthContext';
import { useViewPost } from './post/useViewPost';
import {
getRedirectPostId,
isOutsideLink,
openInSystemBrowser,
postReading,
Expand All @@ -26,8 +29,16 @@ export const useInAppLinks = (): void => {
'openLinksInAppOptOut',
);
const { loadedSettings } = useSettingsContext();
const { user } = useAuthContext();
const onSendViewPost = useViewPost();
const setOptedOutRef = useRef(setOptedOut);
setOptedOutRef.current = setOptedOut;
const viewPostRef = useRef<((postId: string) => void) | null>(null);
viewPostRef.current = user?.id
? (postId) => {
onSendViewPost(postId).catch(() => undefined);
}
: null;

// The wrapper mirrors the choice into the system Settings and reports a
// change made there when the app comes back; both sides say what they
Expand Down Expand Up @@ -60,6 +71,10 @@ export const useInAppLinks = (): void => {
return;
}
event.preventDefault();
const postId = getRedirectPostId(anchor);
if (postId) {
viewPostRef.current?.(postId);
}
openInSystemBrowser(anchor.href);
};
document.addEventListener('click', onClick, true);
Expand Down
Loading