Skip to content

Commit

Permalink
feat: add kvasir support to smart title hook (#4156)
Browse files Browse the repository at this point in the history
  • Loading branch information
capJavert authored Feb 6, 2025
1 parent f9ee8d8 commit 7648a93
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 16 deletions.
18 changes: 15 additions & 3 deletions packages/shared/src/hooks/post/useSmartTitle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import { useLogContext } from '../../contexts/LogContext';
import { useSettingsContext } from '../../contexts/SettingsContext';
import { useToastNotification } from '../useToastNotification';
import { labels } from '../../lib';
import { useTranslation } from '../translation/useTranslation';
import { useActiveFeedContext } from '../../contexts';

type UseSmartTitle = {
fetchSmartTitle: () => Promise<void>;
Expand All @@ -31,20 +33,28 @@ export const useSmartTitle = (post: Post): UseSmartTitle => {
const { isPlus } = usePlusSubscription();
const { completeAction } = useActions();
const { flags } = useSettingsContext();
const { queryKey } = useActiveFeedContext();

const { clickbaitShieldEnabled } = flags || {};

const key = useMemo(
() => [...getPostByIdKey(post?.id), { key: 'title' }],
[post?.id],
);

const { fetchTranslations } = useTranslation({
queryKey: queryKey || getPostByIdKey(post?.id),
queryType: queryKey ? 'feed' : 'post',
clickbaitShieldEnabled: !clickbaitShieldEnabled,
});

const fetchSmartTitleKey = generateQueryKey(
RequestKey.FetchedOriginalTitle,
user,
...getPostByIdKey(post?.id),
);

const { data: smartTitle, refetch } = useQuery({
const { data: smartTitle } = useQuery({
queryKey: key,
queryFn: async () => {
let title = post?.title || post?.sharedPost?.title;
Expand Down Expand Up @@ -89,7 +99,9 @@ export const useSmartTitle = (post: Post): UseSmartTitle => {

const fetchSmartTitle = useCallback(async () => {
if (!fetchedSmartTitle) {
await refetch();
const [translateResult] = await fetchTranslations([post]);

client.setQueryData(key, translateResult?.value || post?.title);
} else {
client.setQueryData(key, post?.title);
}
Expand All @@ -106,8 +118,8 @@ export const useSmartTitle = (post: Post): UseSmartTitle => {
logEvent,
post,
isPlus,
refetch,
key,
fetchTranslations,
]);

const title = useMemo(() => {
Expand Down
41 changes: 28 additions & 13 deletions packages/shared/src/hooks/translation/useTranslation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,9 @@ export enum ServerEvents {
type UseTranslation = (props: {
queryKey: QueryKey;
queryType: 'post' | 'feed';
clickbaitShieldEnabled?: boolean;
}) => {
fetchTranslations: (id: Post[]) => void;
fetchTranslations: (id: Post[]) => Promise<TranslateEvent[]>;
};

type TranslateFields = 'title' | 'smartTitle';
Expand Down Expand Up @@ -93,11 +94,18 @@ const updateTranslation = ({
return updatedPost;
};

export const useTranslation: UseTranslation = ({ queryKey, queryType }) => {
export const useTranslation: UseTranslation = ({
queryKey,
queryType,
clickbaitShieldEnabled: clickbaitShieldEnabledProp,
}) => {
const abort = useRef<AbortController>();
const { user, accessToken, isLoggedIn } = useAuthContext();
const { flags } = useSettingsContext();
const queryClient = useQueryClient();
const clickbaitShieldEnabled = !!(
clickbaitShieldEnabledProp ?? flags?.clickbaitShieldEnabled
);

const { language } = user || {};
const isStreamActive = isLoggedIn && !!language;
Expand All @@ -119,12 +127,12 @@ export const useTranslation: UseTranslation = ({ queryKey, queryType }) => {
updateTranslation({
post: feedData.pages[pageIndex].page.edges[index].node,
translation: translatedPost,
clickbaitShieldEnabled: !!flags?.clickbaitShieldEnabled,
clickbaitShieldEnabled,
}),
);
}
},
[queryKey, queryClient, flags?.clickbaitShieldEnabled],
[queryKey, queryClient, clickbaitShieldEnabled],
);

const updatePost = useCallback(
Expand All @@ -133,20 +141,20 @@ export const useTranslation: UseTranslation = ({ queryKey, queryType }) => {
updateTranslation({
post,
translation: translatedPost,
clickbaitShieldEnabled: !!flags?.clickbaitShieldEnabled,
clickbaitShieldEnabled,
}),
);
},
[queryClient, flags?.clickbaitShieldEnabled],
[queryClient, clickbaitShieldEnabled],
);

const fetchTranslations = useCallback(
async (posts: Post[]) => {
if (!isStreamActive) {
return;
return [];
}
if (posts.length === 0) {
return;
return [];
}

const postsToTranslate = posts
Expand All @@ -161,14 +169,14 @@ export const useTranslation: UseTranslation = ({ queryKey, queryType }) => {
.map((node) => (node?.title ? node : node?.sharedPost));

if (postsToTranslate.length === 0) {
return;
return [];
}

const payload = postsToTranslate.reduce((acc, post) => {
const fields = [];

const shouldUseSmartTitle =
post.clickbaitTitleDetected && flags?.clickbaitShieldEnabled;
post.clickbaitTitleDetected && clickbaitShieldEnabled;

if (shouldUseSmartTitle && !post.translation?.smartTitle) {
fields.push('smartTitle');
Expand All @@ -186,7 +194,7 @@ export const useTranslation: UseTranslation = ({ queryKey, queryType }) => {
}, {} as TranslatePayload);

if (Object.keys(payload).length === 0) {
return;
return [];
}

const response = await fetch(`${apiUrl}/translate/post`, {
Expand All @@ -202,20 +210,27 @@ export const useTranslation: UseTranslation = ({ queryKey, queryType }) => {
});

if (!response.ok) {
return;
return [];
}

const results: TranslateEvent[] = [];

// eslint-disable-next-line no-restricted-syntax
for await (const message of events(response)) {
if (message.event === ServerEvents.Message) {
const post = JSON.parse(message.data) as TranslateEvent;

results.push(post);

if (queryType === 'feed') {
updateFeed(post);
} else {
updatePost(post);
}
}
}

return results;
},
[
accessToken?.token,
Expand All @@ -224,7 +239,7 @@ export const useTranslation: UseTranslation = ({ queryKey, queryType }) => {
queryType,
updateFeed,
updatePost,
flags?.clickbaitShieldEnabled,
clickbaitShieldEnabled,
],
);

Expand Down

0 comments on commit 7648a93

Please sign in to comment.