SignInWithRedirect not working as intended

When I try to SignInWithRedirect in my react project, I get (as expected) redirected to a google site, however, I only see a blue progress bar at the top, before shortly redirecting back to my website. I intend for the thing to show me my google sign in options, but it won’t send me. I found a similar problem with SignInWithPopup, however it threw the Cross-Origin error. I logged in once, and it won’t log me in again it seems, either that or it won’t let me choose accounts. Additionally, if I try to sign in with the same email again, after i log out, it doesn’t work as well. I am a newbie at React. Here’s my code:

import './app.css'
import { Route, Routes, json } from 'react-router-dom'
import { Link, useMatch, useResolvedPath } from "react-router-dom"
import Home from './pages/home.jsx'
import PPapers from './pages/pastp.jsx'
import Logo from './images/re.svg'
import 'bootstrap/dist/css/bootstrap.min.css';
import { auth, googleProvider } from './config/firebase-config';
import { createUserWithEmailAndPassword, signInWithRedirect, signOut } from 'firebase/auth'; 
import { useEffect, useState } from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import GoogleLogo from './images/google.png'
import { onAuthStateChanged } from 'firebase/auth';




function NavBar(){
  useEffect(() => {
    if (cLogged) {
      console.log(auth.currentUser.email);
    }
  });

  const logout = async () => {
    try {
      await signOut(auth);
    } catch (err) {
      console.error(err);
    }

    // Wait for a short time before checking the authentication state again
    setTimeout(() => {
      isLogged();
    }, 2000);
  };

  function isLogged() {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        setLoggedIn(true);
      } else {
        setLoggedIn(false);
      }
    });
  }

  
  const [cLogged, setLoggedIn] = useState(false);
  const [modalShow, setModalShow] = useState(false);
  return (
    <> 
      <div className = "navBar">
      <div id='LHS'>
        <img src= {Logo} alt="" />
          <label className="hamburger-menu">
          <input type="checkbox" />
          </label>
          <aside className="sidebar">
            <nav>
                <div><CustomLink className = "links" to="/">Home</CustomLink></div>
                <div><CustomLink className = "links" to="/pastp">Past Papers</CustomLink></div>
            </nav>
          </aside>
      </div>
        <div id="RHS">
          
          {cLogged ? <button className='accountBtn' onClick={logout}>Logout</button>: <Button variant="primary" className = 'accountBtn'onClick={() => setModalShow(true)}>Log-In</Button>}
          <SignInPopup
            show={modalShow}
            onHide={() => setModalShow(false)}
          /> 
          <Link id='pBtn'>
            Get Premium
          </Link>
        </div>
      </div>
    </>

  )
}

function SignInPopup(props) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [isLogin, setLogin] = useState(true); // State to manage whether it's a login or sign-up
  const [invalid, setInvalid] = useState(false); // State to manage the invalid state

  const signIn = async () => {
    try {
      await createUserWithEmailAndPassword(auth, email, password);
    } catch (err) {
      console.error(err);
      setInvalid(true);
    }
  };

  const signInWithGoogle = async () => {
    try {
      await signInWithRedirect(auth, googleProvider);
    } catch (err) {
      console.error(err);
      setInvalid(true); // Set invalid state to true
    }
  };

  function isInvalid() {
    return (
      email === "" ||
      password === "" ||
      password.length < 6 ||
      !email.includes('@') ||
      !email.includes('.')
    );
  }

  return (
    <Modal
      {...props}
      size="md"
      aria-labelledby="contained-modal-title-vcenter"
      centered
      data-bs-theme="dark"
      className='modal'
    >
      <Modal.Header closeButton>
        <Modal.Title id="contained-modal-title-vcenter">
          <h2>RevisionEase</h2>
        </Modal.Title>
      </Modal.Header>
      <Modal.Body>
        <h4>{isLogin ? 'Sign-in' : 'Sign-Up'}</h4>
        <p className='signIn' onClick={() => setLogin(!isLogin)}>
          {isLogin ? 'Sign-Up?' : 'Sign-in?'}
        </p>
        <div className='su'>
          <input placeholder="Enter Email" onChange={e => setEmail(e.target.value)} />
          <input placeholder="Enter Password" type='password' onChange={e => setPassword(e.target.value)} />
          <button className='signIn' onClick={signIn}>{isLogin ? 'Sign-in' : 'Sign-up'}</button>
          <p>Or sign-in with:</p>
          <button className="googlesu" onClick={signInWithGoogle}>
            <img src={GoogleLogo} alt="" />
          </button>
          <p>{(invalid && isInvalid) ? 'Please enter your details correctly' : ''}</p>
        </div>
      </Modal.Body>
      <Modal.Footer>
        <label>Log-in and Sign-up to gain access to more past papers and more!</label>
      </Modal.Footer>
    </Modal>
  );
}

function App() {
  return (
    <>
      <NavBar />
      <div className="maincontainer">
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/pastp" element={<PPapers />} />
        </Routes>
      </div>
    </>
  )
}
function CustomLink({ to, children, ...props }) {
  const resolvedPath = useResolvedPath(to)
  const isActive = useMatch({ path: resolvedPath.pathname, end: true })

  return (
    <li className={isActive ? "active" : ""}>
      <Link to={to} {...props}>
        {children}
      </Link>
    </li>
  )
}



export default App;

And here is my firebase config code (some details dashed out, but are filled in my actual code):

import { getAuth, GoogleAuthProvider } from "firebase/auth";
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from 'firebase/storage';


const firebaseConfig = {
  apiKey: "---",
  authDomain: "---",
  projectId: "---",
  storageBucket: "---",
  messagingSenderId: "---",
  appId: "---",
  measurementId: "---"
};


const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const googleProvider = new GoogleAuthProvider();
export const db = getFirestore(app);
export const storage = getStorage(app);

I tried searching for answers, but it seemed rather sparse. Perhaps I just am really unfortunate or unintelligent.

Google Maps Javascript API Get Coordinates Of Draggable Polygon

I have a polygon which I am dragging around the map. The problem is when I call the bounds using

var polygonBounds = myPolygon.getPath();

they remain the same as the original getPath coordinates, where I want them shifted based on how I moved the polygon.

For example if I moved it 10 deg north and 20 deg west, I want the new getPath coordinates to reflect that. Any way to do this?

playwright storageSession failing inside docker containers in gitlab pipeline

I’m trying to use playwright inside of docker containers in our Gitlab ci pipeline. I followed the playwright Authenticate documentation. Locally the tests works fine, no issues but in the pipeline it seems to fail as if the storageState doesn’t exist so the routes stay protected in the tests and ultimately timeout (as well as logout button is disabled unless item named header has a token value assigned to it in localstorage and that fails as well so can safely assume there is no token in localstorage).

my playwright_tests/auth.setup.js

import { test as setup, expect } from '@playwright/test';

const authFile = 'playwright/.auth/user.json';

setup('authenticate', async ({ page }) => {
  // Perform authentication steps.
  await page.goto('/');
  await page.setViewportSize({ width: 1920, height: 1080 });
  await page.getByRole('button', { name: 'Sign in' }).click();
  await page.waitForURL('/login');
  await page.setViewportSize({ width: 1920, height: 1080 });
  await page.getByLabel('Username').click();
  await page.getByLabel('Username').fill('user');
  await page.getByLabel('Password', { exact: true }).click();
  await page.getByLabel('Password', { exact: true }).fill('password');
  await page.getByLabel('Password', { exact: true }).press('Enter');
  // Wait until the page receives the cookies.
  //
  // Sometimes login flow sets cookies in the process of several redirects.
  // Wait for the final URL to ensure that the cookies are actually set.
  await page.waitForURL('/');
  // End of authentication steps.

  await page.context().storageState({ path: authFile });
});

my playwright.config.js

// @ts-check
const { defineConfig, devices } = require('@playwright/test');
// import process
const process = require('process');

/**
 * Read environment variables from file.
 * https://github.com/motdotla/dotenv
 */
// require('dotenv').config();

/**
 * @see https://playwright.dev/docs/test-configuration
 */
module.exports = defineConfig({
  testDir: './playwright_tests',
  outputDir: 'playwright/test_results',
  /* Run tests in files in parallel */
  fullyParallel: true,
  /* Fail the build on CI if you accidentally left test.only in the source code. */
  forbidOnly: !!process.env.CI,
  /* Retry on CI only */
  retries: process.env.CI ? 2 : 0,
  /* Opt out of parallel tests on CI. */
  workers: process.env.CI ? 1 : undefined,
  /* Reporter to use. See https://playwright.dev/docs/test-reporters */
  reporter: [
    [
      'html',
      { outputFolder: 'playwright_results/playwright_report', open: 'never' },
    ],
    [
      'junit',
      { outputFile: 'playwright_results/playwright_report/reports.xml' },
    ],
  ],
  /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */
  use: {
    /* Base URL to use in actions like `await page.goto('/')`. */
    baseURL: process.env.FRONTEND_URL,


    /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */
    trace: 'on-first-retry',
  },

  /* Configure projects for major browsers */
  projects: [
    // Setup project
    {
      name: 'setup', testMatch: /.*.setup.js/
    },
    {
      name: 'chromium',
      use: { 
        ...devices['Desktop Chrome'],
        // Use prepared auth state.
        storageState: 'playwright/.auth/user.json',
      },
      dependencies: ['setup']
    },

    {
      name: 'firefox',
      use: { 
        ...devices['Desktop Firefox'],
        // Use prepared auth state.
        storageState: 'playwright/.auth/user.json',
      },
      dependencies: ['setup']
    },

example of what is written in playwright/.auth/user.json when tests are run locally

{
  "cookies": [],
  "origins": [
    {
      "origin": "http://localhost:8080",
      "localStorage": [
        {
          "name": "header",
          "value": "3c9cf469144b01c34eb09dfb9fbfa09b19dc4139"
        }
      ]
    }
  ]
}

Typescript nested switch alternatives

I have various outputs for a variety of combinations of 3 different variables. The best solution I can come up with is nested switch statements. I was simply wondering is there a more efficient/elegant solution that I should be using instead? An example of what I mean can be seen below:

function getPaintDefectSeverity(manufacturer: string, model: string, color: string) : String {
  switch(manufacturer){
    case 'FORD': case 'BMW':
      switch(model){
        case 'puma': case 'ranger': case 'escape': case 'x3': case 'x7':
          switch(color){
            case 'red': case 'yellow': 
               return 'full paint defect'
            default: 
               return 'no paint defect'
          }
       default
         return 'no paint defect'
       }
    case 'RENAULT': case 'SEAT': 
       switch(model){
         case 'clio': case 'ibiza': 
            return 'full paint defect'
         case 'megane':
            return 'partial paint defect'
         default: 
            return 'no paint defect'
        }
    case 'AUDI':
         switch(color){
           case 'blue': 
              return 'full paint defect'
           default: 
              return 'no paint defect' 
          }
    default
      return 'no paint defect'
    }

Obviously this is only a sample but my question is, is having so many nested switch statements necessarily bad? Any advice / guidance on this would be greatly appreciated.

Thanks.

Fix vertical scrolling on true mobile devices (touch devices)

I have a kanban board, that in responsive mode shows one column at a time. I have added column snapping scroll-snap-type: x mendatory; on the parent container, and scroll-snap-align: center; on each child. While the horizontal scrolling works well, when trying to scroll vertically (on each column), instead of just scrolling vertically the content jumps all over the place.

URL: https://mymarini.cogency.io/proxy/EDMv?is_embedded=true

Note: this is happening on true mobile devices only, NOT on desktop;

I am pretty sure there must be some sort of CSS solution to this? or possibly a combination of CSS + JS?

PS: The desired intent is to make it work just like in the trello app, except it CANNOT be a native app.

react-swiper is not re-rendered

function WorkSpace() {
    const dispatch = useDispatch();
    const edit = useSelector((state)=>(state.workSpace.edit));
    const currentMode = useSelector((state)=>(state.workSpace.currentMode));

    useEffect(()=>{
        const swiper = document.querySelector('.swiper').swiper;
        swiper.update();
    }, [edit])

    return(
        <div id="workWrapper">
            <Swiper
                style={{width:"100vw"}}
                slidesPerView={1}
                initialSlide={currentMode}
                onRealIndexChange={(swiper)=>{
                    switch(swiper.realIndex)
                    {
                        case 0:
                            dispatch(changeMode(mode.TODO));
                            break;
                        case 1:
                            dispatch(changeMode(mode.DIARY));
                            break;
                        case 2:
                            dispatch(changeMode(mode.GOAL));
                            break;
                    }
                }}
                onSwiper={(swiper) => console.log(swiper)}
                touchRatio={edit?0:1}
                loop={true}
            >
                <SwiperSlide><ToDoList/></SwiperSlide>
                <SwiperSlide><Diary/></SwiperSlide>
                <SwiperSlide><ToMyGoal/></SwiperSlide>
            </Swiper>
        </div>
    );
}

This is my code. I learned that when parent components get re-rendered, so does its child component. When I change ‘edit’ to false or true, WorkSpace component is re-rendered. I checked it by printing logs. but it seems like even though WorkSpace component gets re-rendered, the Swiper component does not.

When the ‘edit’ is true, the swiper must not be moved, so I set touchRatio to zero when ‘edit’ is true. But since the Swiper is not re-rendered, it is still slidable.

    useEffect(()=>{
        const swiper = document.querySelector('.swiper').swiper;
        swiper.update();
    }, [edit])

I tried to update swiper every time ‘edit’ changed, but it does not work.

Banno External Application/Plugin Card- Support Video and voice communication and scrolling

We have an integration with Banno today with Banno External Application/Plugin Card architecture, current Plug in within dashboard wont support proper scrolling(have UX issues), Video and Voice.

I know Banno will eventually remove scrolling capability for plugin card within Dashboard

We have to embed a card within Banno which should support scrolling and ability to support video and Voice, is there a recommendation architecturing design from Banno ? can we create a new Left NAV apart from Dashboard something like “Support” section where we can embed our application ?

Create Regex JavaScript for input tags [duplicate]

I need to create a regular expression to check the format of the text entered by the user.
I expect text in the format “#tag1 #tag2 #tag3” or “#tag1” or empty “”

Tried getting help from gpt chat but his expression doesn’t fit the test “#tag1 tag2″(should be false)
var tagsRegex = /^#([w-]+ ?(#w+ ?)*)*$/;

arr.map not looping actual values

Been away from code for a few years and I’m giving it another chance. I’m scraping options data from a select element using Puppeteer. Most of the data that I need is contained within the options elements themselves, however, a status icon is also assigned to each option contained in div> abbr > img structure outside of the div > select.

The Code

import puppeteer from "puppeteer";

(async function () {
  const browser = await puppeteer.launch({
    headless: "new",
  });
  const page = await browser.newPage();

  page.on("console", async (e) => {
    const args = await Promise.all(e.args().map((a) => a.jsonValue()));
    console.log(...args);
  });

  await page.goto("https://reports.housefacks.com/index.cfm?event=login");

  await page.type("#email", "[email protected]");
  await page.type("#password", "password");

  const loginBtn = 'input[type="submit"]';
  await page.click(loginBtn);

  const myReports = 'a[href="index.cfm?event=inspector.myReports&init=true"]';
  await page.waitForSelector(myReports);
  await page.click(myReports);

  const report = 'a[href="index.cfm?event=report.setupstep1&reportID=80988"]';
  await page.waitForSelector(report);
  await page.click(report);

  await page.goto(
    "https://reports.housefacks.com/index.cfm?event=report.setupstep4&reportID=80988"
  );

  const abbr = 'abbr[title="Click here to add a new Concern"] > a[href="#"]';

  await page.waitForSelector(abbr);
  await page.click(abbr);


  const concernsData = await page.$$eval("option", (options) => {
    let obj = {};
    return options.map((i) => {
      obj = {
        name: i.text,
        text: i.getAttribute("thetext"),
        value: i.getAttribute("value"),
      };
      return obj;
    });
  });

  const myValues = concernsData.map((i) => i.value);

  await page.$eval(
    "#savedconcern",
    (select, arr, data) => {
      let dataCopy = [...data];
      
      arr.map((v) => {
        const ids = [...document.querySelectorAll("#iconcorral img")]
          .map(
            (i) => !i.getAttribute("src").includes("bw") && i.getAttribute("id")
          )
          .filter((i) => i != false);
        
        dataCopy.map((d) => {
          ids.map((i) => {
            d.icon = i;
          });
        });

        select.value = v;

        const event = new Event("change");
        select.dispatchEvent(event);
      });

      return dataCopy;
    },
    myValues,
    concernsData
  );
})();

Expected Output

[
  {
    name: '----------',
    text: '',
    value: '0',
  },
  {
    name: 'No numbers visible',
    text: 'There was no house number that could be seen from the street',
    value: '662204',
    icon: 'newconcern_saftey'
  },
  {
    name: 'Condominium',
    text: 'Property is a condominium',
    value: '662206',
    icon: 'newconcern_comment'
  },
  {
    ...
  }
]

Current Output

    [
          {
            name: '----------',
            text: '',
            value: '0',
            icon: 'newconcern_comment'
          },
          {
            name: 'No numbers visible',
            text: 'There was no house number that could be seen from the street.'
            value: '662204',
            icon: 'newconcern_comment'
          },
          {
            name: 'Condominium',
            text: 'Property is a condominium.'
            value: '662206',
            icon: 'newconcern_comment'
          },
          {
            ...
          }
        ]

For some reason the map for the ids is not lining up with the actual values. it seems to zoom right to the end and assigns icon: 'newconcern_comment' for each entry. I’ve tried an using a long form for(let obj = 1; obj < dataCopy.length; obj ++) { ... } loop and for ..in with no success. Any pointers would be appreciated!

SvelteKit JS – Unable to change favicon

My package JSON

{
    "name": "WEBSITE_NAME",
    "version": "0.0.1",
    "private": true,
    "scripts": {
        "dev": "vite dev",
        "build": "vite build",
        "preview": "vite preview",
        "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
        "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
        "lint": "prettier --check .",
        "format": "prettier --write ."
    },
    "devDependencies": {
        "@sveltejs/adapter-auto": "^2.0.0",
        "@sveltejs/kit": "^1.27.4",
        "prettier": "^3.0.0",
        "prettier-plugin-svelte": "^3.0.0",
        "svelte": "^4.2.7",
        "svelte-check": "^3.6.0",
        "tslib": "^2.4.1",
        "typescript": "^5.0.0",
        "vite": "^4.4.2"
    },
    "type": "module"
}

My app.html file is such

<!doctype html>
<svelte:head>
    <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" />
</svelte:head>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="apple-touch-icon" sizes="180x180" href="%sveltekit.assets%/favicon/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="%sveltekit.assets%/favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="%sveltekit.assets%/favicon/favicon-16x16.png">
    <link rel="manifest" href="%sveltekit.assets%/favicon/site.webmanifest">
    %sveltekit.head%
</head>

<body data-sveltekit-preload-data="hover">
    <div style="display: contents">%sveltekit.body%</div>
</body>

</html>

I’ve tried what feels like everything and used favicon.io to create my images. I then created a favicon folder in the static folder which should work, but nothing is working. I’ve also tried moving these links into svelte:head but that didn’t work either.

Am I missing something? Could it be an issue in the svelte.config.js file? It’s not working locally nor on the deployed website.

Show alert if selected option is already selected in dropdown

In dropdown list option if selected one option such as optionA then click on plus/add button new row is added of dropdown list, than select optionB than click add button new row added now if again we select optionA from the list than show alert message that already selected option cannot be selected again and make that selection blank.

On adding multiple row of select element stop the user to select already selected option from them and show alert message that this option is already selected.

Fabric JS background image sizing issue

So there’s multiple ways to load in a canvas background image but in my code I’m loading it in like this:

var canvas = new fabric.Canvas('canvas', { backgroundImage: "<?php echo $image; } ?>", }

in the tutorial I found (https://www.tutorialspoint.com/how-to-create-a-canvas-with-background-image-using-fabricjs) it shows how to set the canvas height and width like so:

canvas.setWidth(document.body.scrollWidth / 2.2);
canvas.setHeight(650);

But I need to resize the background image itself not the whole canvas and I cannot find anywhere online describing how to do this. Logically it should be set when I set the canvas background image initially something like this:

var canvas = new fabric.Canvas('canvas', { backgroundImage: "<?php echo $image; } ?>", backgroundImageWidth: "50%", backgroundImageHeight: "100%",}

but that does not work, and I’ve tried a couple other things like setBackgroundImageWidth: or backgroundSize: etc… just shooting in the dark here. I can’t find any stackoverflow questions describing setting the background image size this way. Does anyone know how to do this?

deduce some matching ENCODE function from existing DECODE function

in some web project i found some DECODE function in javascript.
that is to kind of decrypt some obfuscated string.

i lost the source code of the matching counterpart – the ENCODE function.
and i just don’t get how to deduce it from the decoding logic.

/// decrypt helper function
function decryptCharcode(n, start, end, offset) {
    n = n + offset;
    if (offset > 0 && n > end) {
        n = start + (n - end - 1);
    } else if (offset < 0 && n < start) {
        n = end - (start - n - 1);
    }
    return String.fromCharCode(n);
}

/// decrypt string
function decryptString(enc, offset) {
    var dec = "";
    var len = enc.length;
    for(var i=0; i < len; i++) {
        var n = enc.charCodeAt(i);
        if (n >= 0x2B && n <= 0x3A) {
            dec += decryptCharcode(n, 0x2B, 0x3A, offset); // 0-9 . , - + / :
        } else if (n >= 0x40 && n <= 0x5A) {
            dec += decryptCharcode(n, 0x40, 0x5A, offset); // A-Z @
        } else if (n >= 0x61 && n <= 0x7A) {
            dec += decryptCharcode(n, 0x61, 0x7A, offset); // a-z
        } else {
            dec += enc.charAt(i);
        }
    }
    return dec;
}

/// the main function
function decodeMyString(s) {
    console.log( decryptString(s, -3) );
}

in the code there is “decodeMyString”.
and i can’t figure out how to code the counterpart “encodeMyString”.

i have searched all over the web. the “decoding” actually was generated by TYPO3 CMS as some functin called “linkTo_UnCryptMailto”.
but i wasn’t able to find out how it’s doing the “encoding”.

“ERR_DLOPEN_FAILED” error when using the pkg tool

I am attempting to package my Node.js application including canvas package using the pkg tool to create an executable. However, I am running into the following error:Error: error: 126C: code: ‘ERR_DLOPEN_FAILED’ at process.dlopen (pkg/prelude/bootstrap.js:2251:28)

Steps to Reproduce:

-Reproduce the steps explained in the link here after to recreate the nodejs app
https://www.section.io/engineering-education/compile-your-nodejs-application-into-a-exe-file/

-Add the canvas package
-import the canvas package in your index file
-Run the following command: node index.js then pkg index.js and .index-win.exe
-Observe the mentioned error.

Expected Behavior:
I expected the pkg command to generate a working executable without encountering any “ERR_DLOPEN_FAILED” errors.

Actual Behavior:

The pkg command fails with the mentioned error, making it difficult to generate a functional executable.

Environment

Node.js Version: Node.js v16.17.0, 18.5.0 and 18.17.0
Operating System: windows 10
pkg Version: pkg v5.8.1

Additional Context

This issue occurs consistently. The exe file generated without canvas works correctly.

Screenshots :

package.json

package.json

Error message
error message