How to wait for function call in Javascript without calling it directly

I have several functions that call each other asyncronously, and I need to catch a situation when last functionis called.
await statement supposes to call a function I should wait, but it is not to be called directly

function First(){
  console.log('First is called');
  setTimeout(Second(), 1000);
  return;
}

function Second(){
  console.log('Second is called');
}

function Main(){
  First();
  console.log('I called First and I want that Second also is complete');
}

I try to use await, but the problem is that I need to call function First() but should wait until Second is called. And including await in every call seems to be too complicated, since the chain length is quite large.

The solution could be an infinite loop in Main until Second initiate a variable, but I feel there should be more clear solution.

Power BI JS API – difference between Slicer / Page Slicer / Filter / Page Filter / Visual Filter?

I am new to Powerbi and working on a website and successfully integrates the Powerbi using the embed-token and JavaScript API found at the Powerbi Playground.

Following are the steps, how I integrate Powerbi and how end user interacts:

enter image description here

  1. Customer already authorized by his Powerbi account, so I have the bearer access token and refresh token
  2. Using token I got the list of workspaces using Rest API and generates a dropdown for same
  3. Upon selecting a workspace, I generates another dropdown for reports of selected workspace using Rest API
  4. Upon selecting a Report, I generates another dropdown for tab/page of selected report using Rest API
  5. After that when user submit the form, I collect the submitted information and render the selected report

Everything is working fine, now the customer demanding a change in the integration.
So whenever it renders a report, it should also generates another HTML (outside of the report) for the filters available on the rendered report. So the end user can interact with the report and also I need to remember/save the choice of user, so next time when user reopen same report, it should automatically selected previously saved data in the report.

To achieve this, I did some experiment with the below code using Powerbi Slicers:

<script type="text/javascript">
function getvisuals(){
    visSlicerArr = [];
    visSlicerStateArr = [];
    slicerContainer.empty();

    try {
        var pages = report.getPages();
        // console.log('pagesPromise', pages);

        pages.then(function(pagesArr){
            $.each(pagesArr, function(index, page){
                if(page.isActive){
                    activePage = page;
                }
            });

            console.log('activePage', activePage);

            // get all Visuals
            var visuals = activePage.getVisuals();
            // console.log('visualsPromise', visuals);

            visuals.then(function(visualsArr){

                $.each(visualsArr, function(index, vis){
                    if(vis.type == 'slicer'){
                        visSlicerArr.push(vis);
                    }
                });

                console.log('slicerArr (from Visuals)', visSlicerArr);

                // get Visual State
                $.each(visSlicerArr, function(index, visS){
                    var statePromise = visS.getSlicerState();
                    // console.log('visualStatePromise', statePromise);

                    statePromise.then(function(slicerState){
                        visSlicerStateArr.push(slicerState);
                        console.log('visualState', slicerState);

                        showSlicer(index, slicerState);

                        if((visSlicerArr.length - 1) == index){
                            slicerContainer.append('<button style="position: relative;" type="button" onclick="applyFilter()">Redraw Report</button>');
                        }
                    })
                    .catch (function (err) {
                        console.log('Promise Err 3', err);
                    });
                });
            })
            .catch (function (err) {
                console.log('Promise Err 2', err);
            });
        })
        .catch (function (err) {
            console.log('Promise Err 1', err);
        });
    }
    catch (errors) {
        console.log('Try Err 1', errors);
    }
}

function showSlicer(index, slicerState) {
    console.log('in', slicerState);

    var slicerVal = '';
    if(slicerState.filters.length){
        slicerValues = slicerState.filters[0].values;  // Get current slicer values
        slicerVal = slicerValues.join(', ');
        console.log("slicerVal", JSON.stringify(slicerVal), index)
    }

    var target = '';
    if(slicerState.targets.length){
        slicerTargets = slicerState.targets;

        $.each(slicerTargets, function(i, t){
            if(t.table && t.column){
                target += ' (' + t.table + ' / ' + t.column + ') ';
            }
        });
    }

    var slicerName = slicerState.displayName || 'Unnamed';
    var slicerLabel = $('<label>').text('Name: ' + slicerName);
    slicerContainer.append(slicerLabel);
    slicerContainer.append('<br/>');

    var slicerLabelT = $('<label>').text('Target: ' + target);
    slicerContainer.append(slicerLabelT);
    slicerContainer.append('<br/>');

    var input = document.createElement('input')
    input.id = 'slicer_' + index
    input.type = 'text'
    slicerContainer.append(input);
    input.setAttribute('value', slicerVal);

    slicerContainer.append('<br/></hr><br/>');
    slicerContainer.addClass('showBox');
}

function applyFilter(){
    var updatedSlicers = [];

    // Iterate through each slicer and collect the updated values
    console.log('visSlicerStateArr', visSlicerStateArr, visSlicerStateArr.length);
    $.each(visSlicerStateArr, function(index, slicerState) {
        // Get the updated values entered by the user
        var userInput = $('#slicer_' + index).val();
        var selectedValues = userInput.split(',').map(function(value) {
            return value.trim();  // Remove any leading/trailing spaces
        });

        if(selectedValues != ''){

            // Create a new slicer state with updated values
            var newSlicerState = {
                ...slicerState,
                filters: [{
                    ...slicerState.filters[0],
                    values: selectedValues  // Update with user-selected values
                }]
            };

            // Add to the updated slicer array
            updatedSlicers.push(newSlicerState);
        }
    });

    // Apply the updated slicers to the report
    if(updatedSlicers.length){
        applySlicers(updatedSlicers);
        slicerContainer.removeClass('showBox');
    }
}

function applySlicers(updatedSlicers) {
    $.each(updatedSlicers, function(index, slicerState) {
        visSlicerArr[index].setSlicerState(slicerState)
        .then(function() {
            console.log('Slicer updated:', slicerState.displayName);
        })
        .catch(function(err) {
            console.log('Error updating slicer:', err);
            console.log(updatedSlicers);
        });
    });
}
</script>

And the output looks like this:

enter image description here

Its working too, but I am confused with the Powerbi Slicers and Filters. As I checked in general language Slicers working on the user end while Filters are working on the server end.

Following are my questions, please help me to find out the right one:

  1. For my use case, which one is more useful: Slicers or Filters?
  2. Is there any Rest API available to get the Slicers and Filters of a report?
  3. How to get the Slicers name, is it available on Powerbi or possible to fetch, so user can identify easily?
  4. If there are no pre data selected in the filter box in the report, then the JavaScript object of Slicer is not same. Can I get the same object in any case if data is selected or not?

enter image description here

  1. If there are any Powerbi library or code sample to achieve same, please suggest me.

Thanks,

How do I externally reset the state of a controlled downshift component

I have a downshift typeahead component that allows a user to select options from a dropdown that will autocomplete the rest of the fields in the form using react-final-form. If the user input is not present in the pre-existing mortgagees, there will be an option to create a new object and enter a sort of “creating mode”

Example:

const ComboBox = ({
  ...exampleProps,
  value = '',
  isCreating = false,
}) => {
  const [selectedItem, setSelectedItem] = useState(null);   // CONTROLLED STATE
  // ... other state / initial declarations

  useEffect(() => {
    if (value === '' && !isCreating) {
      setSelectedItem(null);
      selectItem(null);
    }
  }
}

This useEffect is primarily utilized by a “reset” button in the parent component that calls react-final-form‘s form.restart() and calls setIsCreating(false)

This works perfectly fine in every case but one:
if the user is creating they can type to change the input value and reset the form to their heart’s content. They can also backspace their input until it is equal to ” while STILL being in that creating state. This is desired.

The problem is that now the input value is equal to '', and thus the useEffect will not be called and the internally controlled selectedItem will not be reset when the user clicks the reset button.

Here is the stateReducer for reference:

    switch (type) {
      case useCombobox.stateChangeTypes.InputKeyDownEnter:
      case useCombobox.stateChangeTypes.ItemClick:
      case useCombobox.stateChangeTypes.ControlledPropUpdatedSelectedItem:
      case useCombobox.stateChangeTypes.FunctionSelectItem:
      case useCombobox.stateChangeTypes.InputBlur:
        if (changes?.selectedItem?.creatable) {
          return {
            ...changes,
            inputValue: state.inputValue,
            selectedItem: { ...changes.selectedItem, label: inputValue },
          };
        } else if (changes?.selectedItem && selectionLabelKey) {
          return {
            ...changes,
            inputValue: changes.selectedItem[selectionLabelKey] || '',
          };
        } else return changes;
      case useCombobox.stateChangeTypes.InputChange:
      case useCombobox.stateChangeTypes.InputClick:
        if (changes?.selectedItem?.creatable) {
          return {
            ...changes,
            isOpen: false,
            selectedItem: {
              ...changes.selectedItem,
              label: changes.inputValue,
            },
          };
        } else return changes;
      default:
        return changes;
    }

In onSelectedItemChange is where I am handling the synchronization of downshift state and controlled state. Like I said, this is weird and pretty complicated in my opinion.

The components are pretty complex and specific, so I am using a stateReducer as well as onSelectedItemChange and onInputValueChange.

I cannot seem to utilize these callbacks to actually fix the aforementioned problem. The user cannot backspace themselves into an empty combobox while creating a new option, and expect the form to reset like normal. The internal downshift state is not changed.

Is there a way to remedy this without reinitializing the downshift component entirely?

Coverage in tab network

i was reading about coverage metrics and how can i use it for optimizing my Next or React application by reducing the unused bytes.i think when i wanna start recording the coverage i should start the instrument coverage after loading my page not before loading, and as i understand i should like try to record in each page and interact in it separately,not navigating and interacting with mulitple page or it i will be hard to optimize them all in the same time (plz correct for me if im wrong).

i open home page and i started recording the coverage , the final result is below

as i understand here react-icons/bs 100% is unused but it appears in the coverage as i undestand it should not appear here or it’s ok but i should reduce it , idk how much should i reduce to in %

webpack-internal:///(app-pages-browser)/./node_modules/react-icons/bs
/index.mjs
JS (per block)  6,243,457   6,242,473100%   
webpack-internal:///(app-pages-browser

i tried to see in register page if im using this icon and i found it so what i did is :
instead of only importing it like this directly
import { BsEyeSlash, BsEye } from “react-icons/bs”;

i used dynamic function from next to import it

const BsEye = dynamic(() => import("react-icons/bs").then((mod) => mod.BsEye), {
  ssr: false,
});
const BsEyeSlash = dynamic(
  () => import("react-icons/bs").then((mod) => mod.BsEyeSlash),
  { ssr: false }
);

the result is in the image above is the same ..

React Module not found error when importing addColor component

I’m working on a React project for a university assignment and I’m encountering an error when trying to import the addColor component. Here’s the error message I’m getting:

(modified to include complete error message)

Failed to compile.

Module not found: Error: Can't resolve './components/addColor' in '/my/base/path/my-app/src'
ERROR in ./src/App.js 8:0-45
Module not found: Error: Can't resolve './components/addColor' in '/my/base/path/my-app/src'

webpack compiled with 1 error

(error message at console on chrome)

Uncaught Error: Cannot find module './components/addColor'
    at webpackMissingModule (bundle.js:19:50)
    at ./src/App.js (bundle.js:19:146)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:22:1)
    at fn (hot module replacement:61:1)
    at ./src/index.js (starRating.jsx:18:1)
    at options.factory (react refresh:6:1)
    at __webpack_require__ (bootstrap:22:1)
    at startup:7:1
    at startup:7:1

This error occurs as soon as I add the import statement for the addColor component in my App.js file. The application works correctly when I remove this import and the usage of the component.

Here are my App.js file and component files

(src/App.js)

import React, { useState } from 'react';
import './App.css';
import colorObjList from './services/color-data.json';
import AddColor from './components/addColor';
import ColorList from './components/colorList';
import { v4 } from 'uuid';


function App() {
  const [colors, setColors] = useState(colorObjList);


  const handleDelete = (id) => {
    const newColors = colors.filter(color => color.id !== id)
    setColors(newColors);
  };

  const handleRating = (id, rating) => {
    const newColors = colors.map(color=>{
      if(color.id === id) {
        color.rating = rating
      }
      return color;
    });
    setColors(newColors);
  }

  const handleAddColor = (title, color) => {
    const colorObj = {
      id: v4(),
      title,color,rating:0
    }
    const newColors = [...colors, colorObj]
    setColors(newColors);
  }

  return (
    <div className="App">
      <h1>This is my Color List</h1>
      <AddColor handleSubmit={handleAddColor}/>
      <ColorList
      colors={colors}
      onDelete={handleDelete}
      onRate={handleRating}
      />
    </div>
  );
}

export default App;

(src/components/colorList.jsx)

import React, { Component } from 'react';
import ColorElement from './colorElement';

const ColorList = ({colors, onDelete = f => f, onRate = f => f}) => {
    if (colors.length === 0 ) {
        return (<div><p>There are no colors display.</p></div>);
    }

    return (
        <div>
            {
                colors.map(color =>
                    <ColorElement
                    color={color}
                    onDelete={onDelete}
                    onRate={onRate}
                    />
                )
            }
        </div>
    );
}
 
export default ColorList;

(src/components/colorElement.jsx)

import React from 'react';
import {FaTrash} from 'react-icons/fa';
import StarRating from './starRating';

const ColorElement = ({color, onDelete = f => f, onRate = f => f}) => {
  return (
    <div>
      <h3>{color.title}</h3>
      <FaTrash onClick = {() => onDelete(color.id)}/>
      <div style={{height:50, backgroundColor: color.color}}/>
      <StarRating
      selectedStars={color.rating}
      onRate={(rating) => onRate(color.id, rating)}
      />
      <p>{color.rating} stars of 5</p>
    </div>
  );
}
 
export default ColorElement;

(src/components/starRating.jsx)

import React, { Component } from 'react';
import Star from './star';

const StarRating = ({totalStars=5, selectedStars=0, onRate = f => f}) => {
    return (
        <>
        {
            [...Array(totalStars)].map((n, i) =><Star 
            index={i}
            isSelected={i < selectedStars}
            onRate={() => onRate(i+1)}
            />)
        }
        </>
    );
}
 
export default StarRating;

(src/components/star.jsx)

import React, { Component } from 'react';
import {FaStar} from 'react-icons/fa';

const Star = ({index, isSelected, onRate = f => f}) => {
    return (
        <>
        {
            <FaStar color={isSelected?"red":"gray"} onClick={onRate} />
        }
        </>
    );
}
 
export default Star;

(src/components/addColor.jsx)

import React, { useState } from 'react';

const AddColor = ({handleSubmit = f=> f}) => {
    const [title, setTitle] = useState("");
    const [color, setColor] = useState("#000000");
    const submit=(e) => {
        e.preventDefault();
        handleSubmit(title, color);
        setTitle("");
        setColor("#000000");
    }

    return (
        <div>
            <form onSubmit = {submit}>
                <input 
                type="text"
                placeholder="Add the color title"
                value={title}
                onChange = {(e) => setTitle(e.target.value)}
                required
                />
                <input type="color"
                value={color}
                onChange = {(e) => setColor(e.target.value)}
                required/>
                <button>Add Color</button>

            </form>
        </div>
    );
}
 
export default AddColor;

My project structure looks like this:

src
├── App.js
├── components
│   ├── addColor.tsx
│   ├── colorElement.jsx
│   ├── colorList.jsx
│   ├── star.jsx
│   └── starRating.jsx
...

I’ve confirmed that the addColor.jsx file exists in the components folder. The other components in the same folder are importing correctly.

What could be causing this “Module not found” error, and how can I resolve it?

When using @tomjs/vite-plugin-vscode, blank page is shown, but only in dev mode

I’m using @tomjs/vite-plugin-vscode to build a VS Code extension with Vue. I started from a WebView Provider, partially following its minimal example.

vite.config.mts:

import pluginVscode from '@tomjs/vite-plugin-vscode';
import pluginVue from '@vitejs/plugin-vue';
import { defineConfig } from 'vite';

export default defineConfig({
  plugins: [
    pluginVscode({
      recommended: true,
    }),
    pluginVue({
      template: {
        compilerOptions: {
          isCustomElement: tag => tag.startsWith('vscode-'),
        },
      },
    }),
  ],
});

The below is my extension code.

index.ts:

import * as vscode from 'vscode';
import { createWebviewProvider } from './webview';

export function activate(context: vscode.ExtensionContext) {
  context.subscriptions.push(
    createWebviewProvider(context),
  );
  const disposable = vscode.commands.registerCommand('oi-runner-2.focus', () => {
    vscode.window.showInformationMessage('Focus!');
  });

  context.subscriptions.push(disposable);
}

webview.ts:

import process from 'node:process';
import * as vscode from 'vscode';

/**
 * @see https://github.com/tomjs/vite-plugin-vscode/blob/v3.0.0/examples/vue/extension/views/helper.ts#L4-L8
 */
function getHtml(webview: vscode.Webview, context: vscode.ExtensionContext) {
  return process.env.VITE_DEV_SERVER_URL
    ? __getWebviewHtml__(process.env.VITE_DEV_SERVER_URL)
    : __getWebviewHtml__(webview, context);
}

class PanelProvider implements vscode.WebviewViewProvider {
  static readonly VIEW_TYPE = 'oi-runner-2.panel';

  constructor(private _context: vscode.ExtensionContext) {}

  resolveWebviewView(webviewView: vscode.WebviewView) {
    webviewView.webview.options = {
      enableScripts: true,
      localResourceRoots: [
        vscode.Uri.joinPath(this._context.extensionUri, 'dist'),
      ],
    };
    webviewView.webview.html = getHtml(webviewView.webview, this._context);
  }
}

export function createWebviewProvider(context: vscode.ExtensionContext) {
  return vscode.window.registerWebviewViewProvider(
    PanelProvider.VIEW_TYPE,
    new PanelProvider(context),
    {
      webviewOptions: {
        retainContextWhenHidden: true,
      },
    },
  );
}

The webview code follows the example.

I expect WebView Provider appears after toggling the command. What is strange, it works fine in production mode, but in dev mode it shows nothing.

Environment:

  • OS: Windows_NT x64 10.0.22631
  • VS Code: 1.94.0 (Node.js 20.16.0)
  • Vite: 5.1.4
  • @tomjs/vite-plugin-vscode: 3.0.0

Unpredictable variable context in Typescript classes

I am trying to create a class in Typescript (React Native) that manages modals in a stack as to not have the modals consume too much memory (use case might not be super important). I am declaring an instance of the class and then pushing and popping from the class. However, when I call the push and pop methods, the stack contents are never what I expect. The ‘this” keyword is never pointing to the correct instance of the class…

I have done some reading up on classes in typescript and followed every suggestion I have found so far. Maybe I am trying to use typescript as if is java and that’s my problem…

Here is my ModalManager class:

type modalData = {
    modalFunction: Function; //Function that loads the modal
    modalParameters: Array<any>; //stack of paramers for function
}
  
class ModalManager {
    private modalMap: Map<string, modalData> = new Map<string, modalData>();
    private defaultView: ReactNode = <View></View>;
    private modalStack: Stack<string> = new Stack<string>([""]);
    private renderCallback: Function;
  
    constructor(renderCallback: Function) {
      this.renderCallback = renderCallback;
      this.setDefaultView = this.setDefaultView.bind(this);
      this.registerModal = this.registerModal.bind(this);
      this.pushModal = this.pushModal.bind(this);
      this.popModal = this.popModal.bind(this);
      this.render = this.render.bind(this);
    }
  
    setDefaultView(defaultView: ReactNode){
      this.defaultView = defaultView;
    }
  
    registerModal(modalName: string, modalFunction: (params: any[], containerModal: ModalManager) => ReactNode){
        if (modalName != "") {
            this.modalMap.set(modalName, {modalFunction: modalFunction, modalParameters: new Array()} as modalData);
        }
    }
  
    pushModal(modalName: string, modalParameters: any){
      //Make sure modal is registered
      if (this.modalMap.has(modalName)) {
        //put modal at top of modal stack
        this.modalStack.push(modalName);
        console.log("1", this.modalStack.peek())
        //put modal parameters in modal parameters stack
        this.modalMap.get(modalName)?.modalParameters.unshift(modalParameters);
        //Cause rerender
        this.renderCallback(modalName);
      }
    }
  
    popModal(){
        console.log("4", this.modalStack.peek())

        if (this.modalStack.peek() != "") {
            this.modalStack.pop()
            console.log("3", this.modalStack.peek())

            this.renderCallback(this.modalStack.peek())
        }
    }
  
    render(currentModal: string){
        console.log("2", this.modalStack.peek())

      return (
        <View>
          <View>
          {(currentModal != "") ? 
            this.modalMap.get(currentModal)?.modalFunction(this.modalMap.get(currentModal)?.modalParameters, this) : <View/>
          }
          </View>
          {this.defaultView}
        </View>
      );
    }
  }

Here is my stack class:

class StackNode<T> {
    next: StackNode<T> | null = null;
    value: T;

    constructor(value: T, next: StackNode<T> | null) {
        this.value = value;
    }
}


class Stack<T> {
    private top: StackNode<T> | null = null;

    constructor(starter: Array<T>) {
        this.push = this.push.bind(this);
        this.pop = this.pop.bind(this);
        this.peek = this.peek.bind(this);

        starter.forEach((item) => {
            this.push(item);
        })
    }

    push(value: T){
        let newTop: StackNode<T> = new StackNode<T>(value, this.top);
        this.top = newTop;
    }

    pop(){
        if (this.top != null) {
            this.top = this.top.next;
        }
    }

    peek(){
        return this.top?.value;
    }
}

And here is my app code:

const [currentModal, setCurrentModal] = useState("");

  const containerModal: ModalManager = new ModalManager(setCurrentModal)

  containerModal.setDefaultView(
    <View>
      <Button title="Open modal 1" onPress={() => {containerModal.pushModal("test", {name: "Eli", value: 10, key: "secret"})}} />
    </View>
  );

  containerModal.registerModal("test", testModalFunction);
  containerModal.registerModal("test2", test2ModalFunction);

  return (
    <View>
      {containerModal.render(currentModal)}
    </View>
  );
};

I have tried changing my methods from this style: () => {}, to the style it is now. I have tried to bind methods that you see present in the code. I really am scratching my head on this one, it seems like a pretty basic thing I’m trying to do.

Thanks for reading if you made it this far.

edit I suspect that it could be due to my render function where I am passing “this” as a parameter to the modal builder function. The modal then calls methods on the “this” that is passed to it and that’s where I’m getting bad behavior. Still not sure how to fix it…

chunk.sortModules is not a function when running yarn run encore production in symfony project

i Just run $yarn run encore production

i have this error:

TypeError: chunk.sortModules is not a function
at /var/www/ppd2_orientation-paysdelaloire_f/livraisons/symfony/node_modules/@symfony/webpack-encore/node_modules/extract-text-webpack-plugin/dist/index.js:188:19

My package.json file:

   {
        "devDependencies": {
        "@babel/cli": "^7.25.7",
       "@babel/core": "^7.25.8",
       "@babel/preset-env": "^7.25.8",
       "@fortawesome/fontawesome-free": "^5.2.0",
       "@symfony/webpack-encore": "^0.20.1",
       "webpack": "^2.7.0"
   },
    "license": "UNLICENSED",
    "private": true,
    "scripts": {
        "dev-server": "encore dev-server",
        "dev": "encore dev",
        "watch": "encore dev --watch",
        "build": "encore production"
    },
    "dependencies": {
        "@babel/polyfill": "^7.0.0",
        "autocomplete.js": "^0.31.0",
        "babel": "^6.23.0",
        "babel-core": "^6.26.3",
        "babel-loader": "7",
        "babel-preset-env": "^1.7.0",
        "babel-preset-stage-3": "^6.24.1",
        "canvg": "^1.5.3",
        "foundation-sites": "6.5.3",
        "highcharts": "^6.1.1",
        "instantsearch.js": "^2.10.*",
        "jquery-validation": "^1.18.0",
        "leaflet": "^1.3.4",
        "leaflet-omnivore": "^0.3.4",
        "leaflet.markercluster": "^1.4.1",
        "moment": "^2.22.2",
        "motion-ui": "^2.0.3",
        "mustache": "^3.0.1",
        "npm": "^6.1.0",
        "ol": "^5.2.0",
        "select2": "^4.1.0-rc.0",
        "slick-carousel": "^1.8.1",
        "svgtodatauri": "^0.0.0",
        "webpack-jquery-ui": "^1.0.0",
        "yarn": "^1.21.0"
    }
}

my webpack.config.js file:

var Encore = require('@symfony/webpack-encore');

Encore
// the project directory where all compiled assets will be stored
.setOutputPath('public/build/')

// the public path used by the web server to access the previous directory
.setPublicPath('/build')

// will create public/build/app.js and public/build/app.css
.addEntry('app', './assets/js/app.js')

// allow legacy applications to use $/jQuery as a global variable
.autoProvidejQuery()

// enable source maps during development
.enableSourceMaps(!Encore.isProduction())

// empty the outputPath dir before each build
.cleanupOutputBeforeBuild()

.configureBabel(function(babelConfig) {
    // add additional presets
    babelConfig.presets.push('stage-3');
    babelConfig.presets.push('env');

    // no plugins are added by default, but you can add some
    // babelConfig.plugins.push('styled-jsx/babel');
})

// create hashed filenames (e.g. app.abc123.css)
// .enableVersioning()

// allow sass/scss files to be processed
// .enableSassLoader()
;

// export the final configuration
module.exports = Encore.getWebpackConfig();

thank you for your help

JavaScript Dropdown Menu animation is buggy

I’m working on a website built with Mura. The header contains multiple dropdown menus that, in theory, fade in and out as you hover over them with the mouse. The code for this functionality is as follows (written in JavaScript):

$('.mura-megamenu li.dropdown).hover(function() {
    $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
  }, function() {
    $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
})

The fadeIn works fine. But whenever the mouse moves away, it doesn’t fade away; it hangs for a moment before disappearing without any fade.

It’s also incredibly jarring because the different dropdowns are layered on top of each other (dropdowns on the left of the header are “beneath” dropdowns on the right), so if you move from a dropdown on the right to the left, the left dropdown fades in beneath the dropdown on the right, defeating the purpose of the animation entirely.

Anyone know of any fixes for this? I would think the above code would work just fine. I’ve also added console.log() statements for hover and unhover, which register as intended.

How to count documents created within specific month or year using createdAt field in mongoDB?

I’m building an admin dashboard and i want to count users created in given month or year. I’m using the countDocuments() method with the query param “createdAt” but the result is 0 and i’m expecting a result of 2.

Here is the code:

const currentMonth = new Date().getMonth();
const currentYear = new Date().getFullYear();

const newClientThisMonth = await User.countDocuments({
    createdAt: { $eq: currentYear },
});

The “newClientThisYear” variable is returning 0 instead of 2. I know i’m using the countDocuments() method in the wrong way with this field but with other fields like the “role” field everything is working fine.

const clientUsersCount = await User.countDocuments({ role: "user" });

So, how will you do it if it was you ?

Console.log no longer printing statements to the console. How to re-enable? [duplicate]

I know this may seem like a basic question but historically I have been able to put this statement into the Chrome Developer tools:

console.log("test");

and the console would then print

test

I don’t know what’s changed, but when I write console.log("test"); now it just writes out undefined. I have verbose enabled and preserve logs checked in the chrome developer tools. I understand that console.log is expected to return undefined, but it was a pretty nice quality of life feature for debugging to actually log the printed statement to the console. I don’t know why they would get rid of this. Is there any way to re-enable printing the actual logged statements instead of the result of the function for console.log in chrome dev tools?

Version: 130.0.6723.59

How to create a Sankey diagram in R where node colors are consistent for providers across different phases of a healthcare pathway?

I am working on a project where I need to visualize the flow of healthcare providers across different phases of a care pathway using a Sankey diagram in R. Each phase represents a step in the care process, and various providers are involved in each phase.

I would like to ensure that each provider is consistently colored throughout the diagram. That means if a provider appears in multiple phases (both as a source and a target), it should have the same color across all instances.

I have already managed to create a Sankey diagram using networkD3::sankeyNetwork, and I can assign colors, but I haven’t figured out how to make sure that the same provider gets the same color in every phase of the care process.

Here’s a simplified version of the code I am working with:

library(dplyr)
library(readxl)

# Load data
data <- read_excel("healthcare_data.xlsx", sheet = "Sheet1")

# Create nodes and links
providers <- unique(c(data$Phase_Provider, data$Next_Phase_Provider))

nodes <- data.frame(name = providers)

links <- data %>%
  mutate(source = match(Phase_Provider, nodes$name) - 1,
         target = match(Next_Phase_Provider, nodes$name) - 1) %>%
  group_by(source, target) %>%
  summarise(value = n()) %>%
  ungroup()

# Assigning the same color to all nodes for now
nodes$color <- "#1f77b4"

# Create the Sankey diagram
sankeyNetwork(Links = links, Nodes = nodes, Source = "source", Target = "target",
              Value = "value", NodeID = "name", fontSize = 12, nodeWidth = 30)

What I want to achieve:

  • Each healthcare provider (identified by Phase_Provider or
    Next_Phase_Provider) should have the same color in all phases (nodes)
    where they appear.
  • The color assignment should be based on the
    provider’s name, so every instance of the same provider across
    different phases will always appear in the same color.

Questions:

  1. How can I assign colors to nodes based on the provider’s name and ensure that the same provider is colored consistently across different phases?
  2. Is there a way to map a unique color to each provider using d3.scaleOrdinal() or another method in R?

Any help or guidance on how to achieve this would be greatly appreciated!

How to Upload a Video Files Template in GrapesJS?

I’m working with GrapeJS for a project and have successfully implemented custom image upload functionality using the tag. Now, I need to do something similar for videos. Specifically, I want to:

Add a video template (like a tag) to the editor.
Allow users to upload a video file and set the video source dynamically.
Ensure the video appears in the GrapeJS canvas after upload (just like how an image would appear with the tag).
My question is: how can I upload the video template itself, so users can interact with it within the GrapeJS editor?
Is there a built-in way or plugin to achieve this in GrapeJS? If not, can you suggest a custom solution for adding video components with upload functionality in GrapeJS?

Any guidance or examples would be appreciated!
https://grapesjs.com/demo this link
[![enter image description here]enter image description here

I am trying to implement a feature where a video tag can be dragged to a specific area. When the user clicks on the video frame, a file upload dialog opens, allowing them to select a video file (e.g., MP4). After selecting the file, I want to convert it to Base64 format and set the src attribute of the video tag to this Base64 string

My question is: how can I upload the video template itself, so users can interact with it within the GrapeJS editor?

Uncaught TypeError: ‘append’ called on an object that does not implement interface URLSearchParams

I am trying to make a php page with pagination function by first submitting a form and then updating the area with a page click function. The Form that will be submitted is like this:

<form class="row g-3" name="search" id="search" method="POST" action="">
    <div class="row g-3 align-items-center">
      <div class="col-sm-3"><label for="departmentSer" class="col-form-label">Select Department:</label></div>
      <div class="col-sm-8">
        <select class="form-select" name="departmentSer" id="departmentSer" aria-label="Default select example">
          <option>Choose1</option>
          <option>Choose2</option>
          <option>Choose3</option>
        </select>
      </div>
      <div class="col-sm-3">
        <button type="submit" class="btn btn-primary" id="lddeptSecSub" name="lddeptSecSub" value="lddeptSearch" onclick="submitFormSea(this.value, 'departmentSer')">Get List</button>
      </div>
    </div>
</form>

And Following is the HTML area where the result from the ajax query will be updated:

<div class="align-items-center mt-4" id="formShowData" name="formShowData"> </div>
    </div>

The Pagination links are generated like this:
<a class="page-link" href="?areac=lddeptSearch&amp;place=Choose...&amp;dsource=listData&amp;page=1" onclick="submitClick(this)">1</a>

This area is first updated with with a form submit. And then replaced when the pages are clicked. The following jQuery is doing the function:

function jajax_qview(datas, field) {
  var request = $.ajax({
    url: "ajax_areac.php",
    method: "POST",
    data: datas,
    cache: false,
    dataType: "html",
  });

  request.done(function( msg ) {
      $('#'+field).html(msg);
  });
 
  request.fail(function( jqXHR, textStatus ) {
    console.log(datas);
    alert( "Request failed: " + textStatus );
  });
  
  request.always(function() {
    datas = undefined;
  });
}

function submitForm(formNameS, elemIdVal) {
  event.preventDefault();
  var datas = {areac:formNameS, place : $('#'+elemIdVal).val()};

  jajax_qview(datas, 'formS');
}

function submitClick(submitLinkVars) {
  event.preventDefault();
  var searchParams = new URLSearchParams(submitLinkVars.search);
  var datas = searchParams;
  jajax_qview(datas, 'formS');
}

Now the problem is that the function “submitForm” is working perfectly fine, when submitting is generation the required data without any error. But when the page number are clicked, the function submitClick is submitted but I am getting the error “Uncaught TypeError: ‘append’ called on an object that does not implement interface URLSearchParams.”
And the variable datas that is generated by the function is “submitClick” is URLSearchParams(4) { areac → "lddeptSearch", place → "7", dsource → "listData", page → "2" }

I have tried with ajax parameters processData: false,contentType: false,. When trying with this option, no data is submitted by the ajax method to the php file. And when trying with dataType: "json" I am getting error Request failed: parsererror.

So, how to solve the problem and submit the data when clicking on the page links.