Notice added Canonical answer required by user022yufjb
Bounty Started worth 50 reputation by user022yufjb
added 2027 characters in body; edited title
Source Link
user022yufjb
  • 41
  • 1
  • 3
  • 13

how to move submenu items from left side panel to top bar instead? Issue with Drag-and-Drop Functionality: Boxes Not Dropping in Correct Columns

In my belowthe code below, I wanthave a weekly calendar displayed as shown below:

enter image description here When I drag and drop these draggable boxes from one date to move submenu itemanother, for example, if I drag the Morooka from leftTuesday 9th to top bar is there any waySunday 7th in column 8th, it will drop it into column 1st. The same happens with other draggable boxes; if I drop them from the 9th in the 1st column to dothe 10th in the 6th column, they still end up in column 1.

I expect the dragbox to be dropped into the column where I release it?. So if I tried butdrop it was messing up css sointo column 5, it should stay in column 5. However, currently, everything is being dropped into column 1. Is there any cleaner way to do itfix this? Also to make it look better

I tried printing in css somy console.log when I click on one submenuitem it should should all other insidethe drag box is dropped, and it at bottom ofseems to identify the correct column and print the date and timeslot correctly. However, it just like normal submenu item enter image description herestill doesn't drop into the correct column

enter image description here

import ExpandLess from "@mui/icons-material/ExpandLess";
import ExpandMore from "@mui/icons-material/ExpandMore";
import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
import Inventory2RoundedIcon from "@mui/icons-material/Inventory2Rounded";
import ReceiptLongRoundedIcon from "@mui/icons-material/ReceiptLongRounded";
importReact, SettingsRoundedIcon{ fromuseState, "@mui/icons-material/SettingsRounded";
importuseRef ShoppingCartCheckoutRoundedIcon} from "@mui/icons-material/ShoppingCartCheckoutRounded";"react";
import {
  Avatar,
  ContainerstartOfWeek,
  IconButtonendOfWeek,
  Tooltipformat,
  TypographyaddDays,
} from "@mui/material";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Collapse from "@mui/material/Collapse";
import CssBaseline from "@mui/material/CssBaseline";
import Divider from "@mui/material/Divider";
import Drawer from "@mui/material/Drawer";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Toolbar from "@mui/material/Toolbar";
import { ThemeProvidersubDays, createThemeset } from "@mui/material/styles";
import PropTypes from "prop"date-types";fns";
import * as Reactaxios from "react";'axios';

import AcumenLogo{ fetchCustomers } from "'../assets../imgsapi/acumencustomer';
const logo.png";DraggableBox = ({
import MWXplusLogo fromday,
 "../assets/imgs/mwx+ logo.png";name: initialName,
import { suburb: initialSuburb,
  SubMenuItemsForBillingcalendarData,
  SubMenuItemsForInventorysetCalendarData,
  SubMenuItemsForSettingschangeName,
  SubMenuItemsForOrderssetChangeName,
} from "./SubMenuItems";changeSuburb,
import Cookies fromsetChangeSuburb,
 "js-cookie"; setChangeDay,
import { LinksetChangeData,
  orderData,
  setOrderData,
  timeSlotIndex,
}) from=> "react-router-dom";{
  const [showTooltip, setShowTooltip] = useState(false);
  const boxRef = useRef(null);

  const drawerWidthfilteredOrders = 240;orderData.order.filter(
    (order) => new Date(order.RequiredDateAndTime).getDate() === parseInt(day)
  );

  const themehandleDragStart = createTheme({
  typography: {
    body1: {
      fontSize: "14px",
    },
  },
  components: {
    MuiDrawer: {
      styleOverrides: {
       e) paper:=> {
          backgroundColor: "#eeeeee",
          color: "black",
          boxSizing: "border-box",
          borderRight: "#eeeeee",
          width: drawerWidth,
        },setShowTooltip(false);
      },setChangeData(filteredOrders[timeSlotIndex]);
    },boxRef.current.classList.add("dragging");
  },
});

function hasJWT const handleDragEnd = () => {
  let flag =boxRef.current.classList.remove("dragging");
 false; };

  //checkconst userhandleDragOver has= JWT(e) token=> {
  Cookies  e.getpreventDefault("token");
 ? (flag =};
 true) : (flag = false);

  return flag;(
    <div
      className="drag-box"
      ref={boxRef}
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDragOver={handleDragOver}
      onMouseEnter={() => setShowTooltip(true)}
      onMouseLeave={() => setShowTooltip(false)}
      style={{
        width: "70px",
        height: "70px",
        textAlign: "center",
        backgroundColor: "#F5F5F5",
        color: "#333333",
        marginTop: "0px",
        position: "relative",
        cursor: "move",
        fontSize: "10px",
      }}
      data-day={day}
      data-name={initialName}
    >
      <div>
        {filteredOrders[timeSlotIndex] && (
          <div key={timeSlotIndex}>
            <p>{filteredOrders[timeSlotIndex].DelCity}</p>
          </div>
        )}
      </div>
    </div>
  );
};

function logOut() {
  Cookies.remove("token");
  window.location.href = "/signin";
}

function ResponsiveDrawer(props) {
  const { window } = props;
  const [openOrders, setOpenOrders] = React.useState(false);
  const [openBilling, setOpenBilling] = React.useState(false);
  const [openInventory, setOpenInventory] = React.useState(false);
  const [openSettings, setOpenSettings] = React.useState(false);
  const [openProcessing, setOpenProcessing] = React.useState(false);

  const drawer = (
    <div>
      <Toolbar style={{ backgroundColor: "rgb(23, 61, 102)", height: "4vw" }}>
        <Box>
          <img
            src={MWXplusLogo}
            alt="Logo"
            style={{
              width: "100%",
              height: "100%",
            }}
          />
        </Box>
      </Toolbar>
      <Divider />
      <List>
        <ListItem disablePadding>
          <ListItemButton component={Link} to="/main">
            <ListItemIcon>
              <HomeRoundedIcon />
            </ListItemIcon>
            <ListItemText primary="Home" />
          </ListItemButton>
        </ListItem>
        <ListItem
          button
          onClick={() => {
            setOpenOrders(!openOrders);
          }}
        >
          <ListItemIcon>
            <ShoppingCartCheckoutRoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Orders" />
          {openOrders ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openOrders} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForOrders
              openProcessing={openProcessing}
              setOpenProcessing={setOpenProcessing}
            />
          </List>
        </Collapse>

        <ListItem
          button
          onClick={() => {
            setOpenBilling(!openBilling);
          }}
        >
          <ListItemIcon>
            <ReceiptLongRoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Billing" />
          {openBilling ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openBilling} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForBilling />
          </List>
        </Collapse>
        <ListItem
          button
          onClick={() => {
            setOpenInventory(!openInventory);
          }}
        >
          <ListItemIcon>
            <Inventory2RoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Inventory" />
          {openInventory ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openInventory} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForInventory />
          </List>
        </Collapse>
      </List>
      <Divider />
      <ListItem
        button
        onClick={() => {
       const RunSheetPreview = setOpenSettings(!openSettings);
        }}
      >
        <ListItemIcon>
          <SettingsRoundedIcon />
        </ListItemIcon>
        <ListItemText primary="Setting" />
        {openSettings ? <ExpandLess /> : <ExpandMore />}
      </ListItem>
      <Collapse in={openSettings} timeout="auto" unmountOnExit>
        <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
          <SubMenuItemsForSettings />
        </List>
      </Collapse>
      <div
        style={{
          bottom: "0",
          position: "absolute"orderData,
          left: "0",
          right: "0"setOrderData,
        }}
      >
        <Typography
          fontSize={"12px"}
          fontFamily={"Arial,Tahoma,PingFangSC,sans-serif"}
          fontWeight={600}
          color={"rgba(22, 24, 35selectedDate, .5)"}
        >
          V1.0.0
        </Typography>
        <img src={AcumenLogo} alt="Logo" width={"50%"} height={"50%"} />
      </div>
    </div>
  );

  initialName,
  initialSuburb,
  setShowTooltip,
  }) => {
  const containerboxRef = useRef(null);
  const [changeName, windowsetChangeName] !=== undefineduseState("");
 ? const [changeDay, setChangeDay] = useState(null);
 => windowconst [changeData, setChangeData] = useState(null).document.body;
 : 
 undefined; const [changeSuburb, setChangeSuburb] = useState(null);
  const [selectedDateState, setSelectedDate] = useState(new Date());
  const handleNextWeek = () => {

  return (
    <ThemeProvider theme={theme}>
      <Box
        sx={{
          width: { xs: "100%", sm: drawerWidth }setSelectedDate(addDays(selectedDateState,
          flexShrink: { sm: 0 },7));
        }}
      >
        <CssBaseline />;

   const handlePreviousWeek = () => <AppBar{
       setSelectedDate(subDays(selectedDateState, 7));
  position="fixed"};
   const formatDate = (date) => {
  style={{const backgroundColor:dateVal "rgb(23,= 61,new 102Date(date)" }};
     const year = >dateVal.getFullYear();
     const month = String(dateVal.getMonth() + <Container1).padStart(2, maxWidth="sx">"0");
       const day = String(dateVal.getDate()).padStart(2, "0");
 <Toolbar disableGuttersreturn style=`${year}-${ height: "4vw" month}-${day}>`;
          };
const handleDragOver = (e) <Box=> sx={{ flexGrow: 1 }} 
 />{" "e.preventDefault();
};
     
const handleDrop = (e, timeSlotIndex, dayOfMonth, year, month) => <Box>{
      e.preventDefault();
  e.stopPropagation();
   
  let d = { <Tooltip...changeData title="Logout">};
        d = new Date(d.OrderDate);
   
  const number = <IconButtone.target.tabIndex.toString();
 sx={{ pconsole.log("Number: 0", }}>number);
           
  const currentYear = e.target.getAttribute('data-year');
  let currentMonth = <Avatare.target.getAttribute('data-month');
   
  // Log the day, month, and year
  console.log("Day:", dayOfMonth);
   
  // Format the month with alt="Grassleading Land"
zero if it's a single digit
  currentMonth = currentMonth.padStart(2, "0");
  console.log("Month:", currentMonth);
   
  console.log("Year:", currentYear);
   
  src="/static/images/avatar/2.jpg"
    Format the day with leading zero
  const formattedDay = dayOfMonth.toString().padStart(2, "0");
   
  const formattedDate = onClick=`${logOutcurrentYear}-${currentMonth}-${formattedDay}`;
              console.log("Formatted Date:", formattedDate);
   
  />d.setDate(dayOfMonth);
   d.setMonth(currentMonth);
  d.setFullYear(currentYear);
  d = d.toISOString();
   
  let fi = { ...changeData </IconButton>};
  fi.OrderDate = d;
  fi.RequiredDateAndTime = d;
   
  let newDate = new </Tooltip>Date(changeData.OrderDate);
      newDate = new Date(currentYear, currentMonth, dayOfMonth, newDate.getHours(), newDate.getMinutes(), </Box>newDate.getSeconds());
       
  // Update the order </Toolbar>data
   let newOrderData = orderData.order.filter(item => item !== </Container>changeData);
        </AppBar>
  // Update the order date for <Box
the dragged item to its new position
  changeData.OrderDate = component="nav"newDate.toISOString();
   changeData.RequiredDateAndTime = newDate.toISOString();
  const timeSlot = sx={`${
 timeSlotIndex + 1}`;
  console.log("Updated changeData:", changeData); // Log the updated changeData

 width: {console.log("Time smSlot: drawerWidth }", timeSlot);

  // Push the updated dragged item to the new position
 flexShrink: newOrderData.push({ sm:...changeData, 0timeSlot },);
   console.log("Updated newOrderData:", newOrderData);



  setCalendarData(newOrderData);
};


// Remove the filter based backgroundColor:on "red",selectedDate
     const dateStrings = orderData.order.map((listItem) => }}{
  const date = new Date(listItem.RequiredDateAndTime);
  const year aria-label="mailbox= folders"date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, >"0");
      const day = String(date.getDate()).padStart(2, <Drawer"0");
     return `${year}-${month}-${day}`;
});



const initialCalendarData = orderData.order.map((order, index) => container={container}
    const name = order.DelCity;
  const suburb = variant="temporary"order.DelPostalCode;
   return {
    day: dateStrings[index], // Use ModalProps={{
dateStrings array here
    name,
    suburb,
    keepMountedinitialName: truename, // BetterAssign openthe performancevalue onto mobile.initialName
    initialSuburb: suburb, // Assign the value to initialSuburb
  };
});
  const [calendarData, setCalendarData] = useState(initialCalendarData);
 
const generateCalendar = () => sx={{
  const startDate = startOfWeek(selectedDateState, { weekStartsOn: 0 });
  const endDate = display:endOfWeek(selectedDateState, { xs: "block", smweekStartsOn: "none"0 },);

  const rows = [];
  let day = startDate;

  while (day "&<= .MuiDrawer-paper":endDate) {
    const formattedDate = formatDate(day);
    const dateObject = new Date(formattedDate);
 boxSizing: "border-box",
  const year = dateObject.getFullYear(); // Extract year (e.g., 2024)
    const month width:= drawerWidth,dateObject.getMonth() + 1;
    const dayName = format(day, "EEEE");
    const dayOfMonth }= format(day, "d");

    const isTargetDate = dateStrings.includes(formattedDate);

    const }}ordersForDay = orderData.order.filter((order) => {
      const orderDate = new >Date(order.RequiredDateAndTime).getDate();
      return orderDate === parseInt(dayOfMonth);
    {drawer});

    // Find the first available time </Drawer>
slot for the current day
    const firstAvailableSlot <Drawer= ordersForDay.findIndex(
      (order) => !order.isAssigned
    variant="permanent");

    const row = (
      <tr sx={key={day}>
        <td className="calendar-cell">
     display: { xs: "none", sm: "block"<div className="day-name">{dayName},</div>
              "&<div .MuiDrawerclassName="day-paper": number">{dayOfMonth}</div>
         </td>
       boxSizing: "border-box"{[...Array(15)].map((_,
     index) => (
         width: drawerWidth,<td
              key={index},
            }className={`grid-cell`}
            opendata-has-data={ordersForDay[index] ? "true" : "false"}
          >
            {drawer/* Render DraggableBox only if there is an order for this column */}
          <  {ordersForDay[index] && (
              <DraggableBox
                day={parseInt(dayOfMonth)}
                initialName={ordersForDay[index].DelCity}
                initialSuburb={ordersForDay[index].DelPostalCode}
                calendarData={calendarData}
                setCalendarData={setCalendarData}
                changeName={changeName}
                setOrderData={setOrderData} /Drawer>/ Pass the setOrderData function
        <        setChangeName={setChangeName}
                changeDay={changeDay}
                setChangeDay={setChangeDay}
                changeSuburb={changeSuburb}
                setChangeSuburb={setChangeSuburb}
                setChangeData={setChangeData}
                orderData={orderData}
                timeSlotIndex={index}
              /Box>>
        <Box    )}
          component="main"  {!ordersForDay[index] && (
          sx=    <p
                style={{
            flexGrow      height: 1"40px",
            p      width: 3"60px",
            width      display: {"flex",
 sm                 alignItems: `calc(100%"center",
 - $                justifyContent: "center",
                }}
                onDragOver={drawerWidthhandleDragOver}px
                onDrop={(e)` }=>
                  handleDrop(
                    e,
                    index,
                    parseInt(dayOfMonth),
                    year,
                    month
                  )
                }
                tabIndex={dayOfMonth}
                data-year={year}
                data-month={month}
              ></Box>p>
            )}
          </Box>td>
        ))}
      </ThemeProvider>tr>
    );
}

ResponsiveDrawer    rows.propTypespush(row);

    day = {addDays(day, 1);
  window:}

 PropTypes.func, return rows;
};

      
     
return (
  <div>
  <div className="delivery-schedule-heading">
      <h2 style={{ color: "", margin: "0 0px 0 0px", textAlign: "left" }}></h2>
      <div style={{ textAlign: "left", margin: "0 0px 0 0px" }}>
  <h2 style={{ margin: 0, color: "#08315b", fontWeight: "bold" }}>
    Delivery Schedule : {format(startOfWeek(selectedDateState), "MMMM d")} -{" "}
    {format(endOfWeek(selectedDateState), "MMMM d, yyyy")}
  </h2>
</div>

      <div style={{ textAlign: "right" }}>
          {/* Button for moving to the previous week */}
          <button onClick={handlePreviousWeek}>&lt; Previous Week</button>
          {/* Button for moving to the next week */}
          <button onClick={handleNextWeek}>Next Week &gt;</button>
        </div>
    </div>
  
<div className="calendar-container">
<table className="calendar-table">
<thead>
<tr>
<th>{/* Empty header cell for labels */}</th>

{[...Array(15)].map((_, index) => (
<th key={index}>{index + 1}</th>
))}

</tr>
</thead>
<tbody>
{generateCalendar()}
</tbody>
</table>
</div>
</div>
);
};

export default ResponsiveDrawer;RunSheetPreview;

how to move submenu items from left side panel to top bar instead?

In my below code I want to move submenu item from left to top bar is there any way to do it? I tried but it was messing up css so any cleaner way to do it? Also to make it look better in css so when I click on one submenuitem it should should all other inside it at bottom of it just like normal submenu item enter image description here

import ExpandLess from "@mui/icons-material/ExpandLess";
import ExpandMore from "@mui/icons-material/ExpandMore";
import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
import Inventory2RoundedIcon from "@mui/icons-material/Inventory2Rounded";
import ReceiptLongRoundedIcon from "@mui/icons-material/ReceiptLongRounded";
import SettingsRoundedIcon from "@mui/icons-material/SettingsRounded";
import ShoppingCartCheckoutRoundedIcon from "@mui/icons-material/ShoppingCartCheckoutRounded";
import {
  Avatar,
  Container,
  IconButton,
  Tooltip,
  Typography,
} from "@mui/material";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Collapse from "@mui/material/Collapse";
import CssBaseline from "@mui/material/CssBaseline";
import Divider from "@mui/material/Divider";
import Drawer from "@mui/material/Drawer";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Toolbar from "@mui/material/Toolbar";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import PropTypes from "prop-types";
import * as React from "react";

import AcumenLogo from "../assets/imgs/acumen logo.png";
import MWXplusLogo from "../assets/imgs/mwx+ logo.png";
import {
  SubMenuItemsForBilling,
  SubMenuItemsForInventory,
  SubMenuItemsForSettings,
  SubMenuItemsForOrders,
} from "./SubMenuItems";
import Cookies from "js-cookie";
import { Link } from "react-router-dom";

const drawerWidth = 240;

const theme = createTheme({
  typography: {
    body1: {
      fontSize: "14px",
    },
  },
  components: {
    MuiDrawer: {
      styleOverrides: {
        paper: {
          backgroundColor: "#eeeeee",
          color: "black",
          boxSizing: "border-box",
          borderRight: "#eeeeee",
          width: drawerWidth,
        },
      },
    },
  },
});

function hasJWT() {
  let flag = false;

  //check user has JWT token
  Cookies.get("token") ? (flag = true) : (flag = false);

  return flag;
}

function logOut() {
  Cookies.remove("token");
  window.location.href = "/signin";
}

function ResponsiveDrawer(props) {
  const { window } = props;
  const [openOrders, setOpenOrders] = React.useState(false);
  const [openBilling, setOpenBilling] = React.useState(false);
  const [openInventory, setOpenInventory] = React.useState(false);
  const [openSettings, setOpenSettings] = React.useState(false);
  const [openProcessing, setOpenProcessing] = React.useState(false);

  const drawer = (
    <div>
      <Toolbar style={{ backgroundColor: "rgb(23, 61, 102)", height: "4vw" }}>
        <Box>
          <img
            src={MWXplusLogo}
            alt="Logo"
            style={{
              width: "100%",
              height: "100%",
            }}
          />
        </Box>
      </Toolbar>
      <Divider />
      <List>
        <ListItem disablePadding>
          <ListItemButton component={Link} to="/main">
            <ListItemIcon>
              <HomeRoundedIcon />
            </ListItemIcon>
            <ListItemText primary="Home" />
          </ListItemButton>
        </ListItem>
        <ListItem
          button
          onClick={() => {
            setOpenOrders(!openOrders);
          }}
        >
          <ListItemIcon>
            <ShoppingCartCheckoutRoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Orders" />
          {openOrders ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openOrders} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForOrders
              openProcessing={openProcessing}
              setOpenProcessing={setOpenProcessing}
            />
          </List>
        </Collapse>

        <ListItem
          button
          onClick={() => {
            setOpenBilling(!openBilling);
          }}
        >
          <ListItemIcon>
            <ReceiptLongRoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Billing" />
          {openBilling ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openBilling} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForBilling />
          </List>
        </Collapse>
        <ListItem
          button
          onClick={() => {
            setOpenInventory(!openInventory);
          }}
        >
          <ListItemIcon>
            <Inventory2RoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Inventory" />
          {openInventory ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openInventory} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForInventory />
          </List>
        </Collapse>
      </List>
      <Divider />
      <ListItem
        button
        onClick={() => {
          setOpenSettings(!openSettings);
        }}
      >
        <ListItemIcon>
          <SettingsRoundedIcon />
        </ListItemIcon>
        <ListItemText primary="Setting" />
        {openSettings ? <ExpandLess /> : <ExpandMore />}
      </ListItem>
      <Collapse in={openSettings} timeout="auto" unmountOnExit>
        <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
          <SubMenuItemsForSettings />
        </List>
      </Collapse>
      <div
        style={{
          bottom: "0",
          position: "absolute",
          left: "0",
          right: "0",
        }}
      >
        <Typography
          fontSize={"12px"}
          fontFamily={"Arial,Tahoma,PingFangSC,sans-serif"}
          fontWeight={600}
          color={"rgba(22, 24, 35, .5)"}
        >
          V1.0.0
        </Typography>
        <img src={AcumenLogo} alt="Logo" width={"50%"} height={"50%"} />
      </div>
    </div>
  );

  const container =
    window !== undefined ? () => window().document.body : undefined;

  return (
    <ThemeProvider theme={theme}>
      <Box
        sx={{
          width: { xs: "100%", sm: drawerWidth },
          flexShrink: { sm: 0 },
        }}
      >
        <CssBaseline />

        <AppBar
          position="fixed"
          style={{ backgroundColor: "rgb(23, 61, 102)" }}
        >
          <Container maxWidth="sx">
            <Toolbar disableGutters style={{ height: "4vw" }}>
              <Box sx={{ flexGrow: 1 }} />{" "}
              <Box>
                <Tooltip title="Logout">
                  <IconButton sx={{ p: 0 }}>
                    <Avatar
                      alt="Grass Land"
                      src="/static/images/avatar/2.jpg"
                      onClick={logOut}
                    />
                  </IconButton>
                </Tooltip>
              </Box>
            </Toolbar>
          </Container>
        </AppBar>
        <Box
          component="nav"
          sx={{
             width: { sm: drawerWidth },
            flexShrink: { sm: 0 },
            backgroundColor: "red",
          }}
          aria-label="mailbox folders"
        >
          <Drawer
            container={container}
            variant="temporary"
            ModalProps={{
              keepMounted: true, // Better open performance on mobile.
            }}
            sx={{
              display: { xs: "block", sm: "none" },
              "& .MuiDrawer-paper": {
                boxSizing: "border-box",
                width: drawerWidth,
              },
            }}
          >
            {drawer}
          </Drawer>
          <Drawer
            variant="permanent"
            sx={{
              display: { xs: "none", sm: "block" },
              "& .MuiDrawer-paper": {
                boxSizing: "border-box",
                width: drawerWidth,
              },
            }}
            open
          >
            {drawer}
          </Drawer>
        </Box>
        <Box
          component="main"
          sx={{
            flexGrow: 1,
            p: 3,
            width: { sm: `calc(100% - ${drawerWidth}px)` },
          }}
        ></Box>
      </Box>
    </ThemeProvider>
  );
}

ResponsiveDrawer.propTypes = {
  window: PropTypes.func,
};

export default ResponsiveDrawer;

Issue with Drag-and-Drop Functionality: Boxes Not Dropping in Correct Columns

In the code below, I have a weekly calendar displayed as shown below:

enter image description here When I drag and drop these draggable boxes from one date to another, for example, if I drag the Morooka from Tuesday 9th to Sunday 7th in column 8th, it will drop it into column 1st. The same happens with other draggable boxes; if I drop them from the 9th in the 1st column to the 10th in the 6th column, they still end up in column 1.

I expect the dragbox to be dropped into the column where I release it. So if I drop it into column 5, it should stay in column 5. However, currently, everything is being dropped into column 1. Is there any way to fix this?

I tried printing in my console.log when the drag box is dropped, and it seems to identify the correct column and print the date and timeslot correctly. However, it still doesn't drop into the correct column

enter image description here

    import React, { useState, useRef } from "react";
import { startOfWeek, endOfWeek, format, addDays, subDays, set } from "date-fns";
import axios from 'axios';

import { fetchCustomers } from '../../api/customer';
const DraggableBox = ({
  day,
  name: initialName,
  suburb: initialSuburb,
  calendarData,
  setCalendarData,
  changeName,
  setChangeName,
  changeSuburb,
  setChangeSuburb,
  setChangeDay,
  setChangeData,
  orderData,
  setOrderData,
  timeSlotIndex,
}) => {
  const [showTooltip, setShowTooltip] = useState(false);
  const boxRef = useRef(null);

  const filteredOrders = orderData.order.filter(
    (order) => new Date(order.RequiredDateAndTime).getDate() === parseInt(day)
  );

  const handleDragStart = (e) => {
    setShowTooltip(false);
    setChangeData(filteredOrders[timeSlotIndex]);
    boxRef.current.classList.add("dragging");
  };

  const handleDragEnd = () => {
    boxRef.current.classList.remove("dragging");
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };
     

  return (
    <div
      className="drag-box"
      ref={boxRef}
      draggable
      onDragStart={handleDragStart}
      onDragEnd={handleDragEnd}
      onDragOver={handleDragOver}
      onMouseEnter={() => setShowTooltip(true)}
      onMouseLeave={() => setShowTooltip(false)}
      style={{
        width: "70px",
        height: "70px",
        textAlign: "center",
        backgroundColor: "#F5F5F5",
        color: "#333333",
        marginTop: "0px",
        position: "relative",
        cursor: "move",
        fontSize: "10px",
      }}
      data-day={day}
      data-name={initialName}
    >
      <div>
        {filteredOrders[timeSlotIndex] && (
          <div key={timeSlotIndex}>
            <p>{filteredOrders[timeSlotIndex].DelCity}</p>
          </div>
        )}
      </div>
    </div>
  );
};




const RunSheetPreview = ({
orderData,  
setOrderData,
  selectedDate,

  initialName,
  initialSuburb,
  setShowTooltip,
  }) => {
  const boxRef = useRef(null);
  const [changeName, setChangeName] = useState("");
  const [changeDay, setChangeDay] = useState(null);
  const [changeData, setChangeData] = useState(null);
  
  const [changeSuburb, setChangeSuburb] = useState(null);
  const [selectedDateState, setSelectedDate] = useState(new Date());
  const handleNextWeek = () => {

    setSelectedDate(addDays(selectedDateState, 7));
  };

  const handlePreviousWeek = () => {
    setSelectedDate(subDays(selectedDateState, 7));
  };
  const formatDate = (date) => {
  const dateVal = new Date(date);
  const year = dateVal.getFullYear();
  const month = String(dateVal.getMonth() + 1).padStart(2, "0");
  const day = String(dateVal.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
};
const handleDragOver = (e) => { 
  e.preventDefault();
};

const handleDrop = (e, timeSlotIndex, dayOfMonth, year, month) => {
  e.preventDefault();
  e.stopPropagation();
   
  let d = { ...changeData };
  d = new Date(d.OrderDate);
   
  const number = e.target.tabIndex.toString();
  console.log("Number:", number);
   
  const currentYear = e.target.getAttribute('data-year');
  let currentMonth = e.target.getAttribute('data-month');
   
  // Log the day, month, and year
  console.log("Day:", dayOfMonth);
   
  // Format the month with leading zero if it's a single digit
  currentMonth = currentMonth.padStart(2, "0");
  console.log("Month:", currentMonth);
   
  console.log("Year:", currentYear);
   
  // Format the day with leading zero
  const formattedDay = dayOfMonth.toString().padStart(2, "0");
   
  const formattedDate = `${currentYear}-${currentMonth}-${formattedDay}`;
  console.log("Formatted Date:", formattedDate);
   
  d.setDate(dayOfMonth);
  d.setMonth(currentMonth);
  d.setFullYear(currentYear);
  d = d.toISOString();
   
  let fi = { ...changeData };
  fi.OrderDate = d;
  fi.RequiredDateAndTime = d;
   
  let newDate = new Date(changeData.OrderDate);
  newDate = new Date(currentYear, currentMonth, dayOfMonth, newDate.getHours(), newDate.getMinutes(), newDate.getSeconds());
 
  // Update the order data
  let newOrderData = orderData.order.filter(item => item !== changeData);

  // Update the order date for the dragged item to its new position
  changeData.OrderDate = newDate.toISOString();
  changeData.RequiredDateAndTime = newDate.toISOString();
  const timeSlot = `${timeSlotIndex + 1}`;
  console.log("Updated changeData:", changeData); // Log the updated changeData

  console.log("Time Slot:", timeSlot);

  // Push the updated dragged item to the new position
  newOrderData.push({ ...changeData, timeSlot });
  console.log("Updated newOrderData:", newOrderData);



  setCalendarData(newOrderData);
};


// Remove the filter based on selectedDate
const dateStrings = orderData.order.map((listItem) => {
  const date = new Date(listItem.RequiredDateAndTime);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
});



const initialCalendarData = orderData.order.map((order, index) => {
  const name = order.DelCity;
  const suburb = order.DelPostalCode;
  return {
    day: dateStrings[index], // Use dateStrings array here
    name,
    suburb,
    initialName: name, // Assign the value to initialName
    initialSuburb: suburb, // Assign the value to initialSuburb
  };
});
const [calendarData, setCalendarData] = useState(initialCalendarData);
 
const generateCalendar = () => {
  const startDate = startOfWeek(selectedDateState, { weekStartsOn: 0 });
  const endDate = endOfWeek(selectedDateState, { weekStartsOn: 0 });

  const rows = [];
  let day = startDate;

  while (day <= endDate) {
    const formattedDate = formatDate(day);
    const dateObject = new Date(formattedDate);
    const year = dateObject.getFullYear(); // Extract year (e.g., 2024)
    const month = dateObject.getMonth() + 1;
    const dayName = format(day, "EEEE");
    const dayOfMonth = format(day, "d");

    const isTargetDate = dateStrings.includes(formattedDate);

    const ordersForDay = orderData.order.filter((order) => {
      const orderDate = new Date(order.RequiredDateAndTime).getDate();
      return orderDate === parseInt(dayOfMonth);
    });

    // Find the first available time slot for the current day
    const firstAvailableSlot = ordersForDay.findIndex(
      (order) => !order.isAssigned
    );

    const row = (
      <tr key={day}>
        <td className="calendar-cell">
          <div className="day-name">{dayName}</div>
          <div className="day-number">{dayOfMonth}</div>
        </td>
        {[...Array(15)].map((_, index) => (
          <td
            key={index}
            className={`grid-cell`}
            data-has-data={ordersForDay[index] ? "true" : "false"}
          >
            {/* Render DraggableBox only if there is an order for this column */}
            {ordersForDay[index] && (
              <DraggableBox
                day={parseInt(dayOfMonth)}
                initialName={ordersForDay[index].DelCity}
                initialSuburb={ordersForDay[index].DelPostalCode}
                calendarData={calendarData}
                setCalendarData={setCalendarData}
                changeName={changeName}
                setOrderData={setOrderData} // Pass the setOrderData function
                setChangeName={setChangeName}
                changeDay={changeDay}
                setChangeDay={setChangeDay}
                changeSuburb={changeSuburb}
                setChangeSuburb={setChangeSuburb}
                setChangeData={setChangeData}
                orderData={orderData}
                timeSlotIndex={index}
              />
            )}
            {!ordersForDay[index] && (
              <p
                style={{
                  height: "40px",
                  width: "60px",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                }}
                onDragOver={handleDragOver}
                onDrop={(e) =>
                  handleDrop(
                    e,
                    index,
                    parseInt(dayOfMonth),
                    year,
                    month
                  )
                }
                tabIndex={dayOfMonth}
                data-year={year}
                data-month={month}
              ></p>
            )}
          </td>
        ))}
      </tr>
    );

    rows.push(row);

    day = addDays(day, 1);
  }

  return rows;
};

      
     
return (
  <div>
  <div className="delivery-schedule-heading">
      <h2 style={{ color: "", margin: "0 0px 0 0px", textAlign: "left" }}></h2>
      <div style={{ textAlign: "left", margin: "0 0px 0 0px" }}>
  <h2 style={{ margin: 0, color: "#08315b", fontWeight: "bold" }}>
    Delivery Schedule : {format(startOfWeek(selectedDateState), "MMMM d")} -{" "}
    {format(endOfWeek(selectedDateState), "MMMM d, yyyy")}
  </h2>
</div>

      <div style={{ textAlign: "right" }}>
          {/* Button for moving to the previous week */}
          <button onClick={handlePreviousWeek}>&lt; Previous Week</button>
          {/* Button for moving to the next week */}
          <button onClick={handleNextWeek}>Next Week &gt;</button>
        </div>
    </div>
  
<div className="calendar-container">
<table className="calendar-table">
<thead>
<tr>
<th>{/* Empty header cell for labels */}</th>

{[...Array(15)].map((_, index) => (
<th key={index}>{index + 1}</th>
))}

</tr>
</thead>
<tbody>
{generateCalendar()}
</tbody>
</table>
</div>
</div>
);
};

export default RunSheetPreview;
Source Link
user022yufjb
  • 41
  • 1
  • 3
  • 13

how to move submenu items from left side panel to top bar instead?

In my below code I want to move submenu item from left to top bar is there any way to do it? I tried but it was messing up css so any cleaner way to do it? Also to make it look better in css so when I click on one submenuitem it should should all other inside it at bottom of it just like normal submenu item enter image description here

import ExpandLess from "@mui/icons-material/ExpandLess";
import ExpandMore from "@mui/icons-material/ExpandMore";
import HomeRoundedIcon from "@mui/icons-material/HomeRounded";
import Inventory2RoundedIcon from "@mui/icons-material/Inventory2Rounded";
import ReceiptLongRoundedIcon from "@mui/icons-material/ReceiptLongRounded";
import SettingsRoundedIcon from "@mui/icons-material/SettingsRounded";
import ShoppingCartCheckoutRoundedIcon from "@mui/icons-material/ShoppingCartCheckoutRounded";
import {
  Avatar,
  Container,
  IconButton,
  Tooltip,
  Typography,
} from "@mui/material";
import AppBar from "@mui/material/AppBar";
import Box from "@mui/material/Box";
import Collapse from "@mui/material/Collapse";
import CssBaseline from "@mui/material/CssBaseline";
import Divider from "@mui/material/Divider";
import Drawer from "@mui/material/Drawer";
import List from "@mui/material/List";
import ListItem from "@mui/material/ListItem";
import ListItemButton from "@mui/material/ListItemButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Toolbar from "@mui/material/Toolbar";
import { ThemeProvider, createTheme } from "@mui/material/styles";
import PropTypes from "prop-types";
import * as React from "react";

import AcumenLogo from "../assets/imgs/acumen logo.png";
import MWXplusLogo from "../assets/imgs/mwx+ logo.png";
import {
  SubMenuItemsForBilling,
  SubMenuItemsForInventory,
  SubMenuItemsForSettings,
  SubMenuItemsForOrders,
} from "./SubMenuItems";
import Cookies from "js-cookie";
import { Link } from "react-router-dom";

const drawerWidth = 240;

const theme = createTheme({
  typography: {
    body1: {
      fontSize: "14px",
    },
  },
  components: {
    MuiDrawer: {
      styleOverrides: {
        paper: {
          backgroundColor: "#eeeeee",
          color: "black",
          boxSizing: "border-box",
          borderRight: "#eeeeee",
          width: drawerWidth,
        },
      },
    },
  },
});

function hasJWT() {
  let flag = false;

  //check user has JWT token
  Cookies.get("token") ? (flag = true) : (flag = false);

  return flag;
}

function logOut() {
  Cookies.remove("token");
  window.location.href = "/signin";
}

function ResponsiveDrawer(props) {
  const { window } = props;
  const [openOrders, setOpenOrders] = React.useState(false);
  const [openBilling, setOpenBilling] = React.useState(false);
  const [openInventory, setOpenInventory] = React.useState(false);
  const [openSettings, setOpenSettings] = React.useState(false);
  const [openProcessing, setOpenProcessing] = React.useState(false);

  const drawer = (
    <div>
      <Toolbar style={{ backgroundColor: "rgb(23, 61, 102)", height: "4vw" }}>
        <Box>
          <img
            src={MWXplusLogo}
            alt="Logo"
            style={{
              width: "100%",
              height: "100%",
            }}
          />
        </Box>
      </Toolbar>
      <Divider />
      <List>
        <ListItem disablePadding>
          <ListItemButton component={Link} to="/main">
            <ListItemIcon>
              <HomeRoundedIcon />
            </ListItemIcon>
            <ListItemText primary="Home" />
          </ListItemButton>
        </ListItem>
        <ListItem
          button
          onClick={() => {
            setOpenOrders(!openOrders);
          }}
        >
          <ListItemIcon>
            <ShoppingCartCheckoutRoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Orders" />
          {openOrders ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openOrders} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForOrders
              openProcessing={openProcessing}
              setOpenProcessing={setOpenProcessing}
            />
          </List>
        </Collapse>

        <ListItem
          button
          onClick={() => {
            setOpenBilling(!openBilling);
          }}
        >
          <ListItemIcon>
            <ReceiptLongRoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Billing" />
          {openBilling ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openBilling} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForBilling />
          </List>
        </Collapse>
        <ListItem
          button
          onClick={() => {
            setOpenInventory(!openInventory);
          }}
        >
          <ListItemIcon>
            <Inventory2RoundedIcon />
          </ListItemIcon>
          <ListItemText primary="Inventory" />
          {openInventory ? <ExpandLess /> : <ExpandMore />}
        </ListItem>
        <Collapse in={openInventory} timeout="auto" unmountOnExit>
          <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
            <SubMenuItemsForInventory />
          </List>
        </Collapse>
      </List>
      <Divider />
      <ListItem
        button
        onClick={() => {
          setOpenSettings(!openSettings);
        }}
      >
        <ListItemIcon>
          <SettingsRoundedIcon />
        </ListItemIcon>
        <ListItemText primary="Setting" />
        {openSettings ? <ExpandLess /> : <ExpandMore />}
      </ListItem>
      <Collapse in={openSettings} timeout="auto" unmountOnExit>
        <List component="div" disablePadding style={{ paddingLeft: "80px" }}>
          <SubMenuItemsForSettings />
        </List>
      </Collapse>
      <div
        style={{
          bottom: "0",
          position: "absolute",
          left: "0",
          right: "0",
        }}
      >
        <Typography
          fontSize={"12px"}
          fontFamily={"Arial,Tahoma,PingFangSC,sans-serif"}
          fontWeight={600}
          color={"rgba(22, 24, 35, .5)"}
        >
          V1.0.0
        </Typography>
        <img src={AcumenLogo} alt="Logo" width={"50%"} height={"50%"} />
      </div>
    </div>
  );

  const container =
    window !== undefined ? () => window().document.body : undefined;

  return (
    <ThemeProvider theme={theme}>
      <Box
        sx={{
          width: { xs: "100%", sm: drawerWidth },
          flexShrink: { sm: 0 },
        }}
      >
        <CssBaseline />

        <AppBar
          position="fixed"
          style={{ backgroundColor: "rgb(23, 61, 102)" }}
        >
          <Container maxWidth="sx">
            <Toolbar disableGutters style={{ height: "4vw" }}>
              <Box sx={{ flexGrow: 1 }} />{" "}
              <Box>
                <Tooltip title="Logout">
                  <IconButton sx={{ p: 0 }}>
                    <Avatar
                      alt="Grass Land"
                      src="/static/images/avatar/2.jpg"
                      onClick={logOut}
                    />
                  </IconButton>
                </Tooltip>
              </Box>
            </Toolbar>
          </Container>
        </AppBar>
        <Box
          component="nav"
          sx={{
            width: { sm: drawerWidth },
            flexShrink: { sm: 0 },
            backgroundColor: "red",
          }}
          aria-label="mailbox folders"
        >
          <Drawer
            container={container}
            variant="temporary"
            ModalProps={{
              keepMounted: true, // Better open performance on mobile.
            }}
            sx={{
              display: { xs: "block", sm: "none" },
              "& .MuiDrawer-paper": {
                boxSizing: "border-box",
                width: drawerWidth,
              },
            }}
          >
            {drawer}
          </Drawer>
          <Drawer
            variant="permanent"
            sx={{
              display: { xs: "none", sm: "block" },
              "& .MuiDrawer-paper": {
                boxSizing: "border-box",
                width: drawerWidth,
              },
            }}
            open
          >
            {drawer}
          </Drawer>
        </Box>
        <Box
          component="main"
          sx={{
            flexGrow: 1,
            p: 3,
            width: { sm: `calc(100% - ${drawerWidth}px)` },
          }}
        ></Box>
      </Box>
    </ThemeProvider>
  );
}

ResponsiveDrawer.propTypes = {
  window: PropTypes.func,
};

export default ResponsiveDrawer;