Missing pointerup event in child element after setting pointerCapture on parent

I want to implement a drag effect on an element, so I used setPointerCapture in its pointerdown event handler like this:

ele.addEventListener('pointerdown', (e)=>{
  e.currentTarget.onpointermove = dosomething()
  e.currentTarget.setPointerCapture(e.pointerId)
})
ele.addEventListener('pointerup', (e)=>{
  e.currentTarget.onpointermove = null
  e.currentTarget.releasePointerCapture(e.pointerId)
})

However, I run into problems when I’m dealing with events on its child elements:

let parent1 = document.querySelector('#parent1') 
let child1 = document.querySelector('#child1')
document.querySelectorAll('.log').forEach(ele => {
  ele.addEventListener('pointerdown', e => console.log(ele.id + " pointerdown"))
  ele.addEventListener('pointerup', e => console.log(ele.id + " pointerup"))
  ele.addEventListener('click', e => console.log(ele.id + " click"))
})
parent1.addEventListener('pointerdown', (e) => {
  e.currentTarget.setPointerCapture(e.pointerId)
})
parent1.addEventListener('pointerup', (e) => {
  e.currentTarget.releasePointerCapture(e.pointerId)
})
<div id='parent1' class='log'><div id='child1' class='log'>click me</div></div>

When I click at the child element, I get the following console logs:

child1 pointerdown
parent1 pointerdown
parent1 pointerup
parent1 click

Where child1 pointerup and child1 click is missing, compared to the following example

document.querySelectorAll('.log').forEach(ele => {
  ele.addEventListener('pointerdown', e => console.log(ele.id + " pointerdown"))
  ele.addEventListener('pointerup', e => console.log(ele.id + " pointerup"))
  ele.addEventListener('click', e => console.log(ele.id + " click"))
})
<div id='parent2' class='log'><div id='child2' class='log'>click me</div></div>

Is this behavior expected? If so, is it possible to capture the mouseup/click event on the child element?

How to add themeswitcher(from MUI) globally

I am new to react and building a React app using Material-UI (MUI v5) and have implemented routing using React Router. I want to include a theme switcher(which is present in SignUp and SignIn MUI Templates) that allows toggling between Light, Dark, and System modes globally . However, the theme switcher doesn’t seem to work as expected, and the theme isn’t applied consistently across all pages when i am trying to do so.

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import Home from './Home';
import SignIn from './sign-in/SignIn';
import SignUp from './sign-up/SignUp';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter, Route, Routes} from 'react-router-dom';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <BrowserRouter>
    <App />
    <Routes>
      <Route path = "/" element={<Home/>}/>
      <Route path = "sign-up" element={<SignUp/>}/>
      <Route path = "sign-in" element={<SignIn/>}/>
    </Routes>
    </BrowserRouter>
  </React.StrictMode>
);


reportWebVitals();

SignUp.js

import * as React from 'react';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import Checkbox from '@mui/material/Checkbox';
import CssBaseline from '@mui/material/CssBaseline';
import Divider from '@mui/material/Divider';
import FormControlLabel from '@mui/material/FormControlLabel';
import FormLabel from '@mui/material/FormLabel';
import FormControl from '@mui/material/FormControl';
import Link from '@mui/material/Link';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import Stack from '@mui/material/Stack';
import MuiCard from '@mui/material/Card';
import { styled } from '@mui/material/styles';
import AppTheme from '../shared-theme/AppTheme';
import ColorModeSelect from '../shared-theme/ColorModeSelect';
import { GoogleIcon, FacebookIcon } from './CustomIcons';


const Card = styled(MuiCard)(({ theme }) => ({
  display: 'flex',
  flexDirection: 'column',
  alignSelf: 'center',
  width: '100%',
  padding: theme.spacing(4),
  gap: theme.spacing(2),
  margin: 'auto',
  boxShadow:
    'hsla(220, 30%, 5%, 0.05) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.05) 0px 15px 35px -5px',
  [theme.breakpoints.up('sm')]: {
    width: '450px',
  },
  ...theme.applyStyles('dark', {
    boxShadow:
      'hsla(220, 30%, 5%, 0.5) 0px 5px 15px 0px, hsla(220, 25%, 10%, 0.08) 0px 15px 35px -5px',
  }),
}));

const SignUpContainer = styled(Stack)(({ theme }) => ({
  height: 'calc((1 - var(--template-frame-height, 0)) * 100dvh)',
  minHeight: '100%',
  padding: theme.spacing(2),
  [theme.breakpoints.up('sm')]: {
    padding: theme.spacing(4),
  },
  '&::before': {
    content: '""',
    display: 'block',
    position: 'fixed',
    zIndex: -1,
    inset: 0,
    backgroundImage:
      'radial-gradient(ellipse at 50% 50%, hsl(210, 100%, 97%), hsl(0, 0%, 100%))',
    backgroundRepeat: 'no-repeat',
    ...theme.applyStyles('dark', {
      backgroundImage:
        'radial-gradient(at 50% 50%, hsla(210, 100%, 16%, 0.5), hsl(220, 30%, 5%))',
    }),
  },
}));

export default function SignUp(props) {
  const [emailError, setEmailError] = React.useState(false);
  const [emailErrorMessage, setEmailErrorMessage] = React.useState('');
  const [passwordError, setPasswordError] = React.useState(false);
  const [passwordErrorMessage, setPasswordErrorMessage] = React.useState('');
  const [nameError, setNameError] = React.useState(false);
  const [nameErrorMessage, setNameErrorMessage] = React.useState('');

  const validateInputs = () => {
    const email = document.getElementById('email');
    const password = document.getElementById('password');
    const name = document.getElementById('name');

    let isValid = true;

    if (!email.value || !/S+@S+.S+/.test(email.value)) {
      setEmailError(true);
      setEmailErrorMessage('Please enter a valid email address.');
      isValid = false;
    } else {
      setEmailError(false);
      setEmailErrorMessage('');
    }

    if (!password.value || password.value.length < 6) {
      setPasswordError(true);
      setPasswordErrorMessage('Password must be at least 6 characters long.');
      isValid = false;
    } else {
      setPasswordError(false);
      setPasswordErrorMessage('');
    }

    if (!name.value || name.value.length < 1) {
      setNameError(true);
      setNameErrorMessage('Name is required.');
      isValid = false;
    } else {
      setNameError(false);
      setNameErrorMessage('');
    }

    return isValid;
  };

  const handleSubmit = (event) => {
    if (nameError || emailError || passwordError) {
      event.preventDefault();
      return;
    }
    const data = new FormData(event.currentTarget);
    console.log({
      name: data.get('name'),
      lastName: data.get('lastName'),
      email: data.get('email'),
      password: data.get('password'),
    });
  };

  return (
    <AppTheme {...props}>
      <CssBaseline enableColorScheme />
      <ColorModeSelect sx={{ position: 'fixed', top: '1rem', right: '1rem' }} />
      <SignUpContainer direction="column" justifyContent="space-between">
        <Card variant="outlined">
        <div class="logo"></div>
          <Typography
            component="h1"
            variant="h4"
            sx={{ width: '100%', fontSize: 'clamp(2rem, 10vw, 2.15rem)' }}
          >
            Sign up
          </Typography>
          <Box
            component="form"
            onSubmit={handleSubmit}
            sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}
          >
            <FormControl>
              <FormLabel htmlFor="name">Full name</FormLabel>
              <TextField
                autoComplete="name"
                name="name"
                required
                fullWidth
                id="name"
                placeholder="Jon Snow"
                error={nameError}
                helperText={nameErrorMessage}
                color={nameError ? 'error' : 'primary'}
              />
            </FormControl>
            <FormControl>
              <FormLabel htmlFor="email">Email</FormLabel>
              <TextField
                required
                fullWidth
                id="email"
                placeholder="[email protected]"
                name="email"
                autoComplete="email"
                variant="outlined"
                error={emailError}
                helperText={emailErrorMessage}
                color={passwordError ? 'error' : 'primary'}
              />
            </FormControl>
            <FormControl>
              <FormLabel htmlFor="password">Password</FormLabel>
              <TextField
                required
                fullWidth
                name="password"
                placeholder="••••••"
                type="password"
                id="password"
                autoComplete="new-password"
                variant="outlined"
                error={passwordError}
                helperText={passwordErrorMessage}
                color={passwordError ? 'error' : 'primary'}
              />
            </FormControl>
            <FormControlLabel
              control={<Checkbox value="allowExtraEmails" color="primary" />}
              label="I want to receive updates via email."
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              onClick={validateInputs}
            >
              Sign up
            </Button>
          </Box>
          <Divider>
            <Typography sx={{ color: 'text.secondary' }}>or</Typography>
          </Divider>
          <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            <Button
              fullWidth
              variant="outlined"
              onClick={() => alert('Sign up with Google')}
              startIcon={<GoogleIcon />}
            >
              Sign up with Google
            </Button>
            <Button
              fullWidth
              variant="outlined"
              onClick={() => alert('Sign up with Facebook')}
              startIcon={<FacebookIcon />}
            >
              Sign up with Facebook
            </Button>
            <Typography sx={{ textAlign: 'center' }}>
              Already have an account?{' '}
              <Link
                href="/sign-in/"
                variant="body2"
                sx={{ alignSelf: 'center' }}
              >
                Sign in
              </Link>
            </Typography>
          </Box>
        </Card>
      </SignUpContainer>
    </AppTheme>
  );
}

I think the theme switcher is from colormodeselect component which I am attaching here,

ColorModeSelect.js

import * as React from 'react';
import { useColorScheme } from '@mui/material/styles';
import MenuItem from '@mui/material/MenuItem';
import Select from '@mui/material/Select';

export default function ColorModeSelect(props) {
  const { mode, setMode } = useColorScheme();
  if (!mode) {
    return null;
  }
  return (
    <Select
      value={mode}
      onChange={(event) => setMode(event.target.value)}
      SelectDisplayProps={{
        'data-screenshot': 'toggle-mode',
      }}
      {...props}
    >
      <MenuItem value="system">System</MenuItem>
      <MenuItem value="light">Light</MenuItem>
      <MenuItem value="dark">Dark</MenuItem>
    </Select>
  );
}

Please guide me with the changes I have to do

I had tried

Wrapping the entire app with ThemeProvider.
Adding the ColorModeSelect component to the App and Home components.

Cannot target button element on mousemove event

My js code is supposed to target the button class and add the cursor-hover-nav on my cursor class

I tried adding a padding on my button and the script worked only when I hovered over the padding and not its main element. Any reasons why it wont work over the main element?

window.addEventListener("mousemove", function(e) {

  if (e.target.className === 'nav-button') {
    cursor.classList.add('cursor-hover-nav');
  } else {
    cursor.classList.remove('cursor-hover-nav');
  }
});
<button onclick="show()" class="nav-button">
  <svg class="plus" viewbox="0 0 100 100" width="40">
    <rect class="line vert" 
      width="80" height="10" x="10" y="45" rx="6">
    </rect>
    <rect class="line horiz" 
     width="10" height="80" x="45" y="10" rx="6">
    </rect>
  </svg>
</button>

Nested subtree traversal in the insert algorithm DOM

In general, those who worked with DOM, heard about insertion methods, for example, append, prepend and some others.

I decided to study how the whatwg specification describes them and I encountered difficulties.

This is what I am talking about (insert algorithm):

  1. For each node in nodes, in tree order:
    1. Adopt node into parent’s node document.
    2. If child is null, then append node to parent’s children.
    3. Otherwise, insert node into parent’s children before child’s index.
    4. If parent is a shadow host whose shadow root’s slot assignment is “named” and node is a slottable, then assign a slot for node.
    5. If parent’s root is a shadow root, and parent is a slot whose assigned nodes is the empty list, then run signal a slot change for
      parent.
    6. Run assign slottables for a tree with node’s root.
    7. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order:
      1. Run the insertion steps with inclusiveDescendant.
      2. If inclusiveDescendant is connected, then:
        1. If inclusiveDescendant is custom, then enqueue a custom element callback reaction with inclusiveDescendant, callback name
          “connectedCallback”, and an empty argument list.
        2. Otherwise, try to upgrade inclusiveDescendant.

That is, the algorithm indicates that we have a cycle in step 7 in which it goes through the nodes of a light tree recursively (DFS) and performs some steps for each node.

But we also have a substep 7.7, which is a subcycle and which, logically, is even broader since it looks at not only light nodes, but also looks at shadow nodes and their descendants.

Now let’s imagine such an example, we have some document there is a body node in which it is empty and we want to insert complex markup (of course it will be node with descendants) into it via the append method, let’s say it will be like this:

<section>
  <div id="1">
    <title>Title 1</title>
    <component-description>
      #shadow-root
        <span>Lorem ipsum</span>
    </component-description>
  </div>
  <div id="2">
    <title>Title 2</title>
    <component-description>
      #shadow-root
        <span>Lorem ipsum</span>
    </component-description>
  </div>
  <div id="3">
    <title>Title 3</title>
    <component-description>
      #shadow-root
        <span>Lorem ipsum</span>
    </component-description></div>
</section>

So when the insertion algorithm is run, when we enter the tree traversal cycle step 7, do some steps for the section node (specified above), then meet step 7.7 and traverse all nodes that contain section and its children including shadow ones. Is it?

Okay, now when we return to step 7, we get a new node that is a child of section, this is div with id="1". Now some steps will be performed for it, and then step 7.7, which will again traverse all nodes for div.

If we analyze the traversal by nodes, then div with id="1" and some of its children will be traversed by step 7.7 several times. For what?

Main question: Why use For each node in nodes, in tree order when the clause For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order is much broader and traverse shadow nodes?

I understand the difference between the traversal cycles (one includes traversal of shadow trees, the other does not). Probably I am missing something. I need help.


There is an even stranger part of this same algorithm below.

  1. For each node of nodes, in tree order:
    1. For each shadow-including inclusive descendant inclusiveDescendant of node, in shadow-including tree order, append inclusiveDescendant to staticNodeList.

Why is this done? I’m probably missing something.

Frame Processor Error: Regular javascript function ” cannot be shared

I am facing an issue when trying to call asynchronous function inside useFrameProcessor() from vision-camera(without expo). I have tried most of the solve available on the internet but unable to find appropriate one. I have used runOnJs()/runAsync() to do asynchronous operation but failed to do so.

  const frameProcessor = useFrameProcessor((frame) => {
    'worklet'
    console.log("I'm running synchronously at 60 FPS!")

    runAsync(frame, () => {
      'worklet'
      console.log("I'm running asynchronously, possibly at a lower FPS rate!")
    })
   
  }, [])

runAsync Error :

I'm running synchronously at 60 FPS!
Frame Processor Error: Regular javascript function '' cannot be shared. Try decorating the function with the 'worklet' keyword to allow the javascript function to be used as a worklet., js engine: VisionCamera
  const frameProcessor = useFrameProcessor((frame) => {
    'worklet'
    console.log("I'm running synchronously at 60 FPS!")

    // Use runOnJS to 
    runOnJS(() => {
     
       console.log("inside run on js")
    })();

  }, [])

runOnJS Error :

I'm running synchronously at 60 FPS!
ERROR  Frame Processor Error: Property '_WORKLET' doesn't exist, js engine: VisionCamera

Parsing Data From Firebase In React

Making an inventory management app for internal use with my side hustle (AV company). My current focus is reading the Gear objects from my Firebase RTDB into usable objects.

The structure of my database (log of snapshot.val()):
DB Structure
DB Structure - specific item example
This is the relevant code that produced that output:

import React, { useEffect, useState } from 'react';
import { rtdb } from './rtdb_config';
import { DatabaseReference, onValue, push, ref, set } from 'firebase/database';
import { Gear } from './Gear';

export default function App() {
  const [gear, setGear] = useState([]);

  useEffect(() => {
    const gearRef = ref(rtdb, "GearContainer");
    onValue(gearRef, (snapshot) => {
      if (snapshot.exists()) {
        console.log(snapshot.val());
      }      
    });
  }, []);

    return ( 
      <div>
      <h1>Data from database</h1>
    </div>
    );
}

Each object is stored under a key randomly generated by Firebase (childByAutoId is the default when push()ing to DB – would rather the key be the name but I’ll look into that). Each object has information that I want to read into React and map to a new Gear object:

export class Gear {
        name: string;
        includes: string[];
        purchaseCost: number;
        rentalCost: number;
        powerDraw: number;
        qtyOwned: number;
        qtyAvail: number;
        serviceTickets: ServiceTicket[];
        notes: string;

        constructor(
                _name: string,
                _includes: string[],
                _purchaseCost: number,
                _rentalCost: number,
                _powerDraw: number,
                _qtyOwned: number,
                _notes: string
        ) {
                this.name = _name;
                this.includes = _includes;
                this.purchaseCost = _purchaseCost;
                this.rentalCost = _rentalCost;
                this.powerDraw = _powerDraw;
                this.qtyOwned = _qtyOwned;
                this.notes = _notes;
                this.serviceTickets = [];
                this.qtyAvail = _qtyOwned;
        }
}

I can’t use the .map() function because I have my containers set up as an object with children, not an array. I did this because to update an item in an array, I have to bring down the whole array, update it, then send it back up to the DB.

Object.keys() isn’t exactly what I need and I haven’t found anything in the docs that would be useful in this situation. Is there any help built into React for this? I would just iterate through the objects in each category (infrastructure/laserFixtures/sfx/etc) but I’m unsure of how to do that for an object with children rather than an array.

Can I

  1. Bring down the gear objects from the DB to properly set up Gear objects in React using built in react functionality (like .map())? or

  2. Convert the JSON objects for my containers (infrastructure, laserFixtures, sfx, etc) into an array of objects when bringing them into React (which I could then .map())?

I can reformat this database any way necessary to make this work, but want to avoid using arrays, which would be very useful when parsing everything, but also compute-intensive and unscalable when I want to update or add items.

This is my second project in React, and the first was 5 years ago, so please excuse my lack of knowledge and point me towards a learning resource if I’m missing anything. Thank you to all!

Tone.js Sampler throwing “url keys must be the note’s pitch” with correct keys

I’m trying to use a tone.js sampler object within p5.js to play notes. I’ve tested out my environment with basic tone.js synths, but now I want to create a sampler using custom samples. The issue is, no matter what I try, tone is throwing a “url keys must be the note’s pitch” error when the sampler constructor is called.

I tried just using the default sampler code from the documentation, but got the exact same results. For scope context, I am defining the sampler variable in the global scope and constructing it in p5’s preload, but I have tried multiple different places to load it to no avail. What am I doing wrong?

The default tone.js sampler constructor I am using (with a different callback and variable name):

voice = new Tone.Sampler({
    urls: {
        A1: "A1.mp3",
        A2: "A2.mp3",
    },
    baseUrl: "https://tonejs.github.io/audio/casio/",
    onload: () => {
        voiceLoaded = true;
    },
});

Logger dependency injection problem, please help me

When I give the logger as a dependency to the class I am getting the following error:

Screenshot of error message details

E:my_sitesrccommondatabaseMongoDBConnector.ts:11
constructor(@inject(COMMON_TYPES.Logger) logger: ILogger) {
^TypeError: Cannot read properties of undefined (reading 'Logger')
at Object.<anonymous> (E:my_sitesrccommondatabaseMongoDBConnector.ts:11:38)
at Module._compile (node:internal/modules/cjs/loader:1469:14)
at Module.m._compile (E:my_sitenode_modulests-nodesrcindex.ts:1618:23)
at Module._extensions..js (node:internal/modules/cjs/loader:1548:10)
at Object.require.extensions.<computed> [as .ts] (E:my_sitenode_modulests-nodesrcindex.ts:1621:12)
at Module.load (node:internal/modules/cjs/loader:1288:32)
at Function.Module._load (node:internal/modules/cjs/loader:1104:12)
at Module.require (node:internal/modules/cjs/loader:1311:19)
at require (node:internal/modules/helpers:179:18)
at Object.<anonymous> (E:my_sitesrccommoncommon_injection_container.ts:4:1)

this is inversify.config.ts

import { Container, ContainerModule } from 'inversify';
import { commonContainer, COMMON_TYPES } from '../common_injection_container';
import { ILogger } from '../../common/interfaces/ILogger';

const appContainer = new Container();

appContainer.load(commonContainer);

const logger = appContainer.get<ILogger>(COMMON_TYPES.Logger);

interface ContainerDefinition {
    container: ContainerModule;
    name: string;
}

const containers: ContainerDefinition[] = [
];

containers.forEach(({ container, name }) => {
    try {
        appContainer.load(container);
        logger.info(`${name} container loaded successfully`);
    } catch (error) {
        logger.error(`Failed to load ${name} container`);
        if (error instanceof Error) {
            logger.trackError(error);
        } else {
            logger.error('An unknown error occurred while loading the container.');
        }
    }
});

export { appContainer };

this is common_injection_container.ts

import { ContainerModule, interfaces } from 'inversify';
import { ILogger } from './interfaces/ILogger';
import Logger from './utils/Logger';
import { MongoDBConnector } from './database/MongoDBConnector';


const COMMON_TYPES = {
    Logger: Symbol.for('Logger'), 
    MongoDBConnector: Symbol.for('MongoDBConnector'), 


};

const commonContainer = new ContainerModule((bind: interfaces.Bind) => {
    bind<ILogger>(COMMON_TYPES.Logger).to(Logger).inSingletonScope();

    bind<MongoDBConnector>(COMMON_TYPES.MongoDBConnector).to(MongoDBConnector);


});

export { commonContainer, COMMON_TYPES };

this is MongoDBConnector.ts

import mongoose from 'mongoose';
import { inject, injectable } from 'inversify';
import { ILogger } from '../../common/interfaces/ILogger';
import { COMMON_TYPES } from '../../common/common_injection_container';

@injectable()
export class MongoDBConnector {
    private logger: ILogger;

    constructor(@inject(COMMON_TYPES.Logger) logger: ILogger) {
        if (!logger) {
            throw new Error('Logger not found during MongoDBConnector injection');
        }
        this.logger = logger;
    }

    public async connectToMongoDB(): Promise<void> {
        try {
            await mongoose.connect(process.env.MONGODB_URI!, {
                serverSelectionTimeoutMS: 30000, 
            });
            this.logger.info('Connected to MongoDB'); 
        } catch (error: any) {
            if (error instanceof Error) {
                this.logger.error('Could not connect to MongoDB'); 
                this.logger.error(`Error details: ${error.message}`); 
            } else {
                this.logger.error('Could not connect to MongoDB with an unknown error');
            }
            throw error; 
        }
    }
}

Only using HTML/CSS how can I show an element ONLY when the parent is overflowing?

Using HTML and CSS, I want to show an element only when content is overflowing. I have a fixed maximum height, which I can hardcode.

The child content can contain any content (text, images, etc), which could have a dynamic size (I don’t know the size of it).

The solution has to be CSS only. This is a strict requirement to keep the page responsive on resize and avoid flickering.

Dynamic header and footer appearing in dev environment but not live deployment

Currently building a website for an archive community, and I am trying to implement a dynamic header and footer that loads on every page so that I don’t have to hardcode them into every single html file. I am currently encountering a problem where all the components show up just fine on localhost, but when I deploy it to a live demo on github none of the components load. I’m using relative paths, where index.html is in the root path of the site’s source, and my global components file is in components/global/global.js. When I try to use absolute paths instead, nothing shows up on any environment. Any help is appreciated.

document.addEventListener("DOMContentLoaded", function() {
    // Dynamically adds favicon
    const addFavicon = () => {
        const link = document.createElement('link');
        link.rel = 'icon';
        link.href = 'favicon.ico'; // Relative path
        link.type = 'image/x-icon';
        document.head.appendChild(link);
    };

    // Fetches an HTML component and inserts it into the specified selector
    const loadComponent = (selector, url) => {
        fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`Failed to load ${url}: ${response.status} ${response.statusText}`);
                }
                return response.text();
            })
            .then(data => {
                const element = document.querySelector(selector);
                if (element) {
                    element.innerHTML = data;
                } else {
                    console.error(`Element with selector "${selector}" not found.`);
                }
            })
            .catch(error => console.error(`Error loading component from ${url}:`, error));
    };

    // Initialize all global functionalities
    const initializeGlobals = () => {
        // Add favicon before anything else
        addFavicon();

        // Load the header and footer using relative paths
        loadComponent("#header", "/components/header/header.html");
        loadComponent("#footer", "/components/footer/footer.html");
    };

    // Initialize globals when the DOM is fully loaded
    initializeGlobals();
});

Emulating “ background color on a “ in dark mode

I’d like to get the background color of a textarea when dark mode is applied so I can apply it to a <div> which I want to ’emulate’ a <textarea>. This seems pretty straightforward, since it doesn’t need to be pure CSS.

I just get the color when the light and dark color-scheme are applied. Here’s an example for getting the dark-mode background color:

let textarea = document.createElement("textarea");
textarea.style.colorScheme = "dark";
document.body.append(textarea);
console.log(getComputedStyle(textarea)["background-color"]);

The problem is, this doesn’t work in Chrome. It returns rgb(18, 18, 18) which is much darker than the actual background color which is rgb(59, 59, 59). It seems to be doing something weird with transparency even though the actual background color is opaque. Or maybe it has some sort of “virtual” background which is not accessible to getComputedStyle.

comparison between textarea backgrounds shown in Chrome dark mode, RE claimed and actual colors

I’m not sure what rgb(18, 18, 18) corresponds to here.

It’s also possible that this is a bug, but it seems more likely that it’s just a user-agent specific thing that I need to take into account. If it’s the latter case, how could the above code be corrected?

Title: Proxy Error: Could Not Proxy Request to Backend Server on Port 6000 (ECONNREFUSED)

I’m encountering a “Proxy error: Could not proxy request” when trying to access the backend route /api/v1/me from my React frontend running on localhost:3000. The error message I receive is:

Proxy error: Could not proxy request /api/v1/me from localhost:3000 to
http://localhost:6000/. ECONNREFUSED

Backend Details:

  • The backend is running on port 6000 and is working properly. It is
    connected to the database as expected, and all routes, including
    /api/v1/me, are functioning correctly when accessed directly from
    Postman.

Here’s the relevant part of my app.js file:

import express from "express";
import dotenv from "dotenv";
import cookieParser from "cookie-parser";
import cors from "cors";
import { connectDatabase } from "./config/dbConnect.js";
import errorMiddleware from "./middlewares/errors.js";

const app = express();

// Load environment variables
if (process.env.NODE_ENV !== "PRODUCTION") {
  dotenv.config({ path: "backend/config/config.env" });
}

// Connect to the database
connectDatabase();

// Middleware for JSON and cookies
app.use(express.json());
app.use(cookieParser());

// Setup CORS for frontend access
app.use(
  cors({
    origin: "http://localhost:3000", // Frontend URL
    credentials: true,
  })
);

// Import routes
import authRoutes from "./routes/auth.js";

// Use routes
app.use("/api/v1", authRoutes);

// Error handling middleware
app.use(errorMiddleware);

// Start the server
const server = app.listen(process.env.PORT, () => {
  console.log(
    `Server started on PORT: ${process.env.PORT} in ${process.env.NODE_ENV} mode.`
  );
});

// Handle unhandled promise rejections
process.on("unhandledRejection", (err) => {
  console.log(`ERROR: ${err}`);
  console.log("Shutting down server due to Unhandled Promise Rejection");
  server.close(() => {
    process.exit(1);
  });
});

Route Definition:
This is the route for the /me endpoint in my backend:

router.route('/me').get(isAuthenticatedUser, getUserProfile);

And the controller method:

export const getUserProfile = catchAsyncErrors(async (req, res, next) => {
  const user = await User.findById(req?.user?._id);
  res.status(200).json({
    user,
  });
});

Redux Action and Reducer:
I’m using Redux to manage authentication. Below is the action that calls the /api/v1/me endpoint:

export const loadUser = () => async (dispatch) => {
  try {
    dispatch({ type: LOAD_USER_REQUEST });

    const { data } = await axios.get('/api/v1/me');

    dispatch({
      type: LOAD_USER_SUCCESS,
      payload: data.user
    });
  } catch (error) {
    dispatch({
      type: LOAD_USER_FAIL,
      payload: error.response.data.message
    });
  }
};

The authReducer handles the response:

export const authReducer = (state = { user: {} }, action) => {
  switch (action.type) {
    case LOAD_USER_REQUEST:
      return {
        loading: true,
        isAuthenticated: false,
      };

    case LOAD_USER_SUCCESS:
      return {
        ...state,
        loading: false,
        isAuthenticated: true,
        user: action.payload
      };

    case LOAD_USER_FAIL:
      return {
        ...state,
        loading: false,
        isAuthenticated: false,
        user: null,
        error: action.payload
      };

    default:
      return state;
  }
};

Frontend Issue:

  • I’m using axios in React with Redux, and the backend is on port 6000.
  • I’ve checked that the backend is running correctly on port 6000, and
    the database is connected properly.

Error:
When trying to access /api/v1/me from the React frontend on port 3000, I get the Proxy error: ECONNREFUSED. This error suggests that the request cannot be forwarded to the backend server.

I have set up a proxy in the package.json file of my React app like this:

"proxy": "http://localhost:6000"

What I have tried:

  • Ensured that both frontend and backend are running on their
    respective ports.
  • Checked the backend server logs, and everything looks fine.
  • Made sure that CORS is configured to allow the frontend
    (localhost:3000) to access the backend.
  • Tried restarting both the frontend and backend servers.

Can anyone suggest what could be causing this issue? Is there something wrong with the proxy configuration or how the request is being sent from the frontend?

Conditional styling of Text component in React Native

Why does this conditional styling work for Presseble, but at the same time doesn’t work for Text? How can I make it correct for the Text component too?

<Pressable style={ () => { return flagA == 0 ? styles.pressable_1 : styles.pressable_2 } } >
<Text style={ () => { return flagA == 0 ? styles.text_1 : styles.text_2 } }>{L5}</Text>

React Native image upload fails only when in Expo

I have a React Native app for iOS that successfully uploads images to Google Cloud Storage. When I import the same code into a new Expo app, the upload fails on both the iOS and Android simulators:

const formData = new FormData();

Object.entries({
  ...data.imageFields,
  file: {
    uri: curPhoto.path, // "/Users/username/Library/Developer/CoreSimulator/Devices/9EDEBECD-B892-4D34-9142-C559B5A32416/data/Containers/Data/Application/2879C35B-DE2C-439F-8AF4-AA53D6D0C380/Library/Caches/EC6FD27A-A8E6-4344-9580-191130EE7045.jpg"
    name: imageId, // "9af64c5f-e0d7-45cf-88a0-4635am46d16e"
    type: curPhoto.mimeType, // "image/jpeg"
  },
}).forEach(([key, value]) => {
  formData.append(key, value as string | Blob);
});

const URL = "https://storage.googleapis.com/my-bucket/";
const result = await fetch(URL, {
  method: "POST",
  body: formData,
  headers: {  // Tried both with and without any headers specified
    Accept: "application/json",
    "Content-Type": "multipart/form-data",
  },
});

// Results in 400 network error with no details

Is there anything I need to do differently for Expo? I’m using RN 0.74.5 and Expo 51.0.28.