Untitled

mail@pastecode.io avatarunknown
plain_text
a month ago
3.6 kB
1
Indexable
Never
import React, {useState, useEffect} from 'react'
import {useClient} from 'sanity'
import {Card, Button, Box, Flex, Autocomplete, Text} from '@sanity/ui'
import {SearchIcon} from '@sanity/icons'
import {set} from 'sanity'
import {useFormValue} from 'sanity'

const UnitTypeReferenceInput = ({type, value, onChange, props}) => {
  const client = useClient()
  const [selectedUnit, setSelectedUnit] = useState(null)
  const [unitTypeOptions, setUnitTypeOptions] = useState([])
  const docId = String(useFormValue(['_id']))

  // Fetch unitType documents when the component is mounted
  useEffect(() => {
    const fetchUnitTypes = async () => {
      const unitTypes = await client.fetch(`*[_type == "unit" && !(_id in path('drafts.**'))]`)
      setUnitTypeOptions(unitTypes)
    }

    fetchUnitTypes()
  }, [client])

  const handleReferenceSelect = (selectedUnitTypeId) => {
    console.log('-- handleReferenceSelect, selectedUnitTypeId: ', selectedUnitTypeId)
    setSelectedUnit(selectedUnitTypeId)
  }

  const populateFields = async () => {
    if (selectedUnit) {
      const unitType = await client.fetch(`*[_id == "${selectedUnit}"][0]`)

      if (unitType?.unit) {
        // 1. Set the current field (unitTypeReference) with the _ref
        onChange(
          set({
            _ref: selectedUnit,
          })
        )

        // 2. Set the value of the 'unit' field in the same document to the value of unitType.unit.
        // Mind that the 'unit' field doesn't belong to the unitTypeReference field, but to the document. They're siblings.
        if (docId) {
          const doc = await client.fetch(`*[_id == "${docId}"][0]`)

          const setValues = {
            unit: unitType.unit,
          }

          if (
            (!doc.images || doc.images.length === 0) &&
            unitType.images &&
            unitType.images.length > 0
          ) {
            setValues.images = unitType.images
          }

          if (!doc.floorplanImage && unitType.floorplanImage) {
            setValues.floorplanImage = unitType.floorplanImage
          }

          if (
            (!doc.hotspots || doc.hotspots.length === 0) &&
            unitType.hotspots &&
            unitType.hotspots.length > 0
          ) {
            setValues.hotspots = unitType.hotspots
          }

          await client
            .patch(docId)
            .set({
              ...setValues,
            })
            .commit()
        }
      }
    }
  }

  return (
    <Box>
      <Flex direction={['column', 'row']} gap={2}>
        <Box flex={1}>
          <Autocomplete
            placeholder="Search for unit type..."
            icon={SearchIcon}
            options={unitTypeOptions.map((unit) => ({value: unit._id, payload: unit}))}
            renderValue={(value, option) => option?.payload.title || value}
            renderOption={(option) => (
              <Card as="button">
                <Flex align="center">
                  <Box flex={1} padding={3}>
                    <Text size={[2, 2, 3]}>{option.payload.title}</Text>
                  </Box>
                </Flex>
              </Card>
            )}
            filterOption={(query, option) =>
              option.payload?.title?.toLowerCase().includes(query.toLowerCase())
            }
            onSelect={(item) => handleReferenceSelect(item)}
          />
        </Box>
        <Box>
          <Button
            text="Populate"
            tone="positive"
            onClick={populateFields}
            disabled={!selectedUnit}
          />
        </Box>
      </Flex>
    </Box>
  )
}

export default UnitTypeReferenceInput