how to overrides the components present in Puck editor and insert a new one from context

i was using puck editor for web builder and has some components , i created a chatBot component and context file , chatbot will return a html code and i will set that value in context value but i wnatthat code into my editor as soon i got that value , for example AI code is in editor of builder

clientEditor.tsx

"use client";

import type { Data } from "@measured/puck";
import { DropZone, Puck } from "@measured/puck";
import config from "../../../puck.config";
import { useEffect, useState } from "react";
import ChatBox from "../../../components/ChatBox/ChatBox";
import { useAppContext } from "../../../contexts/HtmlContext";



export function Client({ path, data }: { path: string; data: Partial<Data> }) {
  const [isOpen, setIsOpen] = useState(false);
  const { html } = useAppContext();

  function ToggleChatBox() {
    setIsOpen((prev) => !prev);
  }

  const [puckData, setPuckData] = useState<Partial<Data>>({});

  useEffect(() => {
    if (html) {
      const newData =
        typeof html === "string" ? JSON.parse(html) : html;
      setPuckData(newData);

    }
  }, [html]);

  return (
    <div>
      {isOpen && (
        <div className="chatbox-container">
          <ChatBox />
        </div>
      )}

      <button className="chatgpt-btn" onClick={ToggleChatBox}>
        {isOpen ? (
          <i className="bi bi-x-lg" style={{ fontSize: "24px" }}></i>
        ) : (
          <i className="bi bi-chat-dots-fill" style={{ fontSize: "24px" }}></i>
        )}
      </button>

      <Puck
        config={config}
        data={puckData}
        onPublish={async (data) => {
          await fetch("/puck/api", {
            method: "post",
            body: JSON.stringify({ data, path }),
          });
        }}
      />

     
    </div>
  );
}

chatBot.tsx


import React, { useRef } from "react";
import "bootstrap/dist/css/bootstrap.min.css";
import { useState } from "react";
import "./style.css";
import axios from "axios";
import { useAppContext } from "../../contexts/HtmlContext";

export default function ChatBox() {
  const [chatHistory, setChatHistory] = useState<
    { role: "user" | "ai"; text: string }[]
  >([]);
  const userMsg = useRef<HTMLInputElement>(null);
  const {  setHtml } = useAppContext();
  const [isReplied, setIsReplied] = useState(false);

  async function SubmitUserMsg() {
    if (!userMsg.current) {
      return;
    }

    const msg = userMsg.current.value;
    if (msg.trim().length <= 0) {
      return;
    }

    setChatHistory((prev) => [
      ...prev,
      { role: "user", text: msg },
      { role: "ai", text: "Thinking..." },
    ]);

    setIsReplied(false);
    userMsg.current.value = "";
    userMsg.current.focus();

    try {
      const res = await axios.post(`${process.env.NEXT_PUBLIC_URL}/api/chat`, {
        messages: msg,
      });
      if (res.data.isResponse) {
       
        if(res.data.isHtml){
          const blockData = {
            content: [
              {
                type: "RawHTMLBlock",
                props: {
                  html: res.data.AIreply,
                },
              },
            ],
          };
          setHtml(blockData);
          
          
            
              
         
        }
        setChatHistory((prev) => {
          const updated = [...prev];
          updated[updated.length - 1] = { role: "ai", text: res.data.AIreply };
          return updated;
        });

        setIsReplied(true);
      }
    } catch (e) {
        
      setChatHistory((prev) => {
        const updated = [...prev];
        updated[updated.length - 1] = {
          role: "ai",
          text: "Error in AI response",
        };
        return updated;
      });
    }
  }

  function copyToClipboard(text: string) {
    navigator.clipboard
      .writeText(text)
      .then(() => {

      })
      .catch((err) => {
        console.error("Failed to copy: ", err);
      });
  }

  return (
    <>
    <div id="webcrumbs" className="bg-white">
      <div className="container-lg rounded-3 shadow-lg p-0 overflow-hidden bg-gradient">
        <div className="bg-white bg-opacity-80 p-3 border-bottom">
          <div className="d-flex justify-content-between align-items-center">
            <div className="d-flex align-items-center">
              <div className="bg-primary rounded-circle d-flex align-items-center justify-content-center me-3 icon-container">
                <i className="bi bi-robot text-white"></i>
              </div>
              <div>
                <h5 className="mb-0 fw-bold text-dark">AI Assistant</h5>
              </div>
            </div>
          </div>
        </div>

        <div className="message-container p-3">
          {chatHistory.map((item, ind) => {
            if (item.role === "user") {
              return (
                <div className="d-flex mb-3 justify-content-end" key={ind}>
                  <div className="bg-white rounded-3 p-2 max-width-75 overflow-hidden">
                    <p className="mb-0 text-break">{item.text}</p>
                  </div>

                  <div className="bg-secondary rounded-circle d-flex align-items-center justify-content-center ms-3 icon-sm">
                    <i className="bi bi-person text-white"></i>
                  </div>
                </div>
              );
            } else {
              return (
                <div className="d-flex mb-3" key={ind}>
                  <div className="bg-primary rounded-circle d-flex align-items-center justify-content-center me-3 icon-sm">
                    <i className="bi bi-robot text-white"></i>
                  </div>
                  
                  <div className={isReplied ? 'ai-message-wrapper d-flex flex-column max-width-75' : 'd-flex flex-column max-width-75' }>
                    <div className="bg-white rounded-3 p-3 border shadow-sm w-100">
                      <p className="mb-0 text-dark">{item.text}</p>
                    </div>
                    <button className="copy-btn "
                      onClick={() => copyToClipboard(item.text)}
                    >
                      <i className="bi bi-clipboard"></i>
                    </button>
                  </div>
                </div>
              );
            }
          })}
        </div>

        <div className="bg-white bg-opacity-90 border-top p-3">
          <div className="d-flex align-items-center">
            <div className="position-relative flex-grow-1 me-2">
              <input
                onKeyDown={(e) => {
                  if (e.key === "Enter") {
                    e.preventDefault();
                    SubmitUserMsg();
                  }
                }}
                ref={userMsg}
                type="text"
                placeholder="Type your message..."
                className="form-control rounded-pill ps-3 pe-5 border-0 bg-light"
              />
              <button
                onClick={SubmitUserMsg}
                className="btn btn-primary position-absolute end-0 top-50 translate-middle-y rounded-circle p-0 d-flex align-items-center justify-content-center send-btn"
              >
                <i className="bi bi-send text-white"></i>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    </>
  );
}

puck.config.ts

import type { Config } from "@measured/puck";
import { DropZone } from "@measured/puck";
import Image from "next/image";
import React, { useState, useEffect } from "react";
import HTMLrender from "./components/HTMLrender";

type Props = {

  RawHTMLBlock: {
    html: string;
  };

};

export const config: Config<Props> = {
  components: {

    RawHTMLBlock: {
      render: HTMLrender,
      fields: {
        html: {
          type: "textarea",
          label: "HTML",
          
        },
      },
    },
}
}

Htmlrenderer.tsx

export default function HTMLrender({ html}: { html: string }) {
    console.log("HTMLrender component received html:", html);
    return (
        <div dangerouslySetInnerHTML={{ __html: html }} />
    )
}```

in console log
{
    "content": [
        {
            "type": "RawHTMLBlock",
            "props": {
                "html": "<button type="button" class="btn btn-primary">Click Me</button>"
            }
        }
    ]
}

Display UI only to the user (hide during screen sharing on Zoom or Google Meet)

I need a solution for:
I have a Chrome extension developed with React, and I want to add a new feature. When a user shares their screen on online platforms such as Zoom or Google Meet, the extension page should be invisible to the viewers watching the screen. However, the user sharing their screen and using the extension should still be able to see the extension page and perform tasks as needed.

How does the Grammarly Chrome extension work on Discord’s message/text field?

Does anyone know how grammarly extension managed to change discord’s message input/text field content, i need some help

i am creating a chrome extension that will modify the text inside the discord’s message input/text field (means if user typed ‘hellow’, my extension will remove the word ‘hellow’ from the discord’s message box and insert a new word ‘hello’ at that place). But looks like discord is using slate.js (a rich text editor) and slate store all the user typed words in a JSON like format in somewhere react’s virtual DOM i guess, that slate internal data looks like this this: [{“type”:”paragraph”,”children”:[{“text”:”hellow”}]}],

so even if my vanilla javascript extension code try to change the DOM input field’s content using “element.textContetnt = ‘new modifed text’“, it is not going to work, because as soon as user start typing another/next word, slate.js will revert all the DOM changes to its original JSON content (means everthing revert back to ‘hellow’ word), i have no idea how can i access that JSON data or react’s virtual DOM using my extension, i tried .innerHTML, .textContetnt, appendChild, execCommand, but seems like they are limited to DOM. but grammarly is easily changing/inserting new text when i click on red underlined words on message field on discord website

how these chrome extensions managed to easily modify react’s virtual DOM, i am new to this…

Show UI Only to User (Hide During Screen Sharing on Zoom/Google Meet)

I have a Chrome extension built with React. I want to add a new feature:

When the user shares their screen (on online platforms like Googlemet, etc) the extension should still be visible and usable only to the user, but should not be visible to others watching the shared screen.

So basically, the extension should open and work normally, but be hidden from screen sharing.

In your proposal, please tell me:
Is this possible? Yes or No?
Have you built something like this before?
What method or technique would you use to do this?

Do I still need an Eloquent decimal cast for DECIMAL(10,6) columns in Laravel 12 / PHP 8.2?

I’m building a Laravel 12 e‑commerce site (PHP 8.2).
Product prices are stored in MySQL as DECIMAL(10,6):

base_price DECIMAL(10,6),
profit     DECIMAL(10,6)

Many articles recommend adding a cast in the model to avoid floating‑point errors:

AppModelsProduct
protected function casts(): array
{
    return [
        'base_price' => 'decimal:6',
        'profit'     => 'decimal:6',
    ];
}

What I tried

  • With no cast and with the decimal:6 cast I get exactly the same results in my calculations.
  • Simple test:
$a = "1097.500000";
$b = "835.700000";
$c = $a - $b;
dd($c);   // 261.8  (as expected)

No visible precision problems.

  • I also have more complex code that deals with profit, base_price, offer_price, and user discount calculations — and so far, I haven’t encountered any floating-point issues or inaccuracies in the results.
$priceSource = (is_numeric($product->offer_price) && $product->offer_price != 0)
    ? $product->offer_price
    : $product->base_price;

$grossPrice = $priceSource + $product->profit; 
$price = $grossPrice - ($grossPrice * $userVipDiscount / 100);

My confusion

  • If the column is already DECIMAL(10,6), does Eloquent still need the cast?

  • Have PHP 8.2 and Laravel 12 improved this enough that the extra cast is redundant?

  • In what practical situations would the decimal:6 cast still make a difference?
    I’d like to understand whether the cast is just defensive habit or still necessary for real‑world money calculations.

Magento 2.4.7-p6: zymion/module-seo-friendly-images 1.5.5 – Class ProductSelectBuilder does not exist on compile

After updating the module zymion/module-seo-friendly-images from version 1.5.4 to 1.5.5 on Magento 2.4.7-p6, I started getting the following error during dependency injection compilation (php bin/magento setup:di:compile):
Impossible to process constructor argument Parameter #16 [ ?MagentoSitemapModelResourceModelCatalogProductSelectBuilder $productSelectBuilder = NULL ] of ZymionSeoFriendlyImagesModelResourceModelCatalogProduct class

Class “MagentoSitemapModelResourceModelCatalogProductSelectBuilder” does not exist

pgsql
Kopiuj
Edytuj

  • This issue did not occur with version 1.5.4 of the module.
  • I have checked the Magento 2.4.7-p6 core code and there is no class called ProductSelectBuilder in MagentoSitemapModelResourceModelCatalog.
  • It seems the new version of the module expects this class to exist, but it doesn’t in my Magento version.

Questions:

  • Has anyone else encountered this issue?
  • Is this a bug in the module or a compatibility problem with my Magento version?
  • Is there a recommended workaround or patch for this problem?

Additional info:

  • Magento version: 2.4.7-p6
  • Module: zymion/module-seo-friendly-images
  • Problem started after upgrading from 1.5.4 to 1.5.5
  • Reverting to 1.5.4 solves the problem, but I would prefer to use the latest version if possible.

Any help or suggestions would be greatly appreciated!

Get Mollie payment API status woocommerce [closed]

I am using Woocommerce with Mollie payments.
If the payment is cancelled or failed Mollie redirect the user to the payment page on my website. For handling errors I want to know which status Mollie returns to my website so I can do something like

if(paymentStatus == 'faild'){ //do something } 

Somebody who knows to do this?

In Angular 19, on keydown event,Spacebar is not getting ignored

I am using Angular 19 keydown event on Textbox. It should allow only numbers and decimals up to 2 places. Valid numbers are: 123.45, 675.1, 12345 etc.

This works properly for all keys except Spacebar. Even though I have ignored it. On clicking Spacebar, 2 three times it inserts space in Textbox. My code is below:

onKeyDown = (event:KeyboardEvent): boolean {

const regex = new RegExp(/^[0-9.]*$/);  
if(!regex.test(event.key) && event.key.length === 1 && event.code !== "Space") {
    event.preventDefault();
    return false;
}     

const target = event.target as HTMLInputElement;
const start = target?.selectionStart || 0;
const value = target.value.substring(0,start)+event.key+target.value.substring(start);                                            

const newRegex = new RegExp(/^(0|[1-9]d*)?(.d{0,2})?$/
if(!newRegex.test(value) && event.key.length === 1 && event.code !== "Space") {
   event.preventDefault();
   return false;
}
return true;

}

Declaring state outside of a functional component

Is that a valid approach to move state logic out of function component code like this?

import { createStore } from 'solid-js/store'

const [user, setUser] = createStore(
  {name: 'Alice', params: {age: 25}},
)

const increaseAge = () => setUser('params', 'age', age => age + 1)

export default function UserProfile() {
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.params.age}</p>
      <div>
        <button onClick={increaseAge}>Increase age</button>
      </div>
    </div>
  )
}

XMLHttpRequest to ReqRes API returns 401 Unauthorized despite correct GET URL”

I’m trying to fetch user data from the ReqRes API using plain JavaScript and XMLHttpRequest inside a basic HTML file. The API is public and should not require authentication for a simple GET request.

<!DOCTYPE html>
<html>
<body>
  <p id="output">Default text</p>
  <input id="user_number" placeholder="Enter User ID (e.g. 2)">
  <button onclick="update_user()">Submit</button>

  <script type="text/javascript">
     function update_user() {
      let user_number = document.getElementById("user_number").value;
      let httpRequest = new XMLHttpRequest();

       httpRequest.onreadystatechange = function () {
         if (this.readyState === 4) {
           if (this.status === 200) {
             let user_data = JSON.parse(this.responseText);
             document.getElementById("output").innerHTML =
               "Name: " + user_data.data.first_name + " " + user_data.data.last_name;
           } else {
             document.getElementById("output").innerHTML =
               "Error: " + this.status + " (" + this.statusText + ")";
           }
          }
       };

       httpRequest.open("GET", "https://reqres.in/api/users/" + user_number);
       httpRequest.send();
     }
   </script>
  </body>
 </html>

Even when I enter a valid user ID like 2, I keep getting:

Error: 401 (Unauthorized)
I’m not adding any headers or tokens.

The URL works fine directly in the browser:
https://reqres.in/api/users/2 returns valid JSON.

I’m serving the file using a local HTTP server (python -m http.server), not as a file:// URI.

Tested in multiple browsers — same issue.

What I’ve Tried:
Inspecting the Network tab → shows 401 status.

Confirmed that no Authorization header is being sent.

Tried using fetch() instead of XMLHttpRequest → same result.

Expected Result:
A 200 OK response and user data like:
{
“data”: {
“id”: 2,
“first_name”: “Janet”,

}
}

Question:
Why am I receiving a 401 Unauthorized error when calling a public GET endpoint on ReqRes, and how can I fix this?

Creating a website that imitates a desktop environment with internal web browser and various pages inspired by GTA 4/5’s eyefind.info

I have a concept for a website & am struggling to find resources that would help me execute the concept. I am somewhat familiar with HTML & have some experience with various WYSIWYG editors.

I would like to create a website that imitates a desktop environment w/ its own internal web browser, faux websites & search functionality. My inspiration for this concept is eyefind.info from the Grand Theft Auto series. The goal is to create a framework that imitates / parodies internet culture of the early 2000s. I want the user to feel as though they have logged onto their computer and are browsing the internet in this fictional world.

I have seen others create desktop environments for the purpose of personal portfolios etc., but these systems seem too complex for my needs. I simply want to create the facade or illusion of being logged in & browsing this fictional world’s web.

For those that have never played GTA 4/5, you can watch this video to see what I’m after. Basically, the user accesses a computer in game which brings up a page that imitates a generic early-2000s desktop. The user can then click on “Web” to bring up an overlay that imitates a web browser & scrolls independently of the “desktop” background. The user can then navigate the “internet” in various ways, either by clicking various links on the hub, utilizing search functionality or by manually inputting a “domain” name that will point to a specific page.

The domain & search functionalities do not need to communicate with the rest of the internet or search engines such as google, all “domains” and search queries will either point to an internal webpage, show search results for internal pages or simply return a generic error such as “this website does not exist” or “no results found”.

I apologize for the broad nature of this question & for not providing samples of previous attempts, I simply don’t know where to look to find the information I need to even begin a project like this.

Storybook/react/webpack5 unable to index

I have a project (node 24, react16, webpack5 & babel )and I’m trying to integrate it with storybook9; when I run the script npm run storybook

It throws:

...
Unable to index ./src/components/Button/stories/index.story.js:
  Error: Invariant failed: No matching indexer found for /Users/me/my-project/src/components/Button/stories/index.story.js
...

main.js

/** @type { import('@storybook/react-webpack5').StorybookConfig } */
const config = {
  stories: [ "../src/**/stories/index.story.@(js|jsx)" ],
  addons: [
    "@storybook/addon-docs",
    "@storybook/addon-webpack5-compiler-babel"
  ],
  framework: {
    name: "@storybook/react-webpack5",
    options: {
        fsCache: true,
        lazyCompilation: true,
      },
  },
};
export default config;

and my story file is

import React, { lazy } from 'react';
import { fn } from 'storybook/test';

import Button from '..';

const InnerComponent = lazy(() => new Promise((resolve) => {
  setTimeout(() => resolve(import('./mockComponent')), 1000);
}));
const Loader = () => <div>Loading...</div>;

export default {
  title: 'Button',
  component: Button,
  tags: ['autodocs'],
  args: {
    Loader,
    Component: InnerComponent,
  },
};

Am I missing something?

array.filter not returning array on click

i am trying to filter() an array using buttons instead of using an input fields when i use console.log() it return the information i want but when i use return nothing is happening

my array looks something like this

let rankList = [
{"invoice_no": "20174", 
"invoice_item_final_amount": 81.86, 
"invoice_total_tax": 40.98, 
"invoice_created_date": "5/31/2011", 
"invoice_customer": "David Lee", 
"invoice_project": "Project E", 
"invoice_tag": "food", 
"invoice_due_date": "6/6/2022", 
"invoice_status": "Paid"
}
...]

array = []

invoice_status can have serveral values eg, unpaid, paid

this is my function for filtering the array

function btnfilter(filter = null){
   let dataTable_filter = filter; 
   if(dataTable_filter != null){
      let temp_array = rankList.filter(function(object){
          return object.invoice_status === filter;
      });
      array = temp_array;
   }else{
      array = rankList;
   }
}

and i am trying to call btnfilter using the click event handler

const unpaidBtn = document.querySelector('[data-quickbtn="unpaid"]');
unpaidBtn?.addEventListener("click", () => {
   btnfilter("Unpaid");
})

but if i call the btnfilter() directly and change it to

function btnfilter(filter = "Unpaid"){
    let dataTable_filter = filter; 
    if(dataTable_filter != null){
        let temp_array = rankList.filter(function(object){
           return object.invoice_status === filter;
        });
       array = temp_array;
    }else{
    array = rankList;
}

}

it works but i cant get it to work on click button

sorry english is not my stongest subject

if i console.log() i get true results i wanting but the second i use return nothing works