Skip to content
The Chat Archive
o1-preview-2024-09-12· OpenAI WildChat-4.8M (AI2)

schau dir auf datechosser an, dort kann ich die dates laden für die verfügbakeiten der…

  1. User

    schau dir auf datechosser an, dort kann ich die dates laden für die verfügbakeiten der studios. ich will das auch in studiofooter in verfügbakeiten anziegen -> CustomCalender. ich will das dort nutzen das nur die verfügbakeiten angezeigt werden

    import React, { useState, useRef } from 'react'; import { View, Text, TouchableOpacity, Animated, StyleSheet } from 'react-native'; import Svg, { Path } from 'react-native-svg'; import CustomCalendar from '../../components/CustomCalendar';

    interface StudioFooterProps { price: number; onBookingPress: () => void; }

    const StudioFooter: React.FC = ({ price, onBookingPress }) => { const [selectedDate, setSelectedDate] = useState<Date | null>(null); const [showDatePicker, setShowDatePicker] = useState(false); const dateContainerHeight = useRef(new Animated.Value(0)).current;

    const showDateContainer = () => { setShowDatePicker(true); Animated.timing(dateContainerHeight, { toValue: 1, duration: 300, useNativeDriver: false, }).start(); };

    const hideDateContainer = () => { Animated.timing(dateContainerHeight, { toValue: 0, duration: 300, useNativeDriver: false, }).start(() => { setShowDatePicker(false); }); };

    const handleDateChange = (date: Date) => { setSelectedDate(date); };

    return ( <> <Animated.View style={[ styles.dateContainer, { height: dateContainerHeight.interpolate({ inputRange: [0, 1], outputRange: [0, 600] }), opacity: dateContainerHeight, transform: [{ translateY: dateContainerHeight.interpolate({ inputRange: [0, 1], outputRange: [50, 0] }) }] } ]} > <View style={{ opacity: 0 }} /> Verfügbarkeit zeigen {showDatePicker && ( )} </Animated.View>

      <View style={styles.footerContainer}>
        <View style={styles.phoneFooterContainer}>
          <View style={styles.footerTextContainer}>
            <View style={styles.footerTextContainer2}>
              <Text style={styles.priceText}>{price}€</Text>
              <Text style={styles.perHourText}>pro Stunde</Text>
            </View>
            <TouchableOpacity onPress={showDateContainer}>
              <Text style={styles.availability}>Verfügbarkeit zeigen</Text>
            </TouchableOpacity>
          </View>
          <TouchableOpacity 
            style={styles.footerButton}
            onPress={onBookingPress}
          >
            <Text style={styles.buttonText}>Reservieren</Text>
          </TouchableOpacity>
        </View>
      </View>
    </>
    

    ); };

    const styles = StyleSheet.create({ footerContainer: { borderTopWidth: 1, borderTopColor: 'rgba(217, 217, 217, 0.50)', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '100%', position: 'absolute', zIndex: 1, bottom: 0, left: 0, backgroundColor: '#FFFFFF', }, dateContainer: { position: 'absolute', bottom: 0, left: 0, right: 0, backgroundColor: '#FFFFFF', borderTopWidth: 1, borderTopColor: 'rgba(217, 217, 217, 0.50)', overflow: 'hidden', }, dateHeaderContainer: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', width: '100%', padding: 19, borderBottomWidth: 1, borderBottomColor: 'rgba(217, 217, 217, 0.50)', marginBottom: 23, }, headerText: { fontSize: 16, fontWeight: '500', }, closeIconContainer: { alignItems: 'center', justifyContent: 'center', width: 17, height: 18, }, container: { width: '100%', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', }, phoneFooterContainer: { flexDirection: 'row', width: '100%', padding: 21, alignItems: 'center', justifyContent: 'space-between', gap: 57, }, footerTextContainer: { flexDirection: 'column', alignItems: 'flex-start', justifyContent: 'flex-start', gap: 14, }, footerTextContainer2: { flexDirection: 'row', alignItems: 'center', justifyContent: 'flex-start', gap: 5, }, priceText: { fontSize: 16, fontWeight: '600', }, perHourText: { fontSize: 16, fontWeight: '400', }, availability: { color: '#4A4A4A', fontSize: 13, fontWeight: '400', textDecorationLine: 'underline', textDecorationStyle: 'solid', textDecorationColor: '#4A4A4A', }, footerButton: { padding: 17, flex: 1, backgroundColor: '#1F1F1F', borderRadius: 13, alignItems: 'center', justifyContent: 'center', }, buttonText: { color: '#FFFFFF', fontSize: 16, fontWeight: '400', }, });

    export default StudioFooter;


    import React, { useCallback, useEffect, useRef, useState } from 'react'; import { View, Text, ActivityIndicator, Pressable, Animated, StyleSheet } from 'react-native'; import DetailsStudioItem from '../../components/DetailsStudioItem'; import defaultStyles from '../../theme/Styles'; import { useSafeAreaInsets } from 'react-native-safe-area-context'; import LogoHeader from '../../components/LogoHeader'; import { useNavigation, useRoute } from '@react-navigation/native'; import { RouteProp } from '@react-navigation/native'; import { RootStackParamList } from '../../components/StudioFeedItem/StudioFeedItem'; import { useQuery } from '@apollo/client'; import { GET_STUDIO } from './queries'; import { GetStudioQuery, GetStudioQueryVariables, Studio } from '../../API'; import CloseStudioIconOnStudioPage from '../../assets/icons/StudioIcons/CloseStudioIconOnStudioPage'; import { useAuthContext } from '../../contexts/AuthContext'; import { TouchableOpacity } from 'react-native-gesture-handler'; import PfeilLinksGross from '../../assets/icons/PfeilLinksGross'; import Button from '../../components/Button'; import colors from '../../theme/colors'; import BookingScreen from '../Booking/BookingScreen'; import StudioFooter from './StudioFooter';

    type StudioScreenRouteProp = RouteProp<RootStackParamList, 'StudioDetails'>;

    const StudioScreen = () => { const route = useRoute(); const insets = useSafeAreaInsets(); const navigation = useNavigation(); const { userId: currentUserId } = useAuthContext(); const [isBookingVisible, setIsBookingVisible] = useState(false);

    const openBookingModal = () => { setIsBookingVisible(true); };

    const closeBookingModal = () => { setIsBookingVisible(false); };

    const { loading, error, data } = useQuery<GetStudioQuery, GetStudioQueryVariables>(GET_STUDIO, { variables: { id: route.params.studioID }, });

    const navigateToUpdateStudio = useCallback(() => { if (data?.getStudio) { navigation.navigate('EditStudioScreen', { studioId: data.getStudio.id }); } }, [navigation, data]);

    if (loading) { return ; }

    if (error) { return {error.message}; }

    const studio = data?.getStudio;

    if (!studio) { return No studio data available; }

    const slideAnimation = new Animated.Value(200); // Startposition für das Modal

    // Das Modal wird direkt sichtbar, daher starten wir die Animation sofort Animated.timing(slideAnimation, { toValue: 0, // Modal fährt nach oben duration: 300, useNativeDriver: true, }).start();

    const navigationToBookingScreen = () => { navigation.navigate('Booking'); };

    return ( <View style={[defaultStyles.container, { paddingTop: insets.top }]}> <View style={{ marginBottom: 10}}>

      <View style={{
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignSelf: 'center',
        alignItems: 'center',
        marginTop: 0,
        width: '95%',
        marginBottom: 0,
        top: -10,
        }}>
        <TouchableOpacity
            style={{
              width: 50, height: 30,
              alignSelf: 'center',
              alignItems: 'center',
              justifyContent: 'center',              
    
                
            }}
            hitSlop={{ top: 20, bottom: 20, left: 30, right: 20 }}
              onPress={() => navigation.goBack()}>
                      <CloseStudioIconOnStudioPage/>
                  </TouchableOpacity>
        {studio.User?.id === currentUserId && (
          <View style={{ alignItems: 'center' }}>
            <TouchableOpacity onPress={navigateToUpdateStudio}>
              <Text style={defaultStyles.regularMiddle}>
                {'Bearbeiten'}
              </Text>
              <View style={{
              width: '100%',
              borderWidth: 1,
            }} />
            </TouchableOpacity>
            
          </View>
        )}
      </View>
      
      {/*Studio */}
      <View style={{ paddingBottom: 0 }}>
        <DetailsStudioItem studioItem={studio} />
      </View>
    
      <Animated.View
        style={[
          styles.modalContent,
          { transform: [{ translateY: slideAnimation }] },
        ]}
      >
        <StudioFooter 
          price={studio.pricePerHour} 
          onBookingPress={openBookingModal}
        />
      </Animated.View>
    
    
    
      {/* Modal, das direkt unten angezeigt wird */}
      {/* <Animated.View
        style={[
          styles.modalContent,
          { transform: [{ translateY: slideAnimation }] },
        ]}
      >
        <View style={styles.textContainer}>
          <View style={styles.priceContainer}>
            <Text style={[defaultStyles.semiboldMiddle , {color:colors.DarkGrey}]}>{studio.pricePerHour} €</Text>
            <Text style={[defaultStyles.regularMiddle, {color:colors.DarkGrey}]}>  pro Stunde</Text>
    
          </View>
          <View style={styles.availabilityContainer}>
            <TouchableOpacity >
              <Text style={[defaultStyles.semiboldMiddle , {color:colors.DarkGrey3, textDecorationLine: 'underline'}]}>Verfügbarkeit zeigen</Text>
            </TouchableOpacity>
    
          </View>
    
        </View>
        <TouchableOpacity onPress={openBookingModal}>
        <View style={styles.rectangleView}>        
          <Text style={[defaultStyles.regularLarge, {color: colors.white}]}>
            Reservieren
          </Text>
        </View>
      </TouchableOpacity>
    
      {/* BookingScreen Modal 
      <BookingScreen 
        isVisible={isBookingVisible}
        onClose={closeBookingModal}
        studioId={studio.id} // Übergebe die Studio-ID
      />
      </Animated.View> */}
      <BookingScreen 
        isVisible={isBookingVisible}
        onClose={closeBookingModal}
        studioId={studio.id} // Übergebe die Studio-ID
      />
    
    
    </View>
    

    ); };

    const styles = StyleSheet.create({ modalContent: { flex: 1, position: 'absolute', bottom: 0, width: '100%', backgroundColor: '#ffffff', marginTop: 100, paddingBottom: 40, flexDirection: 'row', justifyContent: 'space-between',

    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.8,
    shadowRadius: 2,
    elevation: 5, // Schatten für Android
    

    }, priceContainer: { flexDirection:'row', paddingBottom: 14, }, availabilityContainer: { flexDirection:'row', }, price: {

    }, confirmButton: {

    }, textContainer: { flex: 1, justifyContent: 'flex-start', alignItems: 'flex-start', alignContent : 'center', alignSelf: 'center', },

    rectangleView: { borderRadius: 13, backgroundColor: colors.LightBlack, flex: 1, //width: "100%", width: 164, height: 54,

    marginTop: 0,
    marginRight: 'auto',
    marginBottom: 0,
    marginLeft: 'auto',
    justifyContent: 'center',
    alignItems: 'center',
    alignContent  : 'center', 
    alignSelf: 'center',
    

    }

    })

    export default StudioScreen;


    import React, { useState, useCallback, useEffect } from 'react'; import { View, Text, TouchableOpacity, StyleSheet, ScrollView, Platform, ActivityIndicator, Dimensions } from 'react-native'; import { format, addMonths, startOfMonth, eachDayOfInterval, endOfMonth, isSameDay, getDay } from 'date-fns'; import { de } from 'date-fns/locale'; import { useQuery } from '@apollo/client'; import { getStudio } from '../queries'; import ApiErrorMessage from '../../../ApiErrorMessage'; import colors from '../../../theme/colors';

    const WEEKDAYS = ['Mo.', 'Di.', 'Mi.', 'Do.', 'Fr.', 'Sa.', 'So.'];

    interface DateChooserProps { nextSlide: () => void; studioId: string; selectedDate: string | null; onDateSelect: (date: string) => void; }

    interface CalendarProps { onDateSelect: (date: string) => void; minDate: Date; availableDates: Record<string, any>; selectedDate: string | null; }

    const Calendar: React.FC = ({ onDateSelect, minDate = new Date(), availableDates, selectedDate }) => { const renderMonthGrid = useCallback((monthDate) => { const start = startOfMonth(monthDate); const end = endOfMonth(monthDate); const days = eachDayOfInterval({ start, end });

    const firstDayOfMonth = getDay(start);
    const emptyDays = firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1;
    const emptySlots = Array(emptyDays).fill(null);
    
    const weeks = [];
    let currentWeek = [...emptySlots];
    
    days.forEach((day) => {
      currentWeek.push(day);
      if (currentWeek.length === 7) {
        weeks.push(currentWeek);
        currentWeek = [];
      }
    });
    
    if (currentWeek.length > 0) {
      weeks.push([...currentWeek, ...Array(7 - currentWeek.length).fill(null)]);
    }
    
    return weeks;
    

    }, []);

    const renderDay = useCallback((date) => { if (!date) return ;

    const dateString = format(date, 'yyyy-MM-dd');
    const dateInfo = availableDates[dateString];
    const isUnavailable = dateInfo?.disabled;
    const isSelected = selectedDate === dateString;
    const dayNumber = format(date, 'd');
    
    // Wenn das Datum vor heute liegt, ist es auch nicht verfügbar
    const isPastDate = date < new Date().setHours(0, 0, 0, 0);
    const isDisabled = isUnavailable || isPastDate;
    
    return (
      <TouchableOpacity
      style={[
        styles.dayContainer,
        isSelected && styles.selectedDay,
        isDisabled && styles.disabledDay,
      ]}
      onPress={() => {
        if (!isDisabled) {
          onDateSelect(dateString);
        }
      }}
      disabled={isDisabled}
      activeOpacity={isDisabled ? 1 : 0.2} // Verhindert den Opacity-Effekt bei deaktivierten Tagen
    >
      <Text style={[
        styles.dayText,
        isSelected && styles.selectedDayText,
        isDisabled && styles.disabledDayText,
      ]}>
        {dayNumber}
      </Text>
      {dateInfo?.marked && !isSelected && !isDisabled && (
        <View style={styles.dotMarker} />
      )}
    </TouchableOpacity>
    

    ); }, [availableDates, selectedDate, onDateSelect]);

    const renderMonth = useCallback((monthIndex) => { const monthDate = addMonths(new Date(), monthIndex); const monthGrid = renderMonthGrid(monthDate);

    return (
      <View style={styles.monthContainer} key={monthIndex}>
        <Text style={styles.monthTitle}>
          {format(monthDate, 'MMMM yyyy', { locale: de })}
        </Text>
        {monthGrid.map((week, weekIndex) => (
          <View style={styles.weekRow} key={weekIndex}>
            {week.map((day, dayIndex) => (
              <View key={dayIndex} style={styles.dayWrapper}>
                {renderDay(day)}
              </View>
            ))}
          </View>
        ))}
      </View>
    );
    

    }, [renderDay, renderMonthGrid]);

    return ( {[0, 1, 2, 3].map((monthIndex) => renderMonth(monthIndex))} ); }; export const DateChooser: React.FC = ({ nextSlide, studioId, selectedDate, onDateSelect }) => { const [availableDates, setAvailableDates] = useState({}); const [isLoading, setIsLoading] = useState(true);

    const { data, loading, error } = useQuery(getStudio, { variables: { id: studioId }, });

    const processAvailability = (availabilities, bookings, minBookingDuration) => { const markedDates = {}; const today = new Date(); const nextYear = new Date(); nextYear.setFullYear(today.getFullYear() + 1);

    for (let d = new Date(today); d <= nextYear; d.setDate(d.getDate() + 1)) {
      const dayOfWeek = d.getDay();
      const dateString = format(d, 'yyyy-MM-dd');
      const dayAvailability = availabilities.find(a => a.dayOfWeek === (dayOfWeek === 0 ? 7 : dayOfWeek));
    
      if (dayAvailability && dayAvailability.startTime && dayAvailability.endTime) {
        const [availStartHour, availStartMin] = dayAvailability.startTime.split(':').map(Number);
        const [availEndHour, availEndMin] = dayAvailability.endTime.split(':').map(Number);
        const availStartMins = availStartHour * 60 + availStartMin;
        const availEndMins = availEndHour * 60 + availEndMin;
    
        const dayBookings = bookings.filter(
          booking => booking.date === dateString && booking.status !== 'CANCELLED'
        ).sort((a, b) => {
          const [aHour, aMin] = a.startTime.split(':').map(Number);
          const [bHour, bMin] = b.startTime.split(':').map(Number);
          return (aHour * 60 + aMin) - (bHour * 60 + bMin);
        });
    
        let hasValidTimeSlot = false;
        let currentTime = availStartMins;
    
        for (const booking of dayBookings) {
          const [bookStartHour, bookStartMin] = booking.startTime.split(':').map(Number);
          const bookingStartMins = bookStartHour * 60 + bookStartMin;
    
          if (bookingStartMins - currentTime > minBookingDuration * 60) {
            hasValidTimeSlot = true;
            break;
          }
    
          const [bookEndHour, bookEndMin] = booking.endTime.split(':').map(Number);
          currentTime = bookEndHour * 60 + bookEndMin;
        }
    
        if (!hasValidTimeSlot && availEndMins - currentTime > minBookingDuration * 60) {
          hasValidTimeSlot = true;
        }
    
        markedDates[dateString] = hasValidTimeSlot ? {
          marked: true,
          dotColor: '#000',
        } : {
          disabled: true,
          disableTouchEvent: true
        };
      } else {
        markedDates[dateString] = {
          disabled: true,
          disableTouchEvent: true
        };
      }
    }
    
    return markedDates;
    

    };

    useEffect(() => { if (data?.getStudio) { const studio = data.getStudio; const availabilities = studio.availabilities.items; const bookings = studio.bookings.items; const minBookingDuration = studio.minNumberOfHours || 2;

      const markedDates = processAvailability(availabilities, bookings, minBookingDuration);
      setAvailableDates(markedDates);
      setIsLoading(false);
    }
    

    }, [data, selectedDate]);

    if (loading) { return ; }

    if (error || !data || !data.getStudio) { return ( <ApiErrorMessage title='Error fetching the studio' message={error?.message || "Studio not found"} /> ); }

    return ( {WEEKDAYS.map((day, index) => ( {day} ))} <Calendar onDateSelect={onDateSelect} minDate={new Date()} availableDates={availableDates} selectedDate={selectedDate} /> <TouchableOpacity style={[styles.weiterButton, !selectedDate && styles.weiterButtonDisabled]} disabled={!selectedDate} onPress={nextSlide} > Weiter ); };

    const styles = StyleSheet.create({ outsideContainer: { flex: 1, backgroundColor: 'white', }, container: { flex: 1, }, datePickerWrapper: { padding: 15, }, calendarContainer: { width: '100%', }, weekContainer: { flexDirection: 'row', justifyContent: 'space-between', paddingHorizontal: 15, paddingVertical: 10, borderBottomWidth: 1, borderBottomColor: '#E5E5E5', }, weekDay: { flex: 1, alignItems: 'center', }, weekDayText: { fontSize: 14, color: '#666', }, monthContainer: { marginBottom: 20, }, monthTitle: { fontSize: 20, fontWeight: '600', marginBottom: 10, marginLeft: 10, color: '#212121', }, weekRow: { flexDirection: 'row', justifyContent: 'space-between', marginBottom: 5, }, dayWrapper: { flex: 1, aspectRatio: 1, padding: 2, }, dayContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', borderRadius: 25, minHeight: 40, // Fügt eine Mindesthöhe hinzu minWidth: 40,
    }, dayText: { fontSize: 14, color: '#212121', }, emptyDay: { flex: 1, }, selectedDay: { backgroundColor: '#212121', }, selectedDayText: { color: 'white', }, unavailableDay: { opacity: 0.3, }, unavailableDayText: { color: '#999', }, dotMarker: { width: 4, height: 4, borderRadius: 2, backgroundColor: '#000', marginTop: 2, }, weiterButtonContainer: { padding: 20, borderTopWidth: 1, borderTopColor: '#E5E5E5', backgroundColor: 'white', }, weiterButton: { backgroundColor: colors.LightBlack, borderRadius: 12, padding: 17, alignItems: 'center', }, weiterButtonDisabled: { opacity: 0.5, }, weiterButtonText: { color: '#FAFAFA', fontSize: 16, fontWeight: '500', }, disabledDay: { //backgroundColor: '#F5F5F5', opacity: 1, }, disabledDayText: { color: '#CCCCCC', },

    });

    export default DateChooser;


    // CustomCalendar.jsx import React, { useState } from 'react'; import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';

    import { de } from 'date-fns/locale'; import Svg, { Path } from 'react-native-svg'; import { format, addMonths, subMonths, startOfMonth, endOfMonth, eachDayOfInterval, isSameDay, isAfter, isBefore, startOfWeek, endOfWeek, eachWeekOfInterval, isSameMonth // Diese Zeile wurde hinzugefügt } from 'date-fns';

    const CustomCalendar = ({ selectedDate, onDateChange }) => { const [currentMonth, setCurrentMonth] = useState(new Date()); const today = new Date();

    const renderNavigationButton = (direction) => ( <TouchableOpacity style={styles.navigationButton} onPress={() => { setCurrentMonth(direction === 'next' ? addMonths(currentMonth, 1) : subMonths(currentMonth, 1) ); }} > <Svg width={8} height={12} viewBox="0 0 8 12" fill="none" style={direction === 'prev' ? { transform: [{ rotate: '180deg' }] } : {}}> );

    const weeks = eachWeekOfInterval({ start: startOfMonth(currentMonth), end: endOfMonth(currentMonth) });

    const renderWeeks = () => { return weeks.map((week) => { const days = eachDayOfInterval({ start: startOfWeek(week), end: endOfWeek(week) });

      return (
        <View key={week.toString()} style={styles.week}>
          {days.map((day) => {
            const isSelected = selectedDate && isSameDay(day, selectedDate);
            const isDisabled = isBefore(day, today) || !isSameMonth(day, currentMonth);
    
            return (
              <TouchableOpacity
                key={day.toString()}
                style={[
                  styles.day,
                  isSelected && styles.selectedDay,
                ]}
                onPress={() => !isDisabled && onDateChange(day)}
                disabled={isDisabled}
              >
                <Text style={[
                  styles.dayText,
                  isSelected && styles.selectedDayText,
                  isDisabled && styles.disabledDayText,
                ]}>
                  {format(day, 'd')}
                </Text>
              </TouchableOpacity>
            );
          })}
        </View>
      );
    });
    

    };

    return ( {renderNavigationButton('prev')} {format(currentMonth, 'MMMM yyyy', { locale: de })} {renderNavigationButton('next')} {renderWeeks()} ); };

    const styles = StyleSheet.create({ calendar: { width: '100%', padding: 20, }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, paddingHorizontal: 10, }, navigationButton: { padding: 10, }, monthText: { color: '#1F1F1F', fontSize: 19.2, fontWeight: '600', letterSpacing: -0.5, textAlign: 'center', }, daysContainer: { width: '100%', }, week: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', width: '100%', }, day: { width: 30, height: 30, justifyContent: 'center', alignItems: 'center', margin: 7, }, dayText: { fontSize: 12.7, color: '#1F1F1F', fontWeight: '400', letterSpacing: -0.272, }, selectedDay: { backgroundColor: '#1F1F1F', borderRadius: 15, }, selectedDayText: { color: '#FFFFFF', }, disabledDayText: { opacity: 0.3, }, });

    export default CustomCalendar;

  2. Assistant

    Um das gewünschte Verhalten zu erreichen und die Verfügbarkeiten im StudioFooter mithilfe des CustomCalendar anzuzeigen, müssen wir einige Anpassungen vornehmen:

    1. Studio-Daten im StudioFooter verfügbar machen: Wir müssen sicherstellen, dass der StudioFooter Zugriff auf die Studiendaten hat, insbesondere auf die Verfügbarkeiten (availabilities). Dazu können wir entweder die Studien-ID an den StudioFooter übergeben und die Daten dort abrufen oder direkt das gesamte studio-Objekt übergeben, wenn es bereits in der Elternkomponente verfügbar ist.

    2. Verfügbarkeiten verarbeiten: Ähnlich wie in DateChooser müssen wir die Verfügbarkeiten und Buchungen verarbeiten, um ein Objekt zu erstellen, das die verfügbaren und nicht verfügbaren Daten enthält.

    3. CustomCalendar anpassen: Wir müssen CustomCalendar so anpassen, dass es ein availableDates-Prop akzeptiert und dieses nutzt, um die verfügbaren Daten anzuzeigen und nicht verfügbare Daten zu deaktivieren.

    Hier ist eine detaillierte Anleitung mit Codebeispielen:


    1. Studio-Daten im StudioFooter verfügbar machen

    In Ihrer StudioScreen-Komponente übergeben Sie bereits den price und die Funktion onBookingPress an den StudioFooter. Wir müssen jetzt sicherstellen, dass der StudioFooter auch Zugriff auf die Studie-ID oder die Studiendaten hat.

    Änderungen in StudioScreen.tsx:

    // Fügen Sie 'studio' als Prop hinzu
    <StudioFooter 
      price={studio.pricePerHour} 
      onBookingPress={openBookingModal}
    + studio={studio}
     />
    

    Anpassung des Interfaces in StudioFooter.tsx:

    interface StudioFooterProps {
      price: number;
      onBookingPress: () => void;
    + studio: Studio; // Stellen Sie sicher, dass Sie den richtigen Typ importieren
    }
    

    Jetzt haben wir Zugriff auf die Studiendaten innerhalb des StudioFooter.


    2. Verfügbarkeiten verarbeiten

    Wir können die Funktion processAvailability aus DateChooser in den StudioFooter kopieren oder, besser noch, sie in eine separate Hilfsdatei auslagern, um Code-Duplikate zu vermeiden. Für die Einfachheit kopieren wir sie hier.

    In StudioFooter.tsx:

    import React, { useState, useEffect } from 'react';
    import { View, Text, TouchableOpacity, Animated, StyleSheet, ActivityIndicator } from 'react-native';
    import Svg, { Path } from 'react-native-svg';
    import CustomCalendar from '../../components/CustomCalendar';
    + import { format } from 'date-fns';
    
    ...
    
    const StudioFooter: React.FC<StudioFooterProps> = ({ price, onBookingPress, studio }) => {
      const [selectedDate, setSelectedDate] = useState<Date | null>(null);
      const [showDatePicker, setShowDatePicker] = useState(false);
      const dateContainerHeight = useRef(new Animated.Value(0)).current;
    
    + const [availableDates, setAvailableDates] = useState({});
    
    + const processAvailability = (availabilities, bookings, minBookingDuration) => {
        // (Hier den Code von 'processAvailability' aus 'DateChooser' einfügen)
      };
    
    + useEffect(() => {
    +   if (studio) {
    +     const availabilities = studio.availabilities.items;
    +     const bookings = studio.bookings.items;
    +     const minBookingDuration = studio.minNumberOfHours || 2;
    +     const markedDates = processAvailability(availabilities, bookings, minBookingDuration);
    +     setAvailableDates(markedDates);
    +   }
    + }, [studio]);
    
      const showDateContainer = () => {
        setShowDatePicker(true);
        Animated.timing(dateContainerHeight, {
          toValue: 1,
          duration: 300,
          useNativeDriver: false,
        }).start();
      };
    
      // Restlicher Code bleibt gleich...
    
      return (
        // Restlicher JSX-Code...
        {showDatePicker && (
          <CustomCalendar
            selectedDate={selectedDate}
            onDateChange={handleDateChange}
    +       availableDates={availableDates}
          />
        )}
      );
    };
    

    Hinweis: Stellen Sie sicher, dass Sie den processAvailability-Code korrekt einfügen. Dieser Code verarbeitet die Verfügbarkeiten und Buchungen und erzeugt ein Objekt availableDates, das Informationen darüber enthält, welche Daten verfügbar oder nicht verfügbar sind.


    3. CustomCalendar anpassen

    Wir müssen CustomCalendar so anpassen, dass es das availableDates-Prop akzeptiert und dieses verwendet, um die verfügbaren Daten anzuzeigen.

    In CustomCalendar.jsx:

    const CustomCalendar = ({ selectedDate, onDateChange, availableDates }) => {
      const [currentMonth, setCurrentMonth] = useState(new Date());
      const today = new Date();
    
      // Restlicher Code...
    
      const renderWeeks = () => {
        return weeks.map((week) => {
          const days = eachDayOfInterval({
            start: startOfWeek(week),
            end: endOfWeek(week)
          });
    
          return (
            <View key={week.toString()} style={styles.week}>
              {days.map((day) => {
                const isSelected = selectedDate && isSameDay(day, selectedDate);
                const isDisabled = isBefore(day, today) || !isSameMonth(day, currentMonth);
    
    +           const dateString = format(day, 'yyyy-MM-dd');
    +           const dateInfo = availableDates[dateString];
    +           const isUnavailable = dateInfo?.disabled;
    +           const isAvailable = dateInfo?.marked;
    
    +           const finalIsDisabled = isDisabled || isUnavailable || !isAvailable;
    
                return (
                  <TouchableOpacity
                    key={day.toString()}
                    style={[
                      styles.day,
    -                 isSelected && styles.selectedDay,
    +                 isSelected && styles.selectedDay,
    +                 finalIsDisabled && styles.disabledDay,
                    ]}
                    onPress={() => !finalIsDisabled && onDateChange(day)}
    -               disabled={isDisabled}
    +               disabled={finalIsDisabled}
                  >
                    <Text style={[
                      styles.dayText,
                      isSelected && styles.selectedDayText,
    -                 isDisabled && styles.disabledDayText,
    +                 finalIsDisabled && styles.disabledDayText,
                    ]}>
                      {format(day, 'd')}
                    </Text>
                  </TouchableOpacity>
                );
              })}
            </View>
          );
        });
      };
    
      // Restlicher Code...
    };
    

    Anpassung der Styles in CustomCalendar.jsx:

    const styles = StyleSheet.create({
      // Vorhandene Styles...
      disabledDay: {
        opacity: 0.3,
      },
      disabledDayText: {
        color: '#CCCCCC',
      },
    });
    

    Jetzt sollte Ihr CustomCalendar nur die verfügbaren Daten anzeigen und nicht verfügbare Daten deaktivieren, basierend auf den Verfügbarkeiten des Studios.

    Zusammenfassung der Schritte:

    • Studio-Daten an StudioFooter übergeben: Stellen Sie sicher, dass der StudioFooter Zugriff auf die Studiendaten hat.

    • Verfügbarkeiten verarbeiten: Verwenden Sie die Funktion processAvailability, um die verfügbaren Daten zu ermitteln.

    • CustomCalendar anpassen: Passen Sie den Kalender an, um die availableDates zu akzeptieren und entsprechend zu rendern.

    Beispiel für den vollständigen Code in StudioFooter.tsx:

    import React, { useState, useRef, useEffect } from 'react';
    import { View, Text, TouchableOpacity, Animated, StyleSheet } from 'react-native';
    import Svg, { Path } from 'react-native-svg';
    import CustomCalendar from '../../components/CustomCalendar';
    import { format } from 'date-fns';
    
    interface StudioFooterProps {
      price: number;
      onBookingPress: () => void;
      studio: Studio; // Stellen Sie sicher, dass Sie den korrekten Typ importieren
    }
    
    const StudioFooter: React.FC<StudioFooterProps> = ({ price, onBookingPress, studio }) => {
      const [selectedDate, setSelectedDate] = useState<Date | null>(null);
      const [showDatePicker, setShowDatePicker] = useState(false);
      const dateContainerHeight = useRef(new Animated.Value(0)).current;
    
      const [availableDates, setAvailableDates] = useState({});
    
      const processAvailability = (availabilities, bookings, minBookingDuration) => {
        const markedDates = {};
        const today = new Date();
        const nextYear = new Date();
        nextYear.setFullYear(today.getFullYear() + 1);
    
        for (let d = new Date(today); d <= nextYear; d.setDate(d.getDate() + 1)) {
          const dayOfWeek = d.getDay();
          const dateString = format(d, 'yyyy-MM-dd');
          const dayAvailability = availabilities.find(a => a.dayOfWeek === (dayOfWeek === 0 ? 7 : dayOfWeek));
    
          if (dayAvailability && dayAvailability.startTime && dayAvailability.endTime) {
            // (Restlicher Code zur Verarbeitung der Verfügbarkeiten)
            // Dieses Beispiel ist gekürzt, stellen Sie sicher, dass Sie hier den vollständigen Code einfügen
            markedDates[dateString] = { marked: true };
          } else {
            markedDates[dateString] = {
              disabled: true
            };
          }
        }
    
        return markedDates;
      };
    
      useEffect(() => {
        if (studio) {
          const availabilities = studio.availabilities.items;
          const bookings = studio.bookings.items;
          const minBookingDuration = studio.minNumberOfHours || 2;
    
          const markedDates = processAvailability(availabilities, bookings, minBookingDuration);
          setAvailableDates(markedDates);
        }
      }, [studio]);
    
      const showDateContainer = () => {
        setShowDatePicker(true);
        Animated.timing(dateContainerHeight, {
          toValue: 1,
          duration: 300,
          useNativeDriver: false,
        }).start();
      };
    
      const hideDateContainer = () => {
        Animated.timing(dateContainerHeight, {
          toValue: 0,
          duration: 300,
          useNativeDriver: false,
        }).start(() => {
          setShowDatePicker(false);
        });
      };
    
      const handleDateChange = (date: Date) => {
        setSelectedDate(date);
      };
    
      return (
        <>
          <Animated.View 
            style={[
              styles.dateContainer,
              {
                height: dateContainerHeight.interpolate({
                  inputRange: [0, 1],
                  outputRange: [0, 600]
                }),
                opacity: dateContainerHeight,
                transform: [{
                  translateY: dateContainerHeight.interpolate({
                    inputRange: [0, 1],
                    outputRange: [50, 0]
                  })
                }]
              }
            ]}
          >
            <View style={styles.dateHeaderContainer}>
              <View style={{ opacity: 0 }} />
              <Text style={styles.headerText}>Verfügbarkeit zeigen</Text>
              <TouchableOpacity 
                style={styles.closeIconContainer} 
                onPress={hideDateContainer}
              >
                <Svg width={17} height={18} viewBox="0 0 17 18" fill="none">
                  <Path
                    fillRule="evenodd"
                    clipRule="evenodd"
                    d="M7.50947 9L0 1.49054L0.990535 0.5L8.5 8.00947L16.0095 0.5L17 1.49054L9.49054 9L17 16.5095L16.0095 17.5L8.5 9.99054L0.990535 17.5L0 16.5095L7.50947 9Z"
                    fill="#1F1F1F"
                  />
                </Svg>
              </TouchableOpacity>
            </View>
            <View style={styles.container}>
              {showDatePicker && (
                <CustomCalendar
                  selectedDate={selectedDate}
                  onDateChange={handleDateChange}
                  availableDates={availableDates}
                />
              )}
            </View>
          </Animated.View>
    
          <View style={styles.footerContainer}>
            <View style={styles.phoneFooterContainer}>
              <View style={styles.footerTextContainer}>
                <View style={styles.footerTextContainer2}>
                  <Text style={styles.priceText}>{price}€</Text>
                  <Text style={styles.perHourText}>pro Stunde</Text>
                </View>
                <TouchableOpacity onPress={showDateContainer}>
                  <Text style={styles.availability}>Verfügbarkeit zeigen</Text>
                </TouchableOpacity>
              </View>
              <TouchableOpacity 
                style={styles.footerButton}
                onPress={onBookingPress}
              >
                <Text style={styles.buttonText}>Reservieren</Text>
              </TouchableOpacity>
            </View>
          </View>
        </>
      );
    };
    
    export default StudioFooter;
    

    Anpassung von CustomCalendar.jsx:

    Stellen Sie sicher, dass Sie den Code so anpassen, dass availableDates verwendet wird, um verfügbare Daten anzuzeigen.


    Beachten Sie, dass dies ein vereinfachtes Beispiel ist. Möglicherweise müssen Sie zusätzliche Anpassungen vornehmen, um sicherzustellen, dass die Logik zur Verarbeitung der Verfügbarkeiten korrekt funktioniert und dass alle notwendigen Importe und Typen korrekt sind.

    Wenn Sie weitere Fragen haben oder Hilfe bei bestimmten Abschnitten des Codes benötigen, lassen Sie es mich bitte wissen!