Custom context menu with fade transition in JavaScript

I’ve been trying to create a custom context menu with some buttons in it, however there is a problem. I have an opacity transition, and it only runs once when I right click. The next times I right click the menu will show up but without the opacity transition.

Here is my code:
HTML:

<div id="contextMenuDesktop">
    <ul>
        <!-- Some elements here -->
    </ul>
</div>

JavaScript:

document.addEventListener('contextmenu', function(e) {
    event.preventDefault();
    if(!menuOpened) {
        document.getElementById("contextMenuDesktop").style.opacity = "0";
        setInterval(function() {
                document.getElementById("contextMenuDesktop").style.opacity = "1";
        }, 100); // It has to be run few milliseconds after, for some reason
        document.getElementById("contextMenuDesktop").style.display = "block";
        document.getElementById("contextMenuDesktop").style.left = `${e.pageX}px`;
        document.getElementById("contextMenuDesktop").style.top = `${e.pageY}px`;
}});

CSS:

#contextMenuDesktop {
    transition: opacity 500ms;
    opacity: 0;
    height: 375px;
    width: 175px;
    background-color: rgba(100,100,100,.6);
    color: white;
    border-radius: 10px;
    box-shadow: 7px 7px 3px lightgray;
    backdrop-filter: blur(5px);
    position: fixed;
    z-index: 3;
    display: none;
    
}

I believe the problem is that the line that sets the opacity to 0 doesn’t have time to finish, and after only 100 milliseconds it has to be visible again, so the transition doesn’t work. Does somebody know the answer?

unable to get user object from session and req.isAuthenticated() is false after Oauth Google login

Create a login application using the frontend using React, the backend using Express, and the passport GoogleOauth 2.0.
Google auth allows for login, however the req.user is not saved in the system. Following the initial login, the req.isAuthenticated is likewise false. Here is my code for the auth/google/callback and the session. Please point out the mistakes I’m doing to me.

 const express = require("express");
const helmet = require("helmet");
const cors = require("cors");

const passport = require("passport");
// const AuthuRouter = require("./src/routes/user/auth.router");
const StoreRouter = require("./src/routes/store/store.router");

const mongoose = require("mongoose");
const session = require("express-session");
const rateLimit = require("express-rate-limit");

const GoogleStrategy = require("passport-google-oauth20").Strategy;
// const passport = require("./src/configs/passport");
const { isAuthorized, isAuthenticat } = require("./src/middleware/auth");
const User = require("./src/routes/user/user.model");
require("dotenv").config();

const app = express();
app.use(helmet()); 


app.use(
  cors({
    origin: "http://localhost:5173", 
    credentials: true,
  })
);
app.use(express.json()); /

app.use(
  session({
    secret: process.env.COOKIE_KEY, 
    resave: false,
    saveUninitialized: false,
    cookie: {
      secure: false, 
      maxAge: 24 * 60 * 60 * 1000,
      sameSite: "None", 
    },
  })
);
// Passport initialization
app.use(passport.initialize());
app.use(passport.session());
app.use((req, res, next) => {
  console.log("middle ware");
  next();
});
// Rate limiting
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
});
// Applying rate limiting to all routes
app.use(limiter);

passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
      callbackURL: "/auth/google/callback",
    },
    async (token, tokenSecret, profile, done) => {
      try {
        // Check if user already exists in database
        let user = await User.findOne({
          email: profile.emails[0].value,
        }).select("email accessRights name _id");
        // console.log(user);
        if (!user) {
          return done(null, false, {
            message:
              "Email not registered. Please use a registered email or sign up.",
          });
        }

        return done(null, user);
      } catch (err) {
        return done(err, null);
      }
    }
  )
);

// Serialize user into the sessions
passport.serializeUser((user, done) => {
  done(null, user._id); // Store only the user ID in the session
});

// Deserialize user from the sessions
passport.deserializeUser(async (id, done) => {
  try {
    const user = await User.findById(id).select("email accessRights name _id");

    done(null, user); // Attach the user object to req.user
  } catch (err) {
    done(err, null);
  }
});

// Session setup

// MongoDB connection
mongoose.connect(process.env.MONGO_URI);

// Routes
// Session status route
app.get(
  "/signin",
  passport.authenticate("google", {
    scope: ["email"],
  })
);

// Google OAuth callback
app.get(
  "/auth/google/callback",
  passport.authenticate("google", {
    failureRedirect: "/auth/signin",
  }),
  (req, res) => {
    console.log("callback");
    // console.log(req.user);

    if (req.user) {
      req.session.user = req.user;
      req.session.regenerate(function (err) {
        if (err) next(err);

        req.session.user = req.user;

        req.session.save(function (err) {
          console.log(req.isAuthenticated());
          if (err) return next(err);
          return res.redirect(`http://localhost:5173/dashboard`);
        });
      });

      // res.json({ user: req.user });
      // res.redirect(`http://localhost:5173/dashboard`);
    } else {
      res.status(401).json({ message: "No user logged in" });
    }
  }
);

// Logout
// Logout
app.get("/logout", (req, res) => {
  req.session.user = null;

  req.logout((err) => {
    if (err) {
      // Handle error if logout fails
      return res.status(500).json({ message: "Logout failed" });
    }
    req.session.destroy((err) => {
      if (err) {
        // Handle error if session destruction fails
        return res.status(500).json({ message: "Failed to destroy session" });
      }
      res.clearCookie("connect.sid"); // This is the default cookie name for express-session
      res.save.regenerate(function (err) {
        if (err) next(err);
        res.redirect("/auth/signin?message=Logged out successfully");
      });
      res.redirect("/auth/signin?message=Logged out successfully");
    });
  });
});

I am getting some typescript error in my Class component. when exporting in HOC component

Below is my HomePage Class Component. I am getting some typescript error.

   import * as React from "react";
    import { Dispatch, AnyAction } from 'redux';
    import { connect } from 'react-redux';
    import { Link, RouteComponentProps } from 'react-router-dom';
    import isEqual from "lodash/isEqual";
    import "./HomePage.scss";
    import "../assets/styles.scss";
    import { resourceTypeEnum } from '../config/constants';
    import ResourceStocks from "./ResourceStocks";
    import SimcardStocks from "./SimcardStocks";
    import MsisdnStocks from "./MsisdnStocks";
    import DeviceStocks from './DeviceStocks';
    import { ConsulState } from "../consul/consul.types";
    import { consulInit } from "../consul/consul.data";
    import { HomePageActions, resourceStocksDataType, stocksFilterValuesType, lifecycleStatusesTypes, stocksDetailsTypes, resourceFilterValuesTypes, searchableFieldValuesTypes } from './HomePage.actions';
    import { AppState } from '../store';
    const classnames = require("classnames");
    
    interface HomePageStateProps {
        activeResourceType?: string;
    }
    
    interface HomePageProps {
        resourceStocks: resourceStocksDataType,
        stocksFilterValues: stocksFilterValuesType,
        lifecycleStatuses: lifecycleStatusesTypes,
        stocksDetails: stocksDetailsTypes;
        resourceFilterValues: resourceFilterValuesTypes;
        searchableFieldFilterValues: searchableFieldValuesTypes;
        isLoading: boolean;
        match: {
            params: {
                resourceType: string,
                stockId: string
            }
        };
        history: RouteComponentProps["history"];
        consulDetails: ConsulState
    }
    interface HomePageActionProps {
        actions: {
            getResourceStocks: (resourceType: string, stockID: string, stockName: string, SKU: string, currentPage: string) => void;
            getStocksFilterValues: (resourceType: string) => void,
            getLifecycleStatus: (resourceType: string) => void,
            getResourceFilterValues: (resourceType: string, stockID: string) => void,
            getSearchableFieldVFilterValues: (resourceType: string) => void,
        }
    }
    
    type Props = HomePageStateProps & HomePageActionProps & HomePageProps;
    class HomePage extends React.Component<Props, HomePageStateProps> {
        constructor(props: Props, context: any) {
            super(props, context);
            this.state = {
                activeResourceType: this.props.match && this.props.match.params && this.props.match.params.resourceType ? this.props.match.params.resourceType : 'sim-cards',
            };
        }
    
        handleOnCickResourceType = (resourceType: string) => {
            this.setState({
                activeResourceType: resourceType,
            });
            this.props.history && this.props.history.push(`/home/${resourceType}`)
            
        };
    
        static getDerivedStateFromProps(nextProps: Props, prevState: HomePageStateProps) {
            const { match : { params : { resourceType } } = { params : { resourceType: resourceTypeEnum.SIM_CARDS }} } = nextProps;
            if (!isEqual(resourceType, prevState.activeResourceType)) {
                return { ...prevState, activeResourceType:  resourceType }
            }
        }
    
        getStocksAndFilterValues = (resourceType: string) => {
            this.props.actions.getResourceStocks(resourceType,'All', 'All', 'All', '');
            this.props.actions.getStocksFilterValues(resourceType);
        }
    
        getStockDetailsPageData = (resourceType: string, stockId: string) => {
            this.props.actions.getLifecycleStatus(resourceType);
            this.props.actions.getResourceFilterValues(resourceType, stockId);
            this.props.actions.getSearchableFieldVFilterValues(resourceType);
        }
        
        fetchResourceStocks = () => {
            this.props.actions.getResourceStocks(this.state.activeResourceType,'All', 'All', 'All', '')
        }
        render() {
            const { consulDetails: { details } = { details: consulInit }, match: { params : { stockId }} = { params: { stockId: ""}} } = this.props;
            return (
                <React.Fragment>
                    <div className="w-app-body" id="w-app-body">
                        <nav className="w-nav-secondary">
                            <ul>
                                {
                                    details.resourceStockAndSearchConfig && details.resourceStockAndSearchConfig.enableSimCards && details.resourceStockAndSearchConfig.enableSimCards &&
                                    <li
                                        className={classnames({
                                            active:
                                                resourceTypeEnum.SIM_CARDS === this.state.activeResourceType,
                                        })}
                                    >
                                        <a
                                            href="javascript:;"
                                            onClick={() =>
                                                this.handleOnCickResourceType(
                                                    resourceTypeEnum.SIM_CARDS
                                                )
                                            }
                                            id='sim-cards-tab-in-resource-tab'
                                        >
                                            SIM Cards
                                    </a>
                                    </li>
                                }
                                {
                                    details.resourceStockAndSearchConfig && details.resourceStockAndSearchConfig.enableMsisdns && details.resourceStockAndSearchConfig.enableMsisdns &&
                                    <li
                                        className={classnames({
                                            active:
                                                resourceTypeEnum.MSISDNS === this.state.activeResourceType,
                                        })}
                                    >
                                        <a
                                            href="javascript:;"
                                            onClick={() =>
                                                this.handleOnCickResourceType(
                                                    resourceTypeEnum.MSISDNS
                                                )
                                            }
                                            id='Msisdns-tab-in-resource-tab'
                                        >
                                            MSISDNs
                                    </a>
                                    </li>
                                }
                                {
                                    details.resourceStockAndSearchConfig && details.resourceStockAndSearchConfig.enableDevices && details.resourceStockAndSearchConfig.enableDevices && 
                                    <li
                                        className={classnames({
                                            active:
                                                resourceTypeEnum.DEVICES === this.state.activeResourceType,
                                        })}
                                    >
                                        <a
                                            href="javascript:;"
                                            onClick={() =>
                                                this.handleOnCickResourceType(
                                                    resourceTypeEnum.DEVICES
                                                )
                                            }
                                            id='Devices-tab-in-resource-tab'
                                        >
                                            Devices
                                    </a>
                                    </li>
                                }
                            </ul>
                        </nav>
                        {/* <ResourceStocks
                            getStocksAndFilterValues={(resourceType: string) => this.getStocksAndFilterValues(resourceType)}
    
                            getStockDetailsPageData={(resourceType: string, stockId: string) => this.getStockDetailsPageData(resourceType, stockId)}
                            stockIdIfAvailable={this.props.match.params.stockId}
                            stockDetailsIfAvailable={this.props.selectedStockDetails}
                            setSelectedStockDetails={(stockDetails: object) => this.props.actions.setSelectedStockDetails(stockDetails)}
                            history={this.props.history}
    
    
                            resourceStocks={this.props.resourceStocks}
                            stocksFilterValues={this.props.stocksFilterValues}
                            lifecycleStatuses={this.props.lifecycleStatuses}
                            resourceFilterValues={this.props.resourceFilterValues}
                            searchableFieldFilterValues={this.props.searchableFieldFilterValues}
    
    
                            activeResourceType={this.state.activeResourceType}
                            stocksDetails={this.props.stocksDetails}
                            fetchResourceStocks={this.fetchResourceStocks}
    
                        /> */}
                        {(() => {
                            switch (this.state.activeResourceType) {
                                case resourceTypeEnum.SIM_CARDS:
                                    return <SimcardStocks 
                                        getStocksAndFilterValues = {(resourceType: string) => this.getStocksAndFilterValues(resourceType)}
                                        getStockDetailsPageData = {(resourceType: string, stockId: string) => this.getStockDetailsPageData(resourceType, stockId)}
                                        stockIdIfAvailable = {stockId}
                                        history = {this.props.history}
                                        resourceStocks = {this.props.resourceStocks}
                                        stocksFilterValues = {this.props.stocksFilterValues}
                                        lifecycleStatuses = {this.props.lifecycleStatuses}
                                        resourceFilterValues =  {this.props.resourceFilterValues}
                                        searchableFieldFilterValues = {this.props.searchableFieldFilterValues}
                                        activeResourceType = {this.state.activeResourceType}
                                        stocksDetails = {this.props.stocksDetails}
                                        fetchResourceStocks = {this.fetchResourceStocks}
                                    />;
                                case resourceTypeEnum.MSISDNS:
                                    return <MsisdnStocks 
                                        getStocksAndFilterValues = {(resourceType: string) => this.getStocksAndFilterValues(resourceType)}
                                        getStockDetailsPageData = {(resourceType: string, stockId: string) => this.getStockDetailsPageData(resourceType, stockId)}
                                        stockIdIfAvailable = {stockId}
                                        history = {this.props.history}
                                        resourceStocks = {this.props.resourceStocks}
                                        stocksFilterValues = {this.props.stocksFilterValues}
                                        lifecycleStatuses = {this.props.lifecycleStatuses}
                                        activeResourceType = {this.state.activeResourceType}
                                        stocksDetails = {this.props.stocksDetails}
                                        resourceFilterValues =  {this.props.resourceFilterValues}
                                        searchableFieldFilterValues = {this.props.searchableFieldFilterValues}
                                        fetchResourceStocks = {this.fetchResourceStocks}
                                    />;
                                case resourceTypeEnum.DEVICES:
                                    return <DeviceStocks 
                                        getStocksAndFilterValues = {(resourceType: string) => this.getStocksAndFilterValues(resourceType)}
                                        getStockDetailsPageData = {(resourceType: string, stockId: string) => this.getStockDetailsPageData(resourceType, stockId)}
                                        stockIdIfAvailable = {stockId}
                                        history = {this.props.history}
                                        resourceStocks = {this.props.resourceStocks}
                                        stocksFilterValues = {this.props.stocksFilterValues}
                                        lifecycleStatuses = {this.props.lifecycleStatuses}
                                        activeResourceType = {this.state.activeResourceType}
                                        stocksDetails = {this.props.stocksDetails}
                                        resourceFilterValues =  {this.props.resourceFilterValues}
                                        searchableFieldFilterValues = {this.props.searchableFieldFilterValues}
                                        fetchResourceStocks = {this.fetchResourceStocks}
                                    />;
                            }
                        })()}
                        <div className={classnames({"overlay": true, "show-spinner": !this.props.isLoading})}>
                            <i className="fa fa-spinner fa-pulse fa-4x"></i>
                        </div>
                    </div>
                </React.Fragment>
            );
        }
    }
    
    const mapsStateToProps = (state: AppState) => {
        return {
            resourceStocks: state.homePage.resourceStocks,
            stocksFilterValues: state.homePage.stocksFilterValues,
            lifecycleStatuses: state.homePage.lifecycleStatuses,
            stocksDetails: state.homePage.stocksDetails,
            resourceFilterValues: state.homePage.resourceFilterValues,
            searchableFieldFilterValues: state.homePage.searchableFieldFilterValues,
            isLoading: state.homePage.isLoading,
            consulDetails: state.consul,
        };
    }
    
    const mapDispatchToProps = (dispatch: Dispatch<AnyAction>): HomePageActionProps => {
        return {
            actions: {
                getResourceStocks: (resourceType: string, stockID: string, stockName: string, SKU: string, currentPage: string) => {
                    dispatch(HomePageActions.getResourceStocks(resourceType, stockID, stockName, SKU, currentPage))
                },
                getStocksFilterValues: (resourceType: string) => {
                    dispatch(HomePageActions.getStockFilterValues(resourceType));
                },
                getLifecycleStatus: (resourceType: string) => {
                    dispatch(HomePageActions.getLifecycleStatus(resourceType))
                },
                getResourceFilterValues: (resourceType: string, stockID: string) => {
                    dispatch(HomePageActions.getResourceFilterValues(resourceType, stockID))
                },
                getSearchableFieldVFilterValues: (resourceType: string) => {
                    dispatch(HomePageActions.getSearchableFieldVFilterValues(resourceType))
                },
            },
        };
    };
    
    export default connect(mapsStateToProps, mapDispatchToProps)(HomePage)

export default connect(mapsStateToProps, mapDispatchToProps)(HomePage)
i am getting error here

Argument of type ‘typeof HomePage’ is not assignable to parameter of
type ‘ComponentType’. Type ‘typeof HomePage’ is not
assignable to type ‘ComponentClass<never, any>’.
The types returned by ‘getDerivedStateFromProps(…)’ are incompatible between these types.
Type ‘{ activeResourceType: string; } | undefined’ is not assignable to type ‘Partial | null’.
Type ‘undefined’ is not assignable to type ‘Partial |

any suggestion on how to fix this error and why i am getting this error.

How to disable next month dates in current month view in React Flat Pickr with Momentjs

I’m using React Flatpickr in my project with Moment.js. In the current month’s view, dates from the next month are also shown. I want to disable these dates in the current month’s view so that users cannot select them. In React Flatpickr, these dates are disabled but still selectable. How can I prevent users from selecting these dates?

Firstly i went to Ai but not getting desire results.

Svelte 5 reactive store methods

The below code is working as it should, I’m just trying to gain a better understanding of why.

How is the getCurrentElement method of TestState reactive without the use of $derived()? Are store methods that make use of state reactive by default?

Im using [email protected]

test-store.svelte.ts

import { getContext, setContext } from 'svelte';

class TestState {
  elements = [
    {
      id: 'hghxt',
      name: 'Give',
    },
    {
      id: 'vhtl9',
      name: 'Connection',
    },
    {
      id: '5n0t0',
      name: 'Take notice',
    },
    {
      id: 'xlfba',
      name: 'Keep learning',
    },
    {
      id: '1f3z2',
      name: 'Be active',
    },
  ];

  #currentElementId = $state<string>();
  
  getCurrentElement() {
    return this.elements.find(element => element.id === this.#currentElementId);
  }

  setCurrentElement(id: string) {
    if (!this.elements.some(element => element.id === id)) return;

    this.#currentElementId = id;
  }
}

const TEST_STORE_KEY = Symbol('TEST_STORE');

export function setTestState() {
  return setContext(TEST_STORE_KEY, new TestState());
}

export function getTestState() {
  return getContext<ReturnType<typeof setTestState>>(TEST_STORE_KEY);
}

TestComponent.svelte

<script lang="ts">
  import { getTestState } from '$lib/stores/test-store.svelte';

  // initialised at +page.svelte
  const testState = getTestState();
</script>

{#each testState.elements as { name, id }}
  <button 
    class:bg-yellow={testState.getCurrentElement()?.id === id} 
    onclick={() => testState.setCurrentElement(id)}>
    {name}
  </button>
{/each}

Modifying the input triggers the listener with a value that includes the latest user input

For example, if the input is 10 and the user types 1, the detected value becomes 101, which is greater than 50. The value is then set to 50, but on the next detection, it changes to 501 instead of staying at 50.

const inputElement = document.getElementById('myInput');

inputElement.addEventListener('input', function(event) {
  let value = Number(event.target.value)
  console.log(value)
  if (value > 50) {
    event.target.value = 50
    console.log("It cannot be greater than 50");
  }
});
<input type="text" id="myInput" placeholder="Type something...">

My input is:’1′ -> ‘0’ -> ‘1’;

The output I get is:
2test.html:8 1
2test.html:8 10
test.html:8 101
test.html:11 It cannot be greater than 50
test.html:8 501
test.html:11 It cannot be greater than 50

Extend window object and write d.ts files for tsc

we have a javascript project and want to move to typescript.
In the current setup, we have a global object (let’s call it myGlobal) with variables and functions that we are accessing either through windows.myGlobal.myFunction or directly as myGlobal.varA.

As expected, tsc would complain that windows.myGlobal does not exist on the window object.

My guess was to write a global.d.ts declaration file for tsc like this:

interface myGlobal {
  myFunction: any
}


// Extend the Window interface
interface Window {
  myGlobal: MyGlobal;
}

// Declare myGlobal as a global variable
declare let myGlobal: MyGlobal;

and even though I have

  "include": [
    "**/*.ts",
    "**/*.js"
  ],

in my tsconfig, it still complaints about the same error.
Can someone help?

Cannot read properties of undefined (reading ‘actives’) – multi sort

Good day guys. I am currently using ngx-mat-multi-sort. When I try to sort the error occurs which is Cannot read properties of undefined (reading ‘actives’)
at TableData.onSortEvent (table-data.ts:69:49).

Anyone has an idea what seems to be the problem ?. Is it timing issue ? that causes the sorting to fail ?. Thanks and highly appreciated.

#html code

  <table
                          mat-table
                          [dataSource]="closureListTable.dataSource"
                          matMultiSort
                          (matSortChange)="closureListTable.onSortEvent()"
                        >
                          <ng-container *ngFor="let column of displayedColumns" [matColumnDef]="column">
                       
                            <th mat-multi-sort-header="{{column}}" mat-header-cell *matHeaderCellDef>
                              {{ getColumnHeader(column) }}
                            </th>
                            <td mat-cell *matCellDef="let element">
                              <div class="td-value-name">
                                {{ getColumnValue(element, column) }}
                              </div>
                            </td>
                          </ng-container>

                          <tr
                            mat-header-row
                            *matHeaderRowDef="displayedColumns; sticky: true"
                          ></tr>
                          <tr
                            mat-row
                            *matRowDef="let row; columns: displayedColumns"
                          ></tr>
                        </table>

#ts code

 displayedColumns: string[] = [];

    closureListTable: TableData<IStoreClosureProgram>;
    this.closureListTable = new TableData<any>([]);

    ngOnInit(): void {
        // NOTE: do not initialze MatMultiSortTableDataSource here because `this.sort` may not be loaded yet
      }
    
      ngAfterViewInit(): void {
        this.selectedTab = this.selectedTab || 'FL';  // Set default tab if not already set
        this.displayedColumns = this.columnsMapping[this.selectedTab] || this.columnsMapping['FL'];
        setTimeout(() => {
          this.initTable();
          this.initSearch(); 
        }, 5000);
      }
      
      initSearch(): void {
        if (this.searchInput?.nativeElement) {
          fromEvent<any>(this.searchInput.nativeElement, 'keyup')
            .pipe(
              map((event) => event.target.value),
              startWith(''),
              debounceTime(500),
              distinctUntilChanged(),
              switchMap(async (search) => {
                this.closureListTable.pageIndex = 0;
                this.getData();
              })
            )
            .subscribe({ complete: noop });
        }
      }
    
      initTable() {
        this.closureListTable.dataSource = new MatMultiSortTableDataSource(
          this.sort,
          this.CLIENT_SIDE
        );
        this.closureListTable.nextObservable.subscribe(() => {
          this.getData();
        });
        this.closureListTable.sortObservable.subscribe(() => {
          console.log("1234")
          this.getData();
        });
        this.closureListTable.previousObservable.subscribe(() => {
          this.getData();
        });
        this.closureListTable.sizeObservable.subscribe(() => {
          this.getData();
        });
    
        if (
          (!!this.storeClosureAcessSettings?.ReceivingStoreList &&
            this.storeClosureAcessSettings?.ReceivingStoreList !== 'None') ||
          (!!this.storeClosureAcessSettings?.FullStoreClosureList &&
            this.storeClosureAcessSettings?.FullStoreClosureList !== 'None')
        ) {
          this.getData();
        }
    
        if (
          !!this.storeClosureAcessSettings?.AggregatesCounts &&
          this.storeClosureAcessSettings?.AggregatesCounts !== 'None'
        ) {
          // this.getAggregate();
        }
      }

Maps API loaded in NextJs component not directly available to instantiated class

I am using the Google Maps API and am working with NextJS and typescript.

I have to instantiate a class used for rendering purposes, but I am getting an error.

My code:

TLDR: loading Map, MapsLibraries and instantiating the Controller class.

Map.tsx

function GoogleMap() {
  const position = { lat: 53.0708031, lng: 12.7569469 };
  const mapId = "test";
  

  return (
    <div className="h-full w-full relative">
      <APIProvider
        apiKey={process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY as string}
      >
        <Map
          defaultCenter={position}
          defaultZoom={16}
          mapId={mapId}
          fullscreenControl={false}
          tilt={0}
          tiltInteractionEnabled={false}
          rotateControl={false}
          mapTypeControl={false}
          mapTypeId="satellite"
        ></Map>
        <Directions />
      </APIProvider>
    </div>
  );
}

function Directions() {
  const map = useMap();
  const coreLibrary = useMapsLibrary("core");
  const markerLibrary = useMapsLibrary("marker");
  const routesLibrary = useMapsLibrary("routes");
  const mapsLibrary = useMapsLibrary("maps");
  const [directionsService, setDirectionsService] =
    useState<google.maps.DirectionsService>();
  const [directionsRenderer, setDirectionsRenderer] = useState<Directions>();

  useEffect(() => {
    if (
      !routesLibrary ||
      !map ||
      !coreLibrary ||
      !markerLibrary ||
      !mapsLibrary ||
      !window.google
    ) {
      return;
    }
    console.log("google", window.google);
    setDirectionsService(new routesLibrary.DirectionsService());

    // --- relevant initialization ----

    setDirectionsRenderer(new Controller(map));
  }, [
    coreLibrary,
    markerLibrary,
    mapsLibrary,
    routesLibrary,
    map,
  ]);

controller.ts (simplified):

 class Controller extends google.maps.OverlayView implements Directions {
         private map;
        constructor(map: google.maps.Map) {
             this.map = map
        }
 }

But this results in Error: “google is undefined”, even though google is defined at the time we are creating our component.

This can be fixed like this:

    // instead of new Controller() you call initialize() in <Directions/>
    function initialize(map: google.maps.Map){
    class Controller extends google.maps.OverlayView implements Directions {
         private map;
        constructor(map: google.maps.Map) {
             this.map = map
        }
     }
     return new Controller(map)
    }

I thought it could be an issue with nextjs seeing this as server side code and compiling it before it has ever seen the client (and no Maps API loaded) , so I marked controller.ts as “use client”, but the issue persists.


Why is that? How are we “loosing” the window.google object?

Is there another workaround for this?

What are the technical details?

Thank you for any help, I am really stuck here.

Why i cannot fetch my images from my .json file?

here is my html code:

<div id="card-container" class="card-container"></div>
    <!-- card and ftech data from.json -->
    <script>
     document.addEventListener('DOMContentLoaded', function() {
            fetch('data/data.json') // Adjust the path if needed
                .then(response => response.json())
                .then(jsonData => {
                    const container = document.getElementById('card-container');
                    jsonData.forEach(movie => {
                        const card = document.createElement('div');
                        card.className = 'card';
                        card.innerHTML = `
                            <img src="${movie.image}" class="card-img-top" alt="${movie.movie_Name}">
                            <div class="card-body">
                                <h5 class="card-title">${movie.movie_Name}</h5>
                                <p class="card-text">Release Date: ${movie.release_Date}<br>
                                Director: ${movie.director}<br>
                                Location: ${movie.location}<br>
                                Genre: ${movie.genre}</p>
                                <a href="#" class="btn btn-primary">More Details</a>
                            </div>
                        `;
                        container.appendChild(card);
                    });
                })
                .catch(error => console.error('Error fetching JSON:', error));
        });


    </script>

here is my .json file:

 {
        "id": 1,
        "movie_Name": "Mission: Cross",
        "release_Date": "August 9, 2024",
        "director": "Lee Myeong-hun",
        "location": "South Korea",
        "genre": "Action/Comedy",
        "image": "/img/MissionCross.jpg"
        
        
    },

I already try many way, but still it didn’t work. can someone help me?

here is the output I get:
enter image description here

TypeError: Cannot read properties of null (reading ‘getformula’)

function countColoredCells(countRange, colorRef) {

    var activeRange = SpreadsheetApp.getActiveRange();

    var activeSheet = SpreadsheetApp.getActiveSheet();

    var activeformula = activeRange.getformula();

    var countRangeAddress = activeformula.match(/((.*),/).pop().trim();

    var backGrounds = activeSheet.getRange(countRangeAddress).getBackgrounds();

    var colorRefAddress = activeformula.match(/,(.*))/).pop().trim();

    var BackGround = activeSheet.getRange(colorRefAddress).getBackground();

    var countColorCells = 0;

    for (var i = 0; i < backGrounds.length; i++)

    for (var k = 0; k < backGrounds[i].length; k++)

        if (backGrounds[i][k] == BackGround)

            countColorCells = countColorCells + 1;

    return countColorCells;

};

trying to count cells by color and this is the error
how to solve this problem pls

Webauthn on localhost failed to pass navigator.credentials.get()

I am making a sample-app to test a working flow of fido2-server.

I face a ploblem that after registration completed(with Mac touchId or Yubikey 5 series)
chrome sais there is no pass key that registered on the website.

Steps I already made were

  1. registration request (configure Fido2Lib) with user id and send back challenge
  2. receive registration options from server and exec navigator.credentials.create
  3. send credentials to server and save public key to user.
  4. send login request with user id and return fido2 assertionOptions that has allowCredentials.
  5. then try to navigator.credentials.get and have a pop up of “there is no key to this website”

I need to determine what is the cause of the problem.
First I use two way of registration that platform(touch id) and cross-platform(yubikey) for authenticatorAttachment.

when touch id, it sais there is no key to the website(localhost)
when yubikey, this security key is not registered to the website.

I think I made misstake of challenge or allowCredential to pass navigator.credentials.get

codes are too long so I put a part of important.

registerRequest

const fido2 = new Fido2Lib({
  timeout: 60000,
  rpId: "localhost",
  rpName: "localhost:3000",
  rpIcon: "https://example.com/icon.png",
  challengeSize: 32,
  attestation: "direct",
  authenticatorAttachment: "cross-platform",
  authenticatorRequireResidentKey: false,
  authenticatorUserVerification: "preferred"
});
  const user = users[userId] || {
    id: userId,
    name: username,
    displayName: username,
  };
  users[userId] = user;

  const options = await fido2.attestationOptions();
  options.user = user;
  options.challenge = base64url.encode(options.challenge);
  if (options.user && options.user.id) {
    options.user.id = base64url.encode(Buffer.from(options.user.id, 'utf-8'));
  }

registerResponse


    req.body.rawId = new Uint8Array(base64url.toBuffer(req.body.id)).buffer;

    const attestationResult = await fido2.attestationResult(req.body, {
      challenge: user.challenge,
      origin: "http://localhost:3000",
      factor: "either"
    });

    if (attestationResult.audit.complete) {
      const d = attestationResult.authnrData;

      user.authenticator = JSON.stringify({
        publickey : d.get('credentialPublicKeyPem'),
        counter : d.get('counter'),
        fmt: d.get('fmt'),
        credId : base64url.encode(d.get('credId')),
      });
      users[userId] = user;

loginResponse

    const user = users[userId];
    const authenticator = JSON.parse(user.authenticator);
    const assertionOptions = await fido2.assertionOptions();
    assertionOptions.challenge = base64url.encode(assertionOptions.challenge);
    let allowCredentials = [];
    allowCredentials.push({
      type: 'public-key',
      id: authenticator.credId,
      transports: ['usb', 'nfc', 'ble']
      // transports: ['internal']
    });
    assertionOptions.allowCredentials = allowCredentials;

client.js for register

            const options = response.data;

            options.challenge = Uint8Array.from(atob(options.challenge), (c) => c.charCodeAt(0));
            options.user.id = Uint8Array.from(atob(options.user.id), (c) => c.charCodeAt(0));

            const credential = await navigator.credentials.create({ publicKey: options }) as PublicKeyCredential;

            const res = publicKeyCredentialToJSON(credential.response);
// publicKeyCredentialToJSON is kind of base64encode
            if (credential) {
                const attestationResponse = {
                    id: credential.id,
                    rawId: Array.from(new Uint8Array(credential.rawId)),
                    type: credential.type,
                    response: res
                };

client.js for login


            const options = response.data;
            options.challenge = Uint8Array.from(base64url.decode(options.challenge)).buffer;
            options.allowCredentials = options.allowCredentials.map((c: any) => {
                c.id = Uint8Array.from(base64url.decode(c.id)).buffer;
                return c;
            });
            const assertion = await navigator.credentials.get({ publicKey: options }) as PublicKeyCredential;

The passkey of localhost is successfully saved on my Mac.

Let me know if there is any information missing to help me solve the problem.
Or tell me where I’m going wrong in this.

Getting error in installing the nextjs app using npx create-next-app@latest

npm WARN deprecated [email protected]: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
npm WARN deprecated @humanwhocodes/[email protected]: Use @eslint/config-array instead
npm WARN deprecated [email protected]: Rimraf versions prior to v4 are no longer supported
npm WARN deprecated [email protected]: Glob versions prior to v9 are no longer supported
npm WARN deprecated @humanwhocodes/[email protected]: Use @eslint/object-schema instead
npm ERR! code ECONNRESET
npm ERR! network aborted
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network ‘proxy’ config is set properly. See: ‘npm help config’

npm ERR! A complete log of this run can be found in: C:Usersakshay shahiAppDataLocalnpm-cache_logs2024-08-15T05_24_41_129Z-debug-0.log

Aborting installation.
npm install has failed.

I have already installed the latest Nodejs.

Bootstrap not picking up in node.js express.js project

I have a project in which I have installed ejs and bootstrap but for some reason bootstrap is still not picking up. In my app.js file I have:

app.use(express.static("node_modulesbootstrapdistcss"));

Index.html file:

<html>
    <head>
        <link href="bootstrap.min.css" rel="stylesheet" />
        <style>
            .nav-separator {
                border-left: 1px solid rgba(0, 0, 0, 0.2); /* Light gray border */
                height: 30px; /* Adjust height as needed */
                margin: 0 15px; /* Spacing around the line */
            }
        </style>
        <title>Home</title>
    </head>
    <%- include('partials/navbar') %>
    <div class="container">
        <!-- Your page content goes here -->
        <h3>Welcome to Ando's Delivery Services!</h3>
    </div>
    </body>
</html>

I have made sure that the path in app.js is the relative path for bootstrap. I have also changed it so that the nav-bar is not in a seperate file and included in the index.html file and it still will not pick up the bootstrap.

The problem with the Yandex ID authorization settings

import React, { useEffect } from 'react';

  function LoginYaID({ onAuthSuccess }) {
    useEffect(() => {
      if (window.YaAuthSuggest) {
        window.YaAuthSuggest.init(
          {
            client_id: process.env.REACT_APP_YANDEX_CLIENT_ID,
            response_type: 'token',
            redirect_uri: 'https://support.hobbs-it.ru/redirect',
          },
          'https://support.hobbs-it.ru/',

        )
        .then(({ handler }) => handler())
        .then(data => {
          onAuthSuccess(data); // Передаем данные в App
        })
        .catch(error => {
          if (error.code !== 'in_progress') {
            console.error('Ошибка при инициализации Яндекс авторизации:', error);
          }
        });
      }
    }, [onAuthSuccess]);

    return (
      <div id="container"></div>
    );
  }

  export default LoginYaID;


import React, { useEffect } from "react";

const RedirectToken = () => {
  YaSendSuggestToken(
    'https://support.hobbs-it.ru/', 
    {
       flag: true
    }
 )
  useEffect(() => {
    const params = new URLSearchParams(window.location.hash.slice(1));
    const token = params.get('access_token');

  }, );

  return <div></div>;
};

export default RedirectToken;


import React, { useState, useEffect } from "react";
import Header from "./components/Header";
import ContactForm from "./components/ContactForm";
import ListAnnouncement from "./components/ListAnnouncement";
import MessengerWidget from "./components/MessengerWidget";
import LoginYaID from "./components/LoginYaID";
import RedirectToken from "./components/RedirectToken";
import FeedbackForm from "./components/FeedbackForm";
import Feedback from "./components/FeedBack";
import "./App.css";

function App() {
  const [isYandexAuth, setIsYandexAuth] = useState(false);
  const [isFeedbackOpen, setIsFeedbackOpen] = useState(false);

  useEffect(() => {
    // Проверка состояния авторизации при инициализации
    const token = localStorage.getItem("yandexToken");
    const isAuth = localStorage.getItem("isYandexAuth") === "true";

    if (token && isAuth) {
      // Если токен и состояние авторизации сохранены, используем их
      handleAuthSuccess({ access_token: token });
    }
  }, []);

  const handleAuthSuccess = (data) => {
    const token = data.access_token; // Получаем токен из данных
    if (token) {
      // Используем токен для запроса информации о пользователе
      fetch("https://login.yandex.ru/info?format=json", {
        method: "GET",
        headers: {
          Authorization: `OAuth ${token}`,
        },
      })
        .then((response) => response.json())
        .then((userInfo) => {
          const allowedDomains = ["kurganmk.ru", "reftp.ru", "hobbs-it.ru"];
          const userEmail = userInfo.default_email || "";

          if (typeof userEmail === "string" && userEmail.includes("@")) {
            const userDomain = userEmail.split("@")[1];
            if (allowedDomains.includes(userDomain)) {
              setIsYandexAuth(true);
              localStorage.setItem("isYandexAuth", "true");
              localStorage.setItem("yandexToken", token);
            } else {
              setIsYandexAuth(false);
              localStorage.removeItem("isYandexAuth");
              localStorage.removeItem("yandexToken");
              alert("Авторизация с этого домена недопустима.");
            }
          } else {
            alert("Не удалось получить данные пользователя для авторизации.");
          }
        })
        .catch((error) => {
          console.error(
            "Ошибка при получении информации о пользователе:",
            error
          );
        });
    }
  };

  const handleLogout = () => {
    setIsYandexAuth(false);
    localStorage.removeItem("isYandexAuth");
    localStorage.removeItem("yandexToken");
  };

  return (
    <div className="bg-gray-100 min-h-screen p-4">
      <div className="max-w-6xl mx-auto bg-white p-6 rounded-lg shadow-lg">
        <Header isYandexAuth={isYandexAuth} handleYandexLogout={handleLogout} />
        {isYandexAuth ? (
          <>
            <div className="md:flex">
            <ContactForm />
            <ListAnnouncement />
      
            </div>
            <Feedback />
          </>
        ) : (
          <>
            <LoginYaID onAuthSuccess={handleAuthSuccess} />
            <RedirectToken onAuthSuccess={handleAuthSuccess} />
          </>
        )}
      </div>
    </div>
  );
}

export default App;

There are three components, they work in conjunction for authorization by Yandex ID, the authorization status is saved in localStorage so as not to ask to do it several times. Libraries are connected in public/index.html

Now the behavior is unclear to me. Catching the error object object

As expected, the authorization was successful, the data was saved in localstorage and there were no errors.`

enter image description here