@ -5,6 +5,7 @@ import {
ChatThreadShimmer ,
ChatThreadShimmer ,
EmptyStateBox ,
EmptyStateBox ,
InlineSpinner ,
InlineSpinner ,
ShimmerBox ,
} from '../../components/common/ShimmerSkeletons' ;
} from '../../components/common/ShimmerSkeletons' ;
import { useShopApp } from '../../context/ShopAppContext' ;
import { useShopApp } from '../../context/ShopAppContext' ;
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler' ;
import { useHardwareBackHandler } from '../../hooks/use-hardware-back-handler' ;
@ -15,23 +16,30 @@ import { isBareMode, ROUTES, USE_MOCK_DATA } from '../../lib/routes';
import {
import {
type ApiChatMessage ,
type ApiChatMessage ,
type ApiConversation ,
type ApiConversation ,
type ApiStoreSummary ,
shopApi ,
shopApi ,
} from '../../lib/shopApi' ;
} from '../../lib/shopApi' ;
import {
import {
isInFlutterWebView ,
isInFlutterWebView ,
uploadBrowserFileToTmpMedia ,
uploadFileViaFlutterBridge ,
pickFileViaFlutterBridge ,
} from '../../lib/webview-actions' ;
} from '../../lib/webview-actions' ;
const MAX_CHAT_ATTACHMENT_BYTES = 10 * 1024 * 1024 ;
interface FailedOutgoingDraft {
interface FailedOutgoingDraft {
tempId : string ;
tempId : string ;
text : string ;
text : string ;
attachmentFile? : File ;
attachmentUrl? : string ;
attachmentUrl? : string ;
attachmentKind ? : 'image' | 'audio' ;
isObjectUrl? : boolean ;
timeLabel : string ;
timeLabel : string ;
}
}
interface StagedAttachment {
interface StagedAttachment {
url : string ;
url : string ;
file? : File ;
isObjectUrl? : boolean ;
kind : 'image' | 'audio' ;
kind : 'image' | 'audio' ;
label : string ;
label : string ;
durationSec? : number ;
durationSec? : number ;
@ -236,7 +244,7 @@ export const ShopChatPage: React.FC = () => {
const { conversationId } = useParams < { conversationId? : string } > ( ) ;
const { conversationId } = useParams < { conversationId? : string } > ( ) ;
const resolvedConvRef = conversationId || 'al-hujjah-books' ;
const resolvedConvRef = conversationId || 'al-hujjah-books' ;
const smartBack = useSmartBack ( ROUTES . store ( resolvedConvRef ) ) ;
const smartBack = useSmartBack ( ROUTES . store ( resolvedConvRef ) ) ;
const { showToast , language } = useShopApp ( ) ;
const { isUserAuthenticated , requireAuth , showToast , language } = useShopApp ( ) ;
const isRtl = isRtlLanguage ( language ) ;
const isRtl = isRtlLanguage ( language ) ;
const [ menuOpen , setMenuOpen ] = useState ( false ) ;
const [ menuOpen , setMenuOpen ] = useState ( false ) ;
@ -247,8 +255,11 @@ export const ShopChatPage: React.FC = () => {
const [ isRecording , setIsRecording ] = useState ( false ) ;
const [ isRecording , setIsRecording ] = useState ( false ) ;
const [ recordingSeconds , setRecordingSeconds ] = useState ( 0 ) ;
const [ recordingSeconds , setRecordingSeconds ] = useState ( 0 ) ;
const [ conversation , setConversation ] = useState < ApiConversation | null > ( null ) ;
const [ conversation , setConversation ] = useState < ApiConversation | null > ( null ) ;
const [ publicStore , setPublicStore ] = useState < ApiStoreSummary | null > ( null ) ;
const [ messages , setMessages ] = useState < ApiChatMessage [ ] > ( [ ] ) ;
const [ messages , setMessages ] = useState < ApiChatMessage [ ] > ( [ ] ) ;
const [ loadingInitial , setLoadingInitial ] = useState < boolean > ( ( ) = > ! isBare ) ;
const [ loadingInitial , setLoadingInitial ] = useState < boolean > (
( ) = > ! isBare && isUserAuthenticated
) ;
const [ failedDrafts , setFailedDrafts ] = useState < FailedOutgoingDraft [ ] > ( [ ] ) ;
const [ failedDrafts , setFailedDrafts ] = useState < FailedOutgoingDraft [ ] > ( [ ] ) ;
const [ sending , setSending ] = useState ( false ) ;
const [ sending , setSending ] = useState ( false ) ;
@ -313,6 +324,18 @@ export const ShopChatPage: React.FC = () => {
return true ;
return true ;
} , menuOpen ) ;
} , menuOpen ) ;
const replaceStagedAttachment = useCallback (
( next : StagedAttachment | null ) = > {
setStagedAttachment ( ( prev ) = > {
if ( prev ? . isObjectUrl && prev . url && prev . url !== next ? . url ) {
URL . revokeObjectURL ( prev . url ) ;
}
return next ;
} ) ;
} ,
[ ]
) ;
useEffect ( ( ) = > {
useEffect ( ( ) = > {
if ( isBare ) {
if ( isBare ) {
setLoadingInitial ( false ) ;
setLoadingInitial ( false ) ;
@ -320,6 +343,24 @@ export const ShopChatPage: React.FC = () => {
}
}
let cancelled = false ;
let cancelled = false ;
lastIdRef . current = undefined ;
lastIdRef . current = undefined ;
if ( ! isUserAuthenticated ) {
setConversation ( null ) ;
setMessages ( [ ] ) ;
setLoadingInitial ( false ) ;
void shopApi
. fetchStoreDetail ( resolvedConvRef )
. then ( ( store ) = > {
if ( ! cancelled ) setPublicStore ( store ) ;
} )
. catch ( ( ) = > {
// ignore if conv ref is not a store slug
} ) ;
return ( ) = > {
cancelled = true ;
} ;
}
setLoadingInitial ( true ) ;
setLoadingInitial ( true ) ;
const loadInitial = async ( ) = > {
const loadInitial = async ( ) = > {
@ -370,7 +411,7 @@ export const ShopChatPage: React.FC = () => {
cancelled = true ;
cancelled = true ;
window . clearInterval ( interval ) ;
window . clearInterval ( interval ) ;
} ;
} ;
} , [ isBare , resolvedConvRef ] ) ;
} , [ isBare , isUserAuthenticated , resolvedConvRef ] ) ;
useEffect ( ( ) = > {
useEffect ( ( ) = > {
if ( ! isBare ) {
if ( ! isBare ) {
@ -379,18 +420,34 @@ export const ShopChatPage: React.FC = () => {
} , [ isBare , messages . length , failedDrafts . length ] ) ;
} , [ isBare , messages . length , failedDrafts . length ] ) ;
const dispatchMessage = useCallback (
const dispatchMessage = useCallback (
async ( text : string , attachmentUrl? : string , retryId? : string ) = > {
if ( ( ! text . trim ( ) && ! attachmentUrl ) || sending ) return ;
async (
text : string ,
attachment ? : {
file? : File ;
url? : string ;
kind ? : 'image' | 'audio' ;
isObjectUrl? : boolean ;
} ,
retryId? : string
) = > {
const hasAttachment = Boolean ( attachment ? . file || attachment ? . url ) ;
if ( ( ! text . trim ( ) && ! hasAttachment ) || sending ) return ;
if ( isBare ) {
if ( isBare ) {
setMessageText ( '' ) ;
setMessageText ( '' ) ;
return ;
return ;
}
}
if ( ! isUserAuthenticated ) {
const authed = await requireAuth ( { featureName : 'store chat' } ) ;
if ( ! authed ) return ;
}
setSending ( true ) ;
setSending ( true ) ;
try {
try {
const res = await shopApi . sendChatMessage ( resolvedConvRef , {
const res = await shopApi . sendChatMessage ( resolvedConvRef , {
text : text.trim ( ) ,
text : text.trim ( ) ,
attachment_url : attachmentUrl ,
attachment : attachment?.file ,
attachment_url : attachment?.file ? undefined : attachment ? . url ,
} ) ;
} ) ;
if ( res . conversation ) setConversation ( res . conversation ) ;
if ( res . conversation ) setConversation ( res . conversation ) ;
const incomingBatch =
const incomingBatch =
@ -406,10 +463,13 @@ export const ShopChatPage: React.FC = () => {
}
}
return merged ;
return merged ;
} ) ;
} ) ;
if ( attachment ? . isObjectUrl && attachment . url ) {
URL . revokeObjectURL ( attachment . url ) ;
}
if ( retryId ) {
if ( retryId ) {
setFailedDrafts ( ( prev ) = > prev . filter ( ( d ) = > d . tempId !== retryId ) ) ;
setFailedDrafts ( ( prev ) = > prev . filter ( ( d ) = > d . tempId !== retryId ) ) ;
}
}
} catch {
} catch ( err ) {
const now = new Date ( ) ;
const now = new Date ( ) ;
const hh = String ( now . getHours ( ) ) . padStart ( 2 , '0' ) ;
const hh = String ( now . getHours ( ) ) . padStart ( 2 , '0' ) ;
const mm = String ( now . getMinutes ( ) ) . padStart ( 2 , '0' ) ;
const mm = String ( now . getMinutes ( ) ) . padStart ( 2 , '0' ) ;
@ -419,42 +479,77 @@ export const ShopChatPage: React.FC = () => {
{
{
tempId : ` failed- ${ Date . now ( ) } ` ,
tempId : ` failed- ${ Date . now ( ) } ` ,
text : text.trim ( ) ,
text : text.trim ( ) ,
attachmentUrl ,
attachmentFile : attachment?.file ,
attachmentUrl : attachment?.url ,
attachmentKind : attachment?.kind ,
isObjectUrl : attachment?.isObjectUrl ,
timeLabel : ` ${ hh } : ${ mm } ` ,
timeLabel : ` ${ hh } : ${ mm } ` ,
} ,
} ,
] ) ;
] ) ;
}
}
showToast ( 'Message could not be sent — tap Try Again' ) ;
showToast (
err instanceof Error && err . message
? err . message
: 'Message could not be sent — tap Try Again'
) ;
} finally {
} finally {
setSending ( false ) ;
setSending ( false ) ;
}
}
} ,
} ,
[ isBare , resolvedConvRef , sending , showToast ]
[ isBare , isUserAuthenticated , requireAuth , resolvedConvRef , sending , showToast ]
) ;
) ;
const handleSendText = async ( ) = > {
const handleSendText = async ( ) = > {
const trimmed = messageText . trim ( ) ;
const trimmed = messageText . trim ( ) ;
const attachmentToSend = stagedAttachment ;
const attachmentToSend = stagedAttachment ;
if ( ! trimmed && ! attachmentToSend ) return ;
if ( ! trimmed && ! attachmentToSend ) return ;
if ( ! isBare && ! isUserAuthenticated ) {
const authed = await requireAuth ( { featureName : 'store chat' } ) ;
if ( ! authed ) return ;
}
setMessageText ( '' ) ;
setMessageText ( '' ) ;
setStagedAttachment ( null ) ;
setStagedAttachment ( null ) ;
const outgoingText =
const outgoingText =
trimmed ||
trimmed ||
( attachmentToSend ? . kind === 'audio' ? 'Voice message' : '' ) ;
( attachmentToSend ? . kind === 'audio' ? 'Voice message' : '' ) ;
void dispatchMessage ( outgoingText , attachmentToSend ? . url ) ;
void dispatchMessage (
outgoingText ,
attachmentToSend
? {
file : attachmentToSend.file ,
url : attachmentToSend.url ,
kind : attachmentToSend.kind ,
isObjectUrl : attachmentToSend.isObjectUrl ,
}
: undefined
) ;
} ;
} ;
const handleAttachmentClick = async ( ) = > {
const handleAttachmentClick = async ( ) = > {
if ( isBare || attachingMedia ) return ;
if ( isBare || attachingMedia ) return ;
if ( ! isUserAuthenticated ) {
const authed = await requireAuth ( { featureName : 'store chat' } ) ;
if ( ! authed ) return ;
}
if ( isInFlutterWebView ( ) ) {
if ( isInFlutterWebView ( ) ) {
setAttachingMedia ( true ) ;
setAttachingMedia ( true ) ;
try {
try {
const uploadedUrl = await uploadFileViaFlutterBridge ( 'image' ) ;
if ( uploadedUrl ) {
setStagedAttachment ( {
url : uploadedUrl ,
kind : isAudioAttachmentUrl ( uploadedUrl ) ? 'audio' : 'image' ,
label : 'Attached image' ,
const picked = await pickFileViaFlutterBridge ( 'image' ) ;
if ( picked ) {
if ( picked . file && picked . file . size > MAX_CHAT_ATTACHMENT_BYTES ) {
if ( picked . isObjectUrl ) URL . revokeObjectURL ( picked . url ) ;
showToast ( 'Attachment exceeds the 10 MB size limit' ) ;
return ;
}
const isAudio =
picked . file ? . type . startsWith ( 'audio/' ) ||
isAudioAttachmentUrl ( picked . url ) ;
replaceStagedAttachment ( {
url : picked.url ,
file : picked.file ,
isObjectUrl : picked.isObjectUrl ,
kind : isAudio ? 'audio' : 'image' ,
label : picked.name || 'Attached image' ,
} ) ;
} ) ;
}
}
} finally {
} finally {
@ -465,29 +560,33 @@ export const ShopChatPage: React.FC = () => {
fileInputRef . current ? . click ( ) ;
fileInputRef . current ? . click ( ) ;
} ;
} ;
const handleFileInputChange = async (
const handleFileInputChange = (
e : React.ChangeEvent < HTMLInputElement >
e : React.ChangeEvent < HTMLInputElement >
) = > {
) = > {
const file = e . target . files ? . [ 0 ] ;
const file = e . target . files ? . [ 0 ] ;
if ( ! file ) return ;
if ( ! file ) return ;
e . target . value = '' ;
e . target . value = '' ;
setAttachingMedia ( true ) ;
try {
const url = await uploadBrowserFileToTmpMedia ( file ) ;
const isAudio =
file . type . startsWith ( 'audio/' ) || isAudioAttachmentUrl ( url ) ;
setStagedAttachment ( {
url ,
if ( file . size > MAX_CHAT_ATTACHMENT_BYTES ) {
showToast ( 'Attachment exceeds the 10 MB size limit' ) ;
return ;
}
const previewUrl = URL . createObjectURL ( file ) ;
const isAudio = file . type . startsWith ( 'audio/' ) ;
replaceStagedAttachment ( {
url : previewUrl ,
file ,
isObjectUrl : true ,
kind : isAudio ? 'audio' : 'image' ,
kind : isAudio ? 'audio' : 'image' ,
label : file.name || ( isAudio ? 'Voice message' : 'Attached image' ) ,
label : file.name || ( isAudio ? 'Voice message' : 'Attached image' ) ,
} ) ;
} ) ;
} finally {
setAttachingMedia ( false ) ;
}
} ;
} ;
const handleStartRecording = async ( ) = > {
const handleStartRecording = async ( ) = > {
if ( isBare || isRecording || sending ) return ;
if ( isBare || isRecording || sending ) return ;
if ( ! isUserAuthenticated ) {
const authed = await requireAuth ( { featureName : 'store chat' } ) ;
if ( ! authed ) return ;
}
recordedChunksRef . current = [ ] ;
recordedChunksRef . current = [ ] ;
recordingStartMsRef . current = Date . now ( ) ;
recordingStartMsRef . current = Date . now ( ) ;
@ -570,41 +669,45 @@ export const ShopChatPage: React.FC = () => {
setAttachingMedia ( true ) ;
setAttachingMedia ( true ) ;
try {
try {
let audioUrl = '' ;
let audioFile : File | null = null ;
if ( recordedChunksRef . current . length > 0 ) {
if ( recordedChunksRef . current . length > 0 ) {
const mimeType = recorder ? . mimeType || 'audio/webm' ;
const ext = mimeType . includes ( 'mp4' )
const rawMime = recorder ? . mimeType || 'audio/webm' ;
const cleanMime = rawMime . split ( ';' , 1 ) [ 0 ] . trim ( ) || 'audio/webm' ;
const ext = cleanMime . includes ( 'mp4' )
? 'm4a'
? 'm4a'
: mimeTyp e. includes ( 'ogg' )
: cleanMim e. includes ( 'ogg' )
? 'ogg'
? 'ogg'
: mimeTyp e. includes ( 'wav' )
: cleanMim e. includes ( 'wav' )
? 'wav'
? 'wav'
: 'webm' ;
: 'webm' ;
const blob = new Blob ( recordedChunksRef . current , { type : mimeTyp e } ) ;
const blob = new Blob ( recordedChunksRef . current , { type : cleanMim e } ) ;
if ( blob . size > 100 ) {
if ( blob . size > 100 ) {
const f ile = new File ( [ blob ] , ` voice- ${ Date . now ( ) } . ${ ext } ` , {
type : mimeTyp e,
audioF ile = new File ( [ blob ] , ` voice- ${ Date . now ( ) } . ${ ext } ` , {
type : cleanMim e,
} ) ;
} ) ;
audioUrl = await uploadBrowserFileToTmpMedia ( file ) ;
}
}
}
}
if ( ! audioUrl ) {
const synth = createSynthesizedVoiceWav ( elapsedSec ) ;
audioUrl = await uploadBrowserFileToTmpMedia (
synth . file ,
synth . dataUrl
) ;
if ( ! audioFile ) {
audioFile = createSynthesizedVoiceWav ( elapsedSec ) . file ;
}
}
recordedChunksRef . current = [ ] ;
recordedChunksRef . current = [ ] ;
const durationLabel = formatDurationMmSs ( elapsedSec ) ;
const durationLabel = formatDurationMmSs ( elapsedSec ) ;
const previewUrl = URL . createObjectURL ( audioFile ) ;
if ( sendImmediately ) {
if ( sendImmediately ) {
await dispatchMessage ( ` Voice message ( ${ durationLabel } ) ` , audioUrl ) ;
await dispatchMessage ( ` Voice message ( ${ durationLabel } ) ` , {
file : audioFile ,
url : previewUrl ,
kind : 'audio' ,
isObjectUrl : true ,
} ) ;
} else {
} else {
setStagedAttachment ( {
url : audioUrl ,
replaceStagedAttachment ( {
url : previewUrl ,
file : audioFile ,
isObjectUrl : true ,
kind : 'audio' ,
kind : 'audio' ,
label : ` Voice message ( ${ durationLabel } ) ` ,
label : ` Voice message ( ${ durationLabel } ) ` ,
durationSec : elapsedSec ,
durationSec : elapsedSec ,
@ -615,7 +718,7 @@ export const ShopChatPage: React.FC = () => {
}
}
} ;
} ;
const storeDetail = conversation ? . store_detail ;
const storeDetail = conversation ? . store_detail ? ? publicStore ;
const fallbackStoreName = resolvedConvRef
const fallbackStoreName = resolvedConvRef
. replace ( /-/g , ' ' )
. replace ( /-/g , ' ' )
. replace ( /\b\w/g , ( ch ) = > ch . toUpperCase ( ) ) ;
. replace ( /\b\w/g , ( ch ) = > ch . toUpperCase ( ) ) ;
@ -718,6 +821,14 @@ export const ShopChatPage: React.FC = () => {
>
>
{ storeTitle }
{ storeTitle }
< / div >
< / div >
{ ! isBare && loadingInitial && ! storeDetail ? (
< ShimmerBox
width = { 72 }
height = { 11 }
borderRadius = { 4 }
style = { { marginTop : 2 } }
/ >
) : (
< div
< div
style = { {
style = { {
fontFamily : 'var(--font-sans)' ,
fontFamily : 'var(--font-sans)' ,
@ -731,6 +842,7 @@ export const ShopChatPage: React.FC = () => {
>
>
{ tr ( storeLocation ) }
{ tr ( storeLocation ) }
< / div >
< / div >
) }
< / div >
< / div >
{ /* Right 3-Dots Menu Button */ }
{ /* Right 3-Dots Menu Button */ }
@ -927,7 +1039,7 @@ export const ShopChatPage: React.FC = () => {
padding : '24px var(--page-px) 16px' ,
padding : '24px var(--page-px) 16px' ,
} }
} }
>
>
{ ! isBare && loadingInitial ? (
{ ! isBare && loadingInitial && messages . length === 0 ? (
< ChatThreadShimmer / >
< ChatThreadShimmer / >
) : ! isBare &&
) : ! isBare &&
( messages . length > 0 || ( ! useMockFallback && failedDrafts . length > 0 ) ) ? (
( messages . length > 0 || ( ! useMockFallback && failedDrafts . length > 0 ) ) ? (
@ -1108,7 +1220,14 @@ export const ShopChatPage: React.FC = () => {
onClick = { ( ) = > {
onClick = { ( ) = > {
void dispatchMessage (
void dispatchMessage (
draft . text ,
draft . text ,
draft . attachmentUrl ,
draft . attachmentFile || draft . attachmentUrl
? {
file : draft.attachmentFile ,
url : draft.attachmentUrl ,
kind : draft.attachmentKind ,
isObjectUrl : draft.isObjectUrl ,
}
: undefined ,
draft . tempId
draft . tempId
) ;
) ;
} }
} }
@ -1154,7 +1273,8 @@ export const ShopChatPage: React.FC = () => {
} }
} }
>
>
{ draft . attachmentUrl &&
{ draft . attachmentUrl &&
( isAudioAttachmentUrl ( draft . attachmentUrl ) ? (
( draft . attachmentKind === 'audio' ||
isAudioAttachmentUrl ( draft . attachmentUrl ) ? (
< VoiceMessagePlayer
< VoiceMessagePlayer
src = { resolveMediaUrl ( draft . attachmentUrl ) }
src = { resolveMediaUrl ( draft . attachmentUrl ) }
isCustomer
isCustomer
@ -1675,7 +1795,7 @@ export const ShopChatPage: React.FC = () => {
< button
< button
type = "button"
type = "button"
aria - label = "Remove attachment"
aria - label = "Remove attachment"
onClick = { ( ) = > set StagedAttachment( null ) }
onClick = { ( ) = > replace StagedAttachment( null ) }
style = { {
style = { {
width : 24 ,
width : 24 ,
height : 24 ,
height : 24 ,