Inject CSS styles to shadow root

I’m creating a Shadow DOM in a preact project and then injecting style element into Shadow root like this:

import style from "./layout/main.css";

loader(window, defaultConfig, window.document.currentScript, (el, config) =>
{
    const shadowHost = document.querySelector('#widget-_hw');
    shadowHost?.attachShadow({ mode: 'open' });
    const shadowRoot = document.querySelector('#widget-_hw')?.shadowRoot
    const renderIn = document.createElement('div');
    const styleTag = document.createElement('style');
    styleTag.innerHTML = style;
    shadowRoot?.appendChild(styleTag); 
    renderIn.setAttribute('id', 'render-div');
    shadowRoot?.appendChild(renderIn);
    render(h(App, { ...config, element: el }), renderIn)
}
);

When I do console.log(style), I’m getting the all CSS classes as shown in the image below but when I print console.log of shadow root

style element comes like this:

<Style>[object object]<Style>

You can see screenshot for further reference.

My Webpack configuration is like this:

enter image description here

module: {
      rules: [
        // packs SVG's discovered in url() into bundle
        { test: /.svg/, use: 'svg-url-loader' },
        {
          test: /.css$/i,
          use: [
            {
              loader: 'style-loader',
              options: { injectType: 'singletonStyleTag' }
            },
            {
              // allows import CSS as modules
              loader: 'css-loader',
              options: {
                modules: {
                  // css class names format
                  localIdentName: '[name]-[local]-[hash:base64:5]'
                },
                sourceMap: isDevBuild
              }
            }
          ]
        },



Can someone help me find a solution to the problem?

Quasar QSelect is not opening when performing AJAX call

I have been trying to create a simple auto complete using Quasar’s select but I’m not sure if this is a bug or if I’m doing something wrong.

Problem

Whenever I click the QSelect component, it doesn’t show the dropdown where I can pick the options from.

video of the problem

As soon as I click on the QSelect component, I make a request to fetch a list of 50 tags, then I populate the tags to my QSelect but the dropdown doesn’t show.

Code

import type { PropType } from "vue";
import { defineComponent, h, ref } from "vue";
import type { TagCodec } from "@/services/api/resources/tags/codec";
import { list } from "@/services/api/resources/tags/actions";
import { QSelect } from "quasar";

export const TagAutoComplete = defineComponent({
  name: "TagAutoComplete",
  props: {
    modelValue: { type: Array as PropType<TagCodec[]> },
  },
  emits: ["update:modelValue"],
  setup(props, context) {
    const loading = ref(false);

    const tags = ref<TagCodec[]>([]);

    // eslint-disable-next-line @typescript-eslint/ban-types
    const onFilterTest = (val: string, doneFn: (update: Function) => void) => {
      const parameters = val === "" ? {} : { title: val };

      doneFn(async () => {
        loading.value = true;
        const response = await list(parameters);

        if (val) {
          const needle = val.toLowerCase();
          tags.value = response.data.data.filter(
            (tag) => tag.title.toLowerCase().indexOf(needle) > -1
          );
        } else {
          tags.value = response.data.data;
        }

        loading.value = false;
      });
    };

    const onInput = (values: TagCodec[]) => {
      context.emit("update:modelValue", values);
    };

    return function render() {
      return h(QSelect, {
        modelValue: props.modelValue,
        multiple: true,
        options: tags.value,
        dense: true,
        optionLabel: "title",
        optionValue: "id",
        outlined: true,
        useInput: true,
        useChips: true,
        placeholder: "Start typing to search",
        onFilter: onFilterTest,
        "onUpdate:modelValue": onInput,
        loading: loading.value,
      });
    };
  },
});

What I have tried

I have tried to use the several props that is available for the component but nothing seemed to work.

My understanding is that whenever we want to create an AJAX request using QSelect we should use the onFilter event emitted by QSelect and handle the case from there.

Questions

  • Is this the way to create a Quasar AJAX Autocomplete? (I have tried to search online but all the answers are in Quasar’s forums that are currently returning BAD GATEWAY)
  • What am I doing wrong that it is not displaying the dropdown as soon as I click on the QSelect?

Something Went Wrong => TypeError: Cannot read properties of undefined (reading ‘map’)

so I have just made the help command and wanted to test it out. My problem is that I am getting one single error which I have no idea of how to fix it.

Here is my code:

const { Client, Interaction, MessageActionRow, MessageButton, MessageEmbed } = require("discord.js");

module.exports = {
  name: "help",
  description: "Some Help To User",
  type: "CHAT_INPUT",
  /**
   *
   * @param {Client} client
   * @param {Interaction} interaction
   */
  // just for telling that u can also add options
  execute: async (interaction, client) => {
    try {
      if (!interaction.isCommand()) return;

      await interaction.deferReply().catch((_) => {});

      const dirs = [...new Set(client.slashCommands.map((c) => c.directory))];

      const helpArray = dirs.map((d) => {
        const getCmd = client.slashCommands
          .filter((c) => c.directory === d)
          .map((c) => {
            return {
              name: c.name || "No Name",
              description: c.description || "No Description",
            };
          });
        return {
          name: d,
          commands: getCmd,
        };
      });

      // default Page No.
      let pageNo = 1;

      const embed = new MessageEmbed()
        .setColor("WHITE")
        .setThumbnail(client.user.displayAvatarURL({ dynamic: true, size: 4096 }))
        .setAuthor(`Help Command!`)
        .setTimestamp()
        .setFooter(`Page ${pageNo}/${helpArray.length}`);

      const getButtons = (pageNo) => {
        return new MessageActionRow().addComponents(
          new MessageButton()
            .setLabel("Previous")
            .setCustomId("prev")
            .setStyle("SUCCESS")
            .setDisabled(pageNo <= 1),
          new MessageButton()
            .setLabel("Next")
            .setCustomId("next")
            .setStyle("SUCCESS")
            .setDisabled(!(pageNo < helpArray.length)),
        );
      };

      embed.setDescription(`**${helpArray[pageNo - 1].name}**`).addFields(
        helpArray[pageNo - 1].commands.map(({ name, description }) => {
          return {
            name: ``${name}``,
            value: `${description}`,
            inline: true,
          };
        }),
      );

      const intrMsg = await interaction.editReply({ embeds: , components: [getButtons(pageNo)], fetchReply: true });

      const collector = intrMsg.createMessageComponentCollector({ time: 600000, componentType: "BUTTON" });

      collector.on("collect", async (i) => {
        if (i.customId === "next") {
          pageNo++;
        } else if (i.customId === "prev") {
          pageNo--;
        }

        const categ = helpArray[pageNo - 1];

        embed.fields = [];
        embed.setDescription(`**${categ.name}**`).addFields(
          categ.commands.map(({ name, description }) => {
            return {
              name: ``${name}``,
              value: `${description}`,
              inline: true,
            };
          }),
        ).setFooter(`Page ${pageNo}/${helpArray.length}`);

        await i.update({ embeds: , components: [getButtons(pageNo)], fetchReply: true });
      });
    } catch (err) {
      console.log("Something Went Wrong => ", err);
    }
  },
};

and this is the full error I get:

Something Went Wrong =>  TypeError: Cannot read properties of undefined (reading 'map')
    at Object.execute (/Users/Aplex/Documents/Aplel/Commands/Systems/help.js:19:53)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

Can anyone help me with this issue? I would really appreciate it. If you don’t know how to fix but had time to view this, still thank you!

Selected picture and blurry others

I want when click on the img using JS, it will be selected and others will blur out.
That what I’m expect :
enter image description here

enter image description here

Here the code for the HTML :

<section class="choice-grid">
        <div data-choice-id="blepping" data-question-id="one">
          <img src="images/blepdog.jpg"/>
          <img class="checkbox" src="images/unchecked.png"/>
        </div>

        <div data-choice-id="happy" data-question-id="one">
          <img src="./images/happydog.jpg"/>
          <img class="checkbox" src="images/unchecked.png"/>
        </div>

        <div data-choice-id="sleeping" data-question-id="one">
          <img src="./images/sleepingdog.jpg"/>
          <img class="checkbox" src="images/unchecked.png"/>
        </div>

        <div data-choice-id="dopey" data-question-id="one">
          <img src="./images/dopeydog.jpg"/>
          <img class="checkbox" src="images/unchecked.png"/>
        </div>

        <div data-choice-id="burger" data-question-id="one">
          <img src="./images/burgerdog.jpg"/>
          <img class="checkbox" src="images/unchecked.png"/>
        </div>
</section>

Im trying to use target event when click on the img. But I stuck right here and don’t know how to change the attribute of that img tag in the target section.

Here what I’m stuck at :

function getEventTarget(e) {
    e = e || window.event;
    return e.target || e.srcElement; 
  } 

var choice = document.querySelector('.choice-grid');
choice.onclick = function(event) {
    var target = getEventTarget(event);
    

    var test = target.attributes.src;
    // test
    // var test =target.lastChild.src
    alert(test);
}

how to use font awesome in react with map()

I am very new in RectJs and so this may be a very beginner question, However, I have got an array of objects called MyArr like this:

const MyArr =[
   {picture:'faUser' ,  text:'something'},
   {picture:'faUser' ,  text:'something'} ]
export default MyArr

I want to use the value of “picture” in another component to declare which icon from #FontAwesome should be shown.
so I made another component in which I pass that Array of Objects as a props value to the destination, like this

import React, { Component } from 'react'
import MyArr from './MyArr'
import ShowFontAwesome from './ShowFontAwesome'

 class Body extends Component {

  render() {
   return(
        <div>
          <ShowFontAwesome myValue={MyArr} />          
        </div>
)
}}
export default Body

so the component called “ShowFontAwesome” is where I am going to show the result; this is the component’s code

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import * as FontAwesome from '@fortawesome/free-solid-svg-icons';
import React, { Component } from 'react'

 class ShowFontAwesome extends Component {
   constructor(props){
     super(props);}
render() {
    return (
<div>
{this.props.myValue.map(
          (myValues, index)=>{
            return(
<div>
<FontAwesomeIcon icon={`FontAwesome.${myValues.picture}`} />
</div>
)})
</div>
)}}
export default ShowFontAwesome

finally, it logs this error in the console ** could not find icon {prefix: ‘fas’, iconName: ‘FontAwesome.faUser’} **

Disable Typewatch binding when Enter key is pressed

I am using Typewatch jQuery plugin in one of the applications and I have the following code for submitting the form and calling an Ajax request.’

searchForm.on('submit', function(event) {
    if (event) {
        event.preventDefault();
    }
    if (search.data.searchRequest) {
        search.data.searchRequest.abort();
    }
    searchForm.addClass('is-loading');
    search.data['searchStart'] = 0;
    $('#js-postslist--searchpanel').empty();
    $('.js-searchpanel-results').removeClass('is-visible');
    var filterQuery = csUtils.methods.getFilterQuery(true, search.data.terms);
    search.data.searchRequest = search.methods.ajaxCloudSearch(filterQuery);
});

searchField.typeWatch({
    callback: function() {
        return searchForm.submit();
    },
    wait: 500,
    highlight: false
});

Here the issue is, when I press Enter(return) key, the form is getting submitted twice. It is going to the submit function two times as the form has default submit behavior on pressing the Enter key. I can’t remove this as users will press the key once they enter the search term. I need to disable the Typewatch binding when Enter key is pressed so it will not submit the form two times.

How can I do this ?

Radio Input onchange display label innerText in textbox

 <div class="top">
      <label for="locationName">Location:</label>
      <input type="text" class="locationName" id="locationName" maxlength="20" readonly>
 </div>
 <li>
      <input type="radio" id="selected_location_ac" name="selected_location" value="ATLANTIC_CITY" onchange="findSelection('selected_location')">
      <label for="selected_location_ac">Atlantic City</label>
 </li>
 <li>
      <input type="radio" id="selected_location_ac" name="selected_location" value="LAS_VEGAS" onchange="findSelection('selected_location')">
      <label for="selected_location_ac">LAS Vegas</label>
 </li>

JavaScript

function findSelection(rad_name) {
    const locationName = document.querySelector("#locationName");
    let rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
    locationName.value = (rad_val ? rad_val.value : "")
    return (rad_val ? rad_val.value : "");
}

I am trying to get the label value displayed in the input text box.

The person will click a radio button and then the input textbox will display their selection. I don’t want it to show the radio button value since it maybe difficult to understand what it means.

Sequelize: Many to many relationship with two foreign keys

I have two tables related through a relationship table. On the relationship table there are two foreign keys for the same table.

  • Factors
  • Models
  • Models_has_Factors

Models_has_Factors contains foreign keys:

  • ref_models_mhf
  • ref_factors1_mhf
  • ref_factors2_mhf

I want to select models including the factors.
I can’t in any way have an implementation where sequelize returns the correct data without the configuration raw: true, but this returns multiple objects for the same model, which is not ideal. Is there a way to return only one object for each model, with an array of factors associated to them?

I’ll leave my current implementation bellow but I already tried to change the relationship implementation to one using “belongsToMany()” instead but still no luck.

Factor association to models_has_factors

Factors.hasMany(models.models_has_factors, {
    foreignKey: { name: "ref_factors1_mhf" },
    as : "ref_factor1"
  })

  Factors.hasMany(models.models_has_factors, {
    foreignKey: { name: "ref_factors2_mhf" },
    as : "ref_factor2"
  })

Models_has_Factors associations

Models_has_Factors.belongsTo(models.models, {
    foreignKey: { name: "ref_models_mhf" }
  });

  Models_has_Factors.belongsTo(models.factors, {
    foreignKey: { name: "ref_factors1_mhf" },
    as: "factor1"
  });

  Models_has_Factors.belongsTo(models.factors, {
    foreignKey: { name: "ref_factors2_mhf" },
    as: "factor2"
  });

Models

 Models.hasMany(models.models_has_factors, {
    foreignKey: { name: "ref_models_mhf" }
  });

Getter

db.models.findAll({
  where: {
    id_models: id,
  },
  include: {
    model: models.models_has_factors,
    include: [{
      model: models.factors,
      as: 'factor1'
    }, {
      model: models.factors,
      as: 'factor2'
    }]
  }
})

HTML file not reading Javascript file in script

I have the following issue. I have a HTML file called “GUI.html” and I’m trying to load a function from a Javascript file called “guiScript.js” but its only function is not recognized:

Html file:

<body>
    <h1>Selection</h1>
    <script src="guiScript.js"></script>
    <button onclick="obtenerEquipos()">Generar equipos automáticamente</button>
</body>

Javascript file:

import fs from 'fs'

function obtenerEquipos(){
fs.readFile('equipos.txt', 'utf-8', (err, data) => {
    if (err) throw err;
    
    // Converting Raw Buffer to text
    // data using tostring function.
    console.log(data);
})

}

Error log:

Uncaught ReferenceError: obtenerEquipos is not defined
at HTMLButtonElement.onclick (GUI.html:7:44)

Does it have anything to do with the import? I can’t think of anything else really. I’ve already read files this way before and it worked correctly.

Thanks!

I keep getting a Typescript error after upgrading eact-chartjs-2 to a newer version. Can’t figure out what the error means

I started getting the following error when passing data to a react-chartjs-2 chart component after upgrading react-chartjs-2. It was all working fine before the upgrade so I’m not sure what exactly is causing this issue.

TS2322: Type '{ labels: string[]; datasets: never[]; } | ((canvas: HTMLCanvasElement) => { labels: string[]; datasets: DataSet[]; })' is not assignable to type 'ChartData<"line", (number | ScatterDataPoint | null)[], string>'.
  Property 'datasets' is missing in type '(canvas: HTMLCanvasElement) => { labels: string[]; datasets: DataSet[]; }' but required in type 'ChartData<"line", (number | ScatterDataPoint | null)[], string>'.

I’m passing the data like this:

<Line
    data={getDataForChart}
    options={options}
    width={400}
    height={400}
/>

My dataset type looks like this:

type DataSet = {
    label: string;
    data: number[];
    fill: boolean;
    backgroundColor: CanvasGradient | undefined;
    borderColor: string;
    pointRadius: number[];
    pointBackgroundColor: string;
};

And my getDataForChart function looks like this:

const getDataForChart = (canvas: HTMLCanvasElement) => {
        const dateLabels: string[] = [];
        const datasets: DataSet[] = [];
        const chart = canvas.getContext('2d') as CanvasRenderingContext2D;

        if (scores) {
            for (let i = 0; i < assessments.length; i++) {
                dateLabels.unshift(formatWithLocale(assessments[i].userAssessment.finishedAt, 'MM/dd'));
            }

            for (let scoreIndex = 0; scoreIndex < scores.length; scoreIndex++) {
                const values: number[] = [];
                const pointRadius: number[] = [];
                const currentColorIndex = getColorIndex(scoreIndex);

                const transparentColor = colors[currentColorIndex].split(')')[0].concat(', 0.3)');
                const gradient = chart.createLinearGradient(0, 0, 0, 600);

                gradient.addColorStop(0, transparentColor);
                gradient.addColorStop(0.6, transparentBlackColor);

                for (let assessmentIndex = 0; assessmentIndex < assessments.length; assessmentIndex++) {
                    const currentScore = assessments[assessmentIndex].userAssessment.scores?.find(
                        (score) => score.name === scores[scoreIndex].name
                    );

                    if (assessmentIndex === assessments.length - 1) {
                        pointRadius.push(7);
                    } else {
                        pointRadius.push(3);
                    }

                    if (currentScore) {
                        values.unshift(currentScore.score);
                    }
                }

                if (selectedScore && selectedScore.name !== scores[scoreIndex].name) {
                    continue;
                }

                datasets.push({
                    label: intl.formatMessage({
                        id: scores[scoreIndex].name,
                        defaultMessage: scores[scoreIndex].name,
                    }),
                    data: values,
                    fill: true,
                    backgroundColor: gradient,
                    borderColor: colors[currentColorIndex],
                    pointRadius,
                    pointBackgroundColor: colors[currentColorIndex],
                });
            }
        }

        return {
            labels: dateLabels,
            datasets,
        };
    };

how to find the sum of an array between two specific dates in JS [duplicate]

Need to find the sum of allthreshold on 24th date and then sumof all allthreshold on 25th.
eg : “2022-01-24” -> sum-0 ———-> “2022-01-245” -> sum – 0.2
then add both the sum (0+0.2) -> 0.2 is <0.8(constant) return saying false.
If not continues to to check in the other dates of the loop.
“JSON”: [
{
“threshold”: 0.0,
“date”: “2022-01-24”
},
{
“threshold”: 0.0,
“date”: “2022-01-24”
},
{
“threshold”: 0.0,
“date”: “2022-01-24”
},
{
“threshold”: 0.0,
“date”: “2022-01-25”
},
{
“threshold”: 0.0,
“date”: “2022-01-25”
},
{
“threshold”: 0.2,
“date”: “2022-01-25”
},
{
“threshold”: 0.0,
“date”: “2022-01-26”
},
…..continues
]

how to add to alert function the chosen list from dropdown

still very beginner in js…
how to add to alert function the chosen list from dropdown as the sample below ?
thanks!

e.g

enter image description here
enter image description here

var w = new Window ("dialog");
var col = w.add ("edittext", undefined, com[0]);
var list = ['A','-','B','-','C','-','D','-','E'];
var dropdown = w.add ("dropdownlist", undefined, list);  dropdown.selection = dropdown.items[0];
w.show ();

function com(){
   save = "column " + col.text + "+ list"; 
   return save
   }
alert(com());