Skip to content

Commit

Permalink
Ask before navigating away from composer
Browse files Browse the repository at this point in the history
This makes the 'Discard draft?' post show up if you click on a link
within the composer.

That fixes a bug where you write a reply to a post and then lose the
reply by clicking on the avatar of the person who you’re responding to.
You would not be prompted whether you want to discard your draft like
when clicking on **Cancel**. This bug also applies to hovering over the
avatar and clicking on one of the links there.
  • Loading branch information
KevSlashNull committed Dec 22, 2024
1 parent fa2072c commit fe403f6
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 100 deletions.
11 changes: 9 additions & 2 deletions src/components/Link.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react'
import React, {useContext} from 'react'
import {GestureResponderEvent} from 'react-native'
import {sanitizeUrl} from '@braintree/sanitize-url'
import {StackActions, useLinkProps} from '@react-navigation/native'
Expand All @@ -17,6 +17,7 @@ import {
import {isNative, isWeb} from '#/platform/detection'
import {shouldClickOpenNewTab} from '#/platform/urls'
import {useModalControls} from '#/state/modals'
import {ComposerContext} from '#/view/com/composer/Composer'
import {atoms as a, flatten, TextStyleProp, useTheme, web} from '#/alf'
import {Button, ButtonProps} from '#/components/Button'
import {useInteractionState} from '#/components/hooks/useInteractionState'
Expand Down Expand Up @@ -84,9 +85,10 @@ export function useLink({
const isExternal = isExternalUrl(href)
const {openModal, closeModal} = useModalControls()
const openLink = useOpenLink()
const composerContext = useContext(ComposerContext)

const onPress = React.useCallback(
(e: GestureResponderEvent) => {
async (e: GestureResponderEvent) => {
const exitEarlyIfFalse = outerOnPress?.(e)

if (exitEarlyIfFalse === false) return
Expand All @@ -102,6 +104,10 @@ export function useLink({
e.preventDefault()
}

if (composerContext) {
await composerContext.attemptNavigation()
}

if (requiresWarning) {
openModal({
name: 'link-warning',
Expand Down Expand Up @@ -152,6 +158,7 @@ export function useLink({
closeModal,
action,
navigation,
composerContext,
],
)

Expand Down
21 changes: 13 additions & 8 deletions src/components/ProfileHoverCard/index.web.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {useProfileShadow} from '#/state/cache/profile-shadow'
import {useModerationOpts} from '#/state/preferences/moderation-opts'
import {usePrefetchProfileQuery, useProfileQuery} from '#/state/queries/profile'
import {useSession} from '#/state/session'
import {ComposerContext} from '#/view/com/composer/Composer'
import {formatCount} from '#/view/com/util/numeric/format'
import {UserAvatar} from '#/view/com/util/UserAvatar'
import {ProfileHeaderHandle} from '#/screens/Profile/Header/Handle'
Expand Down Expand Up @@ -306,6 +307,8 @@ export function ProfileHoverCardInner(props: ProfileHoverCardProps) {
: `fadeIn ${SHOW_DURATION}ms both`,
}

const composerContext = React.useContext(ComposerContext)

return (
<View
// @ts-ignore View is being used as div
Expand All @@ -318,15 +321,17 @@ export function ProfileHoverCardInner(props: ProfileHoverCardProps) {
{props.children}
{isVisible && (
<Portal>
<div
ref={refs.setFloating}
style={floatingStyles}
onPointerEnter={onPointerEnterCard}
onPointerLeave={onPointerLeaveCard}>
<div style={{willChange: 'transform', ...animationStyle}}>
<Card did={props.did} hide={onPress} />
<ComposerContext.Provider value={composerContext}>
<div
ref={refs.setFloating}
style={floatingStyles}
onPointerEnter={onPointerEnterCard}
onPointerLeave={onPointerLeaveCard}>
<div style={{willChange: 'transform', ...animationStyle}}>
<Card did={props.did} hide={onPress} />
</div>
</div>
</div>
</ComposerContext.Provider>
</Portal>
)}
</View>
Expand Down
14 changes: 11 additions & 3 deletions src/components/Prompt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,12 @@ export function Outer({
control,
testID,
nativeOptions,
onCancel,
}: React.PropsWithChildren<{
control: Dialog.DialogControlProps
testID?: string
nativeOptions?: Omit<BottomSheetViewProps, 'children'>
onCancel?: () => void
}>) {
const {gtMobile} = useBreakpoints()
const titleId = React.useId()
Expand All @@ -45,6 +47,7 @@ export function Outer({
<Dialog.Outer
control={control}
testID={testID}
onClose={onCancel}
nativeOptions={{preventExpansion: true, ...nativeOptions}}>
<Dialog.Handle />
<Context.Provider value={context}>
Expand Down Expand Up @@ -108,18 +111,21 @@ export function Actions({children}: React.PropsWithChildren<{}>) {

export function Cancel({
cta,
onCancel,
}: {
/**
* Optional i18n string. If undefined, it will default to "Cancel".
*/
cta?: string
onCancel?: () => void
}) {
const {_} = useLingui()
const {gtMobile} = useBreakpoints()
const {close} = Dialog.useDialogContext()
const onPress = React.useCallback(() => {
onCancel?.()
close()
}, [close])
}, [onCancel, close])

return (
<Button
Expand Down Expand Up @@ -184,6 +190,7 @@ export function Basic({
cancelButtonCta,
confirmButtonCta,
onConfirm,
onCancel,
confirmButtonColor,
showCancel = true,
}: React.PropsWithChildren<{
Expand All @@ -200,11 +207,12 @@ export function Basic({
* should NOT close the dialog as a side effect of this method.
*/
onConfirm: (e: GestureResponderEvent) => void
onCancel?: () => void
confirmButtonColor?: ButtonColor
showCancel?: boolean
}>) {
return (
<Outer control={control} testID="confirmModal">
<Outer control={control} testID="confirmModal" onCancel={onCancel}>
<TitleText>{title}</TitleText>
<DescriptionText>{description}</DescriptionText>
<Actions>
Expand All @@ -214,7 +222,7 @@ export function Basic({
color={confirmButtonColor}
testID="confirmBtn"
/>
{showCancel && <Cancel cta={cancelButtonCta} />}
{showCancel && <Cancel onCancel={onCancel} cta={cancelButtonCta} />}
</Actions>
</Outer>
)
Expand Down
190 changes: 103 additions & 87 deletions src/view/com/composer/Composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ type CancelRef = {
onPressCancel: () => void
}

export const ComposerContext = React.createContext<{
attemptNavigation: () => Promise<void>
} | null>(null)

type Props = ComposerOpts
export const ComposePost = ({
replyTo,
Expand Down Expand Up @@ -174,6 +178,7 @@ export const ComposePost = ({
const [isPublishing, setIsPublishing] = useState(false)
const [publishingStage, setPublishingStage] = useState('')
const [error, setError] = useState('')
const [navigationCallback, setNavigationCallback] = useState<() => void>()

const [composerState, composerDispatch] = useReducer(
composerReducer,
Expand Down Expand Up @@ -255,9 +260,10 @@ export const ComposePost = ({
const [publishOnUpload, setPublishOnUpload] = useState(false)

const onClose = useCallback(() => {
navigationCallback?.()
closeComposer()
clearThumbnailCache(queryClient)
}, [closeComposer, queryClient])
}, [navigationCallback, closeComposer, queryClient])

const insets = useSafeAreaInsets()
const viewStyles = useMemo(
Expand Down Expand Up @@ -596,93 +602,103 @@ export const ComposePost = ({

const isWebFooterSticky = !isNative && thread.posts.length > 1
return (
<BottomSheetPortalProvider>
<VerifyEmailDialog
control={emailVerificationControl}
onCloseWithoutVerifying={() => {
onClose()
}}
reasonText={_(
msg`Before creating a post, you must first verify your email.`,
)}
/>
<KeyboardAvoidingView
testID="composePostView"
behavior={isIOS ? 'padding' : 'height'}
keyboardVerticalOffset={keyboardVerticalOffset}
style={a.flex_1}>
<View
style={[a.flex_1, viewStyles]}
aria-modal
accessibilityViewIsModal>
<ComposerTopBar
canPost={canPost}
isReply={!!replyTo}
isPublishQueued={publishOnUpload}
isPublishing={isPublishing}
isThread={thread.posts.length > 1}
publishingStage={publishingStage}
topBarAnimatedStyle={topBarAnimatedStyle}
onCancel={onPressCancel}
onPublish={onPressPublish}>
{missingAltError && <AltTextReminder error={missingAltError} />}
<ErrorBanner
error={error}
videoState={erroredVideo}
clearError={() => setError('')}
clearVideo={
erroredVideoPostId
? () => clearVideo(erroredVideoPostId)
: () => {}
}
/>
</ComposerTopBar>

<Animated.ScrollView
ref={scrollViewRef}
layout={native(LinearTransition)}
onScroll={scrollHandler}
style={styles.scrollView}
keyboardShouldPersistTaps="always"
onContentSizeChange={onScrollViewContentSizeChange}
onLayout={onScrollViewLayout}>
{replyTo ? <ComposerReplyTo replyTo={replyTo} /> : undefined}
{thread.posts.map((post, index) => (
<React.Fragment key={post.id}>
<ComposerPost
post={post}
dispatch={composerDispatch}
textInput={post.id === activePost.id ? textInput : null}
isFirstPost={index === 0}
isPartOfThread={thread.posts.length > 1}
isReply={index > 0 || !!replyTo}
isActive={post.id === activePost.id}
canRemovePost={thread.posts.length > 1}
canRemoveQuote={index > 0 || !initQuote}
onSelectVideo={selectVideo}
onClearVideo={clearVideo}
onPublish={onComposerPostPublish}
onError={setError}
/>
{isWebFooterSticky && post.id === activePost.id && (
<View style={styles.stickyFooterWeb}>{footer}</View>
)}
</React.Fragment>
))}
</Animated.ScrollView>
{!isWebFooterSticky && footer}
</View>

<Prompt.Basic
control={discardPromptControl}
title={_(msg`Discard draft?`)}
description={_(msg`Are you sure you'd like to discard this draft?`)}
onConfirm={onClose}
confirmButtonCta={_(msg`Discard`)}
confirmButtonColor="negative"
<ComposerContext.Provider
value={{
attemptNavigation: () =>
new Promise(resolve => {
discardPromptControl.open()
setNavigationCallback(() => resolve)
}),
}}>
<BottomSheetPortalProvider>
<VerifyEmailDialog
control={emailVerificationControl}
onCloseWithoutVerifying={() => {
onClose()
}}
reasonText={_(
msg`Before creating a post, you must first verify your email.`,
)}
/>
</KeyboardAvoidingView>
</BottomSheetPortalProvider>
<KeyboardAvoidingView
testID="composePostView"
behavior={isIOS ? 'padding' : 'height'}
keyboardVerticalOffset={keyboardVerticalOffset}
style={a.flex_1}>
<View
style={[a.flex_1, viewStyles]}
aria-modal
accessibilityViewIsModal>
<ComposerTopBar
canPost={canPost}
isReply={!!replyTo}
isPublishQueued={publishOnUpload}
isPublishing={isPublishing}
isThread={thread.posts.length > 1}
publishingStage={publishingStage}
topBarAnimatedStyle={topBarAnimatedStyle}
onCancel={onPressCancel}
onPublish={onPressPublish}>
{missingAltError && <AltTextReminder error={missingAltError} />}
<ErrorBanner
error={error}
videoState={erroredVideo}
clearError={() => setError('')}
clearVideo={
erroredVideoPostId
? () => clearVideo(erroredVideoPostId)
: () => {}
}
/>
</ComposerTopBar>

<Animated.ScrollView
ref={scrollViewRef}
layout={native(LinearTransition)}
onScroll={scrollHandler}
style={styles.scrollView}
keyboardShouldPersistTaps="always"
onContentSizeChange={onScrollViewContentSizeChange}
onLayout={onScrollViewLayout}>
{replyTo ? <ComposerReplyTo replyTo={replyTo} /> : undefined}
{thread.posts.map((post, index) => (
<React.Fragment key={post.id}>
<ComposerPost
post={post}
dispatch={composerDispatch}
textInput={post.id === activePost.id ? textInput : null}
isFirstPost={index === 0}
isPartOfThread={thread.posts.length > 1}
isReply={index > 0 || !!replyTo}
isActive={post.id === activePost.id}
canRemovePost={thread.posts.length > 1}
canRemoveQuote={index > 0 || !initQuote}
onSelectVideo={selectVideo}
onClearVideo={clearVideo}
onPublish={onComposerPostPublish}
onError={setError}
/>
{isWebFooterSticky && post.id === activePost.id && (
<View style={styles.stickyFooterWeb}>{footer}</View>
)}
</React.Fragment>
))}
</Animated.ScrollView>
{!isWebFooterSticky && footer}
</View>

<Prompt.Basic
control={discardPromptControl}
title={_(msg`Discard draft?`)}
description={_(msg`Are you sure you'd like to discard this draft?`)}
onConfirm={onClose}
onCancel={() => setNavigationCallback(undefined)}
confirmButtonCta={_(msg`Discard`)}
confirmButtonColor="negative"
/>
</KeyboardAvoidingView>
</BottomSheetPortalProvider>
</ComposerContext.Provider>
)
}

Expand Down

0 comments on commit fe403f6

Please sign in to comment.