Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add kvasir support to smart title hook #4156

Merged
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
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',
Comment on lines +46 to +47
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We want to update translation for currently shown post that is passed as a prop to useSmartTitle so if we are in feed I use feed mode and else just single 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);
Comment on lines +102 to +104
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fetch from kvasir directly, it will return the correct one depending on the clickbait shield setting

} 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,
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

to manually control which title we request

}) => {
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