How to send information from flutter to html file

The goal is to send data from flutter to the script field in html.

I think the data is being send and received by html file but i cant get a handle on the data.

the goal is for the script field (html file) to use the data send from the user in the auto complete.

code1:

MonacoEditorWidget(objects: {"current":{"name":"b"}, },)

code2:

import 'dart:convert';
import 'dart:html' as html;
import 'dart:async';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;

class MonacoEditorWidget extends StatefulWidget {
  final Map<String, dynamic> objects;

  MonacoEditorWidget({Key? key, required this.objects}) : super(key: key);

  @override
  _MonacoEditorWidgetState createState() => _MonacoEditorWidgetState();
}

class _MonacoEditorWidgetState extends State<MonacoEditorWidget> {
  late StreamSubscription<html.MessageEvent> _messageSubscription;

  @override
  void initState() {
    super.initState();

    // Send the objects to the iframe for code suggestion
    WidgetsBinding.instance.addPostFrameCallback((_) {
      html.window.postMessage({
        'type': 'initMonaco',
        'objects': jsonEncode(widget.objects)
      }, '*');
    });

    // Listen for messages from the iframe
    _messageSubscription = html.window.onMessage.listen((event) {
      print('Message received from iframe: ${event.data}');
    });
  }

  @override
  void dispose() {
    _messageSubscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // iFrame
    final String iframeId = 'monaco-editor-container';

    // Create iframe element
    final html.IFrameElement iframeElement = html.IFrameElement()
      ..src = 'monaco_editor.html'
      ..style.border = 'none';

    // Register iframe
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      iframeId,
      (int viewId) => iframeElement,
    );

    return HtmlElementView(viewType: iframeId);
  }
}

code3(script field /html file):


<!DOCTYPE html>
<html>

<head>
  <!-- Load the Monaco Editor Loader Script -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs/loader.min.js"
    integrity="sha512-ZG31AN9z/CQD1YDDAK4RUAvogwbJHv6bHrumrnMLzdCrVu4HeAqrUX7Jsal/cbUwXGfaMUNmQU04tQ8XXl5Znw=="
    crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <style>
    body,
    html {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      display: flex;
      /* Establishes a flex container */
      overflow: hidden;
      /* Prevents unwanted overflow */
    }

    #editorArea,
    #output {
      flex: 1;
      /* This ensures both the editor area and output take up equal space */
      min-width: 0;
      /* Prevents flex items from growing beyond their content size, allowing shrinking */
    }

    #editorArea {
      display: flex;
      flex-direction: column;
      overflow: hidden;
      /* Ensures overflow content in the editor is scrollable */
    }

    #toolbar {
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }

    #editorContainer {
      flex-grow: 1;
      overflow: auto;
      /* Allows scrolling within the editor if content overflows */
    }

    #container {
      width: 100%;
      height: 100%;
      /* Ensures the editor uses the full available area */
    }

    #outputArea {
      display: flex;
      flex-direction: column;
      flex: 1;
      /* Equal width with the editor area */
      overflow: hidden;
      /* Hide overflow */
    }

    #outputToolbar {
      display: flex;
      justify-content: space-between;
      padding: 10px;
      background-color: #f5f5f5;
      border-bottom: 1px solid #ccc;
    }


    #output {
      flex-grow: 1;
      padding: 10px;
      overflow: auto;
      /* Make output scrollable */
      border-left: 1px solid #ddd;
      /* Visual separation */
    }
  </style>
</head>

<body>
  <div id="editorArea">
    <div id="toolbar">
      <select id="languageSelector">
        <option value="javascript">JavaScript</option>
  
      </select>
    </div>
    <div id="editorContainer">
      <div id="container"></div>
    </div>
  </div>
  <div id="outputArea">
    <div id="outputToolbar">
      <button id="runCodeButton">Run</button>
      <button id="exitEditorButton" style="float: right;">Exit Editor</button>
    </div>
    <div id="output">Output will appear here...</div>
  </div>



  <script>
    document.addEventListener('DOMContentLoaded', function () {
      require.config({
        paths: {
          'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.47.0/min/vs'
        }
      });
      require(['vs/editor/editor.main'], function () {
        var editor = monaco.editor.create(document.getElementById('container'), {
          value: "// Your code here",
          language: 'javascript',
          theme: 'vs-dark',
          automaticLayout: true
        });

        // Listen for changes in the language selector and update the editor
        document.getElementById('languageSelector').addEventListener('change', function () {
          var newLanguage = this.value;
          monaco.editor.setModelLanguage(editor.getModel(), newLanguage);
        });
      });

      document.getElementById('runCodeButton').addEventListener('click', function () {
        // Save the original console.log
        const originalConsoleLog = console.log;

        // Clear the output window before each run
        document.getElementById('output').textContent = '';

        // Override console.log
        console.log = function (...args) {
          // Display output in the UI's output window
          document.getElementById('output').textContent += args.join(' ') + 'n';
          // Optionally call the original console.log to see output in the browser console as well
          // originalConsoleLog.apply(console, args);
        };

        try {
          // Get the current code from the Monaco editor
          const userCode = monaco.editor.getModels()[0].getValue();

          // Evaluate the user's code
          eval(userCode);
        } catch (e) {
          // If an error occurs, display it in the output window
          document.getElementById('output').textContent = 'Error: ' + e.message;
        } finally {
          // Restore the original console.log
          console.log = originalConsoleLog;
        }
      });

    });
  </script>
</body>

</html>

this is the output i see::

Restarted application in 27ms.
The debugEmulateFlutterTesterEnvironment getter is deprecated and will be removed in a future release. Please use `debugEmulateFlutterTesterEnvironment` from `dart:ui_web` instead.
The platformViewRegistry getter is deprecated and will be removed in a future release. Please import it from `dart:ui_web` instead.
Height of Platform View type: [monaco-editor-container] may not be set. Defaulting to `height: 100%`.
Set `style.height` to any appropriate value to stop this message.
Width of Platform View type: [monaco-editor-container] may not be set. Defaulting to `width: 100%`.
Set `style.width` to any appropriate value to stop this message.
22
{type: initMonaco, objects: {"current":{"name":"b"}}}
17
Message received from iframe: {type: initMonaco, objects: {"current":{"name":"b"}}}

it appears that the data is being received somehow by the html, but i cant get a handle on it.

is it possible to do this?

these are my dependecies::

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
js: ^0.7.1
flutter_js: ^0.8.1

i found this medium article that might help, didnt help me 🙁

https://medium.com/@andcachia/communication-between-flutter-iframe-and-html-parent-9fd7acd33ebf

how to solve javascript and php connect error

<div class="container-fluid mt-4 d-flex justify-content-center w-100">
  <div class="table-responsive w-100">
    <table class="table table-bordered">
      
      <thead>
        <tr>
          <th>#</th>
          <th>Product</th>
          <th>Quantity</th>
          <th>Unit cost</th>
          <th>Total</th>
          <th> </th>
        </tr>
      </thead>

      <tbody>
        <tr>
          <td>1</td>
          <td style="width: 30%;">
            <?php
              include_once "classes/users.php";

              $options = new Selects($connect);
              $options->ProductsSelects();
            ?>
          </td>             
          <td><input type="number" class="form-control quantity" name="quantity[]" oninput="calc(this)" required> Pcs</td>
          <td><input type="number" class="form-control price" name="price[]" oninput="calc(this)" required> EGP</td>
          <td><input type="text" class="form-control total" name="total[]" readonly> EGP</td>
          <td><button type="button" class="delete-row-button btn btn-danger" style="font-size: 12px;" disabled>Delete</button></td>
        </tr>
      </tbody>

    </table>
  </div>
</div>

<div class="container-fluid w-100">
  <button name="submit" class="btn btn-primary float-end mt-4 ms-2"><i data-feather="send" class="me-3 icon-md"></i>Submit</button>
  <button class="btn btn-outline-success float-end mt-4" id="add-row-button"><i data-feather="plus" class="me-2 icon-md"></i>Add Row</button>
</div>


<script>

  let rowCount = 2;

  const addRowButton = document.getElementById("add-row-button");
  const tableBody = document.querySelector("tbody");

  addRowButton.addEventListener("click", () => {
    const newRow = document.createElement("tr");
    newRow.innerHTML = `
      <td>${rowCount}</td>

      <td style="width: 30%;">
      <?php
        include_once "classes/users.php";

        $get_products = new Selects($connect);
        $get_products->ProductsSelects();
      ?>
      </td>

      <td><input type="number" class="form-control quantity" name="quantity[]" oninput="calc(this)" required> Pcs</td>
      <td><input type="number" class="form-control price" name="price[]" oninput="calc(this)" required> EGP</td>
      <td><input type="text" class="form-control total" name="total[]" readonly> EGP</td>
      <td><button type="button" class="delete-row-button btn btn-danger" style="font-size: 12px;">Delete</button></td>
    `;
    tableBody.appendChild(newRow);

    rowCount++;

    const deleteButton = newRow.querySelector(".delete-row-button");
    deleteButton.addEventListener("click", () => {
      tableBody.removeChild(newRow);
      updateTotalSum();
    });
  });

  const initialDeleteButton = document.querySelector(".delete-row-button");
  initialDeleteButton.addEventListener("click", () => {
    tableBody.removeChild(initialDeleteButton.parentElement.parentElement);
    updateTotalSum();
  });

  function calc(inputElement) {
    var row = inputElement.closest("tr");
    var quantities = row.querySelectorAll(".quantity");
    var prices = row.querySelectorAll(".price");
    var totalField = row.querySelector(".total");

    var totalSum = 0;

    for (var i = 0; i < quantities.length; i++) 
    {
      var quantity = parseFloat(quantities[i].value) || 0;
      var price = parseFloat(prices[i].value) || 0;
      var total = quantity * price;
      totalSum += total;
    }

    totalField.value = totalSum.toFixed(2);
    updateTotalSum();
  }

  function updateTotalSum() {
    var totalSum = 0;
    var totalFields = document.querySelectorAll(".total");

    totalFields.forEach(function (totalField) {
        totalSum += parseFloat(totalField.value) || 0;
    });

    const discountAmount = calculateDiscountAmount(totalSum);
    const discountedTotal = totalSum - discountAmount;

    document.getElementById("totally").innerText = `EGP ${totalSum.toFixed(2)}`;
    document.getElementById("discountAmount").innerText = `(-) EGP ${discountAmount.toFixed(2)}`;
    document.getElementById("ftotally").innerText = `EGP ${discountedTotal.toFixed(2)}`;
  }

  function calculateDiscountAmount(totalSum) {
    const discountPercentage = parseFloat(document.getElementById("discount").value) || 0;
    return totalSum * (discountPercentage / 100);
  }

  const discountInput = document.getElementById("discount");
  discountInput.addEventListener("input", updateTotalSum);
</script>

<?php

  if (isset($_POST['submit'])) 
  {
    $quantities = $_POST['quantity'];
    $prices = $_POST['price'];
    $total = $_POST['total'];
    $product = $_POST['product'];

    $number = rand();

    $conn = mysqli_connect("localhost", "root", "", "accounting");
    if (!$conn) {
      die("Connection failed: " . mysqli_connect_error());
    }

    foreach ($quantities as $index => $quantity) 
    {
      $product = $product[$index];
      $price = $prices[$index];
      $total = $total[$index];

      $insert = "INSERT INTO invoice_row (invoice_number, quantity, product, price, total) VALUES ('$number', '$quantity', '$product', '$price', '$total')";
      mysqli_query($conn, $insert);
    }


    echo "Successfully";
  }
?>

I want to add row and get product name but unfortunately the name get at first row but the other row inserted by javascript don’t get the name and not inserted in database and I tried to add the php code straight without function and classes called and the chatGPT and blackbox ai can’t do anything in this error

vuelidate – validating dynamically added/removed fields does not behave as expected

I’ve been working on a Vue 3 application that utilizes Vuelidate for form validation. The form includes dynamic fields, specifically the questions array, where users can add or remove fields as needed. Each field within the questions array has its own validation rules, such as being required.

The issue I’m facing is related to the validation state of the fields when a field is removed from the questions array. Here’s a detailed description of the problem:

  1. Initial State:

    • Let’s say I have three fields in the questions array.
    • I interact with fields 2 and 3, triggering their validation. If they don’t meet the validation criteria, Vuelidate correctly marks them as invalid.
  2. Removing a Field:

    • I decide to remove field 2 from the questions array.
    • Before removing the field, I call jobAdFormValidation.value.questions[questionIndex].$reset() to clear the validation state of the field being removed. This ensures that the validation state associated with the removed field is properly reset.
  3. Shifting of Fields:

    • After removing field 2, field 3 shifts up and takes the position of field 2.
    • However, Vuelidate does not automatically update the validation state based on the new positions of the fields.
  4. Validation State Issue:

    • The validation state that was previously associated with field 3 remains incorrectly attached to the original field 3 position, even though field 3 has now shifted up to become the new field 2.
    • As a result, the newly shifted field (now at position 2) loses its validation error state, even though it should retain the validation error from its previous position.
  5. Adding a New Field:

    • If I then decide to add a new field at position 3 (where the deleted field used to be), Vuelidate incorrectly applies the validation error state from the previously removed field to this newly added field.
    • This means that the new field at position 3 starts with an invalid state, even though it hasn’t been interacted with or validated yet.

The core problem lies in how Vuelidate handles the validation state when fields are dynamically removed and the remaining fields shift positions. The validation state doesn’t correctly follow the fields as they move to new positions, leading to incorrect validation errors being applied to the wrong fields.

I’ve tried various approaches to resolve this issue, such as resetting the validation state of the removed field, revalidating the entire questions array, and even attempting to manually update the validation state. However, none of these solutions have completely addressed the problem of the validation state being lost or incorrectly applied when fields are removed and shifted.

This is how I define my rules:

 const questionRules = computed(() =>
    jobStore.jobAd.questions.map(() => ({
        id: { required, numeric },
        question: { required },
        idealAnswer: { required }
    }))
);

const rules = computed(() => ({
    title: { required, text },
    description: { required, text },
    roleName: { required, text },
    department: { text },
    salary: {
        currency: { required, text },
        min: { required, numeric },
        max: { required, numeric },
    },
    officeLocation: { required, text },
    employmentTypeCode: { required, text },
    candidateRequirements: jobStore.jobAd.candidateRequirements.map(() => ({
        id: { required, numeric },
        requirement: { required, text },
    })),
    candidateResponsibilities: jobStore.jobAd.candidateResponsibilities.map(() => ({
        id: { required, numeric },
        responsibility: { required, text},
    })),
    questions: questionRules.value,
    adGoLiveDate: { required, text },
    jobStartDate: { required, text },
    expiresAt: { required, text },
}));

I am not entirely sure what else I can do. All I want is to be able to add fields dynamically and have them validated. That is all, however vuelidate seems to just not like it.

Apps Script function does not update PDF

I’ve been working on some custom features for a form made in Google Sheets to generate a pdf of the form and also update the PDF is changes are made and saved from the Sheets document.

My below code runs fine after some trouble shooting on a previous question thread, but the PDF remains unchanged even though I have updated and saved the underlying document and ran the function, with no errors.

Here is my script as it stands:

    function replaceFile(theBlob, theFileId) 
{
  var oldFile = DriveApp.getFileById(theFileId);
  Logger.log(oldFile.getId());
  try
  {
    
    Drive.Files.update(
  { mimeType: oldFile.getMimeType() },
    theFileId,
    theBlob,
  { supportAllDrives: true }
  );
    
    Logger.log(Drive.Files.get(theFileId, {supportsAllDrives: true}).getName());
    Logger.log("Success!");
    SpreadsheetApp.getActive().toast("PDF Updated With Success");
    
    
  }
  catch (error)
  {
    Logger.log(error);
    SpreadsheetApp.getActive().toast(error);
    
  }

}

function test1 ()
{
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  SpreadsheetApp.flush();
  var pdfBlob = spreadsheet.getAs('application/pdf');
  replaceFile(pdfBlob,"1ZuftxjH8t6WVKR-sxHl98iywhRPDHnC-");
}

link to previous relevant question:
Overwriting PDF File with Google Apps Scripts Causes Drive App to be unable to locate file

Get the values of two fields in my form as I try to log in?

I am trying to make my Log In page work. I have tons of problemas to make it work, and I want you to help me.

The first problem is that I cannot get the values of the input generated by the user. I mean the Username and Password fields do not work. When I go to console in the Google Development tools I get an undified value insted of the value that I have typed in the Log in page.

This is the code for my Login.js file:

import React, {useState} from 'react'
import "./Login.css"
import linkedin1 from './linkedin1.png';
import { Link } from "react-router-dom";
import Signin from "./Signin";

function Login() {
  const [email, setEmail] = useState();
  const [password, setPassword] = useState();

  const doit = (e) => {
    e.preventDefault();
  }

  return (
    <div className='login'>
      <img src={linkedin1} />
      <form> 
        <input value={email} id="myemail" onChange={(e => setEmail(e.target.value))} placeholder='Enter Email' type="email" />
        <input value={password} onChange={(e => setPassword(e.target.value))} placeholder='Enter password' type="password" />
        <button onClick={doit} type='submit' >
          Sign In
        </button>
      </form> 
    </div>
  )
}

export default Login

I tried to get the value of my input fieds, that is the username field and the password field. I tried to get those values but I just keep getting an Undefined value from the console at the Google development tools.

Google Apps Script; Exception: Cannot retrieve next object: the iterator has reached the end

I’m trying to iterate in diferents rows to collect data from users that have answered a Google forms and generate diferent documents with their data. So far I’ve acomplished that part of my code, but there’s a problem when I try to classifie their documents in several folders. It’s like a hierarchy that starts classifing form their course (highschool), and then from their class (A, B…), but i only get this exception.

Exception: Cannot retrieve next object: the iterator has reached the end.

And I don’t know what to do to solve it

var locBase = DriveApp.getFileById("DOCUMENT_ID").getParents().next();

if (!masterFolder.hasNext()) {

            // If there isn't a principal folder, it creates it
            masterFolder= locBase.createFolder("individual_documents");

            // Creation of the first sub-folder (the course one)
            var courseFolder = masterFolder.next().createFolder(course);

            // The document is moved to the subfolder
            document.moveTo(courseFolder);

          } else {

            // If the principal folder its created it searches de course folder
            var courseFolder = masterFolder.next().getFoldersByName(course);

            if (!courseFolder.hasNext()) {

              // If the course folder doesn't exist, it creates it
              courseFolder = masterFolder.next().createFolder(course);

              // The sub-subfolder it's created (the class one) inside of the course folder
              var classFolder = courseFolder .createFolder(class);

              // The document is moved to the sub-subfolder
              document.moveTo(classFolder);

            } else {

              // If the subfolder exists, it searches the sub-subfolder inside of it
              var classFolder = courseFolder.next().getFoldersByName(class);

              if (!classFolder .hasNext()) {

                // If the sub-subfolder doesn't exist, it creates it
                var classFolder = courseFolder .next().createFolder(class);

                // The document is moved to the sub-subfolder
                document.moveTo(classFolder);

I expected to get in my Drive the main folder with the subfolders that contain de documents of each user, but it does not even manage to generate the documents that I need

How to handle NodeJS errors in TypeScript?

I’m trying to handle exceptions thrown by NodeJS using TypeScript.
For example, if I get an ECONNREFUSED exception, it’s of type SystemError.

But as of now, because err is of type any, I can only do this

redisClient.on('error', (err) => {
  console.log('Error: ', err);
});

But I would like to narrow down the error type, similar to this:

redisClient.on('error', (err) => {
  if (err instanceof ErrnoException) {
    if(err.code === 'ECONNREFUSED ') {
      throw new Error('Connection refused');
    }
  }
  
  throw err;
});

But unfortunately, SystemError is not exported in Node.
I did find a discussion on GitHub from 4 years ago regarding NodeJS.ErrnoException, but seems like it was removed.
Is it currently possible in NodeJS?

How to show multicolor on slider using d3-simple-slider.js

I am using d3-simple slider and want to show multicolor on slider i.e.
enter image description here

From Range 0-9 it should be blue and 9 to 26 is orange and for range 26-60 color should be red and If I move handle which is currently pointing to 26 then slide it towards left then red color should follow it ,similarly for otehr handle too.Can someone please help in regarding this?

How to Set HTML Content in RoosterJS Editor?

I’m currently working with the RoosterJS rich text editor in my project, and I need to set the HTML content programmatically. My goal is to replace the entire content of the editor with a new HTML string.

I’ve gone through the RoosterJS documentation and explored the source code. I found a method called setContent in the source code on GitHub, which seems to do exactly what I need. However, it appears that this method is not included in the package( roosterjs: 9.9.1) I’m using.

Is there an alternative method or recommended approach to set or replace the entire HTML content of the RoosterJS editor programmatically? If setContent is not part of the package, how can I achieve similar functionality?

useFieldArray of react-hook-form not rendering when values are provided by api

I’m using a fieldArray to build a form using react-hook-form. This form is used for both create and update an user and i’m also using the “values” prop from react-hook-form. The field using the fieldArray api has 2 simple time inputs, and there’s a button “add” that you can click to render more time inputs (it starts empty).

form default
added field

The problem is, when i’m fetching data before this form and it has any breakTime (the array field name) it is not rendered immediately in the ui. But, when I click to add it renders all the fields fetched from the api. (see images below)

all fields filled, except the array field

after clicking on add button of array field

My code below:

const form = useForm<OperatorOrManageData>({
    resolver: zodResolver(operatorOrManagerSchema),
    defaultValues: initializeDefaultValues(),
    mode: "all",
    values: data,
})

const { fields, append, remove } = useFieldArray({
    name: "breakTime",
    control: form.control,
})

    {fields.map((field, index) => (
                                    <div className="flex w-full flex-row items-center gap-3" key={field.id}>
                                        <div className="w-56 flex-row items-start whitespace-nowrap rounded-full bg-primaryBlue-100 px-4 py-2">
                                            <span>Horário de intervalo</span>
                                        </div>
                                        <FormField
                                            control={form.control}
                                            name={`breakTime.${index}.start` as const}
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormControl>
                                                        <div className="relative">
                                                            <Input
                                                                {...field}
                                                                type="time"
                                                                className="flex rounded-full border border-primaryGray-400 py-2 pe-4 ps-12"
                                                                value={field.value}
                                                            />
                                                            <div className="absolute left-0 top-1/2 z-10 flex h-10 w-10 -translate-y-1/2 transform items-center justify-center rounded-s-full bg-primaryGray-100">
                                                                <span>De</span>
                                                            </div>
                                                        </div>
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />
                                        <FormField
                                            control={form.control}
                                            name={`breakTime.${index}.finish` as const}
                                            render={({ field }) => (
                                                <FormItem>
                                                    <FormControl>
                                                        <div className="relative">
                                                            <Input
                                                                {...field}
                                                                type="time"
                                                                className="flex rounded-full border border-primaryGray-400 py-2 pe-4 ps-12"
                                                                value={field.value}
                                                            />
                                                            <div className="absolute left-0 top-1/2 z-10 flex h-10 w-10 -translate-y-1/2 transform items-center justify-center rounded-s-full bg-primaryGray-100">
                                                                <span>Até</span>
                                                            </div>
                                                        </div>
                                                    </FormControl>
                                                    <FormMessage />
                                                </FormItem>
                                            )}
                                        />
                                        <TooltipProvider>
                                            <Tooltip>
                                                <TooltipTrigger asChild>
                                                    <Button
                                                        variant={"destructive"}
                                                        size={"sm"}
                                                        type="button"
                                                        className="rounded-full p-2"
                                                        onClick={() => remove(index)}
                                                    >
                                                        <Trash />
                                                    </Button>
                                                </TooltipTrigger>
                                                <TooltipContent className="border-0 bg-red-500 text-secondaryWhite-100 dark:border-0 dark:bg-red-500">
                                                    <p>Excluir</p>
                                                </TooltipContent>
                                            </Tooltip>
                                        </TooltipProvider>
                                    </div>
                                ))}

I’ve tried to use controlled field array as in the docs https://react-hook-form.com/docs/usefieldarray but didn’t work.

How to set scale of images according to resolution and window size

I am in the midst of a fairly complex project, creating a floorplan and adding desks to that floorplan. I have the floorplan image with height and width in px of the image, and also the physical size of the floor in mm. I also have the same data for each desk being placed, along with top and left locations in px.

How am I able to use getBoundingClientRect and this information to determine correct scaling of desks to may image size?

This is the code I currently have but I am unsure how to relate width/height (in px) to wMM/hMM.

const getScale = () => {
    const site = maps.maps[currentMap]; // the id on the select
    if (!site) return;

    let map = mapRef.current;
    let rect = map?.getBoundingClientRect();
    let mapWidth = rect.width; // Width of the floorplan image in px
    let mapHeight = rect.height; // Height of the floorplan image in px

    // Scale calculations based on physical dimensions (in mm)
    let scaleW = (mapWidth && site.wMM) ? (mapWidth / site.wMM) : 1; // Width scale factor
    let scaleH = (mapHeight && site.hMM) ? (mapHeight / site.hMM) : 1; // Height scale factor

    // Store scale values
    mapScale = { height: scaleH, width: scaleW, top: rect.top, left: rect.left };
    return mapScale;
};

// desk component, showing only relevant size and location calculations
    const top = parseInt((desk.y * scale.height) + scale.top); // Top position of the desk
    const left = parseInt((desk.x * scale.width) + scale.left); // Left position of the desk
    let deskWidth = 0;
    let deskHeight = 0;
    try {
        if (dImg) {
            deskImg = dImg.deskImage;

            // Calculate desk size in pixels based on its physical dimensions
            deskWidth = (dImg.wMM * scale.width); // Desk width in pixels
            deskHeight = (dImg.hMM * scale.height); // Desk height in pixels

        }

To be absolutely clear, the site variable in getScale() has 4 fields: height, width, hMM and wMM. The dImg variable has these same 4 fields. The first 2 are measurements in PX and the second 2 are the physical measurements in millimetres.

How can these calculations be modified appropriately to correctly set the scale for my (current) window size and resolution?

Chrome extension – Uncaught TypeError: Error in invocation of tabs.group

Goal

  1. Create two tabs using Chrome.tabs.create()
  2. Group both taps using Chrome.tabs.group()

Set-up

html

<button id="create">Create<button>

popup.js

const createBtn = document.querySelect('#create');
createBtn.addEventListener('click', createTabs);
let tabsToGroup = []; // For storing tab Id's

function createTabs() {
    chrome.tabs.query({ active: true, lastFocusedWindow: true }, (tabs) => {
        tabsToGroup.push(tabs[0].id); // Push current window to array

        chrome.tabs
            .create({ url: `https://site1.com` })
            .then((tab) => tabsToGroup.push(tab.id));

        chrome.tabs
            .create({ url: `https://site2.com` })
            .then((tab) => tabsToGroup.push(tab.id));

        chrome.tabs.group({ tabIds: tabsToGroup });
    });
}

Full error message

Uncaught TypeError: Error in invocation of tabs.group(object options, optional function callback): Error at parameter 'options': Error at property 'tabIds': Value did not match any choice. at HTMLButtonElement.openTabs (popup.js:226:14)

enter image description here

I have set up chrome.tabs.group(). It has an object. And when I check thevalue of tabsToGroup it successfully returns an array.

Update item in handlebars

im using handlebars and i want to make a update page with the value of each item from my database on the “value” field, as i kinda did with my stock display page

{{#each itens}}
<!-- Item N:{{@index}} -->
<div clas="padding">
    <ul class="list-group ms-3 me-3 mt-3 mb-3">
    <li class="list-group-item active">Desc: {{Descricao}}</li>
    <li class="list-group-item">Quantidade: {{Quantidade}}</li>
    <li class="list-group-item">COD: {{Codigo}}</li>
    <li class="list-group-item">Preco: {{Preco}}R$</li>
    <li class="list-group-item">Preço de Compra: {{Pcompra}}R$</li>
    <li class="list-group-item">Lucro Liquido: {{Lucroliq}}R$</li>
    <li class="list-group-item">Lucro : {{Lucro}}%</li>
    <a href="/rotadeleteitem/{{id}}"><button class="btn btn-danger mt-2">Deletar</button></a>
    <a href="/edititem/{{id}}"><button class="btn btn-warning mt-2">Editar</button></a>
    </ul>
</div>
    <hr>
{{/each}}

in the {{#each itens}}
i can display the itens from my database

how can i use data from my database without using the each segment (need a individual reference for a single item on the database)

here’s how i tried to do:

<h1>Edição de item do estoque</h1>

<form action="/updateitem" method="POST">
    <p>Código</p>
    <input type="text" value="{{Codigo}}" name="Codigo" placeholder="Codigo  do Produto"> <br><br>
    <p>Descrição</p>
    <input type="text" value="{{Descricao}}" name="Descricao" placeholder="Descricao do Produto"> <br><br>
    <p>Quantidade</p>
    <input type="text" value="{{Quantidade}}" name="Quantidade" placeholder="Quantidade de itens"> <br><br>
    <p>Preço</p>
    <input type="text" value="{{Preco}}" name="Preco" placeholder="Preço do Produto"><br><br>
    <p>Preço de Compra</p>
    <input type="text" value="{{Pcompra}}" name="Pcompra" placeholder="Preço de Compra"> <br><br>
    <input type="submit" Enviar>
</form>