Add customer id or custom field to ClickPatrol from protection

We’re using ClickPatrol’s form protection.
To integrate it with HubSpot, we need to modify the main HubSpot JavaScript. Normally, this allows us to add custom inputs such as prefilled email addresses, user IDs, etc.

According to GetFormProtection.com, it’s possible to insert this data, but I’m not sure how to implement it. Can you advise on the correct method?

What is my main issue:
All the custom field we inject are not visible in Hubspot. The field:

customfield

is not getting visible in Hubspot.

My current hubspot code is looking like this some what:

<script>
  hbspt.forms.create({
    region: "na1",
    portalId: "123456",
    customfield: "name of the user"
    formId: "abcdef12-3456-7890-abcd-1234567890ab";
  });
</script>

The code that i get form get form protection is:

<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/embed/v2.js"></script>
<script charset="utf-8" type="text/javascript" src="https://api.getformprotection.com/?skid=[[user_id]]"></script>

So how to add the details like, region, portalId, formId and optional other fields like email?

I’ve tried to add te custom fields in a seperate js file also i’ve tried via tagmanager to inject them no results.

How can I make my parameters in a nested anonymous function for use in a separate module?

I have a module that contains a function(createForm()) which creates a form when executed. The form created has two text input boxes(for ‘task name’ and ‘task description’) as well as a submit button at the end of the form. The submit button currently console logs the two values entered from the user(userInputForTaskName and userInputForDescription).

In a separate module, I have a function getTaskData() which I call on createForm() then declares two variables(userInputForTaskName and userInputForDescription) which I want to assign the values that were entered and console logged to so that I can use them in a separate function but still in the same module.

How can I make the two values entered by the user in createForm() available for use in a function in a separate module?

This is my current createForm function:

export function createForm(onSubmit) {
    // CREATES <FORM>
    const form = createFormElement();
    // CREATES TEXT INPUT(TEXT BOX) FOR TASK NAME & TASK DESCRIPTION
    const taskNameLabel = createInputLabel('taskName', 'Task Name:');
    const taskNameInputElement = createTextInput('taskName');
    const taskDescriptionLabel = createInputLabel('taskDescription', 'Task Description:');
    const taskDescriptionInputElement = createTextInput('taskDescription');
    // CREATES SUBMIT BUTTON
    const submitButton = createSubmitButtonInput(
        taskNameInputElement, 
        taskDescriptionInputElement, 
        function(userInputForTaskName, userInputForDescription) {
            console.log(userInputForTaskName)
            console.log(userInputForDescription)
            
            taskNameLabel.remove();
            taskNameInputElement.remove();
            taskDescriptionLabel.remove();
            taskDescriptionInputElement.remove();
            submitButton.remove();

            return userInputForTaskName, userInputForDescription;
    });

In my current getTaskData() function, I call on createForm() to create the form, then I declare two variables(userInputForTaskName and userInputForDescription) and assign the values createForm.userInputForTaskName and const userInputForDescription = createForm.userInputForDescription; to them. At the end of the function, I created an alert for alert(createForm.userInputForDescription); to see if it’s working but the alert never executes leading me to think that the function ends when the submit button is clicked and that the user inputted data never makes it back to the getTaskData() function.

Stringify object hook dependency array issue

There are issues when it comes to dependency array giving inconsistent data when using value stringify in dependency array. When I filtered the data by cities the charts fails to filter out data when y variable is the same. Say for example I was filtering meetings in Tokyo, JP with 2 meetings and it will not change dot plot horizontally to current city to say Toronto, CN which also has 2 meetings. This is consistent inconsistency in the data whenever you have the city with the same number of objects, fails to notice the change in content of those objects fyi city name reference.

APP Main Component Code

import React from 'react';
import { useEffect, useState } from 'react';
import CitySearch from './components/CitySearch';
import EventList from './components/EventList';
import NumberOfEvents from './components/NumberOfEvents'
import { getEvents, extractLocations } from './api';
import './App.css';
import { CityAlert, NumberAlert, EventAlert } from './components/Alert';
import CityEventsChart from './components/CityEventsChart';
import EventGenresChart from './components/EventGenresChart';

const App = () => {
  const [events, setEvents] = useState([]);
  const [allLocations, setAllLocations] = useState([]);
  const [currentCity, setCurrentCity] = useState("See all cities");
  const [currentNOE, setCurrentNOE] = useState(32);
  const [cityAlert, setCityAlert] = useState("");
  const [numberAlert, setNumberAlert] = useState("");
  const [eventAlert, setEventAlert] = useState("");
  const [isOnline, setIsOnline] = useState(navigator.onLine);
  // const [defaultFiltered, setDefaultFiltered] = useState("")

  const updateOnlineStatus = () => {
    const online = navigator.onLine;
    setIsOnline(online);
    setEventAlert(online ? "" : "Currently viewing Offline Database");
  };
  useEffect(() => {
    updateOnlineStatus();
    fetchData();
    window.addEventListener("online", updateOnlineStatus);
    window.addEventListener("offline", updateOnlineStatus); 
    return () => {
      window.removeEventListener("online", updateOnlineStatus);
      window.removeEventListener("offline", updateOnlineStatus);
    };
  }, [currentCity, currentNOE]);

  const fetchData = async () => {
    const allEvents = await getEvents();
    const filteredEvents = currentCity === "See all cities" ?
      allEvents :
      allEvents.filter(event => event.location === currentCity)
    setEvents(filteredEvents.slice(0, currentNOE));
    setAllLocations(extractLocations(allEvents));
  }

  return (
    <div className="App">
      <h1 data-testid="outside-element">Meetup App</h1>
      <img className="time" alt="meet-logo" src='/calendar.png'></img>
      <div className="cityError-Message">
        {eventAlert.length ? <EventAlert text={eventAlert}/> : null}
      </div>
      <CitySearch 
        allLocations={allLocations} 
        setCurrentCity={setCurrentCity} 
        setCityAlert={setCityAlert} 
      />

      <div className="cityError-Message">
        {cityAlert.length ? <CityAlert text={cityAlert}/> : null}
      </div>
      <NumberOfEvents 
        currentNOE={currentNOE}
        setCurrentNOE={setCurrentNOE}
        setNumberAlert={setNumberAlert}
      />
      <div className="cityNumber-Message">
        {numberAlert ? <NumberAlert text={numberAlert}/> : null}
      </div>
      <div className="charts-container">
      <EventGenresChart
      events={events}
      />
      <CityEventsChart 
      allLocations={allLocations} 
      events={events} 
      />
      </div>
      <EventList 
        events={events} 
        setEventAlert={setEventAlert}
      />
    </div>
  );
}

export default App;
import mockData from './mock-data';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';  // Include the CSS for styling

export const getAccessToken = async () => {
  const accessToken = localStorage.getItem('access_token');
  const tokenCheck = accessToken && (await checkToken(accessToken));

  if (!accessToken || tokenCheck.error) {
    await localStorage.removeItem("access_token");
    const searchParams = new URLSearchParams(window.location.search);
    const code = await searchParams.get("code");
    if (!code) {
      const response = await fetch(
        "https://pp3rdn62qf.execute-api.us-east-1.amazonaws.com/dev/api/get-auth-url"
      );
      const result = await response.json();
      const { authUrl } = result;
      return (window.location.href = authUrl);
    }
    return code && getToken(code);
  }
  return accessToken;
};

export const extractLocations = (events) => {
  const extractedLocations = events.map((event) => event.location);
  const locations = [...new Set(extractedLocations)];
  return locations;
};

const checkToken = async (accessToken) => {
  const response = await fetch(
    `https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=${accessToken}`
  );
  const result = await response.json();
  return result;
 };
 
 const removeQuery = () => {
  let newurl;
  if (window.history.pushState && window.location.pathname) {
    newurl =
      window.location.protocol +
      "//" +
      window.location.host +
      window.location.pathname;
    window.history.pushState("", "", newurl);
  } else {
    newurl = window.location.protocol + "//" + window.location.host;
    window.history.pushState("", "", newurl);
  }
 };
 
export const getEvents = async () => {
  if (window.location.href.startsWith("http://localhost")) {
   return mockData;
  }
  if (!navigator.onLine) {
    const events = localStorage.getItem("lastEvents");
    NProgress.done();
    return events?JSON.parse(events):[];
  }
  const token = await getAccessToken();
  if (token) {
    removeQuery();
    const url =  "https://pp3rdn62qf.execute-api.us-east-1.amazonaws.com/
    dev/api/get-calendar- events" + "/" + token;
    const response = await fetch(url);
    const result = await response.json();

if (result) {
NProgress.done();
localStorage.setItem("lastEvents", JSON.stringify(result.events));
return result.events;
  } else {
    return null;
  }
};
return null;
};

const getToken = async (code) => {
  try {
    const encodeCode = encodeURIComponent(code);
 
const response = await fetch( 'https://pp3rdn62qf.execute-api.us-east-1.amazonaws.com/dev/api/token' + '/' + encodeCode);
if (!response.ok) {
  throw new Error(`HTTP error! status: ${response.status}`)
}
const { access_token } = await response.json();
access_token && localStorage.setItem("access_token", access_token);
return access_token;
  } catch (error) {
    error.json();
  }
 }

src/components/CityEventsChart.jsx

import React, { useState, useEffect } from 'react';
import {
  ScatterChart,
  Scatter,
  XAxis, YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  Label
} from 'recharts';   

const CityEventsChart = ( {allLocations, events}  ) => {
  const [data, setData] = useState([]);
  const getData = () => {
    const data = allLocations.map((location) => {
      const countnumber = events.filter((event) => event.location === location).length
      const city = location.split((/, | - /))[0]
      return { city, countnumber };
    })
    return data;
  };
  useEffect(() => {
    setData(getData());
  }, [JSON.stringify(events)]);// this works consistantly 

   // [`${events}`]) SAME NUMBER OBJECTS = SAME ARRAY WHEN VALUE SHOULD OF CHANGED CF PLEASE   INVESTIGATE
   
  return (
    <ResponsiveContainer width="50%" height={400}>
      <ScatterChart
        margin={{
          top: 100,
          right: 50,
          bottom: 100,
          left: 40,
        }}
      >
        <CartesianGrid />
        <XAxis type="category" dataKey="city" name="City"
          angle={60} interval={0} tick={{ dx: 20, dy: 40, fontSize: 14 }} >
        <Label value="Cities" offset={-70} position="insideBottom" />
        </XAxis>
        <YAxis type="number" dataKey="countnumber" name="Meetings" allowDecimals={false} >
        <Label value="Number of Meetings" offset={-120} position="insideLeft" />
        </YAxis>
        <Tooltip cursor={{ strokeDasharray: '3 3' }} />
        <Scatter name="A school" data={data} fill="#8884d8" />
     </ScatterChart>
    </ResponsiveContainer>
  );
}

export default CityEventsChart;

Event Genres Chart

import React from 'react';
import { PieChart, Pie, Cell, ResponsiveContainer, Legend } from 'recharts';
import { useEffect, useState} from 'react';

const EventGenresChart = ({ allLocations, events }) => {
  const [data, setData] = useState([]);
  const genres = ['React', 'JavaScript', 'Node', 'jQuery', 'Angular' ];
  const COLORS = ['#0088FE','#00C49F','#FFBB28','#FF8042','#8884d8'];
  const getData = () => {
    const data = genres.map((genre) => {
      const filteredEvents = events.filter(event => event.summary.includes(genre));      
      return {
        name: genre,
        value: filteredEvents.length
      }
    })
    return data;
  };
  useEffect(() => {
    setData(getData());
  }, [JSON.stringify(events)]);// this works consistantly 
  
  
 // [`${events}`]) SAME NUMBER OBJECTS = SAME ARRAY WHEN VALUE SHOULD OF CHANGED CF PLEASE  INVESTIGATE
  
return (
    <ResponsiveContainer width="50%" height={400}>
      <PieChart width={400} height ={400} >
        <Pie
            data={data}
            labelLine={false}
            outerRadius={125}
            fill="#8884d8"
            dataKey="value"
            label="name"
        >
            {data.map((entry, index) => (
              <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
            ))}
        </Pie>
        <Legend verticalAlign="bottom" height={36}/>
      </PieChart>
    </ResponsiveContainer>
  );
}

export default EventGenresChart;

City Search component

import React from 'react';
import { useState, useEffect, useRef } from "react";
import '../../src/App.css';

const CitySearch = ({ setCurrentCity, allLocations,  
setCityAlert}) => {
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [suggestions, setSuggestions] = useState(allLocations);
  const SuggestionListRef = useRef(null);
  const [eventAlert, setEventAlert] = useState("");
  const [query, setQuery] = useState("");

  const handleInputChanged = (event) => {
    const value = event.target.value;
    setQuery(value); // Always reflect what's typed
  
    const trimmedValue = value.trim();
  
    // Filter suggestions based on input
    const filteredSuggestions = allLocations.filter((location) 
=>    
location.toLowerCase().includes(trimmedValue.toLowerCase())
    );
  
    if (filteredSuggestions.length === 0) {
      setSuggestions([]);
      setCityAlert("We can not find the city you are looking 
      for. Please try another city.");
    } else {
      setSuggestions(filteredSuggestions);
      /// setCityAlert(""); CANNOT FIND FUNCTION DON'T GET 
      WHY!!!!
    }
    setShowSuggestions(true);
  };

  const handleItemClicked = (event) => {
    const value = event.target.textContent;
    setQuery(value);
    setShowSuggestions(false); // Hide suggestions
    setCurrentCity(value);
    setEventAlert("");
  };

  // Handle clicking outside the dropdown
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (SuggestionListRef.current && 
!SuggestionListRef.current.contains(event.target)) {
        setShowSuggestions(false); // Hide suggestions when 
    clicking outside
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", 
handleClickOutside);
    };
  }, [`${allLocations}`]);

  return (
    <div id="citySearch" data-testid="city-search">
        <h3>Choose your nearest city</h3>
      <input
        type="text"
        className="city"
        placeholder="Search City for meetings"
        value={query}


        onFocus={() => {
          if (query.trim() === "") {
            setSuggestions(allLocations);
          }
          setShowSuggestions(true);
        }}
        onChange={handleInputChanged}
        data-testid="search-input"
        />
      {showSuggestions && (
        <ul data-testid="CityList" className="suggestions" ref=. 
      {SuggestionListRef}>
          <div className="listCities">
            {suggestions.map((suggestion, index) => (
              <li
                className="cityName"
                onClick={handleItemClicked}
                key={`${suggestion}-${index}`}
              >
                {suggestion}
              </li>
            ))}
            <li
              className="cityName"
              key="See all cities"
              onClick={handleItemClicked}
            >
              <b>See all cities</b>
            </li>
          </div>
        </ul>
      )}
    </div>
  );
};

export default CitySearch;

Number of Events Component

import React from 'react';
import { useState } from "react";
import '../App.css';

const NumberOfEvents = ({setCurrentNOE, currentNOE, 
setNumberAlert }) => {
    const handleInputChanged = (event) => {
        const value = event.target.value;

        // Convert value to a number if it's a valid numeric 
        string
        const numericValue = Number(value);

        setCurrentNOE(value);

        // Validate the input
        if (isNaN(numericValue)) {
            setNumberAlert('Enter a valid number');
        } else if (numericValue < 1) {
            setNumberAlert('Number must be greater than 0');
        } else if (!Number.isInteger(numericValue)) {
            setNumberAlert('Input must be a whole number')
        }
        else
        {
            setNumberAlert('');
            setCurrentNOE(numericValue); // Update the main 
            state only when input is valid
        }
    };

    return (
        <div id="numberSearch" data-testid="number-of-events">
            <h5>Number of Events:</h5>
                <input 
                    className="eventNumber"
                    type="number"
                    value={currentNOE}
                    role="textbox"
                    onChange={handleInputChanged}
                    data-testid="NumberOfEventsInput"
                />
        </div>
    );
};

export default NumberOfEvents;

src/components/EventList.js

import React from 'react';
import Event from "./Event";
import '../../src/App.css';
const EventList = ({ events }) => {
 return (
   <ul className="event-list" data-testid="event-list">
     {events ?
       events.map(event => <Event key={event.id} event={event} 
         />) :
     null}
   </ul>
 );
}

export default EventList;

src/components/Event.js

import React from 'react';
import Button from './Button'
import '../../src/App.css';

const Event = ({ event }) => {
  return (
    <li className="event">
      <h3>{event.summary}</h3>
      <p className="eventAttribute">{event.start.dateTime}</p>
      <p className="eventAttribute">{event.end.dateTime}</p>
      <p className="eventAttribute">{event.location}</p>
      <Button event={event} />
    </li>
  );
}
  
export default Event;

How to replace require statement with import statement

I am struggling to get some sample code to work for learning purposes. This is the first two lines of code. How do I convert that to a simple javascript that will load the packages?

const tf = require('@tensorflow/tfjs');
const speechCommands = require('@tensorflow-models/speech-commands');

Clearly those are two packages on NPM, and I have downloaded them via NPM, but I don’t get how I am then supposed to use the packages in the javascript.

It seems like I should be able to download them, put them in a directory, and then import them. But I have not been able to get this to work.

import {tf} from @tensorflow/tfjs;
import {speechCommands} from @tensorflow-models/speech-commands;

This is where it comes from.

How is this site blocking .click() while allowing actual mouse clicks?

A site has a series of coupon buttons, each with a unique id. From the dev console, if I run document.getElementById('couponAddBtn1234').click() nothing happens. But if I manually click the button with the mouse, it triggers the button action.

I’ve tried triggering .click() on the parent element and also dispatching events for mousedown, mouseup and click but nothing works.

What magic is this site using to block/detect programmatic button clicks?

Markup of button element

How do I Implement “speaker_wav” for “tts-server” (coqui-ai), in a JavaScript API call

I am trying to send a “POST” request to the tts-server API, found at the endpoint “http://localhost:5002/api/tts”.

In the past I have had no issues working with the voices that don’t require an additional audio file to process. I.e. “tts_models/en/jenny/jenny”.

But my new requirements specifiy that I need to use xtts with a “speaker_wav” file to “clone” a voice.

Before when I used the “jenny” voice I used to have the “text” argument within a query string, so: “http://localhost:5002/api/tts?text=”${customText}””. Which I have tried adding the path for the speaker_wav to the query string, but it doesn’t seem to be looking there.

Next I tried moving everything into a body, with a JSON.stringify. That also doesn’t seem to want to work. I tried converting the data to a FormData object. Also didn’t work. And I even tried having the “text” in the query string with the “speaker_wav” and “language_idx” in the body with their values.

Now I am able to get this working with the “tts-server” terminal tool. For which I used this line:

tts --model_name tts_models/multilingual/multi-dataset/xtts_v2 --text "Testing, 1 2 3..." --speaker_wav "C:UserspersoDownloadsPhonetic SentenceConvertedspeaker.wav" --language_idx en

Which worked perfectly fine, but I am looking to avoid the spin up that comes from each one of those calls, where you include the “text”. The app is going to be running a good amount of these API calls, so that extra spin up time is going to total up fast.

If there is a way to include the “speaker_wav” file in the initial terminal call. To get the server running on “http://localhost:5002”. Then that would work too. Here is my current bat file that is used to call the “tts-server”:

set TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1

echo TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=%TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD%

"C:Userspersominiconda3envsTTSScriptstts-server.exe" --model_path "C:UserspersoAppDataLocalttstts_models--multilingual--multi-dataset--xtts_v2" --config_path "C:UserspersoAppDataLocalttstts_models--multilingual--multi-dataset--xtts_v2config.json"

Please feel free to ask any questions if I have not given enough information. I am unable to provide specifics due to the nature of the app. But I will try and reword to give the best possible information.

MudBlazor Drag&Drop between MudTable and MudDropZone

I have the razor page (with MudBlazor) with a MudTable at the top. The table displays . Beneath that, I have a grid of MudDropZones, rooms as columns and roles as rows. I called it . So a person has a duty in a room at a role. Existing Duties, you can successfully drag&drop inside the grid. But I want to create new Duties by grabbing a person from the MudTable and dragging it into the grid…. doesn’t work.The ItemDropped method does not fire. The cherry on top would be, if the dragged duty would be displayed as if the drag would have been started inside the grid.

Here is my minimalized Code:

@page "/duty2"

@* No marking while Drag&Drop *@
<div class="@(_isDragging ? "no-select" : "")">
    @* No scroll while Drag&Drop *@
    <div style="@(_isDragging ? "overflow: hidden; height: 350px;" : "overflow: auto; height: 350px;")">
        <MudTable Items="@_persons"
        Dense="true"
        Hover="true"
        Bordered="true"
        Striped="true"
        Virtualize="true"
        FixedHeader="true"
        Filter="new Func<Person,bool>(FilterFunc1)"
        SortLabel="Sort By"
        Loading="@_loading"
        @bind-SelectedItem="selectedItem1"
        Class="mud-table-sticky-header">
            <ToolBarContent>
                <MudText Typo="Typo.h6">Personen</MudText>
                <MudSpacer />
                <MudTextField @bind-Value="searchString1" Placeholder="Search"
                Adornment="Adornment.Start"
                AdornmentIcon="@Icons.Material.Filled.Search"
                IconSize="Size.Medium"
                Immediate="true"
                Class="mt-0" />
            </ToolBarContent>
            <HeaderContent>
                <MudTh><MudTableSortLabel SortBy="new Func<Person, object>(x=>x.PersonId)">ID</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortBy="new Func<Person, object>(x=>x.Lastname)" InitialDirection="SortDirection.Ascending">Lastname</MudTableSortLabel></MudTh>
                <MudTh><MudTableSortLabel SortBy="new Func<Person, object>(x=>x.Firstname)">Firstname</MudTableSortLabel></MudTh>
            </HeaderContent>
            <RowTemplate>
                <MudTd DataLabel="ID">
                    <div draggable="true" @ondragstart="e => OnOfficialDragStart(e, context)" style="cursor: grab;">@context.PersonId</div>
                </MudTd>
                <MudTd DataLabel="Lastname">
                    <div draggable="true" @ondragstart="e => OnOfficialDragStart(e, context)" style="cursor: grab;">@context.Lastname</div>
                </MudTd>
                <MudTd DataLabel="Firstname">
                    <div draggable="true" @ondragstart="e => OnOfficialDragStart(e, context)" style="cursor: grab;">@context.Firstname</div>
                </MudTd>
            </RowTemplate>
        </MudTable>
    </div>

    <MudDivider DividerType="DividerType.Middle" Class="my-6" />

    @if (_rooms == null)
    {
        <p>Loading...</p>
    }
    else
    {
        <MudDropContainer T="Duty"
        Items="_duties"
        ItemsSelector="@((item, dropzone) => item.Identifier == dropzone)"
        ItemDropped="ItemDropped"
        ItemRenderer="@DutyRenderer"
        Class="duty-table-container">

            <ChildContent>
                <table class="duty-table">
                    <thead>
                        <tr>
                            <th class="header-cell"></th>
                            @foreach (Room comp in _rooms)
                            {
                                <th class="header-cell" style="background-color:@comp.Color">@comp.Name</th>
                            }
                        </tr>
                    </thead>

                    <tbody>
                        @foreach (var role in _roles)
                        {
                            <tr>
                                <!-- Rowheader -->
                                <td class="role-cell">@role.Label</td>

                                @foreach (Room comp in _rooms)
                                {
                                    string identifier = $"{role.Id};{comp.RoomId}";
                                    <td class="dropzone-cell">
                                        <MudDropZone T="Duty" Identifier="@identifier" Class="mud-dropzone-box" />
                                    </td>
                                }
                            </tr>
                        }
                    </tbody>
                </table>
            </ChildContent>
        </MudDropContainer>



    }
</div>

@code {
    private string searchString1 = "";
    private bool _loading = false;
    private Person selectedItem1 = null;
    private HashSet<Person> selectedItems = new HashSet<Person>();
    private List<Person> _persons = new List<Person>();


    private List<Room> _rooms = new();
    private List<Duty> _duties = new();
    private RenderFragment<Duty> DutyRenderer => duty =>@<div class="duty-chip" style="background-color: @(string.IsNullOrWhiteSpace(duty.Person?.Color) ? "#e3f2fd" : duty.Person.Color);">@duty.Person?.Firstname<br />@duty.Person?.Lastname</div>;
    private bool _isDragging = false;
    private record Role(int Id, string Label);
    private List<Role> _roles = new() {
        new Role(1, "TL"),
        new Role(2, "BS"),
        new Role(3, "PR"),
        new Role(4, "MU"),
    };


    protected override async Task OnInitializedAsync()
    {
        _loading = true;
        _persons = new()
        {
            new Person() { PersonId = 1, Lastname = "Kirk", Firstname = "James T.", Color = "#2590ff;" },
            new Person() { PersonId = 2, Lastname = "McCoy", Firstname = "Leonard", Color = "#326711;" },
            new Person() { PersonId = 3, Lastname = "Scott", Firstname = "Montgomery", Color = "#87ab6c;" },
            new Person() { PersonId = 4, Lastname = "Uhura", Firstname = "Nyota", Color = "#f8f1cc;" },
            new Person() { PersonId = 5, Lastname = "Sulu", Firstname = "Hikaru", Color = "#54f834;" }
        };
        _loading = false;

        _rooms = new()
        {
            new Room() { RoomId = 1, Name = "R1", Color = "#889900;" },
            new Room() { RoomId = 2, Name = "R2", Color = "#9944cc;" },
            new Room() { RoomId = 3, Name = "R3", Color = "#00ff56;" },
            new Room() { RoomId = 4, Name = "R4", Color = "#cf2233;" }
        };

        _duties = new()
        { 
            new Duty(){ DutyId = 1, RoomId = 1, RoleId = 1, PersonId = 1, Person = new Person() { PersonId = 1, Lastname = "Kirk", Firstname = "James T.", Color = "#2590ff;" } },
            new Duty(){ DutyId = 1, RoomId = 2, RoleId = 4, PersonId = 2, Person = new Person() { PersonId = 2, Lastname = "McCoy", Firstname = "Leonard", Color = "#326711;" } },
            new Duty(){ DutyId = 2, RoomId = 3, RoleId = 2, PersonId = 2, Person = new Person() { PersonId = 2, Lastname = "McCoy", Firstname = "Leonard", Color = "#326711;" } },
            new Duty(){ DutyId = 3, RoomId = 2, RoleId = 3, PersonId = 4, Person = new Person() { PersonId = 5, Lastname = "Sulu", Firstname = "Hikaru", Color = "#54f834;" } }
        };
    }

    private bool FilterFunc1(Person element) => FilterFunc(element, searchString1);

    private bool FilterFunc(Person element, string searchString)
    {
        if (string.IsNullOrWhiteSpace(searchString))
            return true;

        string[] search = searchString.Split(" ");

        foreach (string s in search)
        {
            if (element.Firstname.Contains(s, StringComparison.OrdinalIgnoreCase)
                || element.Lastname.Contains(s, StringComparison.OrdinalIgnoreCase))
                continue;
            else
                return false;
        }
        return true;
    }


    private async void OnOfficialDragStart(DragEventArgs e, Person person)
    {
        _isDragging = true;

        Duty duty = new Duty()
            {
                PersonId = person.PersonId,
                RoleId = 0,
                RoomId = 0
            };

        await InvokeAsync(StateHasChanged);
    }

    private void ItemDropped(MudItemDropInfo<Duty> dropItem)
    {
        _isDragging = false;

        string[] dzi = dropItem.DropzoneIdentifier.Split(";");
        dropItem.Item.RoleId = Convert.ToInt32(dzi[0]);
        dropItem.Item.RoomId = Convert.ToInt32(dzi[1]);
    }


    public class Room
    {
        public int RoomId { get; set; }
        public string Name { get; set; }
        public string Color { get; set; }
    }

    public class Duty 
    {
        public int DutyId { get; set; }
        public int PersonId { get; set; }
        public int RoomId { get; set; }
        public int RoleId { get; set; }
        public Person Person { get; set; } 
        public string Identifier => $"{RoleId};{RoomId}";
    }

    public class Person
    {
        public int PersonId { get; set; }
        public string Lastname { get; set; }
        public string Firstname { get; set; }
        public string Color { get; set; }
    }
}

Fetch request to dummyapi.io fails in browser – CORS or app-id issue with vanilla JS?

I’m currently working on a small front-end project where the main goal is to fetch and display employee data from dummyapi.io using JavaScript. I want to create a simple user interface that lists employees with their name, picture, and other basic information, and style everything using CSS.

I’ve set up the fetch call using the required app-id in the headers as instructed by the dummyapi documentation. The structure of my code seems fairly straightforward. I’m using plain JavaScript (no frameworks yet) and standard CSS for styling. The issue I’m facing is that every time I try to make the request, I receive a fetch error in the browser console.

React useControllableState hook as a Vue composable

I am trying to build a component that can either be controlled or uncontrolled and I am trying to mimic how a React library Vaul uses this hook. The drawer component only calls the onChange handler if the component is uncontrolled.

If I try to mimic this behavior with Vue, I can use defineModel with watch but then if the parent controls the state the watcher will fire since the props are reactive.

I am looking for a bare bones example how I can turn this into a Vue composable. I tried returning computed({ get() {}, set()}) from a composable, but I was not able to mimic the same behavior.

const [isOpen = false, setIsOpen] = useControllableState({
    defaultProp: defaultOpen,
    prop: openProp,
    onChange: (o: boolean) => {
      onOpenChange?.(o);

      if (!o && !nested) {
        restorePositionSetting();
      }

      setTimeout(() => {
        onAnimationEnd?.(o);
      }, TRANSITIONS.DURATION * 1000);

      if (o && !modal) {
        if (typeof window !== 'undefined') {
          window.requestAnimationFrame(() => {
            document.body.style.pointerEvents = 'auto';
          });
        }
      }

      if (!o) {
        // This will be removed when the exit animation ends (`500ms`)
        document.body.style.pointerEvents = 'auto';
      }
    },
  });

Here is a React composable for useControllableState

import React from 'react';

type UseControllableStateParams<T> = {
  prop?: T | undefined;
  defaultProp?: T | undefined;
  onChange?: (state: T) => void;
};

type SetStateFn<T> = (prevState?: T) => T;

function useCallbackRef<T extends (...args: any[]) => any>(callback: T | undefined): T {
  const callbackRef = React.useRef(callback);

  React.useEffect(() => {
    callbackRef.current = callback;
  });

  // https://github.com/facebook/react/issues/19240
  return React.useMemo(() => ((...args) => callbackRef.current?.(...args)) as T, []);
}

function useUncontrolledState<T>({ defaultProp, onChange }: Omit<UseControllableStateParams<T>, 'prop'>) {
  const uncontrolledState = React.useState<T | undefined>(defaultProp);
  const [value] = uncontrolledState;
  const prevValueRef = React.useRef(value);
  const handleChange = useCallbackRef(onChange);

  React.useEffect(() => {
    if (prevValueRef.current !== value) {
      handleChange(value as T);
      prevValueRef.current = value;
    }
  }, [value, prevValueRef, handleChange]);

  return uncontrolledState;
}
export function useControllableState<T>({ prop, defaultProp, onChange = () => {} }: UseControllableStateParams<T>) {
  const [uncontrolledProp, setUncontrolledProp] = useUncontrolledState({ defaultProp, onChange });
  const isControlled = prop !== undefined;
  const value = isControlled ? prop : uncontrolledProp;
  const handleChange = useCallbackRef(onChange);

  const setValue: React.Dispatch<React.SetStateAction<T | undefined>> = React.useCallback(
    (nextValue) => {
      if (isControlled) {
        const setter = nextValue as SetStateFn<T>;
        const value = typeof nextValue === 'function' ? setter(prop) : nextValue;
        if (value !== prop) handleChange(value as T);
      } else {
        setUncontrolledProp(nextValue);
      }
    },
    [isControlled, prop, setUncontrolledProp, handleChange],
  );

  return [value, setValue] as const;
}

Sziaszok, szeretnék segítséget kérni html és css-el és javascripttel kapcsolatban, hogyan tudok [closed]

Nem tudok fethcelni javascripttel. sgeíííts 🙁

Szeretnék segítséget kapni

Még sok sok sok betűt le kell írjak mert nincs elég szó a kérdés feltételéhez el kell érjem a 220 karaktert, szóval gyors iderakom a palacsinta recepjét:
Hozzávalók
3 db tojás
2 ek cukor
1 csomag vaníliás cukor
240 g finomliszt
2.5 dl tej
2.5 dl szódavíz
0.5 dl napraforgó olaj

powerscript to create subfolders in folders

Am getting errors when executing powershell script.I got folders on the name of date DD MMM example 01 May,02 May go on to 31 May.I want to get the name of the folder 01 May covert it to 01 May 2025 to check if the date is monday then add subfolders of different name in it.But I got stuck with this part of code guving me errors when run

if([datetime]::TryParseExact(“$folderName $currentYear”, “dd MMM yyyy”, $null, [System.Globalization.DateTimeStyles]::None, [ref]$dateParsed)

how to proxy an iframe

I want to use an iframe to show some kind of chart with xmind-embed-viewer. inside this package there is iframe that send request to xmind.app and fetch some data and show it.
recently this website block our region so I need to use a proxy inside that iframe.
how can I do it ?

TypeError: 0, _reduxSaga.default is not a function (it is undefined), js engine: hermes

I’ve been working on a mobile app with Expo React-Native for a while. Everything worked fine with Expo 52.0.37 and React-Native 0.76.7. However, since updating to Expo 53.0.9 and React-Native 0.79.2, my app has been crashing with the following error when I call createSagaMiddleware():

TypeError: 0, _reduxSaga.default is not a function (it is undefined), JS engine: Hermes

The Redux-Saga version is 1.2.3. I encountered the same issue after updating it.

import AsyncStorage from '@react-native-async-storage/async-storage';
import {legacy_createStore as createStore, applyMiddleware} from 'redux';
import {persistStore, persistReducer} from 'redux-persist';
import createSagaMiddleware from 'redux-saga';
import logger from 'redux-logger';
import rootReducer from '@reducers';
import rootSagas from '@sagas';

/**
 * Redux Setting
 */
const persistConfig = {
  key: 'root',
  storage: AsyncStorage,
  blacklist: ['home', 'wishlist', 'list', 'messenger', 'notification'],
  timeout: 100000,
};
const sagaMiddleware = createSagaMiddleware();

let middleware = [sagaMiddleware];
if (process.env.NODE_ENV === `development`) {
  middleware.push(logger);
}

const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(persistedReducer, applyMiddleware(...middleware));
sagaMiddleware.run(rootSagas);
const persistor = persistStore(store);

export {store, persistor};

I’m trying to add redux-saga middleware.