nodejs worker is not getting called

My nodejs server dir structure is as following:
./src/rest/api/longJob.js
This file contains following method for long running operation, which I want to handover to worker:

const { Worker } = require('node:worker_threads')
async runWorker(scriptfile, input) {
  console.log('Running worker python script:', scriptfile);
  return new Promise(function(resolve, reject) {
    const worker = new Worker("./src/rest/api/worker.js", {
      workerData: {
        thread_count: 3
      },
    });
    worker.on("message", (data) => {
      console.log("[[Worker]]:", data);
      resolve(data);
    });
    worker.on("error", (msg) => {
      reject(`An error ocurred: ${msg}`);
    });
  });

  return p;
}

I am using promise, so that when the promise is resolved, I can send back the data as response to the rest-api.

The worker file is located at: ./src/rest/api/worker.js

import { parentPort, workerData } from "worker_threads";

async function worker() {
  console.log("started");
  parentPort.postMessage("fixed!");
}
console.log('worker executing');
worker();

whenever a new worker is created, the worker code is not executed and worker stays online.
The console logs from worker.js is also not printed in the js debug terminal for vscode. Not sure what is wrong with the code.

I start my nodejs application from . dir using npm start. It would be helpful to get help on this.
Thanks!

FullCalendar `prev()` and `next()` buttons show the wrong month after selecting a month using `gotoDate()

I am using FullCalendar in my React project, and I have an issue with the navigation buttons (prev() and next()) after clicking on a specific month.

Here’s a simplified version of my code:

const handleMonthClick = (monthIndex) => {
  const calendarApi = calendarRef.current?.getApi();
  const currentDate = calendarApi.getDate(); // Get the current date
  let c_year = Number(moment(currentDate).format("YYYY"));
  let c_month = Number(moment(currentDate).format("MM"));

  if (calendarApi) {
    // Navigate to the clicked month
    const newDate = new Date(c_year, monthIndex, 1); // monthIndex is 0-based
    calendarApi.gotoDate(newDate);
    setSelectedMonth(monthIndex); // Set the selected month
    setSelectedYear(c_year); // Set the selected year
  }
};

const handleNavigation = (direction) => {
  const calendarApi = calendarRef.current?.getApi();
  const currentDate = calendarApi.getDate();
  let c_year = Number(moment(currentDate).format("YYYY"));
  let c_month = Number(moment(currentDate).format("MM"));

  if (direction === "prev") {
    c_month -= 1; // Decrease month for prev
    if (c_month < 0) {
      c_month = 11; // Wrap around to December
      c_year -= 1; // Decrease the year
    }
  } else if (direction === "next") {
    c_month += 1; // Increase month for next
    if (c_month > 11) {
      c_month = 0; // Wrap around to January
      c_year += 1; // Increase the year
    }
  }

  // Update state with the new year and month
  setSelectedMonth(c_month);
  setSelectedYear(c_year);

  // Navigate to the updated month
  const newDate = new Date(c_year, c_month, 1);
  calendarApi.gotoDate(newDate);
};

Problem:

  • When I click on a month using handleMonthClick(), the calendar correctly navigates to that month.
  • However, when I use the prev() or next() buttons after selecting a month, it sometimes shows the wrong month.
    • For example, after selecting February (month 1) and clicking “next”, the calendar might display March correctly, but if I click “prev”, it might show December instead of January.

What I’ve tried:

  • I’ve tried adjusting the selectedMonth and selectedYear states after each month change, but it doesn’t seem to affect the behavior of the prev() and next() buttons.
  • I’m using calendarApi.gotoDate() to navigate to the selected month, but I’m unsure if this is properly synchronized with the prev() and next() functions.

Question:

  • How can I fix the issue so that the prev() and next() buttons correctly show the previous and next months after using gotoDate() to navigate to a specific month?

Any help would be greatly appreciated!

How to Optimize DevExtreme DataGrid Performance with 6000+ Records and 160+ Columns in React?

I have implemented a data table using the DevExtreme DataGrid in React. The table has over 6000 records and more than 160 columns. Here’s how it works:

Initially, I load only the column names.
Upon clicking a button, all the records are fetched from an API.
The table uses virtual scrolling for better performance.
However, I’m facing an issue where skeleton loaders appear both above and below the viewport while scrolling, which creates a weird visual effect. Here’s a simplified version of my code:

import React, { memo } from "react";
import DataGrid, {
  Column,
  ColumnChooser,
  Export,
  Paging,
  Scrolling,
  SearchPanel,
  Selection,
  Sorting,
  Summary,
  TotalItem
} from "devextreme-react/data-grid";
import PropTypes from "prop-types"; // Import PropTypes

const DataGridComponent = memo((props) => {

  const {
    data,
    keyExpr,
    onSelectionChanged,
    selectedRows,
    columns,
    stickyIndex,
    summaryItems,
    extraColumn,
    onIconClick,
    cellRender,
    height
  } = props;

  // Memoize data to avoid re-renders on each row selection change
  const memoizedData = React.useMemo(() => data, [data]);

  // Memoize columns (if an extra column is provided)
  const memoizedColumns = React.useMemo(() => {
    return extraColumn ? [extraColumn, ...columns] : columns;
  }, [extraColumn, columns]);

  const memoizedCellRender = React.useCallback((e, col) => {
    if (cellRender) {
      return cellRender(e, col);
    }
  }, [cellRender]);

  // Detect if the screen is mobile
  const isMobile = React.useMemo(() => window.innerWidth <= 768, []);

  return (
    <div style={{ height: "100%", display: "flex", flexDirection: "column", padding: "10px 0" }}>
      <DataGrid
        dataSource={memoizedData}
        animation={{ enabled: false }}
        keyExpr={keyExpr}
        showBorders={true}
        allowColumnResizing={false}
        columnAutoWidth={true}
        height={height}
        onSelectionChanged={(e) => onSelectionChanged(e?.selectedRowKeys)}
        selectedRowKeys={selectedRows}
        showColumnLines={true}
        loadPanel={{
          enabled: false,
          showIndicator: true,
        }}
      >
        <ColumnChooser enabled />
        <Selection mode="multiple" showCheckBoxesMode="always" />
        <Scrolling mode="virtual" />
        <Paging enabled={false} />
        <Sorting mode="multiple" />
        <SearchPanel visible highlightCaseSensitive />
        <Export enabled />

        {Array.isArray(memoizedColumns) && memoizedColumns.map((col, index) => (
          <Column
            key={index}
            fixed={!isMobile && index < stickyIndex} // Disable fixed columns on mobile
            fixedPosition="left"
            dataField={col.accessorKey}
            caption={col.header}
            visible={col.is_visible}
            alignment={col.textAlign}
            allowFiltering={true}
            allowSorting={true}
            cellRender={(e) => memoizedCellRender(e, col)}
          />
        ))}

        <Summary>
          {summaryItems.map((item, index) => (
            <TotalItem
              key={index}
              column={item.column}
              summaryType={item.summaryType}
              displayFormat={item.displayFormat}
              skipEmptyValues={false}
            />
          ))}
        </Summary>
      </DataGrid>
    </div>
  );
});

// Define PropTypes
DataGridComponent.propTypes = {
  data: PropTypes.array,
  keyExpr: PropTypes.string,
  onSelectionChanged: PropTypes.func,
  selectedRows: PropTypes.array,
  columns: PropTypes.array,
  stickyIndex: PropTypes.number,
  summaryItems: PropTypes.array,
  loading: PropTypes.bool,
  onIconClick: PropTypes.func,
  cellRender: PropTypes.func,
};

// Set default props to avoid crashes
DataGridComponent.defaultProps = {
  data: [],
  keyExpr: "diamond_id",
  onSelectionChanged: () => { },
  selectedRows: [],
  columns: [],
  stickyIndex: 0,
  summaryItems: [],
  loading: true,
  onIconClick: () => { },
  cellRender: null
};

export default DataGridComponent;

Key Points:
I’m using virtual scrolling mode.
Skeleton loaders show up awkwardly during scrolling.
The issue is noticeable because of the large dataset and many columns.

What I’ve Tried:
Disabling animations using animation: { enabled: false }.
Optimizing data and column rendering using useMemo.

Questions:

  • Is there a way to prevent skeleton loaders from appearing above and below the viewport while scrolling?
  • Are there additional optimizations for handling large datasets and many columns with the DevExtreme DataGrid?

Any suggestions or best practices for improving the scrolling behavior and overall performance would be greatly appreciated!

What I Tried:

  1. I disabled animations in the DataGrid using animation: { enabled: false }.
  2. I used React.useMemo to optimize the rendering of both data and columns.
  3. I configured the grid to use virtual scrolling with scrolling: { mode: "virtual" }.

What I Expected:
I expected smoother scrolling with no skeleton loaders or rendering artifacts, ensuring a seamless user experience even with large datasets and many columns.

What Actually Happened:
Despite these optimizations, skeleton loaders still appear above and below the viewport during scrolling, creating a visually unappealing experience.

Unable to inline JS and CSS using webpack

I have been dealing with this problem for past 2 days and couldn’t resolve it. I tried few other steps posted in stackoverflow but couldn’t make it work and all the questions were 3-4 years old as well.

I have a build folder containing – bundle.js, bundle.css and index.html. The index.html contains <link href="bundle.css"> and <script src="bundle.js">.

I am trying to inline the bundle.js and bundle.css into index.html using webpack. I am facing two problems:

  1. JS file gets inlined but the index.html still has script src="bundle.js"
  2. CSS does not get inlined at all and neither does it appear in dist folder

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset='utf-8'>
    <meta name='viewport' content='width=device-width,initial-scale=1'>

    <title>Internal site</title>
    <script src='bundle.js'></script>
    <link rel='stylesheet' href='bundle.css'>
</head>
<body></body>
</html>

webpack.config.js

const path = require('path');
const HTMLWebpackPlugin = require('html-webpack-plugin');
const HtmlInlineCSSWebpackPlugin = require('html-inline-css-webpack-plugin').default;
const HtmlInlineScriptWebpackPlugin = require('html-inline-script-webpack-plugin');

module.exports = {
    context: path.resolve(__dirname, './internal_site/public/'),
    entry: {
        main: './bundle.js', // Entry JavaScript file
    },
    output: {
        filename: '[name].js', // Output JS bundle
        path: path.resolve(__dirname, 'dist'), // Output directory
        clean: true, // Clean output directory before build
    },
    module: {
        rules: [
            {
                test: /.css$/, // Match CSS files
                use: [
                    'style-loader', // Extract CSS into separate files
                    'css-loader', // Resolve CSS imports
                ],
            },
        ],
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: './index.html', // Path to your index.html
            inject: 'body', // Inject scripts into the body

            minify: {
                collapseWhitespace: true, // Minify HTML
                removeComments: true, // Remove comments
            },
        }),
        new HtmlInlineCSSWebpackPlugin(), // Inline CSS into <style> tags
        new HtmlInlineScriptWebpackPlugin(), // Inline JavaScript into <script> tags
    ],
    optimization: {
        minimize: true,
        minimizer: [
            new (require('terser-webpack-plugin'))({
                extractComments: false, // Remove comments
            }),
        ],
    },
    mode: 'production',
};

Versions:

"webpack": "^5.97.1",
"webpack-cli": "^6.0.1"

How to using setTimeout in side loop javascript for wait a second and then process next loop?

How to using setTimeout in side loop javascript for wait a second and then process next loop ?

i tried to using setTimeout in side for loop javascript for wait a second and then process next loop, but it’s not work.

<script>
for (let i = 1; i < 3; i++) {
  setTimeout(function(){
      alert(i);
    }, 2000);
}
</script>

When run code i want to get result like this

wait 2 second then alert “1” wait 2 second then alert “2

Invariant Violation: requireNativeComponent: “RNCSafeAreaProvider” was not found in the UIManager. React Native

I get this error when i click ‘AppSettings’ button

Node version: v18.20.3

Yarn version: 1.22.22

I tried so much things like, install pods after cleaning all cache and removing currents Pods and lock files.

And also upgrade and downgrade versions of same packages like @react-navigation/native, react-native-safe-area-context

**Invariant Violation: requireNativeComponent: "RNCSafeAreaProvider" was not found in the UIManager.
This error is located at:
    in RNCSafeAreaProvider (at SafeAreaContext.tsx:92)
    in SafeAreaProvider (at SafeAreaProviderCompat.tsx:46)
    in SafeAreaProviderCompat (at NativeStackView.native.tsx:343)
    in NativeStackView (at createNativeStackNavigator.tsx:69)
    in Unknown (at createNativeStackNavigator.tsx:68)
    in NativeStackNavigator (at AppSettings.navigator.tsx:15)
    in AppSettingsNavigator (at SceneView.tsx:132)
    in StaticContainer
    in EnsureSingleNavigator (at SceneView.tsx:124)
    in SceneView (at useDescriptors.tsx:217)
    in RCTView (at View.js:32)
    in View (created by TabBarElement)
    in RNSScreen (at createAnimatedComponent.js:211)
    in AnimatedComponent (at createAnimatedComponent.js:264)
    in AnimatedComponentWrapper (at src/index.native.tsx:314)
    in Suspender (at src/index.tsx:40)
    in Suspense (at src/index.tsx:39)
    in Freeze (at src/index.native.tsx:206)
    in DelayedFreeze (at src/index.native.tsx:313)
    in InnerScreen (at src/index.native.tsx:566)
    in Screen (created by ResourceSavingScene)
    in ResourceSavingScene (created by TabBarElement)
    in RNSScreenContainer (at src/index.native.tsx:400)
    in ScreenContainer (created by TabBarElement)
    in RCTView (at View.js:32)
    in View (created by TabBarElement)
    in TabBarElement (created by BottomTabNavigator)
    in BottomTabNavigator (at App.tsx:78)
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:430)
    in BaseNavigationContainer (at NavigationContainer.tsx:132)
    in ThemeProvider (at NavigationContainer.tsx:131)
    in NavigationContainerInner (at App.tsx:77)
    in Observer (at App.tsx:75)
    in App (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)
    in WaCon(RootComponent) (at renderApplication.js:60)
 LOG  BleManagerDiscoverPeripheral listener removed!
 LOG  BleManagerStopScan listener removed!
 LOG  BleManagerDisconnectPeripheral listener removed!
 LOG  BleManagerDidUpdateValueForCharacteristic listener removed!
 LOG  BleManagerDidUpdateState listener removed!
Error: Unable to resolve module ./Libraries/Components/DatePicker/DatePickerIOS from /Users/menduhcaylak/Desktop/furkan/wacon/node_modules/react-native/index.js: 
None of these files exist:
  * node_modules/react-native/Libraries/Components/DatePicker/DatePickerIOS(.native|.native.js|.js|.native.json|.json|.native.ts|.ts|.native.tsx|.tsx)
  * node_modules/react-native/Libraries/Components/DatePicker/DatePickerIOS/index(.native|.native.js|.js|.native.json|.json|.native.ts|.ts|.native.tsx|.tsx)
  15 | import typeof ActivityIndicator from './Libraries/Components/ActivityIndicator/ActivityIndicator';
  16 | import typeof Button from './Libraries/Components/Button';
> 17 | import typeof DatePickerIOS from './Libraries/Components/DatePicker/DatePickerIOS';
     |                                   ^
  18 | import typeof DrawerLayoutAndroid from './Libraries/Components/DrawerAndroid/DrawerLayoutAndroid';
  19 | import typeof FlatList from './Libraries/Lists/FlatList';
  20 | import typeof Image from './Libraries/Image/Image';

My package.json

{
  "name": "wacon",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx",
    "build": "react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res",
    "postinstall": "npx jetify"
  },
  "dependencies": {
    "@miblanchard/react-native-slider": "^2.1.0",
    "@react-native-async-storage/async-storage": "^1.24.0",
    "@react-navigation/bottom-tabs": "^6.2.0",
    "@react-navigation/native": "^6.0.10",
    "@react-navigation/native-stack": "^6.5.2",
    "@types/sync-storage": "^0.4.3",
    "axios": "^1.7.2",
    "convert-string": "^0.1.0",
    "css-to-react-native": "^3.0.0",
    "mobx": "^6.5.0",
    "mobx-react": "^7.3.0",
    "react": "^17.0.2",
    "react-native": "0.67.4",
    "react-native-animated-nav-tab-bar": "^3.1.8",
    "react-native-ble-manager": "^8.0.2",
    "react-native-country-flag": "^2.0.2",
    "react-native-device-info": "^11.1.0",
    "react-native-dropdownalert": "^4.5.1",
    "react-native-fast-image": "^8.6.3",
    "react-native-floating-action": "^1.22.0",
    "react-native-gesture-handler": "2.14.1",
    "react-native-location": "^2.5.0",
    "react-native-paper": "^5.12.3",
    "react-native-paper-dates": "^0.8.7",
    "react-native-safe-area-context": "5.0.0",
    "react-native-screens": "3.29.0",
    "react-native-scroll-wheel-picker": "^0.0.2",
    "react-native-switch-selector": "^2.2.1",
    "react-native-vector-icons": "^9.1.0",
    "react-native-view-slider": "^1.1.1",
    "react-native-wheel-scrollview-picker": "^2.0.4",
    "styled-components": "^5.3.5",
    "sync-storage": "^0.4.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9",
    "@babel/plugin-proposal-decorators": "^7.17.8",
    "@babel/runtime": "^7.12.5",
    "@react-native-community/eslint-config": "^2.0.0",
    "@types/convert-string": "^0.1.1",
    "@types/jest": "^26.0.23",
    "@types/react-native": "^0.66.15",
    "@types/react-native-vector-icons": "^6.4.10",
    "@types/react-test-renderer": "^17.0.1",
    "@typescript-eslint/eslint-plugin": "^5.7.0",
    "@typescript-eslint/parser": "^5.7.0",
    "babel-jest": "^26.6.3",
    "eslint": "^7.14.0",
    "jest": "^26.6.3",
    "jetifier": "^2.0.0",
    "metro-react-native-babel-preset": "^0.66.2",
    "react-test-renderer": "17.0.2",
    "typescript": "^4.4.4"
  },
  "resolutions": {
    "@types/react": "^17"
  },
  "jest": {
    "preset": "react-native",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }
}

My App.tsx:

import * as React from 'react';
import MyDevicesScreen from './src/scenes/MyDevices.screen';
import appStore from './src/shared/stores/App.store';
import IconFeather from 'react-native-vector-icons/Feather';
import IconMaterial from 'react-native-vector-icons/MaterialCommunityIcons';
import DropdownAlert from 'react-native-dropdownalert';
import deviceHelper from './src/shared/helpers/Device.helper';

import {SettingsStackNavigator} from './src/navigations/SettingsStack.navigator';
import {Alert, useEffect} from 'react-native';
import {EventArg, NavigationContainer} from '@react-navigation/native';
import {BottomTabScreenProps} from '@react-navigation/bottom-tabs';
import {AnimatedTabBarNavigator} from 'react-native-animated-nav-tab-bar';
import {LogBox} from 'react-native';
import {navigationRef} from './src/shared/helpers/RootNavigation.helper';
import {translate} from './src/services/translations';
import configStore from './src/shared/stores/Configs.store';
import {observer, Observer} from 'mobx-react';
import {AppSettingsNavigator} from './src/navigations/AppSettings.navigator';
import {getData} from './src/shared/stores/Storage.store';

LogBox.ignoreAllLogs();

type BottomTabScreenParamList = {
  MyDevices: undefined;
  DeviceSettings: undefined;
  Profiles: undefined;
  AppSettings: undefined;
};

type Props = BottomTabScreenProps<BottomTabScreenParamList, 'MyDevices'>;

const Tabs = AnimatedTabBarNavigator();

const App = () => {
  function checkIsDeviceConnected(
    e: EventArg<string, true, undefined>,
    navigation: Props['navigation'],
  ) {
    if (!appStore.isConnected) {
      // Prevent default behavior
      e.preventDefault();
      Alert.alert(translate('alert'), translate('no_device_connected_2'), [
        {
          text: translate('okay'),
          onPress: () => {
            if (appStore.isConnected) {
              navigation.navigate('MyDevices');
            }
          },
        },
      ]);
    } else {
      deviceHelper.getAllSettings();
    }
  }

  const TabBarIcon = (props: any) => {
    return props.fontName === 'feather' ? (
      <IconFeather
        name={props.name}
        size={props.size ? props.size : 24}
        color={props.tintColor}
      />
    ) : props.fontName === 'material' ? (
      <IconMaterial
        name={props.name}
        size={props.size ? props.size : 24}
        color={props.tintColor}
      />
    ) : null;
  };

  return (
    <Observer>
      {() => (
        <NavigationContainer ref={navigationRef}>
          <Tabs.Navigator
            initialRouteName="MyDevices"
            tabBarOptions={{
              activeTintColor: '#2F7C6E',
              inactiveTintColor: '#222222',
            }}
            appearance={{
              shadow: true,
              floating: false,
            }}>
            <Tabs.Screen
              name={'MyDevices'}
              component={MyDevicesScreen}
              options={{
                title: translate('my_devices'),
                tabBarIcon: ({focused, color}) => (
                  <TabBarIcon
                    focused={focused}
                    fontName="feather"
                    tintColor={color}
                    name="search"
                  />
                ),
              }}
            />
            <Tabs.Screen
              name={'DeviceSetttings'}
              component={SettingsStackNavigator}
              listeners={({navigation}) => ({
                tabPress: e => {
                  checkIsDeviceConnected(e, navigation);
                },
              })}
              options={{
                title: translate('device_settings'),
                tabBarIcon: ({focused, color}) => (
                  <TabBarIcon
                    focused={focused}
                    fontName="material"
                    tintColor={color}
                    name="timer-cog-outline"
                  />
                ),
              }}
            />
            <Tabs.Screen
              name={'AppSetttings'}
              component={AppSettingsNavigator}
              listeners={({navigation}) => ({
                tabPress: () => {
                  navigation.navigate('PhoneSettings');
                },
              })}
              options={{
                title: translate('app_settings'),
                tabBarIcon: ({focused, color}) => (
                  <TabBarIcon
                    focused={focused}
                    fontName="feather"
                    tintColor={color}
                    name="settings"
                  />
                ),
              }}
            />
          </Tabs.Navigator>
          <DropdownAlert
            closeInterval={700}
            ref={ref => {
              if (ref) {
                appStore.setDropDownAlertRef(ref);
              }
            }}
          />
        </NavigationContainer>
      )}
    </Observer>
  );
};

export default App;

My AppSettingsNavigator.navigator.tsx:

import React from 'react';
import {createNativeStackNavigator} from '@react-navigation/native-stack';

import PhoneSettings from '../scenes/PhoneSettings.screen';
import PhoneInfo from '../scenes/PhoneInfo.screen';

const Stack = createNativeStackNavigator();

const screenOptionStyle = {
  headerShown: false,
};

const AppSettingsNavigator = () => {
  return (
    <Stack.Navigator screenOptions={screenOptionStyle}>
      <Stack.Screen name="PhoneSettings" component={PhoneSettings} />
      <Stack.Screen name="PhoneInfo" component={PhoneInfo} />
    </Stack.Navigator>
  );
};

export {AppSettingsNavigator};

My PhoneSettings.tsx:

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
  ScrollView,
} from 'react-native';
import Header from '../components/Header.component';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import {NavigationProp, ParamListBase} from '@react-navigation/native';
import {translate} from '../services/translations';

const AppSettings = ({
  navigation,
}: {
  navigation: NavigationProp<ParamListBase>;
}) => {
  return (
    <SafeAreaView style={styles.container}>
      <Header onBackPress={navigation.goBack} />
      <ScrollView style={styles.scrollStyle}>
        <TouchableOpacity
          onPress={() => {
            navigation.navigate('PhoneInfo');
          }}>
          <View style={styles.button}>
            <Icon size={50} name={'cellphone-information'} color={'#019267'} />
            <Text style={styles.buttonLabels}>
              {translate('phone_settings')}
            </Text>
          </View>
        </TouchableOpacity>
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  button: {
    height: 100,
    backgroundColor: 'white',
    marginHorizontal: 10,
    marginVertical: 5,
    borderRadius: 5,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 25,
  },
  buttonLabels: {
    paddingLeft: 30,
    fontSize: 23,
  },
  scrollStyle: {
    marginBottom: 10,
  },
});
export default AppSettings;

Svelte 5 – an object could not be cloned

After I switched to Svelte 5 syntax I am getting this error when I pass a reactive variable to a function

let details = $state({
  user: '',
  pass: ''
 })

 ...
 await login(details) // <- error

but works if I destructure the state var

 await login({...details})

Why is destructuring needed in Svelte 5 but not 4, and why is it not mentioned in the migration guide?

How to get a list of controller class names instead of class objects in Express with routing-controllers?

I’m using the routing-controllers package with Express to load controllers dynamically from files in my project.

My app.ts :

import "reflect-metadata";


import express from 'express';
import dotenv from 'dotenv';
import { useExpressServer } from 'routing-controllers';
import {  connectDB } from './config/db';
import requireAll from 'require-all';
import path from 'path';
import { fileURLToPath } from 'url';



dotenv.config();
// Create an instance of an Express app
const app = express();

// Get __filename
const __filename = fileURLToPath(import.meta.url);

// Get __dirname
const __dirname = path.dirname(__filename);

const controllers = Object.values(
  requireAll({
    dirname: path.join(__dirname, 'controllers'),
    filter: /(.+.controller).(ts|js)$/,   // Match both .ts and .js files
  })
).map((controllerModule: any) =>
  Object.values(controllerModule).map((controller: any) => controller.default || controller)
).flat();

useExpressServer(app, {
  controllers,
});

// Connect to the database and start the server
const port =  3000;

connectDB().then(() => {
  console.log("controllers", controllers);
  app.listen(port, () => {
    console.log("Successfully running on ", `${port}`);
  });
});

When I log the controllers array, it outputs class references like:

[[class Demo1Controller], [class Demo2Controller]]

However, I want to extract just the class names like this:

[Demo1Controller, Demo2Controller]

How can I modify my code to get only the class names of the controllers instead of the entire class objects?

What I Tried:
I attempted using map() and flatMap() to extract the names from the class objects, but neither approach worked as expected.

My Environment :

Nodejs version 20.12.2 and npm version 9.9.4

Issue with jsPDF and AutoTable: “Error generating PDF: RangeError: Invalid string length at Array.join” when adding too many images

I’m using jsPDF with the AutoTable plugin to generate PDFs that include a large number of images. However, when there’s too much data (specifically, images), I encounter the error:

Error generating PDF: RangeError: Invalid string length at Array.join

I’ve narrowed the issue down to the following code block where images are added:

doc.addImage(imgSrc,
    textPos.x + (data.cell.padding('horizontal') / 2),
    textPos.y + (data.cell.padding('vertical') / 2),
    dim_width,
    dim, 
    imgAlias,
    'FAST');

It seems that when the total concatenated imgSrc (which contains all the image URLs) becomes too long, the PDF fails to generate or save correctly.

If I remove the imgAlias parameter from addImage(), the PDF generates successfully without the "string is too long" issue, but the problem is that all the rows in the table display the same image, rather than the relevant image for each row.

How can I solve this issue in a manner where it wouldn’t occur again? Even if the image src URL were to be further shortened, it will still eventually reach the maximum string length resulting in this issue occuring again.

<table id="image-table">
    <thead>
        <tr>
            <th>Index</th>
            <th>Image</th>
        </tr>
    </thead>
    <tbody>
        @foreach($cvData as $index => $data)
            <tr>
                <td>{{ $index }} - {{ $data->id }}</td>
                <td>
                    <img 
                    src="{{ env('IMG_URL') . '/' . $data->image_url }}" 
                    class="lazyload" 
                    alt="Image" 
                    crossorigin="anonymous">
                </td>
            </tr>
        @endforeach
    </tbody>
</table>

doc.autoTable({
    html: table,
    theme: 'grid',
    startY: 15,
    rowPageBreak: 'avoid',
    styles: { cellPadding: 2, fontSize: 10, rowPageBreak:'avoid', minCellHeight:10},
    didParseCell: async function(cell, opts) {
        console.log("Parsing");
        if (cell.cell.section === 'body') {
            var td = cell.cell.raw;
            if (td !== undefined) {
                var img = td.getElementsByTagName('img');
                if (img.length > 0) {
                    cell.cell.styles.minCellHeight = 30;
                    cell.cell.contentHeight = 30;
                }
            }
        }
    },
    didDrawCell: function(data) {
        console.log("Drawing");
        if (data.cell.section === 'body') {
            var td = data.cell.raw;
            if (td !== undefined) {
                var img = td.getElementsByTagName('img');
                if (img.length > 0) {
                    var dim = data.cell.height - data.cell.padding('vertical');
                    var dim_width = data.cell.width - data.cell.padding('horizontal');
                    var textPos = data.cell;
                    var imgSrc = img[0].src;


                    var imgAlias = "img-"+imageIndex
                    console.log("imgSrc = " +imgSrc);
                    console.log("imgAlias = " +imgAlias);
                    doc.addImage(imgSrc,
                        textPos.x + (data.cell.padding('horizontal')/2),
                        textPos.y + (data.cell.padding('vertical')/2),
                        dim_width,
                        dim, 
                        imgAlias,
                        'FAST');

                    imageIndex ++;
                }
            }
        }
    }
});

Moving picture like a carousel

SO here is the deal, I have a typescript project that looks like this


const MainPage = () => {
const allBooks = [, , , , ];
const [currentIndex, setCurrentIndex] = useState(0);

const moveLeft = () => {
    setCurrentIndex((prevIndex) => (prevIndex - 1 + allBooks.length) % allBooks.length);
};

const moveRight = () => {
    setCurrentIndex((prevIndex) => (prevIndex + 1) % allBooks.length);
};

return (
    <div className="body-container">
        <div className="left-button-container">
            <button className="left-button" onClick={moveLeft}>
                LEFT
            </button>
        </div>

        <div id="bannerBooks">
            {allBooks.map((book, index) => (
                <div
                    key={index}
                    className={`book-container ${
                        index === currentIndex ? "active" : "inactive"
                    }`}
                >
                    {book}
                </div>
            ))}
        </div>

        <div className="right-button-container">
            <button className="right-button" onClick={moveRight}>
                RIGHT
            </button>
        </div>
    </div>
);

};

export default MainPage;


As you can see I have elements like books, and I want to create a function that will be working like a carousel for example
buttonLeft Book1 book2 book3 book4 book5 buttonRight
when you press buttonLeft the book in the middle moves to the left and book that was on the right moves to the center and the same with the right button, so I will try to visualize it
buttonLeft Book1 book2 book3 book4 book5 buttonRight
button left pressed
buttonLeft Book2 book3 book4 book5 book1 buttonRight
button left pressed again
buttonLeft Book3 book4 book5 book1 book2 buttonRight
And the same for right button, I know I can use chatGPT but I DONT USE IT ON PURPOSE FOR NOT BECOMING A CHATGPT SENIOR, thank you everyone for the attention 🙂

What are best practices for migrating a Next.js JavaScript project to TypeScript

I have a Next.js project built with JavaScript, and I’m considering migrating it to TypeScript.

My current project setup:

Next.js (version 14)
Tailwind CSS
shadcn-ui components
JavaScript (no TypeScript configuration yet)

My specific questions are:

What is the recommended approach for gradually converting .js files to .tsx/.ts without breaking the existing functionality?

I am no big expert of TypeScript. Are there any automated tools that can help with this migration? What are the critical files that should be converted first?

I have read two Stackoverflow’s posts on the topic:

  1. Converting Next.js – Javascript code to Typescript
  2. Converting Typescript to Javascript Best Practices

But these posts tackle narrow usecases, while I want to consult on the approach related to the Next.js project written in JavaScript.

Also I’ve reviewed the Next.js documentation about TypeScript but didn’t find the answer.
So, I would appreciate practical advice from developers who have done similar migrations.

JavaScript in HTML vs seperate File

I am currently learning JavaScript and I’m trying to seperate my Code from HTML to a JavaScript-file.

WORKING CODE:

<!DOCTYPE html>
<html>
    <head>
        <title> DOM </title>
        <link rel="stylesheet" href="stylesheet.css">
    </head>
    <body>
        <button>hello</button>
        <script>
            console.log(document.body.innerHTML);
        </script>
    </body>
</html> 

NOT WORKING CODE:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title> DOM </title>
        <script src="basics.js" defer></script>
        <link rel="stylesheet" href="stylesheet.css">
    </head>
    <body>
        <button>hello</button>
    </body>
</html>

JavaScript:

console.log(document.body.innerHTML);

From my not working Code I get a lot of unnessecary output in the console.

        <button>hello</button>
        <script src="basics.js" defer=""></script>
    <!-- Code injected by live-server -->
<script>
    // <![CDATA[  <-- For SVG support
    if ('WebSocket' in window) {
        (function () {
            function refreshCSS() {
                var sheets = [].slice.call(document.getElementsByTagName("link"));
.
.
.
<script>

How do I get rid of it?

Thanks in advance.

Ways to access “Add to Custom Colors” or other extensions in

Is there currently any way to access “Add to Custom Colors” or other (local, browser or OS specific) extensions in the <input type="color"> Element?

enter image description here

(Old Aero theme example, as seen in Firefox.) This is probably a Windows-specific… quirk? vestige, even? — but, it’s interesting to me that the “Custom colors:” list can be populated from a datalist Element (via the list attribute), and also from within the dialog; but this state is lost when the dialog is closed, and it is re-initialized from the attached list with no state ever passed back to the document.

The MDN documentation for instance, doesn’t mention anything specific, but I take that to mean there isn’t anything currently developed for Firefox, nor stipulated in the underlying standard; but that doesn’t mean no browsers support such means.

To be clear, I would expect — if such a feature exists on any platform — it might present as an array of color strings in the corresponding input event, or perhaps even the underling datalist is mutated to match (when so enabled by the document). But there are lots of ways this could be handled; my question is, was this ever done?

I’m also guessing, if such a feature exists anywhere at all, it’s far from portable, so, I don’t intend on using this for any actual content, just curious if this has been toyed with before. And I expect there are more featureful libraries that provide such functionality natively [in JS and etc.], but this is also not my concern here.

I have some dropdowns inside a section, and when the dropdown is expanded, the section that the dropdowns are inside does not expand to fit the text

https://codepen.io/buttadogg_/pen/WbeZvjg

<section>
        <h1>Here’s The Basics!</h1>
        <div class="dropdowns">
            <div class="dd1c">
                <button class="dropdown dropdown1">Sydney's Public Transport & How To Use Them!</button>
                <img src="images/chevron-down.svg" alt="" class="dropdownarrow">
                <div class="dd1cdrop ddcdrop"></div>
            </div>
            <div class="dd2c">
                <button class="dropdown dropdown2">Finding a Doctor or Medical Service / OSHC</button>
                <img src="images/chevron-down.svg" alt="" class="dropdownarrow">
                <div class="dd2cdrop ddcdrop"></div>
            </div>
            <div class="dd3c">
                <button class="dropdown dropdown3">Understanding Your Housing/Accomodation Rights</button>
                <img src="images/chevron-down.svg" alt="" class="dropdownarrow">
                <div class="dd3cdrop ddcdrop"></div>
            </div>
            <div class="dd4c">
                <button class="dropdown dropdown3">Working in Sydney & Finding A Job</button>
                <img src="images/chevron-down.svg" alt="" class="dropdownarrow">
                <div class="dd3cdrop ddcdrop"></div>
            </div>
        </div>
    </section>



section:first-of-type {
    padding-top: 1.5vw;
    min-height: fit-content;
    z-index: revert-layer;
}

When the dropdown is expanded, the text just overlaps the second section and header. I want the section in which the dropdowns are to expand to fit the content of the dropdown, and then shrink back down.

Also, there is overlapping styles in the css because there is two files linked to the html, so i just added both of them to the codepen.

So far, I have tried to change the min-height, removing the min-height entirely, using a max-height, using margin,setting the display to flex, removing the z-index, but i got the exact same result, no change at all.

I do not get any error messages, so im assuming it has nothing to do with the javascript.