Skip to content
The Chat Archive
gpt-4o-2024-05-13· OpenAI WildChat-4.8M (AI2)

import { FileType, MemberType } from "@openchat/types" import { DateUtils } from…

  1. User

    import { FileType, MemberType } from "@openchat/types" import { DateUtils } from "@openchat/core" import classNames from "classnames" import { Fragment, useEffect, useRef, useState } from "react" import { Document, Page } from "react-pdf" import { Icon } from "../../../ui-component/icon/icon.component" import { useModal } from "../../../ui-component/modal" import { memoComponent } from "@openchat/ui" import styles from "./message-attachment-pdf-viewer-modal.styles.module.css" import { AppController } from "../../../app/app.globals.js"

    export const MessageAttachmentPdfViewerModal = memoComponent( "MessageAttachmentPdfViewerModal", ({ fileId, sender, date, }: { fileId: string sender: MemberType date: Date }) => { // --------------------------------------------------------------------------- // variables // ---------------------------------------------------------------------------

    const modal = useModal()
    const leftSideScrollRef = useRef<HTMLDivElement>(null)
    const rightSideScrollRef = useRef<HTMLDivElement>(null)
    
    const [pageIndex, setPageIndex] = useState(1)
    const [page, setPage] = useState(1)
    const [selectedIndex, setSelectedIndex] = useState(0)
    const [zoom, setZoom] = useState(1)
    const [file, setFile] = useState<FileType | null>(null)
    
    const dateTime = [
      date.getDate(),
      date.getMonth() + 1,
      date.getFullYear(),
    ].join("/")
    let hours = date.getHours()
    let amORpm = hours >= 12 ? "PM" : "AM"
    
    // ---------------------------------------------------------------------------
    // effects
    // ---------------------------------------------------------------------------
    
    useEffect(() => {
      loader()
    }, [fileId])
    
    useEffect(() => {
      if (!rightSideScrollRef.current || !leftSideScrollRef.current) return
    
      const handleScroll = () => {
        if (!rightSideScrollRef.current || !leftSideScrollRef.current) return
        const { scrollTop } = rightSideScrollRef.current
    
        const rightItemHeight =
          document.getElementsByClassName(styles.mainPage)[0].clientHeight + 50
    
        const leftItemHight =
          document.getElementsByClassName(styles.navPage)[0].clientHeight + 50
    
        const newIndex = Math.floor(scrollTop / rightItemHeight)
    
        const totalPages = Math.ceil(
          rightSideScrollRef.current.scrollHeight / rightItemHeight,
        )
    
        if (
          newIndex !== selectedIndex &&
          newIndex >= 0 &&
          newIndex < totalPages
        ) {
          setSelectedIndex(newIndex)
          setPageIndex(newIndex + 1)
          leftSideScrollRef.current.scrollTop =
            newIndex < totalPages / 2
              ? leftItemHight * newIndex
              : (rightItemHeight * newIndex) / 2
        } else {
          setSelectedIndex(newIndex)
          setPageIndex(newIndex + 1)
          leftSideScrollRef.current.scrollTop = newIndex * leftItemHight
        }
      }
    
      const handleWheelZoom = (event: WheelEvent) => {
        if (event.ctrlKey || event.metaKey) {
          event.preventDefault()
          const newZoom = zoom + event.deltaY * -0.01
          if (newZoom > 0.5 && newZoom < 5) {
            setZoom(newZoom)
          }
        }
      }
    
      rightSideScrollRef.current.addEventListener("scroll", handleScroll)
      rightSideScrollRef.current.addEventListener("wheel", handleWheelZoom)
    
      return () => {
        if (rightSideScrollRef.current) {
          rightSideScrollRef.current.removeEventListener("scroll", handleScroll)
          rightSideScrollRef.current.removeEventListener(
            "wheel",
            handleWheelZoom,
          )
        }
      }
    }, [zoom])
    
    // ---------------------------------------------------------------------------
    // functions
    // ---------------------------------------------------------------------------
    
    async function loader() {
      const file = await AppController.file.getFromLocal({ id: fileId })
      setFile(file)
    }
    
    function handleItemClick(index: number) {
      setSelectedIndex(index)
      onScrollRightSideToIndex(index)
    }
    
    function onScrollRightSideToIndex(index: number) {
      if (!rightSideScrollRef.current || !leftSideScrollRef.current) return
    
      const itemHeight =
        document.getElementsByClassName(styles.mainPage)[0].clientHeight + 50
      const scrollTop = index * itemHeight
      rightSideScrollRef.current.scrollTop = scrollTop
    }
    
    // ---------------------------------------------------------------------------
    if (!file) return
    return (
      <div className={styles.wrapper}>
        <div className={styles.header}>
          <div className={styles.headerTitleWrap}>
            <p className={styles.pageCount}>{`PDF ${pageIndex} of ${page} `}</p>
    
            <div className={styles.senderNameWrap}>
              <strong className={styles.senderName}>{sender.name}</strong>
              <span className={styles.dateTime}>
                {` ${dateTime} at ${DateUtils.getMessageListItemDateTime(
                  date,
                )} ${amORpm}`}
              </span>
            </div>
          </div>
    
          <div>
            <Icon
              className={styles.ellipsisButton}
              name="fal fa-ellipsis-v"
              onClick={() => {}}
            />
            <Icon
              className={styles.crossButton}
              name="fal fa-times"
              onClick={() => modal.close()}
            />
          </div>
        </div>
    
        <div className={styles.container}>
          <nav className={styles.nav} ref={leftSideScrollRef}>
            <Document
              className={styles.navDocument}
              file={file.data}
              onLoadSuccess={({ numPages }) => setPage(numPages)}
            >
              {Array.from(Array(page).keys()).map((index) => (
                <Fragment key={`page${index + 1}`}>
                  <Page
                    className={classNames({
                      [styles.navPage]: true,
                      [styles.focused]: index === selectedIndex,
                    })}
                    onClick={() => handleItemClick(index)}
                    height={240}
                    width={165}
                    pageNumber={index + 1}
                  />
                  <>{index + 1}</>
                </Fragment>
              ))}
            </Document>
          </nav>
          <div className={styles.documentWrap} ref={rightSideScrollRef}>
            <div
              className={styles.mainDocument}
              style={
                zoom >= 2 && zoom <= 5
                  ? { width: "-webkit-fill-available" }
                  : {}
              }
            >
              <Document
                file={file.data}
                onLoadSuccess={({ numPages }) => setPage(numPages)}
              >
                {Array.from(Array(page).keys()).map((index) => (
                  <Fragment key={`page${index + 1}`}>
                    <Page
                      className={styles.mainPage}
                      height={545}
                      width={373}
                      pageNumber={index + 1}
                      scale={zoom}
                    />
                  </Fragment>
                ))}
              </Document>
            </div>
          </div>
        </div>
        <div className={styles.footer}>
          <Icon className={styles.icon} name="fal fa-cloud-download" />
          <div>
            <Icon
              className={styles.icon}
              name="fal fa-search-plus"
              onClick={() => {
                if (zoom > 4) return
                setZoom((prevZoom) => prevZoom * 1.2)
              }}
            />
            <Icon
              className={styles.icon}
              name="fal fa-search-minus"
              onClick={() => {
                if (zoom < 0.5) return
                setZoom((prevZoom) => prevZoom / 1.2)
              }}
            />
            <Icon
              className={styles.icon}
              name="fal fa-undo"
              onClick={() => setZoom(1)}
            />
          </div>
        </div>
      </div>
    )
    

    }, ) please convert it to react native

  2. Assistant

    Converting a React component that renders a PDF viewer in a modal window for a web application to React Native involves considerable changes. React Native does not support JSX elements like <div> or libraries like react-pdf, used for rendering PDFs in real-time.

    Instead, you will use equivalents like <View>, <ScrollView>, react-native-pdf, and other React Native components. Below is a rough outline of how this conversion might look like:

    1. Install necessary packages: You will need additional packages for React Native, such as react-native-pdf to render the PDFs.

      npm install react-native-pdf
      
    2. Convert the web-based components and logic to React Native components: We'll create a similar structure using React Native components and adjust styles accordingly. Below is an example of how you could convert the code to React Native:

    import React, { useEffect, useState, useRef } from 'react'
    import {
      View,
      Text,
      ScrollView,
      StyleSheet,
      TouchableOpacity,
    } from 'react-native'
    import Pdf from 'react-native-pdf'
    import Icon from 'react-native-vector-icons/FontAwesome'
    import { useModal } from 'react-native-modals'
    
    const styles = StyleSheet.create({
      wrapper: {
        flex: 1,
        backgroundColor: '#fff',
      },
      header: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 16,
        borderBottomWidth: 1,
        borderBottomColor: '#ccc',
      },
      headerTitleWrap: {
        flexDirection: 'row',
        alignItems: 'baseline',
      },
      pageCount: {
        fontSize: 14,
        color: '#333',
      },
      senderNameWrap: {
        marginLeft: 10,
      },
      senderName: {
        fontWeight: 'bold',
      },
      dateTime: {
        fontSize: 12,
        color: '#777',
      },
      container: {
        flexDirection: 'row',
        flex: 1,
      },
      nav: {
        width: 165,
        padding: 10,
        borderRightWidth: 1,
        borderRightColor: '#ddd',
      },
      navPage: {
        marginBottom: 10,
      },
      focused: {
        borderColor: 'blue',
      },
      documentWrap: {
        flex: 1,
        padding: 10,
      },
      mainDocument: {
        flex: 1,
        alignItems: 'center',
      },
      footer: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        padding: 16,
        borderTopWidth: 1,
        borderTopColor: '#ccc',
      },
      icon: {
        padding: 10,
      },
    })
    
    const MessageAttachmentPdfViewerModal = ({
      fileId,
      sender,
      date,
    }) => {
      const modal = useModal()
      const rightSideScrollRef = useRef()
      const leftSideScrollRef = useRef()
    
      const [pageIndex, setPageIndex] = useState(1)
      const [page, setPage] = useState(1)
      const [selectedIndex, setSelectedIndex] = useState(0)
      const [zoom, setZoom] = useState(1)
      const [file, setFile] = useState(null)
    
      const dateTime = [
        date.getDate(),
        date.getMonth() + 1,
        date.getFullYear(),
      ].join('/')
      let hours = date.getHours()
      let amORpm = hours >= 12 ? 'PM' : 'AM'
    
      // Load PDF file
      useEffect(() => {
        loader()
      }, [fileId])
    
      async function loader() {
        const file = await AppController.file.getFromLocal({ id: fileId })
        setFile(file)
      }
    
      const handleItemClick = (index) => {
        setSelectedIndex(index)
        onScrollRightSideToIndex(index)
      }
    
      const onScrollRightSideToIndex = (index) => {
        if (rightSideScrollRef.current && leftSideScrollRef.current) {
          const itemHeight = 545 // Height used for each PDF page
          const scrollTop = index * itemHeight
          rightSideScrollRef.current.scrollTo({ y: scrollTop, animated: true })
        }
      }
    
      if (!file) return null
    
      return (
        <View style={styles.wrapper}>
          <View style={styles.header}>
            <View style={styles.headerTitleWrap}>
              <Text style={styles.pageCount}>{`PDF ${pageIndex} of ${page}`}</Text>
              <View style={styles.senderNameWrap}>
                <Text style={styles.senderName}>{sender.name}</Text>
                <Text style={styles.dateTime}>{` ${dateTime} at ${hours % 12 || 12}:${date.getMinutes()} ${amORpm}`}</Text>
              </View>
            </View>
    
            <View>
              <Icon
                style={styles.icon}
                name="ellipsis-v"
                size={20}
                onPress={() => {}}
              />
              <Icon
                style={styles.icon}
                name="times"
                size={20}
                onPress={() => modal.close()}
              />
            </View>
          </View>
    
          <View style={styles.container}>
            <ScrollView style={styles.nav} ref={leftSideScrollRef}>
              <Pdf
                source={{ uri: file.data }}
                onLoadComplete={(numberOfPages) => setPage(numberOfPages)}
                onPageChanged={(page) => setPageIndex(page)}
                style={{ width: 165, height: 240 }}
              >
                {Array.from(Array(page).keys()).map((_, index) => (
                  <TouchableOpacity
                    key={`page${index + 1}`}
                    style={[
                      styles.navPage,
                      index === selectedIndex && styles.focused,
                    ]}
                    onPress={() => handleItemClick(index)}
                  >
                    <Pdf
                      source={{ uri: file.data }}
                      page={index + 1}
                      style={{ height: 240, width: 165 }}
                    />
                    <Text>{index + 1}</Text>
                  </TouchableOpacity>
                ))}
              </Pdf>
            </ScrollView>
            <ScrollView
              style={styles.documentWrap}
              ref={rightSideScrollRef}
              onScroll={onScrollRightSideToIndex}
            >
              <View style={styles.mainDocument}>
                <Pdf
                  source={{ uri: file.data }}
                  spacing={6}
                  onLoadComplete={(numberOfPages) => setPage(numberOfPages)}
                  onPageChanged={(page) => setPageIndex(page)}
                  scale={zoom}
                  style={{ height: 545, width: 373 }}
                />
              </View>
            </ScrollView>
          </View>
          <View style={styles.footer}>
            <Icon style={styles.icon} name="cloud-download" size={24} />
            <View>
              <Icon
                style={styles.icon}
                name="search-plus"
                size={24}
                onPress={() => {
                  if (zoom > 4) return
                  setZoom((prevZoom) => prevZoom * 1.2)
                }}
              />
              <Icon
                style={styles.icon}
                name="search-minus"
                size={24}
                onPress={() => {
                  if (zoom < 0.5) return
                  setZoom((prevZoom) => prevZoom / 1.2)
                }}
              />
              <Icon
                style={styles.icon}
                name="undo"
                size={24}
                onPress={() => setZoom(1)}
              />
            </View>
          </View>
        </View>
      )
    }
    
    export default MessageAttachmentPdfViewerModal
    

    Note:

    • The styling and layout must be tailored to React Native's styling system, which uses StyleSheet.
    • Navigation and modal handling might differ based on your stack, ensure you integrate the modal system appropriately.
    • Adjust any missing functionality based on the specifics of your React Native environment and use of the react-native-pdf library.

    This code does not include all behaviors and may require further adjustments, especially on PDF rendering and zoom functionality given React Native's restrictions and layout system.