fabric.js The layer is not updated immediately

I encountered that the fabric update level is not timely, what I want is that when I drag up, the corresponding text or image will also go up a level, and when I drag down, the corresponding text or layer will also go down to the next level, but in fact, I didn’t change the level when I dragged up the first time, but I changed the level when I dragged it on the second time, and the console didn’t report an error. Using fabric.js, I printed data, newIndex, and hcnumber, but the results were all correct, but they didn’t update the level for the first time
Depending on how many positions you have dragged, you can change the level, and the parameters that svg_font_hierarchy pass are hcnumber to pass in a few levels up or down a few levels, font to descend the element, and Type ‘increase’ | ‘decrease’ is up or down, and kind is dragging image or text

where data is the fabric instance that is searched according to text or typepath, this.canvas.moveTo(); Accept two arguments, the first is a fabric instance, the second is a hierarchy, this.canvas.renderAll(); is to refresh the canvas

lang-jssvg_font_hierarchy(hcnumber,font,type,kind){
  let data
  switch(kind){
    case "Image":
    data = this.fabricImg.find(Image => Image.typepath === font);
    break;
    case "text":
    console.log("Text")
    data = this.textvalue.find(text => text.text === font);
    break;
  }
    if (!data) {
        console.log('未找到对应的文本');
        return;
    }

    let newIndex;
    switch (type) {
        case "increase":
            newIndex = data.moveTo + hcnumber;
            console.log(newIndex)
            this.canvas.moveTo(data, newIndex);      
            this.canvas.renderAll();
            break;
        case "decrease":
            newIndex = data.moveTo - (hcnumber +1);
            this.canvas.moveTo(data, newIndex);
            this.canvas.renderAll(() => {
                console.log('渲染完成');
            });
            break;
        default:
            console.log('无效的类型');
            return;
    }
}

Drag method

$(function() {
    $("#sortableList").sortable({
       start: function(event, ui) {
            // 在拖动开始时,记录拖动元素的初始索引
            ui.item.data('startIndex', ui.item.index());
        },
      stop: function(event, ui) {
            const draggedElement = ui.item;
            const startIndex = draggedElement.data('startIndex');
            const endIndex = draggedElement.index(); 
            const change = endIndex - startIndex;
            draggedElement.data('value', endIndex + 1);
            const textValue = draggedElement.find('.textvalue').text();
            console.log(textValue);

            // 判断拖动的内容是文字还是图片
            const isImage = textValue.startsWith('Image'); // 根据文本判断
            if (isImage) {
                console.log("拖动的是图片");
                if (change > 0) {
                svg_colors.svg_font_hierarchy(change, textValue, "decrease",'Image');
                } else if (change < 0) {
                    svg_colors.svg_font_hierarchy(change + 1, textValue, "increase",'Image');
                } else {
                    console.log("位置没有变化");
                }
            } else {
                console.log("拖动的是文字");
                if (change > 0) {
                svg_colors.svg_font_hierarchy(change, textValue, "decrease",'text');
                } else if (change < 0) {
                    svg_colors.svg_font_hierarchy(change + 1, textValue, "increase",'text');
                } else {
                    console.log("位置没有变化");
                }
            }

            
        }
    });
});

Oracle APEX interactive grid date validation with javascript

I am trying to validate two dates (one can’t be smaller than the other) with javascript and dynamic action. Currently it works but only when I pick a date and save it (it lets me pick a smaller date when it shouldn’t) and when I edit the entry that’s when the error message pops up. Can’t seem to figure out how to make the error pop up immediately after picking an incorrect date.

This is javascript code and I am calling the function in dynamic action set to change-columns-departure

function validateDates() {
    console.log("Validation function called");

    var regionStaticId = "my_ig";
    var grid;

    try {
        grid = apex.region(regionStaticId).widget().interactiveGrid("getViews", "grid");
    } catch (e) {
        console.error("Interactive grid not found.", e);
        return;
    }

    var model = grid.model;
    var arrivalIdx = model.getFieldKey("ARRIVAL");
    var departureIdx = model.getFieldKey("DEPARTURE");

    // Clear any previous error messages
    apex.message.clearErrors();

    // Get the current editable record
    var editableView = grid.view$.grid("getSelectedRecords");

    if (editableView.length > 0) {
        var record = editableView[0];
        var arrival = record[arrivalIdx];
        var departure = record[departureIdx];

        console.log("Checking record: ", record);
        console.log("Arrival: ", arrival, "Departure: ", departure);

        // Check if the dates are valid and if "Departure" date is smaller than "Arrival" date
        if (arrival && departure) {
            var arrivalDate = new Date(arrival);
            var departureDate = new Date(departure);

            console.log("Arrival Date: ", arrivalDate, "Departure Date: ", departureDate);

            if (departureDate < arrivalDate) {
                console.log("Invalid date detected");

                // Show error message immediately
                apex.message.showErrors([{
                    type: "error",
                    location: "page",
                    message: "Pick a different date.",
                    pageItem: null
                }]);

                // Re-focus the invalid cell to prompt correction
                grid.view$.grid("gotoCell", {
                    row: model.getRecordId(record),
                    field: departureIdx
                });

                // Clear the invalid date
                model.setValue(record, departureIdx, null);
            }
        }
    } else {
        console.error("No editable record selected.");
    }
}

// Bind the validation function to the change event of the Departure column
$(document).on("change", "input[name=f06]", function() {
    validateDates();
});
 
validateDates();

REACT NATIVE padding issue white spaces on top and bottom of the IOS screen (notch area) even if the SafeAreaView is not given

I am new to ReactNative development and I couldn’t figure out the white spaces that occur on top and bottom of the screen even without the SafeAreaView component. I am testing this on ExpoGo app on my mobile.

import React from "react";
import { Text, View, StyleSheet } from "react-native";
import Footer from "../components/Footer";
import LittleLemonHeader from "../components/LittleLemon";
import WelcomeScreen from "../components/WelcomeScreen";
import MenuItems from "../components/MenuItems";

export default function Index() {
  return (
    //<View style={{ flex: 1, backgroundColor: "#495E57" }}>
    <View style={styles.container}>
      <LittleLemonHeader />
      <MenuItems />
      <Footer />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#495E57",
    padding: 0, // Ensure no padding in the container
    margin: 0,
  },
});

Problems with context when updating an array

I have a problem with the state of my context when updating a state that is an array.

The issue is the following, I have an object which stores the days selected by the user and which can be removed one by one. When removing one it does not update the react state and does not execute the useEffect.

dates in type

remove a date

remove date again

// context/index.tsx
export const MyAppContext = ({children}: any) => {
  const [afterSchool, setAfterSchool] = useReducer(afterSchoolReducer, initialAfterSchoolState);

  return (
      <AppContext.Provider value={{afterSchool, setAfterSchool}}>
        {children}
      </AppContext.Provider>
  )
}

// context/reducer/after-school.reducer.ts
export const afterSchoolReducer = (state: IAfterSchoolState, action: IAfterSchoolAction): IAfterSchoolState => {
  const { type, payload } = action;

  switch (type) {
    case 'removeSchedule': {
      const { removeDate } = payload;
    
      if (!removeDate) return state;
    
      const updatedSelectedDays = state.type.selectedDays.filter(date => date !== removeDate);
    
      return {
        ...state,
        type: {
          ...state.type,
          selectedDays: [...updatedSelectedDays],
        },
      };
    };
case "updateServiceTypes":
  console.log("updateServiceTypes type:", state.type)
  const newTypes = state.service.types.map(type =>
    (type.id === state.type.id)
      ? state.type
      : type
  );
  
  return {
    ...state,
    service: {
      ...state.service,
      types: newTypes
    }
  };
    default:
      return state;
  }

// hooks/after-school.ts
export const useAfterSchool = () => {
  const { afterSchool: { type, service }, setAfterSchool } = useAppContext();

  const handleDateRemove = (date: string) => {
    setAfterSchool({ type: "removeSchedule", payload: { removeDate: date } });
    setAfterSchool({ type: "updateServiceTypes", payload: {} });
  };

  useEffect(() => {
    console.log("type:", type);
  }, [type]);
}

How to selectively allow self-signed certificates when using built-in Node.js fetch()?

With node-fetch or https module directly, you can specify that unauthorized HTTPS requests should not be rejected. For example:

const fetch = require('node-fetch');
const https = require('https');

const httpsAgent = new https.Agent({
      rejectUnauthorized: false,
    });

const response = await fetch(url, {
      method: 'POST',
      headers: headers,
      body: body,
      agent: httpsAgent,
    });

However what if I use fetch that is already built in in Node.js? I don’t see any documentation about any special “non-browser” arguments. I don’t want to globally disable HTTPS verification, only for the requests I am making while testing a particular endpoint.

I tried just passing agent like with node-fetch, but unsurprisingly, that does not work:

const httpsAgent = new https.Agent({
    rejectUnauthorized: false,
});
const request = await fetch("https://my_test_api.local/test", {
    method: "GET",
    agent: httpsAgent
});

Result:

TypeError: fetch failed
    at node:internal/deps/undici/undici:13178:13
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async file:///home/me/myproject/apitest.js:60:25 {
  [cause]: Error: self-signed certificate
      at TLSSocket.onConnectSecure (node:_tls_wrap:1676:34)
      at TLSSocket.emit (node:events:520:28)
      at TLSSocket._finishInit (node:_tls_wrap:1087:8)
      at ssl.onhandshakedone (node:_tls_wrap:873:12) {
    code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
  }
}

Also, it is kinda weird that fetch here throws a TypeError, but that’s beside the point.

Why data of array in abject is showing undefined? [closed]

In this simple function data.images is showing undefine but I know it not null and when I console.log(data) array of images are showing on console please help…..

import { results } from "../../product"


export default function FetchProduct(products) {
   const productsDetailArray = () => {
       const temp = []
       for (let i = 0; i < products.length; i++) {
           const productId = products[i].productId
           console.log(products[i])
           const data = results.filter((item) => item.id === productId)
           console.log(data.images)
           temp.push({
               count: products[i].count,
               product: { ...data, images: [...data.images] },
           })
       }
       return temp
   }

   return productsDetailArray()
}

What is the rational for custom events not bubbeling by default?

Today I found out that custom events to do not bubble by default. This completely contradicted my intuition and expectation.

This is a follow-up question to that:

What was the rational, if known, behind this design choice?

The linked answers only references as a reason the fact bubbles defaults to false, which isn’t what I am looking for here, as that is merely an implementation fact and does not really tell me why the default is as it is.

In the past, I also already wondered why audio- and video-events don’t bubble, so that is a related question, but the reasoning given there, in my opinion, does not apply here.

const customEventHandling = () => {
    document.addEventListener('this-is-my-custom-event', (event) => {
        console.log('THIS SHOULD PRINT ON DISPATCHED EVENT!');
    });

    document.onreadystatechange = () => {
        if (document.readyState !== "complete") {
            console.log('not ready yet');

            return;
        }

        console.log('before dispatch');
        const event = new Event('this-is-my-custom-event', {bubbles: true}); // bubbles
        // const event = new Event('this-is-my-custom-event'); // won't bubble by default
        const element = document.querySelector('body');
        element.dispatchEvent(event);
        console.log('after dispatch');
    };
}

customEventHandling();

ES6 include references/dependencies in dynamic import

I have FileA that dynamically import FileB from different directory.
The dynamic import fail because FileB importing module ‘lodash’.

The error show

Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'lodash'.

FileA.js

// ... My other codes
import("file://D:/plugins/FileB.js");
// ... My other codes

FileB.js

import { now } from "lodash";
console.log(now());

export const Person = {
    name: "John Doe"
}

My question is how to add dependency that needed in dynamic import (here to add lodash in dynamic import)?

Note:

  • The codes is not for browser.
  • The FileA is npm project that have “lodash” installed as dependency. FileB is a single file located outside that project.
  • If I remove codes related to “lodash” in FileB the dynamic import
    work fine.

I want to add some options to an appendChild tag

I want to make a shopping basket for my website, and I used offcanvas for it. after making offcanvas page, I tried to append child ( appending some divs in my offcanvas page ) to my offcanvas. And then, I want to add my product details in my divs, after clicking on each product. for example, I click on first product, then my offcanvas would show a div and then, I want my div show’s the details of that product such as img, name and price.

But I have no idea how to append my details to my appended divs! I mean I can append my divs to my offcanvas but I have no idea about appending details on it. What should I do ? thank you.

this is my Code :

let list_pro = new Array();
let count = 0

function add_bas(t) {
  let imgs = t.parentNode.parentNode.children[0];
  let start_pro = imgs.src.search('img');
  let add_img = imgs.src.slice(start_pro, imgs.length);
  let name_pro = t.parentNode.parentNode.children[1].innerHTML;
  let price_pro = parseInt(t.parentNode.parentNode.children[5].innerHTML);
  let obj_pro = {
    'name': name_pro,
    'price': price_pro,
    'addres': add_img
  };
  list_pro.push(obj_pro)
  console.log(list_pro)


  // offcanvas
  let table_pro = document.createElement('div')
  table_pro.classList.add("tableCss");
  let listOff = document.getElementById('offcanvasBody');
  listOff.appendChild(table_pro);

  document.getElementById('pOFf').innerHTML = ''
}  
<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
  <div class="offcanvas-header">
    <h5 id="offcanvasRightLabel">Basket</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body" id="offcanvasBody">
    <P id="pOFf"> no product to show! </P>
  </div>
</div>

React native navigation unable to navigate

I am using react navigation in my react native app but am unable to navigate between pages.
Here is my app.ts

import React, { useEffect } from "react";
import { StatusBar } from "expo-status-bar";
import { NavigationContainer } from "@react-navigation/native";
import RootStack from "./App/Routes/routes";
import { PaperProvider } from "react-native-paper";
import { ToastProvider } from "react-native-toast-notifications";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import * as NavigationBar from "expo-navigation-bar";

function App() {
  useEffect(() => {
    const navColor = () => {
      NavigationBar.setVisibilityAsync("hidden");
    };
    navColor();
  }, []);
  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <NavigationContainer>
        <ToastProvider
          successColor="#37e9bb"
          dangerColor="#FF5449"
          swipeEnabled
          style={{ borderRadius: 30 }}
        >
          <PaperProvider>
            <RootStack />
          </PaperProvider>
        </ToastProvider>
        <StatusBar style="dark" backgroundColor="#FFEA70" />
      </NavigationContainer>
    </GestureHandlerRootView>
  );
}

export default App;

here are my routes in routes.tsx

import React from "react";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import HomeScreen from "../Screens/HomeScreen";
import ProfileScreen from "../Screens/ProfileScreen";
import EmployeeDetailScreen from "../Screens/EmployeeDetailScreen";
import LoginScreen from "../Screens/Login";
import SignUpScreen from "../Screens/SignUp";
import { useAuthStatus } from "../Hooks/useAuthStatus";

const Stack = createNativeStackNavigator();

export default function RootStack() {
  const isSignedIn = useAuthStatus();
  return (
    <Stack.Navigator initialRouteName={isSignedIn ? "Home" : "SignIn"}>
      {isSignedIn ? (
        <>
          <Stack.Screen
            name="Home"
            component={HomeScreen}
            options={{
              header: () => null,
              animation: "slide_from_bottom",
            }}
          />
          <Stack.Screen
            name="Profile"
            component={ProfileScreen}
            options={{
              header: () => null,
              animation: "simple_push",
            }}
          />
          <Stack.Screen
            name="EmployeeDets"
            component={EmployeeDetailScreen}
            options={{
              header: () => null,
              animation: "simple_push",
            }}
          />
        </>
      ) : (
        <>
          <Stack.Screen
            name="SignIn"
            component={LoginScreen}
            options={{
              header: () => null,
              animation: "slide_from_right",
            }}
            initialParams={{ heading: "Login", isSignIn: true }}
          />
          <Stack.Screen
            name="SignUp"
            component={SignUpScreen}
            options={{
              header: () => null,
              animation: "slide_from_left",
            }}
            initialParams={{ heading: "Signup", isSignIn: false }}
          />
        </>
      )}
    </Stack.Navigator>
  );
}

Now whenever I am trying to navigate between the pages like this

const navigation = useNavigation();
navigation.navigate("Home");

it gives me this error

The action ‘NAVIGATE’ with payload {“name”:”Home”} was not handled by any navigator.

Do you have a screen named ‘Home’?

If you’re trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator.

This is a development-only warning and won’t be shown in production.

react-native-config library not working on iOS device

I’m experiencing an issue with the react-native-config library in my React Native project where it works as expected on Android, but fails to function on iOS.

Environment:

React Native version: 0.69
Node version: 20
react-native-config versions tested: 1.5.1 to 1.5.3
Xcode version: 15.1
Testing device: iPhone 11
iOS version on device: 18.0
Issue Details:

After installing react-native-config and following the setup instructions, I confirmed that environment variables work correctly on Android, but on iOS, they do not seem to load or return undefined. I have tried several configurations to resolve this, but the issue persists.

Steps Taken to Resolve:

Ensured that my .env file is properly set up and contains the necessary environment variables.
Verified that the library is linked correctly and rebuilt the project in Xcode after cleaning the build folder.
Followed the video tutorial at YouTube video link ( https://www.youtube.com/watch?v=8lA0wP-0vEo&t=154s ) to double-check my configuration steps for iOS.
Code Example:

javascript
Copy code
import Config from ‘react-native-config’;

console.log(Config.MY_VARIABLE); // Works on Android but logs undefined on iOS
Additional Notes: I’ve also checked that the variables are correctly referenced in the Info.plist file as recommended in some guides, but this has not resolved the issue.

Question: What additional configurations or troubleshooting steps should I consider to get react-native-config working on iOS? Are there any iOS-specific requirements for this library that I might have missed?

Testing with Different Versions of react-native-config:

I installed and tested with the latest three versions of the react-native-config library (1.5.1, 1.5.2, and 1.5.3) to see if an earlier or later version would work on iOS. Despite these version changes, I still encountered the same issue: environment variables work on Android but not on iOS.
Double-Checking the Configuration:

I thoroughly reviewed my configuration setup for react-native-config multiple times to ensure all required steps were followed. This included:
Verifying that my .env file is in the root directory and that the variable names are in uppercase.
Ensuring that the react-native-config setup in Podfile is correct, and running pod install after each change to make sure dependencies are up to date.
Rebuilding the iOS project in Xcode and cleaning the build folder after each configuration adjustment to rule out any residual build issues.
Reviewing Online Resources and Documentation:

I consulted the official react-native-config documentation to verify that I hadn’t missed any steps specific to iOS.
Additionally, I watched the setup video on YouTube (link to the video) to cross-check my setup and ensure I followed the configuration steps correctly.
Attempting Troubleshooting Solutions Found Online:

After Googling the issue, I tried various troubleshooting tips found on Stack Overflow, GitHub issues, and other forums. This included:
Adding variables directly in Info.plist as recommended in some discussions.
Checking that react-native-config is linked correctly and visible in the Build Phases and Link Binary with Libraries sections of my Xcode project settings.
Attempting to manually set environment variables in the scheme settings in Xcode for the iOS build.
Despite these efforts, the environment variables still show up as undefined when the app is run on iOS, although they work fine on Android.

Why doesn’t my link randomizer webapp work on mobile devices?

Currently i work on a project of research with google form, i need to randomize my target responses to 4 different group of question, i use google script app to create a link that randomize which group of question that my responses have to fill.

It work perfectly on desktop, but can’t work on mobile devices, on a question with multiple choice i can’t even select the answer.

I code this code from here

Here my code :

function doGet() {
    var webpages = [];
    webpages.push("google form link 1");
    webpages.push("google form link 2");
    webpages.push("google form link 3");
    webpages.push("google form link 4");
    //------------------------------------------
    var random_page = Math.floor(Math.random()*webpages.length);
    var redirect = webpages[random_page];
    return HtmlService.createHtmlOutput("<script>location.href = '" + redirect + "';</script>");
    //return HtmlService.createHtmlOutput(UrlFetchApp.fetch(redirect));
}

do i need to change my script to work on mobile devices or there are no option to run this randomizer on mobile?

Find the solution to execute this script on mobile devices

Pdf downloaded by pupeeteer is saying “We can’t open this file”

I am using pupeeteer to download the pdf and send it to front-End,

So the below code is the back-end code using pupeeteer

const downloadResumeAsPdf = async (req, res) => {
    try {
        const browser = await puppeteer.launch({ headless: false });
        const page = await browser.newPage();
        await page.goto('http://localhost:4200/resumeBuilder/preview/resume_ooo', { waitUntil: 'networkidle2' });
        const selector = '.resume';
        await page.waitForSelector(selector, { timeout: 20000 });

        await page.evaluate(async (selector) => {
            const container = document.querySelector(selector);
            const images = Array.from(container.querySelectorAll('img'));
            await Promise.all(images.map(img => {
                if (img.complete) return;
                return new Promise(resolve => img.onload = img.onerror = resolve);
            }));
        }, selector);

        const pdfBuffer = await page.pdf({
            format: 'A4',
            printBackground: true,
            margin: {
                top: '20px',
                bottom: '10px'
            },
        });
        console.log('PDF Buffer Size:', pdfBuffer.length);
        console.log('PDF saved as output.pdf');
        res.set({
            'Content-Type': 'application/pdf',
            'Content-Disposition': 'attachment; filename="resume.pdf"',
        });

        res.send(pdfBuffer);
        await browser.close();
    } catch (error) {
        console.error('Error:', error);
        res.status(500).send(`An error occurred: ${error.message}`);
    }
};

Below is the services code to call the api

getResumeAsPdf() {
        const options = { responseType: 'blob' as 'json' };
        return this.apiService.post(`${this.targetUrl}/downloadResumeAsPdf`, options);
    }

Below is the front-end code which is called when clicked a button

downloadResume() {
        this.resumeBuilderService.getResumeAsPdf().subscribe(
            (response: Blob) => {
                const blob = new Blob([response], { type: 'application/pdf' });
                const link = document.createElement('a');
                link.href = URL.createObjectURL(blob);
                link.download = 'resume.pdf';
                link.click();
                URL.revokeObjectURL(link.href);
            },
            (error) => {
                console.error('Error downloading the resume:', error);
            }
        );
    }

How to fix this issue ? This is my first stack overflow question..

I have tried using pupeeteer but its not working