-
Notifications
You must be signed in to change notification settings - Fork 245
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: stream translation titles in feed and post page #4098
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
2b5b7c9
feat: stream translation titles in feed
omBratteng cb293c9
fix: don't call Kvasir if language is unset
omBratteng cc575fb
fix: prepare to support translation on post page
omBratteng b65f69e
feat: stream translation on post page
omBratteng 6343527
fix: mock TransformStream
omBratteng 087a1db
fix: add abort signal to stream
omBratteng 020414f
fix: merge into `isStreamActive`
omBratteng d880ae1
fix: isStreamActive boolean logic
omBratteng 55f6de5
Merge branch 'feat-realtime-translation' into AS-925-kvasir-stream
omBratteng 7fe2c72
fix: filter based on shared post title if no title exists
omBratteng e40f6e6
refactor: replace `stream` with `events`
omBratteng 3cc900b
fix: require language in isStreamActive
omBratteng 928af03
fix: force memo to re-run when feed query is updated
omBratteng a81d57a
refactor: move filter logic into hook
omBratteng 6e2db93
Merge branch 'feat-realtime-translation' into AS-925-kvasir-stream
omBratteng 82fc409
fix: fetch translation for original title when clickbait shield is di…
omBratteng 84ccf8b
fix: lint
omBratteng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
166 changes: 166 additions & 0 deletions
166
packages/shared/src/hooks/translation/useTranslation.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,166 @@ | ||
import { useCallback, useEffect, useRef } from 'react'; | ||
import type { InfiniteData, QueryKey } from '@tanstack/react-query'; | ||
import { useQueryClient } from '@tanstack/react-query'; | ||
import { events } from 'fetch-event-stream'; | ||
import { useAuthContext } from '../../contexts/AuthContext'; | ||
import { apiUrl } from '../../lib/config'; | ||
import type { FeedData, Post } from '../../graphql/posts'; | ||
import { | ||
updateCachedPagePost, | ||
findIndexOfPostInData, | ||
updatePostCache, | ||
} from '../../lib/query'; | ||
import { useSettingsContext } from '../../contexts/SettingsContext'; | ||
|
||
export enum ServerEvents { | ||
Connect = 'connect', | ||
Message = 'message', | ||
Disconnect = 'disconnect', | ||
Error = 'error', | ||
omBratteng marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
type UseTranslation = (props: { | ||
queryKey: QueryKey; | ||
queryType: 'post' | 'feed'; | ||
}) => { | ||
fetchTranslations: (id: Post[]) => void; | ||
}; | ||
|
||
type TranslateEvent = { | ||
id: string; | ||
title: string; | ||
}; | ||
|
||
const updateTranslation = (post: Post, translation: TranslateEvent): Post => { | ||
const updatedPost = post; | ||
if (post.title) { | ||
updatedPost.title = translation.title; | ||
updatedPost.translation = { title: !!translation.title }; | ||
} else { | ||
updatedPost.sharedPost.title = translation.title; | ||
updatedPost.sharedPost.translation = { title: !!translation.title }; | ||
} | ||
Comment on lines
+40
to
+42
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Doesn't this set it wrong in cache? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No, don't think so |
||
|
||
return updatedPost; | ||
}; | ||
|
||
export const useTranslation: UseTranslation = ({ queryKey, queryType }) => { | ||
const abort = useRef<AbortController>(); | ||
const { user, accessToken, isLoggedIn } = useAuthContext(); | ||
const { flags } = useSettingsContext(); | ||
const queryClient = useQueryClient(); | ||
|
||
const { language } = user || {}; | ||
const isStreamActive = isLoggedIn && !!language; | ||
|
||
const updateFeed = useCallback( | ||
(translatedPost: TranslateEvent) => { | ||
const updatePost = updateCachedPagePost(queryKey, queryClient); | ||
const feedData = | ||
queryClient.getQueryData<InfiniteData<FeedData>>(queryKey); | ||
const { pageIndex, index } = findIndexOfPostInData( | ||
feedData, | ||
translatedPost.id, | ||
true, | ||
); | ||
if (index > -1) { | ||
updatePost( | ||
pageIndex, | ||
index, | ||
updateTranslation( | ||
feedData.pages[pageIndex].page.edges[index].node, | ||
translatedPost, | ||
), | ||
); | ||
} | ||
}, | ||
[queryKey, queryClient], | ||
); | ||
|
||
const updatePost = useCallback( | ||
(translatedPost: TranslateEvent) => { | ||
updatePostCache(queryClient, translatedPost.id, (post) => | ||
updateTranslation(post, translatedPost), | ||
); | ||
}, | ||
[queryClient], | ||
); | ||
|
||
const fetchTranslations = useCallback( | ||
async (posts: Post[]) => { | ||
if (!isStreamActive) { | ||
return; | ||
} | ||
if (posts.length === 0) { | ||
return; | ||
} | ||
|
||
const postIds = posts | ||
.filter((node) => | ||
node?.title | ||
? !node?.translation?.title | ||
: !node?.sharedPost?.translation?.title, | ||
) | ||
.filter((node) => | ||
flags.clickbaitShieldEnabled && node?.title | ||
? !node.clickbaitTitleDetected | ||
: !node.sharedPost?.clickbaitTitleDetected, | ||
) | ||
.filter(Boolean) | ||
.map((node) => (node?.title ? node.id : node?.sharedPost.id)); | ||
|
||
if (postIds.length === 0) { | ||
return; | ||
} | ||
|
||
const params = new URLSearchParams(); | ||
postIds.forEach((id) => { | ||
params.append('id', id); | ||
}); | ||
|
||
const response = await fetch(`${apiUrl}/translate/post/title?${params}`, { | ||
signal: abort.current?.signal, | ||
headers: { | ||
Accept: 'text/event-stream', | ||
Authorization: `Bearer ${accessToken?.token}`, | ||
'Content-Language': language as string, | ||
}, | ||
}); | ||
|
||
if (!response.ok) { | ||
return; | ||
} | ||
|
||
// 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; | ||
if (queryType === 'feed') { | ||
updateFeed(post); | ||
} else { | ||
updatePost(post); | ||
} | ||
} | ||
} | ||
}, | ||
[ | ||
accessToken?.token, | ||
flags.clickbaitShieldEnabled, | ||
isStreamActive, | ||
language, | ||
queryType, | ||
updateFeed, | ||
updatePost, | ||
], | ||
); | ||
|
||
useEffect(() => { | ||
abort.current = new AbortController(); | ||
|
||
return () => { | ||
abort.current?.abort(); | ||
}; | ||
omBratteng marked this conversation as resolved.
Show resolved
Hide resolved
|
||
}, []); | ||
|
||
return { fetchTranslations }; | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
You are using this because native EventSource does not allow headers? I would rather use the query param from AI search and native
EventSource
, wasteful to add dependencies for this.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, it's because it doesn't allow headers, think it's a neater solutions than token (don't really like auth tokens in params, even short lived ones 🙈) and language as query param. Package is 730B gzipped, so negligible small imo.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can shave it down to
608B gzipped
by usingevents
and not theirstream
wrapper which just adds two headers and checks if response is OK before returningevents
🤪There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If anything, I think we should move AI search over to use this as well. Especially now when we're starting to send smart prompts, we might encounter issues with max length of URLs in browsers.
Also because
EventSource
is kinda "deprecated", no browsers is going to remove it, but it's not getting any new features.So the package is just for parsing the stream,
fetch
natively supports streaming.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Wondering can we just use
fetch
then?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So the package name is a bit misleading, it's more a parser than fetch. It exposes
events
which is the stream parser (608B) thenstream
(122B) which just wraps around fetch and returns theevents
parsed stream.