custom rendered text position not calculated correctly

I’m creating a basic PDF viewer in Vue.js 2 (since the customer does not want to migrate to Vue 3) using PDF.js (latest version of pdfjs-dist).

The loading and rendering of pages is working perfectly fine.

I am now trying to create a search functionality from scratch, since the latest version of PDF.js does no longer include the PDFViewerApplication and find controllers etc.

For the purpose of being able to highlight matched words, I was thinking of creating the text layers on top of the PDF’s canvas. Retrieving the text contents is alright, but the problem here is that the calculation of the desired position for the text is not correct.

I’ve tried using the transform properties from the text items and doing some calculations with it, I’ve tried scaling, doing some custom calculations but it just doesn’t work out.

My 3 latest attempts were the following (by the way I have created a repo in which the problem is reproduced, you can find it here: https://gitlab.com/dante.cassiman/pdf-viewer-bug-reproduction)

1.

      span.style.left =`${item.transform[4] * scale}px`;
      span.style.top = `${(viewport.height - item.transform[5]) * scale}px`;
      span.style.transform = `rotate(${item.transform[0]}deg)`
      span.style.fontSize = `${item.height * scale}px`;
      span.style.left =${item.transform[4] * scale}px;
      span.style.top = ${(viewport.height - item.transform[5]) * scale}px;
      span.style.transform = rotate(${item.transform[0]}deg)
      span.style.fontSize = ${item.height * scale}px;

      span.style.fontFamily = fontMap[item.fontName].loadedName;
      const [scaleX, , , scaleY, translateX, translateY] = item.transform;

      // calculate left and top positions
      const leftPosition = (translateX * scale) + (item.width * scaleX * scale) / scaleX;
      const topPosition = (viewport.height - translateY * scale) - (item.height * scaleY * scale) / scaleY;

      // set the calculated left and top
      span.style.left = `${leftPosition}px`;
      span.style.top = `${topPosition}px`;

      // calculate font size using the actual item height adjusted by scale
      span.style.fontSize = `${item.height * scaleY * (scale / scaleY)}px`; // Scale the font size appropriately

The scale variable comes from the renderPage function, which calculates it like this:

    const scale = canvasEl.offsetWidth / page.getViewport({ scale: 1 }).width * (window.devicePixelRatio || 1);
    const viewport = page.getViewport({ scale: scale, rotation: page.rotate });

It’s all a lot more clear in the Gitlab repo, so please feel free to take a look at it. When you run the app, the red text is the what’s rendered in the text layers and has to appear on top of it’s corresponding text item in the canvas, which it does not.

This is a screenshot of my latest attempt in the repo:
enter image description here

I also just noticed that zooming out the page does not change the size of the canvas (which is perfect for me), but it does zoom out / scale the text layers on top…

Some help would be greatly appreciated!

EDIT: It appears that I am making it way harder than it has to be. The following calculations seem to be working perfectly fine, the only problem now is that the text seems to be rendered bottom to top (if that makes sense) instead of top to bottom. So I assume that I need some sort of transform or inversion of Y coordinate now?

Also, the zooming problem in the browser still persists.

      span.style.left = `${item.transform[4] * scale / 2}px`;
      span.style.top = `${(viewport.height - item.transform[5]) * scale / 2}px`;
      span.style.fontSize = `${item.height * scale / 2}px`;

Cross origin redirect sign-in is no longer supported in many browsers using Firebase here

I am using firebase authentication for my application but when I tried signInWithRedirect() method it gives me the below error.

Cross origin redirect sign-in is no longer supported in many browsers. Update your app to ensure that your users can continue to sign in to your app.

Upon further investigation I got to know that signInWithRedirect() won’t work for my application and instead there were a bunch of different ways to perform the same operation. I opted for signInWithPopup() for obvious reasons.

const googleSignIn = () => {
    const provider = new GoogleAuthProvider();
    signInWithPopup(auth, provider);
}

The reference of the documentation: Best practices for using signInWithRedirect on browsers that block third-party storage access

Is there any workaround for this if I wanna opt for signInWithRedirect() and I don’t wanna handle provider signin independently?

How do I make the set the background to an image in three.js?

Sorry, I’m new to three.js and I know (most) of the basics but somehow I don’t know how to set the background image. I need to set the background image to a space-themed background, because in my website I’m trying to make different worlds for the game. But, the background is just black. I want it to be an image, not a color.

I didn’t try anything because, well, I just don’t know what to do. Need Help!

Conditional background pattern on object in React + Leaflet.js

I have a React app, drawing a map with multiple objects on it. So far I have each GeoJSON object colored using the “style={}” property, however I would like to have a background with some pattern (stripes for example) based on certain condition.

If I try to set any “background:” properties to the style fillColor property – all GeoJSON objects default to grey background.

Is there a way to do this in using Leaflet.js or any other third-party library?

Create continuous date intervals from an unsorted array of dates [closed]

Hello stackoverflow community,

I am currently trying to create a continuous timeline from an array of time periods. My input array looks like this:

$array = [
    0 => [
        'from' => '28.10.2024',
        'to' => '03.11.2024',
    ],
    1 => [
        'from' => '30.09.2024',
        'to' => '06.10.2024',
    ],
    2 => [
        'from' => '04.11.2024',
        'to' => '10.11.2024',
    ],
    3 => [
        'from' => '21.09.2024',
        'to' => '29.09.2024'
    ],
    3 => [
        'from' => '14.10.2024',
        'to' => '20.10.2024',
    ],
];

And the result I’m looking for, is this:

$resultArray = [
    0 => [
        'from' => '21.09.2024',
        'to' => '06.10.2024'
    ],
    1 => [
        'from' => '14.10.2024',
        'to' => '20.10.2024',
    ],
    2 => [
        'from' => '28.10.2024',
        'to' => '10.11.2024',
    ],
];

As hard as I’m trying, I’m unable to find a proper solution. Has anyone an idea how to solve this in PHP or JS?

I tried to iterate in a loop with the creation of auxiliary arrays, but the solution turns out to be too cumbersome.

Using JsObject in an async Function

How do I await a JsObject in dart. I am JavaScript to connect to Microsoft SignalR server, as I did not find any dart packages that support signalR client in Flutter Web. I included https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/8.0.7/signalr.min.js" in my head tag. Then I initialize the connection using

js.JsObject connection
connection= js.JsObject(js.context['signalR']['HubConnectionBuilder'])
        .callMethod('withUrl', [
      url,
    ]).callMethod('build');

final completer = Completer<void>();

    connection.callMethod('start').callMethod('then', [
      () {
        completer.complete();
      },
      (error) {
        completer.completeError(error);
      }
    ]);

The error occurs on the following line of code

final message = JSPromise<JSAny>(await connection.callMethod(
            'invoke', [
          'Send',
          message,"
        ]));

The JSPromise is currently not awaiting the result from my server. How can I ensure that JSPromise await a result from my server?

Render html from database which comes as text in the front end asp.net [closed]

I’m having some value in the database like below – I wanted this html to be rendered which the page is loaded. When I try to do that, it just shows as text instead of actually rendering. I tried many ways including innerHtml, but nothing works. The thing is, if I do this as a static it works, but my requirement is, I’m going to generate this HTML text from backend based on rules. So when I checked in the DeveloperTool, it is quoted with double quotes, so I guess it shows as text only.

Database value

enter image description here

enter image description here
When I load the page, its shown as below (yellow highlighted). Instead I actually needed a link to be rendered.

enter image description here

Developer option – rendering text

enter image description here

push to array index and reduce index having same key

Please help me merge array’s cities whereas the state is same and remove duplicate index. The expecting output is given below

Input array

[
    {
        "state": "delhi",
        "cities": "central delhi"
    },
    {
        "state": "jharkhand",
        "cities": "dumka"
    },
    {
        "state": "jharkhand",
        "cities": "deoghar"
    },
    {
        "state": "jharkhand",
        "cities": "jasidih"
    },
    {
        "state": "karnataka",
        "cities": "bail hongal"
    },
    {
        "state": "ladakh",
        "cities": "kargil"
    }
]

I have tried multiple code but adding this one as i am still trying to get my desired output

arr1.map((row, index) => ({
    itemLabel: arr1.state,
    itemValue: arr1.cities - arr2[index].cities
}))

Need this output

[
    {
        "state": "delhi",
        "cities": "central delhi"
    },
    {
        "state": "jharkhand",
        "cities": ["dumka","deoghar","jasidih"]
    },
    {
        "state": "karnataka",
        "cities": "bail hongal"
    },
    {
        "state": "ladakh",
        "cities": "kargil"
    }
]

Strange issue with exclude and include in tsconfig.json

I have strange issue. When I do

"exclude": [
    "node_modules",
    "**/__tests__",
    "**/*.test.*",
    "**/server-handlers/**/*",
    "**/*.stories.*",
    "tmp/components/form-controls/company-search",
    "tmp/components/form-controls/address",
],
"extends": "./tsconfig.json",
"include": [
    "tmp/components/**/*",
]

Everything is right, address component is not included and not compiled.

But when I replace it by (specified only 1 subdirectory to be excluded)

    "tmp/components/form-controls/address/address-city"

the address-city is included. Why its happening?

FabricJS Add Image classList Error – Unable to add an image

I am creating a canvas based tool using FabricJS within a React App. I am using the latest NPM Package 6.4.3 and I am struggling to add an image to the canvas. Very recently they have switched to TypeScript and what used to be ‘fabric.image.fromUrl’ to add an image to the canvas has changes to ‘FabricImage’. When I try to implement this I get an error stating ‘TypeError: Cannot read properties of null (reading ‘classList’) at Qo.setElement’. I have implemented the other new method ‘FabricText’ in exactly the same way and it works totally fine.

This is the full error stack taken from my codePen example that is linked below. Image.ts is part of the FabricJS repo (src/shapes/Image.ts):

Uncaught TypeError: Cannot read properties of null (reading 'classList')
    at n.setElement (Image.ts:236:13)
    at new n (Image.ts:205:10)
    at pen.js?key=pen.js-5015e621-c65c-5079-a72d-17f3c0ea1cfa:35:23
    at Mb (react-dom.production.min.js:111:280)
    at Yh (react-dom.production.min.js:121:327)
    at R (react.production.min.js:11:265)
    at va (react.production.min.js:12:403)
    at react.production.min.js:25:14

and this is the stacktrace from my dev environment, as you can see the codepen stacktrace gives more information but the error is the same:

TypeError: Cannot read properties of null (reading 'classList')
    at Qo.setElement (http://localhost:3000/static/js/bundle.js:160422:172)
    at new Qo (http://localhost:3000/static/js/bundle.js:160415:251)
    at http://localhost:3000/static/js/bundle.js:11400:23
    at commitHookEffectListMount (http://localhost:3000/static/js/bundle.js:82913:30)
    at commitPassiveMountOnFiber (http://localhost:3000/static/js/bundle.js:84406:17)
    at commitPassiveMountEffects_complete (http://localhost:3000/static/js/bundle.js:84378:13)
    at commitPassiveMountEffects_begin (http://localhost:3000/static/js/bundle.js:84368:11)
    at commitPassiveMountEffects (http://localhost:3000/static/js/bundle.js:84358:7)
    at flushPassiveEffectsImpl (http://localhost:3000/static/js/bundle.js:86243:7)
    at flushPassiveEffects (http://localhost:3000/static/js/bundle.js:86195:18)

Having looked in the FabricJS repo for information or to see if there were any existing issues but as this is a very recent change, there is no mentionof this issue. I have also raised an issue on the FabricJS Repo and I am waiting for a response. In the meantime, I wanted to aks the Stack Overflow collective to see if anyone has come across this or could point out my error.

The error occurs when it is trying to as a class to the element classlist?? I originally assumed that it could not access the image but having looked at the FabricJS code it has already created the element and complete a number of tasks on it so it must have the image object.

I have created a codepen in React using the 6.4.3 FabricJS NPM Package and you can see the exact error by right clicking and looking at the console output, you will see the error mentioned above.

https://codepen.io/hedlro/pen/poMNOZq?editors=0110

If you comment out the image add section (lines 35 to 44) you will see that it works and creates the canvas and places a rectangle and text on the canvas.

The text uses the similarly renamed method ‘FabricText’ which works.

Below is the new TypeScript method to add an image, or at least what I think the correct syntax is:

const backImg = new FabricImage(testImage, {
              left: 0,
              top: 0,
              height: 400,
              width: 500,
              selectable: false,
              hasControls: false,
              hasBorders: false
              })
canvas.add(backImg).setActiveObject(backImg);

Below is the new typescript method for adding text to the canvas which works. I have based the code for the image on the code below as they both have new methods.

const recttext = new FabricText('Printable Area', {
                  fontSize: 14,
                  fontFamily: 'sans-serif',
                  left: 253,
                  top: 80,
                  fill: 'rgba(0,0,0,0.3)',
                  selectable: false,
                  hasControls: false,
                  hasBorders: false
                  });
                  
canvas.add(recttext);

My question is ‘ Have I got the syntax wrong or am I missing something that I should be sending through. I have checked the tyoescript interfaces for the method but nothing is standing out as required. It may be me making a mistake but at the moment there is minimal documentation for the change so I have no way of checking if I have. Any help would be greatly appreciated.

Why sub package cannot find dependencies when use alias in parent TS project?

I have an older Lerna TypeScript project that contains several packages. I recently added a package called ‘kc-vue’, which is a Vue wrapper for the latest Keycloak-JS. The latest Keycloak-JS requires moduleResolution: bundler, while the other packages use moduleResolution: node.

Additionally, I have another parent TypeScript Vue project that I use to debug the Lerna packages. This parent project also uses moduleResolution: node.

To facilitate debugging, I configured the following alias (where ‘design-system’ refers to the root directory of the Lerna project):

chainWebpack: (config) => {
    config.resolve.alias
      .set('@', resolve('src'))
      .set('assets', resolve('src/assets'))
      .set('components', resolve('src/components'))
      .set('public', resolve('public'))
      .set(
        '@xxx/common',
        resolve('design-system', 'packages', 'common', 'src', 'public-api.ts'),
      )
      .set('@xxx/kc-vue', resolve('design-system', 'packages','kc-vue', 'src', 'public-api.ts'))

When I start the parent project, it will always throw info like:

ERROR  Failed to compile with 1 error                                                                                                                                                                        17:49:32

This dependency was not found:

* keycloak-js in ./design-system/packages/kc-vue/src/public-api.ts

Actually the keycloak-js is correctly imported in the kc-vue project, and the kc-vue project is tested successfully in a separated vue2 project.
I haven’t any clue why it will throw this error when start the parent project.

I’m making a maze generator

So I’m making a maze generator, but the entrance locations don’t add up.
Currently, the entrance markers aren’t on the room tiles, so I’m trying to fix that.

Here’s what I made:

const canvas = document.getElementById('Canvas');
var dimentions = {
  width: canvas.width,
  height: canvas.height
}
const context = canvas.getContext('2d');
var open = ['N',"E",'S','W'];
var rooms = 0;
class room {
  constructor(x, y, entrance) {
    this.x = x;
    this.y = y;
    this.entrance = entrance;
    this.exit = open[(Math.floor(Math.random() * open.length))]
    while (this.exit == this.entrance) {
      this.exit = open[(Math.floor(Math.random() * open.length))]
    }
    context.fillStyle = 'black';
    console.log(this.entrance,this.exit,this.x,this.y);
    drawRoom(this.x,this.y,this.entrance,this.exit)
    rooms+=1;
    if (rooms < 10) {
      newRoom(this.x,this.y,this.exit);
    }
  }
}
function drawRoom(x,y,entrance,exit) {
  this.x = x;
  this.y = y;
  this.centerX = (this.x*dimentions.width/10)+dimentions.width/2;
  this.centerY = (this.y*dimentions.height/10)+dimentions.height/2;
  this.size = dimentions.width/10;
  this.entrance = entrance;
  this.exit = exit;
  context.fillRect(this.centerX-this.size/2,this.centerY-this.size/2, dimentions.width / 10, dimentions.height / 10)
  context.fillStyle = 'green';
  context.fillRect(this.centerX,this.centerY,1,1)
  if (this.entrance == 'N') {
    context.fillRect(this.centerX-this.size/2,this.centerY-this.size/2, this.size, this.size / 10)
  } else if (this.entrance == 'E') {
    context.fillRect(this.centerX+this.size/2-this.size/10,this.centerY+this.size/2, this.size / 10, this.size)
  } else if (this.entrance == 'S') {
    context.fillRect(this.centerX-this.size/2,this.centerY+this.size/2-this.size/10, this.size, this.size / 10)
  } else if (this.entrance == 'W') {
    context.fillRect(this.centerX-this.size/2,this.centerY-this.size/2, this.size / 10, this.size)
  }
}
function newRoom(x, y, exit) {
  //console.log(x,y,exit)
  console.log(y)
  if (exit == 'N') {
    return new room(x, y+1, 'S');
  } else if (exit == 'E') {
    return new room(x+1, y, 'W');
  } else if (exit == 'S') {
    return new room(x, y-1, 'N');
  } else if (exit == 'W') {
    return new room(x-1, y, 'E');
  }
  //console.log(x,67,y,67,exit,67)
}
newRoom(0,0,'N')
<canvas id='Canvas' width='500' height='500'></canvas>

I’m expecting that the entrances (the green rectangles) are where the entrances to the rooms are.
I couldn’t figure out how to format the code properly for Stack Overflow.`

Why Are All Cards of Equal Height Despite Content Variation?

I’m working on a reviews section in my React application using Tailwind CSS, where I want each review card to adjust its height based on the amount of text it contains. However, despite using a flexbox layout, all the cards are displaying at equal height, which is not the behavior I expect.

import React from 'react';

const comments = [
  { id: 1, name: 'User 1', title: 'Review Title 1', comment: 'This is a short comment.', date: '2024-10-11' },
  { id: 2, name: 'User 2', title: 'Review Title 2', comment: 'This is a much longer comment to test how the card height adjusts based on content. We want to see if it affects the layout.', date: '2024-10-11' },
];

export default function ReviewSection() {
  return (
    <div className="flex justify-center flex-wrap gap-3">
      {comments.map((comment) => (
        <div
          key={comment.id}
          className="bg-gray-100 w-[90%] mx-auto mb-5 md:mx-0 md:w-[40%] lg:w-[30%] rounded-3xl border border-gray-300 shadow-xl"
        >
          <div className="p-5">
            <h1 className="font-semibold">{comment.title}</h1>
            <p className="text-sm mt-5">{comment.comment}</p>
          </div>
          <div className="px-5 pb-3 text-sm">
            <p className="text-gray-600">{comment.date}</p>
          </div>
        </div>
      ))}
    </div>
  );
}
  • Ensured that the card div does not have any flex properties that could cause height equalization.
  • Verified that there are no min-height or max-height styles applied globally or inherited from parent elements.
  • Tested with varying lengths of content in comment.comment, but the issue persists.
    Question:
    What changes can I make to allow each review card to have a height that adjusts independently based on its content? Are there specific Tailwind CSS classes or styles that I should implement to achieve this behavior?

How does Google Meet do this borderless popup?

I’m wondering how they implemented a minimal window like this. I did not find any window.open parameter to achieve the same easily. I’m guessing it needs at least some validation like HTTPS or some Web Apps?

Screenshot of Meet Tab with Picture-in-Picture in front of it

Trying any combination of window.open parameters didn’t yield the same result easily. It seems the topic also evolved since earlier questions were answered. Debugging through the app also is no easy feat.

JavaScript 2D arrays and returning matching rows

I have 2 arrays, each is like a database table row set.

array1 = [
['AB2C', 'Red', 113],
['BE4F', 'Green', 164],
['AE3G', 'Blue', 143],
]

array2 = [
[143, 'FabricB2', 'W5'],
[189, 'FabricC9', 'W4'],
[113, 'FabricA3', ' W5'],
[143, 'FabricD1', 'W6']];

I want to do a join and find matching rows, returning the matched rows in array2 along with the matched row in array1. The returned matching array should look like this:

[143, 'FabricB2', 'W5',  'AE3G', 'Blue', 143],
[113, 'FabricA3', ' W5', 'AB2C', 'Red', 113],
[143, 'FabricD1', 'W6',  'AE3G', 'Blue', 143]

I tried to use JavaScript methods map(), filter(), flatMap(), spread operator but can’t get the result.
Anyone can help me with this? With the shortest code? The one I have below does not work.

function testArrayFunction() {

array1 = [
['AB2C', 'Red', 113],
['BE4F', 'Green', 164],
['AE3G', 'Blue', 143],

];

array2 = [
[143, 'FabricB2', 'W5'],
[189, 'FabricC9', 'W4'],
[113, 'FabricA3', ' W5'],
[143, 'FabricD1', 'W6']];

var array1Element = 2;
var array2Element = 0;

var res = array1
.map(x => [  ...  array2
.filter(    y => y[array2Element] === x[array1Element ] )  ,...x ] );

console.log(res);

}

Does not give the expected result which is this

[143, 'FabricB2', 'W5', 'AE3G', 'Blue', 143],
[113, 'FabricA3', ' W5', 'AB2C', 'Red', 113],
[143, 'FabricD1', 'W6',  'AE3G', 'Blue', 143]

Gives this which is not what I want

Info    
[ [ [ 113, 'FabricA3', ' W5' ], 'AB2C', 'Red', 113 ],
[ 'BE4F', 'Green', 164 ],
[ [ 143, 'FabricB2', 'W5' ],
[ 143, 'FabricD1', 'W6' ], 'AE3G', 'Blue', 143 ] ]