How to use the default font size selector with custom Quill toolbar?

The normal/default Quill editor uses this kind of size editor:

Picture of the quill.js editor's size dropdown

I am building a custom toolbar using the tools provided by Quill. That looks like this:

        const toolbarOptions = [
            [
                { font: ['Lato,sans-serif'] },
            ],
            ['size'],
            ['bold', 'italic', 'underline'],
            ['link'],
            ['clean'],
        ];

If I alter the ‘size’ array to be [{ size: ['10px', '12px' ... }] etc, the dropdown ends up looking like this:

custom quilljs dropdown with the word 'normal' for all sizes

How can I use the default size that comes with the editor in a custom configuration of options?

Javascript automation — submitting form does not use updated input textfield values

I am writing a Javascript function to set the date-range on a TradingView chart. Javascript is run from Chrome console (or as a snippet).

Here’s the setup:

enter image description here

  • I click the GoTo icon to the right of the ‘TimeIntervals’ tray (which is under the chart)

enter image description here

  • I click ‘Custom Range’ tab on the popup

enter image description here

(Note that if I had not selected something like ‘1 minute’ for the time-granularity, those 2 time boxes would be greyed out).

Now my challenge is to use Javascript to fill in those 4 input boxes and hit the GoTo button.

I can set text on the input boxes with:

    $($('#overlap-manager-root > div input')[0]).val(startDate);
    $($('#overlap-manager-root > div input')[2]).val(endDate);
    $($('#overlap-manager-root > div input')[1]).val(startTime);
    $($('#overlap-manager-root > div input')[3]).val(endTime);

… and click the ‘goto’ button with:

$('#overlap-manager-root > div button')[1].click();

The problem is that the values I injected are not used.

I don’t even need to write code to replicate the problem.

I can just mauaally edit the value of one of the input-boxes in Chrome DevTools and click the ‘GoTo’ button, and I get the same thing.

So the question is: How to force the form to “update” with the new input-box values before submitting it?

Is there some did_change() event on an input box that I need to invoke?

I’ve tried $($('#overlap-manager-root > div input')[1]).trigger('click'); but that didn’t do it.


PS Initially I tried to track down the API function that executes when the submit button is pressed — that would be a cleaner solution. But that rabbitholed and I gave up on that approach.

PPS Complete code below automates everything (except for setting the time-interval to 1-minute, which still needs to be done manually).

async function goToDateRange(startDate = '2022-02-01', startTime = '14:00', endDate = '2022-02-03', endTime = '15:00') {
    console.log(startDate, startTime, endDate, endTime);

    function delay(func, ms) {
        return new Promise(res => {
            setTimeout(() => {
                func();
                res();
            }, ms);
        });
    }

    function clickDivElement(attr, value) {
        var divs = $('div');
        divs.each(function(idx) {
            var d = $(divs[idx]);
            if (d.data()[attr] !== value) {
                return;
            }
            d.click();
        });
    }
    clickGoTo = () => clickDivElement('name', 'go-to-date');
    clickCustomRange = () => clickDivElement('value', 'CustomRange');
    clickGoToButton = () => $('#overlap-manager-root > div button')[1].click();
    await delay(clickGoTo, 500);
    await delay(clickCustomRange, 1000);
    // Set the values of the start date and end date
    $($('#overlap-manager-root > div input')[0]).val(startDate);
    $($('#overlap-manager-root > div input')[0]).trigger('click');
    $($('#overlap-manager-root > div input')[2]).val(endDate);
    $($('#overlap-manager-root > div input')[2]).trigger('click');
    // Set the values of the start time and end time
    $($('#overlap-manager-root > div input')[1]).val(startTime);
    $($('#overlap-manager-root > div input')[1]).trigger('click');
    $($('#overlap-manager-root > div input')[3]).val(endTime);
    $($('#overlap-manager-root > div input')[3]).trigger('click');
    await delay(clickGoToButton, 3000);
};

Get the coordinate of click inside iframe (pdf)

I display pdf documents in an iframe on my website (all documents are stored in the same domain).

I would like users to be able to click in the document to add comments at a specific location.
To do this, I am looking for a way to get the coordinate inside of an iframe (when we click).

It does not seem possible… However, there are paid solutions that offer this kind of functionality. Example : https://pdfjs.express/demo
So, what process is used?

Thanks for you help.

How to calculate the average of all object properties without specifying them explicitly by name?

I’m trying to figure out a robust way to calculate the average of object properties in case there are too many to be specified explicitly by their name.

I found this nice gist that helps in case we have just a few properties:

const someData = 
[   
    { height: 176, weight: 87 },
    { height: 190, weight: 103 },
    { height: 180, weight: 98 } 
]

// for height
var sumHeight = (prev, cur) => ({height: prev.height + cur.height});
var avgHeight = someData.reduce(sumHeight).height / someData.length;
console.log(avgHeight); // => gives 182

// for weight
var sumWeight = (prev, cur) => ({weight: prev.weight + cur.weight});
var avgWeight = someData.reduce(sumWeight).weight / someData.length;
console.log(avgWeight); // => gives 96

But this method is limited in terms of scaling if we have lots of properties, for example:

const someDataExtended = 
[   
    { height: 176, weight: 87, salary: 100000, age: 20, numOfCats: 2 },
    { height: 190, weight: 103, salary: 100050, age: 40, numOfCats: 0 },
    { height: 180, weight: 98, salary: 20345, age: 50, numOfCats: 1 } 
]

How can I average across all properties without specifying them by name? Ideally, I’d like to map over someDataExtended without mutating the initial data, but rather generate a summary such as:

const finalSummary = {
    height: 182,
    weight: 96,
    salary: 73465,
    numOfCats: 1
}

Postgres querying related performance question? I am querying from three different tables and merging result

I am creating an API for my Instagram clone app. I am using a postgres database with knexjs.

I have four tables for my app i.e. users, posts and likes.

I am building a profile page where user info is displayed. Profile page will display info from all the tables.

My question is whether making five separate queries to the database affect loading times of the profile page? I will be making Count, group by etc. queries that can not be merged or joined together.

Or is there any other alternative that won’t affect the performance or the loading times?

Here is my route code: –

router.get('/:id', async (req, res) => {
    const userID = req.params.id;

    //Get the profile info from the db
    const profile = await getUserInfo(userID);
    
    if (profile.length === 0) {
        return res.json({
            errors: "No user found!"
        })
    }

    //Get last 9 created post ordered by creation date in DESC order
    const posts = await getUserPosts(userID)
    //Get posts count 
    const count = await getUserPostCount(userID)

    return res.json({
        profile: profile[0],
        posts,
        postCount: count[0].count
    }).status(201);
})

You can see there are three constants profile, posts and count which are making individual queries. Is that okay?

My full source code is here: – https://github.com/ajaybirbal/photogram-backend/blob/main/routes/profile.js

TS2684: The ‘this’ context of type ‘this’ is not assignable to method’s ‘this’ of type ‘HTMLInputElement’

I’m using typescript 4.5.5

Maybe my understanding of TS isn’t that great.
I’m using arrow functions to create listeners for my elements. I would assume the context of this to be always set to the same context as the caller and not the callee.

class MyClass {
    someProperty: boolean = true;

    // Ommited
    constructor() {
        this.myButton = document.createElement("input");

        // this.myButton is of type HTMLInputElement
        if (this.myButton) this.myButton.addEventListener("click", (e) => {
            ***this***.someProperty
            // TS2684: The 'this' context of type 'this' is not assignable to method's 'this' of type 'HTMLInputElement'
        });

        this.myDiv = document.getElementById("myDiv");

        // this.myDiv is of type HTMLElement
        if (this.myDiv) this.myDiv.addEventListener("click", (e) => {
            this.someProperty
            // this is correctly set to MyClass
        });
    }
}

I’m pretty sure that’s the way I’ve been doing it for a couple of years now

  • this.myDiv listener signature listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => any
  • this.myButton listener signature listener: (this: HTMLInputElement, ev: MouseEvent) => any

Is there a valid reason why TS tries to assign this as MyClass to this as HTMLInputElement inside the listener?

Type 'MyClass' is missing the following properties from type 'HTMLInputElement': accept, align, alt, autocomplete, and 331 more.

Changing the Output Folder in canvas-sketch doesn’t work

I’ve just tried to set up canvas-sketch. I need to see my output files and this instruction didn’t work. Any opinion?
My steps of installing and changing the default output folder:
npm install canvas-sketch-cli -g ; mkdir my-sketches ;cd my-sketches; canvas-sketch sketch-01.js --new --open
and then for changing default folder(actually I didn’t even find the default folder):canvas-sketch sketch-01.js --output=output/01
There is no error btw.

JavaScript: Why is request.method not cloned when copying a request

MDN says you can pass in a request to new Request() to make a copy of it::

A Request object, effectively creating a copy

However that is not the behavior I see when testing, here I am trying to “clone with a modified body” the request object, which is an intercepted request from a service worker fetch:

request.method
'POST'
x = new Request(request)
Request {method: 'GET', url: 'http://127.0.0.1:8000/[object%20Object]', headers: Headers, destination: '', referrer: 'about:client', …}
x.method
'GET'

As you can see the .method is not copied (was POST now GET). This makes me wonder how much is actually “cloned”? I could force the method property, but then what else needs to be forced? It tell me I don’t understand how it works.

Heres my code that doesnt work because of the above behavior

export async function updateCSRFTokenInPOSTRequestBody(csrfToken, request) {
    // When performing a sync, the user may have logged out/logged in again, and hence fail csrf check
    const body = request.body.replace(/(?<=csrfmiddlewaretoken=)w+(?=&)/, csrfToken);
    const init = {
        body: body,
    };
    const newRequest = new Request(request, init);
    return newRequest;
}

The error it gives is (which is understandable because of the above behavior):

VM18:1 Uncaught TypeError: Failed to construct 'Request': Request with GET/HEAD method cannot have body.

node.JS Express passport stuck in infinte loop on auth check

My node.JS passport authentification check is stuck in an infinite loop if I return 400 status for requests which are not authentified:

  //ensure authentification
  function authorizeApi(req, res, next) {
    if (req.isAuthenticated()) {
        return next();
    } 
      else res.status(400).json({
        message : "User Not Authenticated",
       user : null
     })
    
}

// retrieve logged in user profile
router.post("/login/success",authorizeApi, (req, res) => {

}

app.use(bodyParser.json({ limit: "50mb", extended: true }));

app.use(bodyParser.urlencoded({ extended: true }));

app.use("/auth", authRoutes);

If I return only the profile for users which are authentificated I get a request from the client which remains in pending…

React conditional Rendering isn’t working on server

I want to uncheck input if the item status is false. it’s working fine in my localhost. But it’s not working after deploying to the server.

{data.map((item) => (
  <tr key={item.id}>
  <td>{item.name}</td>
  <td>{item.body.slice(0, 90)}</td>
  <td>
      {item.status === 1 ?
          <Form.Check
              type="switch"
              id="custom-switch"
              checked
          /> :
          <Form.Check
              type="switch"
              id="custom-switch"
          />
  }
  </td>
  <td>{item.author.username}</td>
  <td>
      <Link to={`/admin/categories/view/${item.id}`} style={{ paddingRight: "12px" }}> <FaEye
          style={{ fontSize: "22px", color: "#071337", cursor: "pointer" }} /></Link>
      <span onClick={() => deleteHandler(item.id)} style={{ paddingRight: "12px" }}><TiDelete
          style={{ fontSize: "22px", color: "#c0392b", cursor: "pointer" }} /></span>
      <Link to={`/admin/categories/edit/${item.id}`} style={{ paddingRight: "12px" }}> <FaEdit
          style={{ fontSize: "22px", color: "#f39c12", cursor: "pointer" }} /></Link>
  </td>
  </tr>
))}

enter image description here

how to get upcoming time in from the list of time?

I am building a website using create-react-app and I need to get the upcoming time from the list as compared to the current time.
my time list is

  let times = [
    {
      time: "05:33",
    },
    {
      time: "12:20",
    },
    {
      time: "15:23",
    },
    {
      time: "17:46",
    },
    {
      time: "19:08",
    },
  ];

I have tried many solutions but all in vain, one solution that is also unsuccessful is

  const compareTime = moment().format("hh:mm");
  time7.map((item, i) => {
    console.log(
      Date.parse(
        `01/01/2011 ${format(parse(item.time, "HH:mm", new Date()), "hh:mm")}45`
      ) > Date.parse(`01/01/2011 ${compareTime}:10`)
    );
  });

I am super stuck in this and trying to solve this problem for almost a week I need a proper solution to get the upcoming time from the list any kind of help will be appreciated.

Check whether the user has a valid credentials Jira rest API

I am using jira-client npm module to make API calls on my jira instance, I want to check that if the user has a valid credentials before doing anything else, depending on that I would either:

  • Tell the user that they don’t have a valid username or token.

  • or Let the user use the project functionalities

is that possible? I am able to make calls and with invalid credentials I will got response with a special message, but I want to know if there is a specific call for checking username and token.