Safe alternative of new Function() [closed]

My requirements are to get unsafe-eval issues removed from project. new Function() has this issue which I am trying to remove. Over a Lot of places new Function() is used to get functions from strings. Example –

var functionBody = "with(context){with(data){return{'css':function(){return $root.css.root }}}}"
return new Function("context", "element", functionBody);

This has unsafe-eval issue occuring in line new Function()

Any alternative/safe libraries to this? I know eval() does the same but comes with unsafe-eval issues

Nuxt3 data fetching from Directus

Nuxt Noob here. I want to create a Site that uses Directus as backend.

I followed tutorials about fetching data in Nuxt and using the Directus SDK.

On initial page load, everything seems fine and data is fetched correctly. But when I change the route and go back to the index.vue the data is lost, won’t, fetch again and therefore the page is not rendered.

I’m getting this error H3Error: Failed to fetch and the global.value is null

So what am I doing wrong? I know what to do in plain Vue, but what am I doing wrong with Nuxt?

Does this have to do with Live Cycle hooks, I’m not aware of in Nuxt?
I don’t think the problem is on the Directus side. It has to be something with the fetching in Nuxt or caching or live cycles or … .

my code:

plugins/directus.js:

import { createDirectus, rest, readItems} from '@directus/sdk';
const directus = createDirectus('https://foo.bar').with(rest())

export default defineNuxtPlugin(() => {
    return {
        provide: { directus, readItems},
    };
});

pages/index.vue:

<script setup>
const { $directus, $readItems } = useNuxtApp();

const { data: global } = await useAsyncData('global', async () => {
    const response = await $directus.request($readItems('global'));
    return response;
});

console.log(global);
</script>
<template>
  <div class="flex px-5 bg-base-100 mt-9 sm:mt-0">
    <p class="text-2xl">
        bla bla bla
           <NuxtLink to="/about">
             {{ global.name }}
           </NuxtLink>
         {{ global.about }}
    </p>
   </div>
</template>

await AJAX Exception details

I have code like:

            try {
                LoadingStart();
                const result = await $.ajax({
                    type: 'Get',
                    url: url,
                    data: data,
                });
                LoadingEnd();
                window.location.replace(result.redirectUrl);
            } catch (err) {
                LoadingEnd();
                console.error('MyFunction', err);
            }

The exception, when logged comes out like

Object { readyState: 0, getResponseHeader: getResponseHeader(a), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(a, b), overrideMimeType: overrideMimeType(a), statusCode: statusCode(a), abort: abort(a), state: state(), always: always(), catch: catch(a), … }

How do I get the detail of an await AJAX exception?

I have tried ‘err.message’ but it seems to be undefined. I was expecting a text showing the error reason. I found detail by not using await with try/catch, instead using the AJAX error function that takes in the xhr and the exception. I would like the same kind of detail in the exception caught.

Creating non-module bundled JS and CSS using Vite

I’m looking to create concatenated / minified / source mapped JS files from non-module JS files.

Simplified concrete example: I have 2 libraries: jQuery Validation, Unobtrusive Validation (Microsoft extension to jQuery Validation).

I want to combine these 2 libraries into 1 file, minify it and source map it.

This used to be relatively easy with Gulp / Grunt. I realize these are outdated and the common thing I hear is to move to Webpack or, better yet, Vite.

I’ve used both Webpack and Vite before, however they seem suited for if you have specific entry points.

It seems like this is the wrong tool for the job or I’m simply not looking for the correct thing. All searches, AI chats, etc. seem to point to an idea of an entry point and importing my dependencies, etc. I don’t want that here.

What is a common way to approach this type of problem in 2025?

Example of what I want

[validation-lib1.js, validation-lib2.js] -> validation.min.js, validation.min.js.map
[other-lib1.js, other-lib2.js] -> other.min.js, other.min.js.map
[site.scss, site.theme.scss] -> site.min.css (I actually have this part working)

Why refresh token is called twice in axios interceptors

With the following code, it’s work on almost all my pages except one where I load many tabs in same time (eager tab on vuetify2)

expected:

  • send http request
  • if response is 401 (token is expired) we get a new fresh token and rerty all request with new token.
  • if response is 200, continue

But in this page I get:

  • send http request
  • get 10 response 401 (9 response to 10:15:10 and 1 to 10:15:11) (1 seconde)
  • get fresh token and remake 9 request
  • get fresh token again and remake other request

Why the last request dont use the same token ? How can I do to avoid to create a new token again if the old is valid)

let isTokenRefreshing = false;
let subscribers = [];
let refreshTokenPromise = null;  // Nous allons utiliser cette variable pour partager la promesse de rafraîchissement du token entre toutes les requêtes.

function onTokenRefreshed(token) {
    console.log("Token refreshed:", token);
    // Relance toutes les requêtes qui attendaient le token
    subscribers.forEach(callback => callback(token));
    subscribers = []; // Vide la file d'attente
}

function subscribeToTokenRefresh(callback) {
    console.log("Nouvelle requête ajoutée à la file d'attente.");
    subscribers.push(callback); // Ajoute les callbacks dans la file d'attente
}

window.axios.interceptors.response.use(
    response => response, // Si la réponse est OK, on la retourne
    async error => {
        const originalRequest = error.config;

        // Vérifie si c'est bien une erreur 401 et que la requête n'a pas déjà été retentée
        if (error.response && error.response.status === 401 && !originalRequest._retry) {
            console.log("401 détectée, tentative de rafraîchissement du token.");


            // Si le token est déjà en cours de récupération, on attend
            if (refreshTokenPromise) {
                console.log("Le rafraîchissement du token est déjà en cours, on attend...");
                return new Promise((resolve, reject) => {
                    subscribeToTokenRefresh(token => {
                        originalRequest.headers['Authorization'] = `Bearer ${token}`; // Mets à jour l'en-tête pour cette requête
                        resolve(axios(originalRequest)); // Relance la requête d'origine avec le nouveau token
                    });
                });
            }

            console.log("Détails de la requête originale qui a échoué avec 401 :");
            console.log("URL de la requête:", originalRequest.url);
            console.log("Méthode de la requête:", originalRequest.method);
            console.log("Headers de la requête:", originalRequest.headers);



            // Marque cette requête comme étant en cours de réessai
            originalRequest._retry = true;

            console.log("Démarrage du rafraîchissement du token...");
            // Si ce n'est pas encore fait, on initialise la promesse de rafraîchissement du token
            refreshTokenPromise = axios.post('/api/refresh-token') // Remplacez cette URL par votre API de rafraîchissement de token
                .then(response => {
                    const newToken = response.data.token;
                    console.log("Nouveau token récupéré :", newToken);

                    // Sauvegarde du nouveau token (par exemple, dans localStorage, Vuex, etc.)
                    localStorage.setItem('UserToken', newToken);

                    const user = {
                        isLoggedIn: true,
                        user: response.data.user
                    };
                    localStorage.setItem('User', JSON.stringify(user));

                    // On relance toutes les requêtes qui attendaient
                    onTokenRefreshed(newToken);

                    // Retourne le nouveau token
                    return newToken;
                })
                .catch(err => {
                    console.error("Erreur lors du rafraîchissement du token :", err);
                    return Promise.reject(err);
                })
                .finally(() => {
                    // Réinitialise la promesse de rafraîchissement du token
                    refreshTokenPromise = null;
                });

            // Maintenant on attend que la promesse de rafraîchissement se termine
            const newToken = await refreshTokenPromise;

            // Relance la requête initiale avec le nouveau token
            originalRequest.headers['Authorization'] = `Bearer ${newToken}`;
            return axios(originalRequest);
        }

        return Promise.reject(error); // Autres erreurs, on les passe
    }
);

Open the dropdown of Quasar’s only when starting to type

The default behavior or q-select with the use-input prop is that when we click on the input, the dropdown appears. I want to prevent this behavior and instead show the dropdown with the relevant data, only when a user starts typing in the input. I have looked at the documentation and I couldn’t find a built-in behavior for this. Is it possible to somehow achieve it with Quasar or do I need to write the logic manually?

<q-select
    v-model="model"
    :options="suggestions"
    label="Search for items"
    use-input
    hide-selected
    fill-input
    input-debounce="0"
    @filter="filterFn"
    @update:modelValue="goToLink"
></q-select>

I’m looking for a possible solution.

Superstruct validation for object with dynamic fields

I am currently using superstruct to type and validate an object. This object is returned via an API and then validated and type cast using the superstruct struct.

The structure of the object depends on a list of strings I only have at runtime, an example is below. There can be an arbitrary number of these arbitrary fields but they always have the same structure.

{
  parent: 
  {
    thisFieldIsAlwaysHere: number;
    arbitraryObject1: { body: number; };
    arbitraryObject2: { body: number; };
    arbitraryObject3: { body: number; };
  }
}

For this I use a struct with a record with a string for the name and the object for the body of each of these which are the same like so

const Struct = type({
  parent: record(string(), type({ body: number() }))
})

This is fine with typescripts types when using infer to cast. But my object fails to validate due to thisFieldIsAlwaysHere being a number not an object. Including thisFieldIsAlwaysHere using an intersection does not help. It appears the record is applied to every field.

const Struct = type({
  parent: intersection([
    type({ thisFieldIsAlwaysHere: number()),
    record(string(), type({ body: number() }))
  ])
})

Is there a way to get this to work elegantly? I have tried using dynamic. I was wondering if there is a way to exclude certain field names from the record? Or potentially exlclude other fields in the type

How to simulate a zebra printer environment [closed]

I need to develop an app that will detect all connected Zebra printers (whether via USB or TCP/IP within a server), check their status (if they have ribbon, paper, if they are powered on, active, etc.), and also monitor the print queue (if it’s active, if there are jobs in the queue, what is in the queue, etc.).

Additionally, I will simulate an environment similar to Zebra Design Essentials to adjust the positioning of information on the label.

I will be doing this using JavaScript (and Python if necessary), but I don’t have a Zebra printer (only at the office, but I am working remotely).
I would like to know if there is a Zebra printer simulator that allows me to fully simulate the environment, from connection to a fake print job.

I need to simulate everything

  • Printer status
  • Available printers
  • Print result (simulate the paper)
  • Printer queue

Problem with adsense ads Quirks mode and CORS

I am currently programming a digital multiplatform for content management and I followed the instructions for inserting the code for adsense ads but they are not displayed. I have these messages:

One or more documents in this page is in Quirks Mode, which will render the affected document(s) with quirks incompatible with the current HTML and CSS specifications.

Quirks Mode exists mostly due to historical reasons. If this is not intentional, you can add or modify the DOCTYPE to be <!DOCTYPE html> to render the page in No Quirks Mode.

Affected Resources

https://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-1690383206587209&output=html&adk=2926845670&adf=1797764267&abgtt=6&lmt=1739972569&plat=3%3A6 5536%2C4%3A65536%2C9%3A134250496%2C16%3A8388608%2C17%3A32%2C24%3A32%2C25%3A32%2C32% 3A32%2C41%3A32%2C42%3A32&format=0x0&url=https%3A%2F%2Fartiheba.com%2F&pra=5&wgl=1&a ihb=0&asro=0&ailel=1~2~4~7~8~9~10~11~12~13~14~15~16~17~18~19~20~21~24~29~30~34&aiae l=1~2~3~4~7~8~9~10~11~12~13~14~15~16~17~18~19~20~21~24~29~30~34&aicel=33~38&aifxl=2 9_18~30_19&aiixl=29_5~30_6&itsi=-1&aiapm=0.15&aiapmi=0.33938&aiescf=1&uach=WyJBbmRy b2lkIiwiNi4wIiwiIiwiTmV4dXMgNSIsIjEzMi4wLjI4MjgwLjE5NiIsbnVsbCwxLG51bGwsIjY0IixbWyJ Ob3QgQShCcmFuZCIsIjguMC4wLjAiXSxbIkNocm9taXVtIiwiMTMyLjAuMjgyODAuMTk2Il0sWyJBdmFzdC BTZWN1cmUgQnJvd3NlciIsIjEzMi4wLjI4MjgwLjE5NiJdXSwwXQ..&dt=1739972569488&bpp=4&bdt=9 0&idt=32&shv=r20250213&mjsv=m202502130101&ptt=9&saldr=aa&abxe=1&eoidce=1&nras=1&cor relator=5523664341743&frm=20&pv=2&u_tz=60&u_his=2&u_h=824&u_w=738&u_ah=824&u_aw=738 &u_cd=24&u_sd=2&dmc=8&adx=-12245933&ady=-12245933&biw=738&bih=824&scr_x=0&scr_y=0&e id=95344787%2C95350548&oid=2&pvsid=4426035825368710&tmod=1448730259&uas=0&nvt=2&fsa pi=1&fc=1920&brdim=0%2C0%2C0%2C0%2C738%2C0%2C738%2C824%2C738%2C824&vis=1&rsz =%7C%7Cs%7C&abl=NS&fu=32768&bc=31&bz=1&td=1&tdf=2&ifi=1&uci=a!1&fsb=1&dtd=39

Cross-Origin Read Blocking (CORB) blocked a cross-origin response.
sodar?id=sodar2&v=232&t=2&li=gda_r20250213&jk=4426035825368710&bg=!CgmlCUbNAAZ8UNeg XFA7ADQBe5WfOCm40sBOzJ9LcdOX0zDjqmBDnouG_d_4nwI1AbKwx0KxuT3uDcra7irAYBn4EYwbAgAAAHx SAAAAAA2gBB34ANfI1X-gj_F9lxSJYNRO6Y_GPcq7xwVtylb64pHWua42d9FB1yc93HeKCLq7m0HuzYwTq1M SoCgCRrDLzGei6Y9HpR6pj_hgkFwZl6dy0ED4Sabd8N4m_j2aLLpbiKVYEa4fstuVTL96Q2SPArNOq3naFi 4sMJqj4cRqJzDZ2hzqrWGt2pj1qV-MccTx2PglUW644UhaJeiWL802DLr_37R0-FIfAb-hOQ1hbDKwnmaAb FA0fWnU0aMbmzudDM8XI_ahdMOcq6vyHH5kCkBhruk1gU2iAkh-fxgdfX3K0Rp5BHiUUpRie8e1yTdHDgVK W0B–0iqdHPOdN8f6HqaXb1VpXsD0CVcw8H8nMyVhgFkA15CYQfKlRnAlyWf20ujanFQpzgKVffoBXRCWdI qvMsxJpMNSyJ8UuzZCXxnQ9jsSC7qZCPufMBTKbOmknFCp7ydBa_KhKmFR_98eN6LCr9QRH5_MTVLReelCsg KTiW6Ijw8i0gf4KHqTW9NkYtbIA-KWTBjaBcaDMryvNW6kHWXQYtWZg9StD-qDZtNfeDTaSS-H1Ibi9uosb GWBPDisy5kww2TYlAdwMO4uPoPeNueF6fa2jA-bJWZ-2C_vEpLEb3STvcFBfyK3nc1ood6awe1R_ECHHTdq vX7t6ij5hHS_miIl7GghFwBNRk1f1LRVlPfKKAKGZtzBpfcxJRtNEIXcIlxyXV8OFtT-zAN-e2liyrHSnVu 0Jnd1ke5IQPxoujqxR1vfd3VrGXM9L7bB1sXnkglhLJ5Je7DG-xxLRdpGWPshsNW4OZ4mK7LOVAXQUraKXu 9dqBRKxbbQnIBibekWBP77-TctfYILH5SSIjYr-smUO6eODf0LehQKfqhzIgXtgAajQ37BMhfGXMeOHsonL ECGCqRiLkJZJu1NqavyUzCV1AHTNAJVcFedoqp3mcqbDb2YBL0H2QeJ4v5IdT_VXraF6O_qIQk2BW4QkEms eau26ETO_ZnGhHX-DadgYsSusevwgV_XgCbfxcPGcDMVb9irYQ7MA6PI4X0sfYrZC1ywLrXlv12z_SU3EVhKWBZV_syLb1sfiH6gvhebHHTL9nY9HSqDCS59U8ZQUDgEK2epnp1vTosyE9UokjZyxNzl7c3PUxvpYvWl
IF anyone has a solution I’m interested, thank you.

My website : https://artiheba.com/

Re-appearing old values in React TS when applying custom validation on field from ‘reactstrap’

I’m having issue with re-appearing old values in React TS. I’m initially providing my code so you can check it as well:

 const initialState = {
        name: '',
      };

  const [registeredValidations, setRegisteredValidations] = useState({} as RegisteredValidationMap);
      const [formData, setFormData] = useState({
        ...initialState,
        name: requestStore.formData.name[0] || initialState.name
      });
      

And here is the call of my custom implemented validation for input field and the validation:

      <ValidatedInput
        name="name"
        value={formData.name}
        onChange={handleOnChange}
        validations={[GenericInputValidation]}
        isOptional={!fieldsRequired}
        setRegisteredValidations={setRegisteredValidations}
        registeredValidations={registeredValidations}
      />
   <Row>
        <Navigation handleOnNextClick={handleOnNextClick} registeredValidations={registeredValidations} />
      </Row>

the onChange listener implementation:

  const handleOnChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    
    setFormData(prevState => ({
      ...prevState,
      [name]: value,
    }));
  };

the GenericInputValidation:

export class GenericInputValidation extends Validation {
  // eslint-disable-next-line @typescript-eslint/require-await
  static async validate(props: ValidationProps): Promise<string[]> {
    const errors = [];

    if (props.newValue === '' && !props.isOptional) {
      errors.push(translate('error.missing-value'));
    }

    return errors;
  }
}
export default GenericInputValidation;

and now the ValidatedInput field implementation:

export const ValidatedInput = (props: ValidatedInputProps) => {
  const [errors, setErrors] = useState([...(props.externalErrors || [])]);

  const errorMessages = filterMessagesByType(errors, ERROR_TEMPLATES) || [];
  const warningMessages = filterMessagesByType(errors, WARNING_TEMPLATES) || [];
  
  let css = '';
  if(errorMessages.length !== 0){
    css= 'validation-failed'
  }else if(warningMessages.length !== 0){
    css = 'validation-warning'
  }

  const DOMprops = getDomProps(props);
  registerValidationComponent(props, errorMessages.length > 0 ? errorMessages : warningMessages, setErrors);

  return (
    <div>
      <Input
        {...DOMprops}
        onBlur={e => {
          generateBlur<HTMLInputElement>(props, errors, setErrors)(e);
        }}
        id={props.id || props.name}
        className={css}
        key={props.id + errors.length}
        readOnly={props.readOnly}
        type={props.type}
        maxLength={props.maxLength}
      />
      {errors.length !== 0 && (
        <Tooltip anchorSelect={`#${props.id || props.name}`} place="top">
          {getErrorsForTooltip(errors)}
        </Tooltip>
      )}
    </div>
  );
};

export default ValidatedInput;

and the Navigation implementation:

    const navigate = useNavigate();
      const dispatch = useDispatch();
      const defaultBack = () => {
        navigate(-1);
      };
      const [warningAcknowledged, setWarningAcknowledged] = useState(false);
      const handleBackClick = () => {
        dispatch(setWarningsAcknowledged(false));
        setWarningAcknowledged(false);
        if (props.handleOnBackClick) {
          props.handleOnBackClick();
        } else {
          defaultBack();
        }
      };
    
      useEffect(() => {
        setWarningAcknowledged(false);
      }, [JSON.stringify(props.registeredValidations)]);
    
      const nextFunction = async () => {
        const foundErrors = [];
        for (const registered of Object.values(props.registeredValidations)) {
          const { value, validations, customValidations, errors, setErrors } = registered;
          const validationProps: ValidationProps = {
            name: registered.name,
            newValue: value,
            validations,
            customValidations,
            errors,
            setErrors,
            isOptional: registered.isOptional,
            maxLength: registered.maxLength,
          };
    
          foundErrors.push(...(await runValidations(validationProps)));
        }
    
        const errorMessages = filterMessagesByType(foundErrors, ERROR_TEMPLATES);
        const warningMessagesFiltered = filterMessagesByType(foundErrors, WARNING_TEMPLATES);
        const infoMessages = filterMessagesByType(foundErrors, INFO_TEMPLATES);
        const hintMessages = filterMessagesByType(foundErrors, HINT_TEMPLATES);
        const warningMessagesAndInfo = warningMessagesFiltered.concat(infoMessages);
        const warningMessages = warningMessagesAndInfo.concat(hintMessages);
    
        if (errorMessages.length > 0) {
          return;
        } else if (warningMessages.length > 0 && !warningAcknowledged) {
          setWarningAcknowledged(true);
          return;
        }
    
        props.handleOnNextClick();
return (
    <Container className="mt-4">
      <Row>
        <Col xs={6}>
          {!props.hideBack && (
            <Button name={'zurück' + (props.nameSuffix || '')} id={'back-button' + (props.nameSuffix || '')} onClick={handleBackClick}>
              <FontAwesomeIcon icon={faArrowLeft}></FontAwesomeIcon> <Translate contentKey="generic.back" />
            </Button>
          )}
        </Col>

        <Col xs={6} className="next-button-col">
          {!props.hideNext && (
            <Button
              name={'weiter' + (props.nameSuffix || '')}
              id={'next-button' + (props.nameSuffix || '')}
              onClick={() => {
                nextFunction();
              }}
            >
              <Translate contentKey="generic.next" /> <FontAwesomeIcon icon={faArrowRight}></FontAwesomeIcon>
            </Button>
          )}
        </Col>
      </Row>
    </Container>
  );

Now when everything is done and call the ValidatedInput in a page, and save the values ones(which happens onNextClick) then go back on that page I got the values from the request store shown in the Input field which is prefectly fine.And now when I want to remove the input(just for triggering the validation) and click next – the validation is triggered which is ok, but the value in the field returns the old one, instead to hold on the new one and show that this field is incorrect.

Example:

Field has value: “test123”
I change to: “”
Clicking Next button triggers the validation and instead of staying the value to “” it returns the “test123”

Any ideas how to fix it ?

Angular 12 Host Application Not Rendering Nested Component from Angular 15 MFE

I’m facing an issue while rendering Angular Micro Frontends (MFE) in a host application with a different Angular version.

Application Setup:

Host/shell Application: Angular 12.1.5

Micro Frontends Remote (MFE): Angular 15.2.10

Issue:
I am successfully loading the MFE into the host application.The main page from the MFE renders correctly, and some elements appear as expected. However, nested components inside the MFE are not rendering.

Host/Shell App:

enter image description here

In Remote App (MFE):

enter image description here

Above image I’m able to load MFE in the host/shell application and

tag but not loading component HTML.

inside component have some static text.

MEF(Remote) HomeComponent

<p>Remote Application version - 17 </p>
<test-root></test-root>

MFE(Remote) TestComponent

<p>Hello World !!!!!!!!</p>

MFE(Remote) Webpack.config.js

const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const mf = require("@angular-architects/module-federation/webpack");
const path = require("path");
const share = mf.share;

const sharedMappings = new mf.SharedMappings();
sharedMappings.register(
  path.join(__dirname, 'tsconfig.json'),
  [/* mapped paths to share */]);

module.exports = {
  output: {
    uniqueName: "angular15App",
    publicPath: "auto",
    scriptType: 'text/javascript'
  },
  optimization: {
    runtimeChunk: false,
    splitChunks: false,
  },
  plugins: [
    new ModuleFederationPlugin({
      name: "mfe1",
      filename: "remoteEntry.js",
      exposes: {
        './MfeModule': './src/app/admin/admin.module.ts',
      },
      shared: share({
        "@angular/core": {
          singleton: true,
          strictVersion: true,
          requiredVersion: ">=1.0.0",
        },
        "@angular/common": {
          singleton: true,
          strictVersion: true,
          requiredVersion: ">=1.0.0",
        },
        "@angular/common/http": {
          singleton: true,
          strictVersion: true,
          requiredVersion: ">=1.0.0",
        },
        "@angular/router": {
          singleton: true,
          strictVersion: true,
          requiredVersion: ">=1.0.0",
        }, 
        ...sharedMappings.getDescriptors()
      })

    }),
    sharedMappings.getPlugin()
  ],
};

Host/Shell Routes to load MFE(Remote)

import { loadRemoteModule } from '@angular-architects/module-federation-runtime';

export const routes: Routes = [
  {
    path: 'mfe1',
    loadChildren: () =>
      loadRemoteModule({
        remoteEntry: 'http://localhost:4201/remoteEntry.js',
        remoteName: 'mfe1',
        exposedModule: './MfeModule',
      }).then((m) => {
        return m.AdminModule;
      }),
  }];

Verified that TextComponent is declared inside the MFE module.
Checked the browser console (no errors related to missing components).
Verified that the shared dependencies in webpack.config.js are correctly configured.

Page Numbers Adding Issue – PHP

I want to insert page number on each page when page is printed by @Media print
below is the PHP code which has a page break.

so before a page break I will get Page 1 on footer below the footer text. Footer text is given un the end too. Then after page break there is more html and then on footer, Page 2 will come. IN this case, only Page 1 of 2 is appearing.

PHP CODE

<?php 
// Check the number of stakeholders and activities
$stakeholders_count = count($stakeholder_percentage);
$activities_count = count($activity_name_en);

if ($stakeholders_count >= 5 || $activities_count >= 10) {
// Apply page break when the condition is met
echo '<div class="page-break" style="page-break-before: always;"></div>';
echo '<div class="print-breaks">
    <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
</div>';
} else {
echo '<div>';
}
?>

window.addEventListener("beforeprint", function(event) {
  var totalPages = 0; // Initialize total pages

  // Find all the page breaks
  var pageBreaks = document.querySelectorAll(".page-break");

  // Total pages = number of page breaks + 1 for the first page
  totalPages = pageBreaks.length + 1;

  // Loop through the page breaks and append page numbers
  pageBreaks.forEach(function(element, index) {
    var pageNumberElement = document.createElement("div");
    pageNumberElement.classList.add("page-number");
    pageNumberElement.textContent = "Page " + (index + 1) + " of " + totalPages;

    // Insert page number after the page break
    element.parentNode.appendChild(pageNumberElement);
  });

  // If there's only one page, we handle it separately
  if (totalPages === 1) {
    var pageNumberElement = document.createElement("div");
    pageNumberElement.classList.add("page-number");
    pageNumberElement.textContent = "Page 1 of 1";
    document.body.appendChild(pageNumberElement);
  }
});
@media print {

  /* Ensuring page numbers appear on each page */
  .page-number {
    position: fixed;
    bottom: 10mm;
    right: 10mm;
    font-size: 12px;
  }


}
FOOTER CONTENT

<div style="position: fixed; bottom: 20px; left: 0; width: 100%; text-align: center;" id="printFooter">
  <div style="display: flex; margin-left: 12%; justify-content: space-between; align-items: center; margin-bottom: 10px;">
    <div style="text-align: left; margin-bottom: 3px;">
      <h1 style="font-size: 18px;">مـديـر الـبـلـديـة</h1>
    </div>
    <div style="text-align: right; margin-right: 5%;margin-right: 11%; margin-bottom: 3px;">
      <h1 style="font-size: 18px;">رئيــس القســم</h1>
    </div>
  </div>
  <div style="display: flex; justify-content: space-between; align-items: center; width: 100%; margin-top: 20px;">
    <h1 style="margin: 0; font-size: 14px; margin-left: 12%;">This document is considered as commercial registry</h1>
    <h1 style="margin-right: 10%; font-size: 14px;">تقوم هذه الرخصة بمثابة شهادة سجل تجاري</h1>
  </div>
  <div class="page-number1"></div>


</div>

Get descendant children with a specific class efficiently in vanilla Javascript

I’m currently using the following JavaScript function to get all direct .layout children of a given parent, ensuring that the selected elements are:

  • Not nested inside another .layout
  • Directly inside the specified parent
  • The given parent element may or may not have the .layout class

Here’s my implementation:

const getDirectChildren = (parent) => {
  return [...parent.querySelectorAll('.layout')].filter(layout => {
    const closest = layout.parentNode?.closest('.layout');
    return closest == null || closest === parent;
  });
}

Expected Behavior Example

Given the following HTML structure:

<div class="parent">
  <div class="layout" id="layout-1"></div>   <!-- Direct child : Yes -->
  <div class="a">
    <div class="layout" id="layout-2"></div> <!-- Indirect child : Yes -->
  </div>
  <div class="layout" id="layout-3">         <!-- Direct child : Yes -->
    <div class="layout" id="layout-4"></div> <!-- Indirect child with .layout parent : No -->
  </div>
</div>

If I call getDirectChildren(document.querySelector('.parent')), the expected output should be:

[
  <div class="layout" id="layout-1"></div>,
  <div class="layout" id="layout-2"></div>,
  <div class="layout" id="layout-3"></div>
]

My implementation works as expected, but I’m wondering: Is there a more optimized approach to achieve the same result while reducing the number of DOM queries?

Any suggestions for improving the performance of this function? I’m looking for a vanilla JavaScript solution only.

How do I refactor an `@Input` which is being updated directly, which is not possible to do in `input` signal

I am refactoring my angular code to work with signals. I have this below code, which needs to be refactored.

@Component({ ... })
export class SomeComponent {
  @Input() test = null;

  ngOnInit() {
    this.test = 'qwerty';
  }
  ...

There was no error when I update an @Input before input signal.

Logically I would refactor this to:

@Component({ ... })
export class SomeComponent {
  test = input(null);

  ngOnInit() {
    this.test.set('qwerty'); // <- set does not exist for input signal
  }
  ...

So in the above code, input signal does not have a set or update method, so my refactor is wrong, what is the logical way to solve this problem, the update must be done.