How to store/access an image in Supabase/vue

Pls, I have a table “posts” in supabase. I have a form in my vue app to add a row to that table, this form takes in an image url. How do I setup the supabase storage and the code for storing user selected image in the table from my vue app?

  1. I created a function to handle file change
  2. I converted it into object url using (URL.createobjecturl(file.value)
  3. when I upload to storage.objects, I get an error

How to check if an object is a Set in Joi?

how to create a Joi validation to check a Set type? my object does contains a field with a new Set([]) type, but using Joi.array().unique throws an error when validating.

const data = { name: "Thank you", mode: new Set(["happy"]) };

const dataSchema = Joi.object({
   name: Joi.string().required(),
   mode: Joi.array().unique().items(Joi.string())
})

but when calling dataSchema.validate(data) it throws an error "mode" must be an array

Using React dnd kit to receive the coordinates of the dropped item relatively to the Droppable area

I’m working on a React project using the dnd Kit library for drag-and-drop functionality.
The idea is to have a sidebar with placeholder fields as draggable entities and a PDF-document preview as a droppable area. You can see what i’m trying to recreate here:
https://codepen.io/ValerioEmanuele/pen/pGRZqe#

So what im trying to do is I want to get the absolute coordinates of the dropped item relative to the droppable area, but I’m currently only able to retrieve the delta coordinates (the position relative to where the item was picked up) via the event object returned by the onDragEnd.

Here’s a simplified version of my code:

import { DndContext, useDraggable, useDroppable } from '@dnd-kit/core';

const DraggableItem = () => {
  const { attributes, listeners, setNodeRef } = useDraggable({
    id: 'draggable',
  });

  return (
    <div ref={setNodeRef} {...listeners} {...attributes}>
      Drag me
    </div>
  );
};

const DroppableArea = () => {
  const { setNodeRef } = useDroppable({
    id: 'droppable',
    onDrop(event) {
      // Attempting to get coordinates here
    },
  });

  return <div ref={setNodeRef} style={{ width: '400px', height: '400px', border: '2px dashed black' }}>Drop here</div>;
};

const App = () => {
  return (
    <DndContext>
      <DroppableArea />
      <DraggableItem />
    </DndContext>
  );
};

How can I modify my code to calculate the absolute coordinates of the dropped item relative to the droppable area? Specifically, I would like to know how to access the mouse position when the drop occurs and use it to determine the exact position within the droppable area.

Any guidance or examples would be greatly appreciated!

fetch api response with accent marks [duplicate]

I am trying to make a fetch call to retrieve a list of cities from the DB to place in <option> tags in a drop down list. However, when the town "César Chávez" is included in the results, it breaks the response.

The above is how that town is stored in the DB with utf8mb4_unicode_ci and I can print the results displaying the accents but it will not allow me to access this in the response.

I have searched similar questions but many are unanswered and those that aren’t I have tried to implement such as adding a contentType header to text utf-8, using htmlentities (which just omits it)

htmlentities(utf8_encode($city), 0, "UTF-8")] 

As well as adding parameters to the json_encode on the server side :

JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE

Sometimes I can at least see the result in the response in the developer console but the HTML characters are preventing it from displaying in the drop down list options.

This seems like this should not be difficult but I’m stumped. Appreciate any assistance!

EDIT:
I usually get the error: “Uncaught (in promise) SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data”.
That’s why Ive been trying to manipulate the server side

The response part of the fetch is as follows

if(data.arr){
      for(let i=0; i<data.arr.length; i++){
        const town = data.arr[i][1];
        html += "<option data-id=" + data.arr[i][0] + " value='" + town + "'>";
      }
    }

I tried town = encodeURIComponent(data.arr[i][1]) but to no avail

Object.create() returns an empty object

When compiling this typescript code:

interface Jugador {
  id?: string;
  equipoId?: string[];
}

let jugador:Jugador = Object.create({
  id: '283428724', 
  equipoId: ['234827382']
});

console.log( jugador ); 
console.log( typeof jugador );

I get this javascript code:

var jugador = Object.create({
    id: '283428724',
    equipoId: ['234827382']
});
console.log(jugador);
console.log(typeof jugador);

And the execution returns the following:

$ node test.js
{}
object

Why is the created object empty??? The result I expect is something similar to

{ 
id: '283428724',
equipoId: ['234827382']
}

React and Tailwind Positioning an Item on Hover within DOM

I have an icon that shows only when I hover over a container. It’s currently position relative because I need it to stay within the container. With it being relative though it pushes down the rest of the items within the container; however, I want them to stay vertically centered. I know I could use negative margin to force them back up, but that is typically seen as bad practice so I’m trying to figure out another way to handle this.


enter image description here

^^ What the front end looks like with the position relative, the icon stays within the white container.


enter image description here

^^ What the front end looks like with the position absolute, no matter where I position the icon its gonna be on the same spot on the screen regardless of which container I hover over.


This is the react code for the scrolling list of containers

return (
        <div className="container mx-auto p-4">
            <h1 className="text-4xl font-bold text-center mb-6 text-amber-100">Task List</h1>
            <div className="overflow-x-auto  scrollbar-custom">
                <ul className="flex space-x-4 mb-10 blue" style={{ listStyleType: 'none', padding: 0 }}>
                    { tasks.map((task) =>
                        (
                            <li key={task.id} 
                                className="TaskBox bg-white shadow-lg shadow-amber-200/60 rounded-lg p-8 shadow-sm min-w-[300px] max-w-[300px] flex-shrink-0">
                                <div className="deleteTask">
                                    <DeleteTask task={task}/>
                                </div>
                                <div className="TaskInfo">
                                <h4 className="text-2xl font-semibold text-gray-800 mb-2">{task.title}</h4>
                                <p  className="text-sm text-gray-500 mb-2"
                                    >Created on: {new Date(task.createdAt).toLocaleDateString('en-US', {
                                    year: 'numeric',
                                    month: 'long',
                                    day: 'numeric'
                                })}</p>
                                <p className="text-gray-600 mb-4">{task.description}</p>
                                <p  className={`text-sm ${task.isCompleted ? 'text-green-500' : 'text-red-500'}`}>Completed: {task.isCompleted ? 'Yes' : 'No'}</p>
                                </div>
                            </li>
                        ))}
                </ul>
            </div>
        </div>
    );

CSS for the code

.trashIcon
{
  width: 1.75em;
  height: 1.95em;
  color: indianred;
  transition: transform 0.15s ease;
}

.deleteTask:hover .trashIcon
{
  transform: scale(1.1);
  color: firebrick;
}

.deleteTask
{
   position: absolute !important;
   left: 50%;
   bottom: 12%;
   padding: 6px 6px;
   background-color: lightslategray;
   border-radius: 12px;
   transition: transform 0.15s ease;
   visibility: hidden;
}
.deleteTask:hover
{
  background-color: dimgrey;
}

.TaskBox:hover .deleteTask
{
   display: inline-block;
   transform: scale(1.1);
   visibility: visible;
}

.TaskInfo
{
  display: flex-column;
  justify-content: center;
  align-items: center;
}

.newTaskForm
{
  width: 50%;
}

I tried switching to position absolute as it doesn’t effect other DOM elements, I was expecting it to stay within the white container though, but it only stays within the container like shown in the first picture with position relative.

Quickchart ticks.callback for labelling does not work when shortening url

I want to make a chart with double y-axes which have each callback for y labeling using quickchart rendering.

It is well generated if I used the below config in “https://quickchart.io/chart?c={config}”
(well generated chart)
Chart with full config in url

Because the length of this url is quite long, I want to shorten this url using “https://quickchart.io/chart/create” here.

However, If I use the create post method for shortening url, the callback does not work.
(Chart with shorten url)
enter image description here

Is there a way to use ticks.callback when I use create short url?

Config is the below:

{
  type: 'line',
  data: {
    labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
    datasets: [
      {
        label: 'My First dataset',
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgb(255, 99, 132)',
        data: [93, -29, -17, -8, 73, 98, 40],
        fill: false,
        yAxisID: 'y1',

      },
      {
        label: 'My Second dataset',
        fill: false,
        backgroundColor: 'rgb(54, 162, 235)',
        borderColor: 'rgb(54, 162, 235)',
        data: [20, 85, -79, 93, 27, -81, -22],
        yAxisID: 'y2',

      },
    ],
  },
  options: {
    title: {
      display: true,
      text: 'Chart.js Line Chart',
    },
    scales:{
      yAxes: [
        {
          id: 'y1',
          display: true,
          position: 'left',
          stacked: true,
          ticks: {
                callback: function(value, index, ticks) {
                  return '$' + value;
                }
              }

        },
        {
          id: 'y2',
          display: true,
          position: 'right',
          ticks: {
                callback: function(value, index, ticks) {
                  return '$' + value;
                }
              }
        },
      ],
    }
  },
}

How to focus an input dynamically (bind:this doesn’t work)

When a user presses a button, an input is displayed, I simply want to focus the input at that time. Something like this:

<script>
    let edit = false;
    let focusInput = {};
    const toggleEdit = ()=>{
        edit = true;
        focusInput.focus();
    }
</script>

<button on:click={toggleEdit}>Edit</button>
{#if edit}
    <input type="text" bind:this={focusInput}>
{/if}

The problem is that focusInput is undefined. I know that you are supposed to use onMount() for this, but it is user input, the component has already long been mounted by the time the button is pressed. So it doesn’t make sense that focusInput is still undefined.

Also, I can’t call a function in the HTML that is defined in onMount(). How can I get access to a DOM element during user input?

It honestly doesn’t make sense, it is like Svelte is blocking me from ever having access to DOM elements.

Using React in existing Django Project

I have an existing Django project. Its a website that displays a map with leaflet.
Markers and everything is loaded dynamically from django.
Now I want to enhance that with React. In a sense that when you click a marker on the map, react will render based on marker_id the specific marker-details in a sidebar or something.
I am not sure how to do that. In the django template I have a onclick event to get the marker-details:

                    marker.uri = `/map/api/marker_details/?marker_id=${marker.marker_id}&marker_type=${marker.marker_type}`
                    marker.on('click', function (e) {

                        jQuery.get(this.uri);

                    });

Since this is all in django template and not in React, the result is probably not accessible via react to render the details. Do I have to implement the map with the marker and everything in React to then be able to render the details via API? What am I missing?

Avalanche effect on React re-renders due to Context API

I know this is an over-asked question, but I have a specific problem with Context and, actually, the React rendering mechanism.

I’ll be quick:

  • I have a sort of canvas where I add and remove React components.
  • These React components are added, removed, and updated inside a global JS object (canvas)
  • The canvas is actually a tree with different layers: a column, a row, a component, a subcomponent…
  • There is a history of changes (copies of the canvas stacked into an array)
    • Undos and redos substitute the copy of the canvas

    • changes are pushed to the history as a new canvas version

  • I use a Global Context that wraps everything.
    • I have tried splitting the context in different parts

    • I have tried getting rid of the context

    • The problem is always the push to the history

So far, I have tried the following solution: Every component changes by itself, only updating the single part of the canvas that is actually changed. I was using Immer to do this. Everything fine, re-rendering of components was triggered due to change of state in the component itself, without triggering other re-renders (no other component shared state).As soon as I got to the history feature, I met my fate: Pushing the state to the history requires a change of state for the history, that has to be shared.

  • The history is basically a global component

  • Every change has to be notified to the history, so the history has to change and has to be shared amongst components.

  • I can accept that undos and redos trigger re-renders for the entire page.

So, the main issue here is that I still have to notify a change of state to the history which is shared. Even if the history would be just a copy of every single component, and stored in the single component, what happens if I delete a component? I still need to push to the history.

I mean, you can see I’m lost here.
I found a temporary workaround that I had to delete from my project: Intersection Observers. The problem with those was that user experience was drastically impacted by unpredictable behaviors during scrolling. But, it was working fine.

Right now, I have left my app as a re-render machine, that re-renders at every single damn change.Even if I do the slightest change, the state changes in the context (in the history) and it triggers changes.

I even tried a pub/sub approach, where components would subscribe to changes in the history, but we’re still there, the history is shared and has to change at every change.What’s the best thing I can do here? My best bet so far is that I get Intersection Observers to work so damn good that I don’t need to worry about re-rendering because everything is limited to what I see in the page.

Unless I do create a sophisticated history that only contains sort of OP codes, like (UNDO_ADD_COMPONENT => {// Reverse logic of ADD_COMPONENT}
But still… I have to push this to the history ahahah
And it would also require me to refactor the entire codebase, which is not small at all right now and is going to increase.

Any suggestions?
Thanks!

Can a Firefox extension read variables in the distribution/install folder?

We want to verify that only our devices can use our extension, therefore devices need to give an ID and be put on our allowed list.

Similar questions have been asked before, and the answer boils down to “extensions can’t access a unique device ID” – privacy concerns. The given alternative is storing some data, but this isn’t useful for shared devices where multiple accounts are expected to have the extension with a single device ID.

However, our extension is used on devices in our business that IT can put files on. For example, C:Program FilesMozilla Firefoxdistribution contains policies to auto install our extension, and I can add files here without non-admin users being able to edit/remove.

Is there a way to put our own device signatures in the distribution/install folder and then have an extension read it?

Date Milliseconds same for two dates

I have a date string of format ‘dd-mm-yyyy’ which I want to convert to Milliseconds.

let split_date = '31-01-2024'.split('-');
let d = new Date(parseInt(split_date[2]), parseInt(split_date[1]), parseInt(split_date[0]), 0, 0, 0, 0).getTime();
console.log(d);

let split_date2 = '02-02-2024'.split('-');
let d2 = new Date(parseInt(split_date2[2]), parseInt(split_date2[1]), parseInt(split_date2[0]), 0, 0, 0, 0).getTime();
console.log(d2);

This gives me output of 1709317800000 which seems to be incorrect. Also I get same milliseconds value for ’02-02-2024′.

Why is the milliseconds value incorrect and same for multiple dates?