TipTaps/ProseMirror: The CustomNode (CustomImage) can not disable or configure to “openOnClick: false”

I tried to create an Img Tag and then I can wrap the a tag around it, I tried to create the custom node Call CustomImage, I try some code from Generative AI and tweak but hard to understand, now I want to prevent it to click on the edit when it has link on them, it like the Link.configure({openOnClick: false,}), but since this is the custom node it does not have the property. and it seems my CustomImage is so fragile and might be broke because I just make it work not ensuring it stability and reusability and pass all test case.

here the secnario

  1. when the image is idle it can be select and can be add the link
  2. when I added the link it have the link and be clickable
  3. but when I tried to edit the link on the editor it just prompt me to the link on the image it can not be change the link.

Due to limit of how much code I can share, here is the github link that have all the code github.com/mk-working/tiptap-question/tree/main , Thank you

The Things I want to Archieved

My Current Situation

Creating a histogram in MUI X Charts with a reference line

I am creating a histogram in MUI X Charts using a Bar Chart component. I do the binning separately using d3.

I’ll provide a minimal working example. Let’s say that I have

const freqs = [23, 103, 280, 540, 589, 417, 276, 113, 32, 4, 4, 8, 2, 1]
const thresholds = [0.2, 0.4, 0.6, 0.8, 1, 1.2, 1.4, 1.6, 1.8, 2, 2.2, 2.4, 2.6, 2.8]

and that I create my “histogram” as follows.

<BarChart
  xAxis={[
    {
      data: thresholds,
      scaleType: 'band',
      categoryGapRatio: 0,
      tickPlacement: 'end',
      tickLabelPlacement: 'tick'
    }
  ]}
  series={[
    {
      data: freqs,
      type: 'bar'
    }
  ]}
/>

See the output here: histogram

I now want to set a reference line at x=0.7. I try to do this as follows:

<ChartContainer
  xAxis={[
    {
      data: labels,
      scaleType: 'band',
      categoryGapRatio: 0,
      tickPlacement: 'end',
      tickLabelPlacement: 'tick'
    }
  ]}
  series={[
    {
      data: freqs,
      type: 'bar'
    }
  ]}
>
  {/* Bars */}
  <BarPlot />
  {/* Standard chart extras */}
  <ChartsXAxis />
  <ChartsYAxis />
  <ChartsTooltip />

  {/* Reference line */}
  <ChartsReferenceLine
    x={0.7}
  />
</ChartContainer>

The problem is that my scaleType is not continuous, so I don’t get the desired output.

I can set x={0.8} and get a line, as shown in histogram with line. Note that it looks like it’s at x=0.6 because of the tick placement, but that’s something that I can deal with.

What can I do to achieve the desired behaviour?. The data is dynamic and will be constantly changing, so I would like to avoid hard-coding the thresholds.

Form Ajax Post, cannot access form request data

I have the following simple form and I am posting the form as JSON object, however, I can’t seem to be able to parse the json data on the API.

testing with the following two methods which both work and post the form content as json to the api, but I cant seem to be able to access the request data/body.

  $( "#signupBtn" ).on( "click", function(event) {
  event.preventDefault();
  var formData = new FormData(document.getElementById('signup'))   
  $.ajax({
      type: "POST",
      url: "http://campaign.marktech.ltd:8080/mt/signup.jssp",
      data: JSON.stringify(Object.fromEntries(formData)),
      processData: false,
      contentType: 'json',
      error: function(jqXHR, textStatus, errorMessage) {
          console.log(errorMessage);
      },
      success: function(data) {console.log(data)} 
  });
});


 /*   var form = document.getElementById('signup'); 
    $( "#signupBtn" ).on( "click", function(event) {

            var xhr = new XMLHttpRequest();
            var formData = new FormData(form);
            //open the request
            xhr.open('POST', 'http://campaign.marktech.ltd:8080/mt/signup.jssp')
            xhr.setRequestHeader("Content-Type", "application/json");
            //send the form data
            xhr.send(JSON.stringify(Object.fromEntries(formData)));
            xhr.onreadystatechange = function() {
              if (xhr.readyState == XMLHttpRequest.DONE) {
                //form.reset(); //reset form after AJAX success or do something else
              }
            }
            //Fail the onsubmit to avoid page refresh.
            return false;
         });
         */

and here is the bit of code the API returning a response after the post request is made

           var response = {
                            'response':'apiHelo',
                            'Refererr':request.getHeader("referer"),
                            'data':JSON.stringify(request.body)
                          }                  
                    
              document.write(JSON.stringify(response)); 

Here is the request json

enter image description here

The form is making contact with the api, the api is responding but I am trying to process,parse, or return the request data/body and doesnt work. Ive tried request.data request.body and also stringified it, to no avail. My goal is to return the request data back to the form for my testing, then I can be sure that I am accessing it correctly on the API and begin storing it.

enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>martech.network</title>
  <link rel="icon" href="https://martech.network/favicon.ico" type="image/x-icon">
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-4Q6Gf2aSP4eDXB8Miphtr37CMZZQ5oXLH2yaXMJ2w8e2ZtHTl7GptT4jmndRuHDT" crossorigin="anonymous">
  
  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-j1CDi7MgGQ12Z7Qab0qlWQ/Qqz24Gc6BM0thvEMVjHnfYGF0rmFCozFSxQBxwHKO" crossorigin="anonymous"></script>
  <!--<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>-->
</head>
<body>

<div class="container px-5 my-5">
<form id="signup">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="John"><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="Doe"><br><br>
  <input type="submit" id="signupBtn" value="Submit">
</form> 
</div>

    <script type="text/javascript">
    
          $( "#signupBtn" ).on( "click", function(event) {
          event.preventDefault();
          var formData = new FormData(document.getElementById('signup'))   
          $.ajax({
              type: "POST",
              url: "http://campaign.marktech.ltd:8080/mt/signup.jssp",
              data: JSON.stringify(Object.fromEntries(formData)),
              processData: false,
              contentType: 'json',
              error: function(jqXHR, textStatus, errorMessage) {
                  console.log(errorMessage);
              },
              success: function(data) {console.log(data)} 
          });
    });

    
    
     /*   var form = document.getElementById('signup'); 
        $( "#signupBtn" ).on( "click", function(event) {

                    var xhr = new XMLHttpRequest();
                    var formData = new FormData(form);
                    //open the request
                    xhr.open('POST', 'http://campaign.marktech.ltd:8080/mt/signup.jssp')
                    xhr.setRequestHeader("Content-Type", "application/json");
                    //send the form data
                    xhr.send(JSON.stringify(Object.fromEntries(formData)));
                    xhr.onreadystatechange = function() {
                      if (xhr.readyState == XMLHttpRequest.DONE) {
                        //form.reset(); //reset form after AJAX success or do something else
                      }
                    }
                    //Fail the onsubmit to avoid page refresh.
                    return false;
                 });
                 */
    </script>
</body>
</html>

Set iFrame Height Based on Today’s Date

I have a dozen iframes displaying content on the same WordPress page, but I want to set the iframe height to zero if a specified date for each iframe is less than the current date. Each iframe contains date sensitive content that I want to hide until specified dates. I have seen script that assigns a height to a variable, but I don’t know how to assign that variable to the frame height.

What I’m trying to do is set height= h.

Any help is appreciated.

<iframe width="694" height="666" frameborder="0" scrolling="no" 
src="https://docs.google.com/spreadsheets/...
</iframe>

I am trying to incorporate this script logic into the HTML:

script>    
  var end = new Date('2025-05-21');
  var now = new Date();
  if (end - now <= 0) {
    var h = "0";
  } else {
    var h = "666";
  }
</script>

How do I access other’s public user data from my Vite+React front end? I’m using Clerk

I am trying to access public user data from my Vite+React front end, but I need other users’ data. I do have a PHP back end, but the library for getting the data is broken. ChatGPT refuses to give me help besides telling me to use the broken library. Here is my current PHP file for fetching user data, and my React component that displays the data.

<?php
declare(strict_types=1);

require_once __DIR__ . "vendor/autoload.php";
include "env-variables.php";

use ClerkBackendClerkBackend;

header("Content-Type: application/json");

$clerkSecret = $env["clerk_secret"] ?? null;

if (!$clerkSecret) {
    http_response_code(500);
    echo json_encode(["error" => "Clerk secret key is not set."]);
    exit;
}

$userId = $_GET["id"] ?? null;

if (!$userId) {
    http_response_code(400);
    echo json_encode(["error" => "Missing user ID."]);
    exit;
}


try {
    $clerk = ClerkBackend::builder()
        ->setSecurity($clerkSecret)
        ->build();
    $response = $clerk->users->get($userId);

    if ($response->statusCode !== 200 || $response->user == null) {
        http_response_code($response->statusCode);
        echo json_encode(["error" => "Failed to retrieve user data."]);
        exit;
    }

    $user = $response->user;
    $publicData = [
        "id" => $user->id,
        "first_name" => $user->firstName,
        "last_name" => $user->lastName,
        "image_url" => $user->imageUrl,
    ];
    echo json_encode($publicData);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(["error" => "An error occurred.", "details" => $e->getMessage()]);
}
import { useEffect, useState } from "react"
import type Post from "../types/post"
import { useClerk } from "@clerk/clerk-react"

function formatDate(dateString: string): string {
    const date = new Date(dateString)
    return date.toLocaleDateString("en-US", {
        year: "numeric",
        month: "long",
        day: "numeric",
        hour: "numeric",
        minute: "2-digit",
    })
}

interface PostCardProps {
    post: Post
    isLink: boolean
}

export default function PostCard({ post, isLink, }: PostCardProps) {
    const clerk = useClerk()
    const [user, setUser] = useState<any>(null)

    useEffect(() => {
        async function fetchUser() {
            const fetchedUserRes = await fetch(`/api/get-user.php?id=${post.userid}`)
            const fetchedUser = await fetchedUserRes.json()
            setUser(fetchedUser)
        }
        fetchUser()
    }, [post, clerk])

    const element = <>
        <h2>{post.title}</h2>
        <div className="flex items-center gap-[.5rem]">
            <img src={user?.image_url} alt="#" />
            <span>{user?.username ?? user?.firstname ?? user?.email ?? "Anonymous"}</span>
        </div>

        <div className="ml-[1rem]">{post.text.split("n").map((line: string) => <p>{line}</p>)}</div>

        <span className="my-[.5rem] text-foreground-2 text-sm">Posted {formatDate(post.created_at)}</span>
    </>

    return isLink ?
        <a href={`/post.php?id=${post.id}`} className="override-typography flex flex-col p-[1rem] bg-theme border-[.2rem] border-foreground-2 rounded-[.5rem]">
            {element}
        </a>
        : <div className="flex flex-col p-[1rem] bg-theme border-[.2rem] border-foreground-2 rounded-[.5rem]">
            {element}
        </div>
}

FormData HTTP request sent by Angular is not readable by Spring backend

I am sending a File in a POST request using Angular. I use standard HttpClient and set the payload as FormData in order to send multipart/form-data:

const url = '...';
const formData = new FormData();
formData.append('file', file); // file is type File

this.httpClient.post(url, formData);

Since I don’t override Content-Type header, Angular creates it for me, together with the multipart ‘boundary’. That can be seen by copying the request as cURL in Chrome Dev tools:

-H 'content-type: multipart/form-data; boundary=----WebKitFormBoundary0jzgUXpnrXuu4Fjt'

However, the same cURL request shows, after all the headers (-H), a row that begins with --data-raw:

--data-raw $'------WebKitFormBoundary0jzgUXpnrXuu4Fjtrn...

Allegedly that --data-raw is not compatible with what the backend is expecting to read and is causing the request to fail when read.

When doing the request from Postman, setting the same form-data format with a File, the cURL request shows a different row after the headers, beginning with --form:

--form 'file=@"/path_to_file/file_name.ext"'

What else could I set to the request so that Angular sends it with --form instead of --data-raw so that the Spring backend could read it?

ERR_MODULE_NOT_FOUND Problem With NestJs And TypeOrm

I am getting the following error while running my NestJs (11.1.1) app with TypeOrm (0.3.24). I have searched for days but couldn’t find any answer to fix it so i decided to ask it here. The error i get is:

[Nest] 21495  - 05/21/2025, 10:34:53 PM    WARN [CLI Plugin] Skipping dtoFileNameSuffix option ".ts" because it can cause unwanted behaviour.
webpack 5.98.0 compiled successfully in 20943 ms
node:internal/modules/esm/resolve:1072
    throw error;
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/Documents/app/api/node_modules/typeorm/browser/globals' imported from /home/Documents/app/api/node_modules/typeorm/browser/index.js
    at finalizeResolution (node:internal/modules/esm/resolve:275:11)
    at moduleResolve (node:internal/modules/esm/resolve:932:10)
    at defaultResolve (node:internal/modules/esm/resolve:1056:11)
    at ModuleLoader.defaultResolve (node:internal/modules/esm/loader:654:12)
    at #cachedDefaultResolve (node:internal/modules/esm/loader:603:25)
    at ModuleLoader.getModuleJobForRequire (node:internal/modules/esm/loader:353:53)
    at new ModuleJobSync (node:internal/modules/esm/module_job:341:34)
    at ModuleLoader.importSyncForRequire (node:internal/modules/esm/loader:326:11)
    at loadESMFromCJS (node:internal/modules/cjs/loader:1411:24)
    at Module._compile (node:internal/modules/cjs/loader:1544:5) {
  code: 'ERR_MODULE_NOT_FOUND',
  url: 'file:///home/Documents/app/api/node_modules/typeorm/browser/globals'
}

Node.js v22.13.0

Here is my package.json

{
  "name": "api",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "build": "nest build",
    "format": "prettier --write "apps/**/*.ts" "libs/**/*.ts"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/apps/api/main",
    "lint": "eslint "{src,apps,libs,test}/**/*.ts" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./apps/api/test/jest-e2e.json"
  },
  "dependencies": {
    "@kafkajs/confluent-schema-registry": "^3.8.0",
    "@nestjs/axios": "^4.0.0",
    "@nestjs/cache-manager": "^3.0.0",
    "@nestjs/common": "^11.1.1",
    "@nestjs/config": "^4.0.0",
    "@nestjs/core": "^11.1.1",
    "@nestjs/jwt": "^11.0.0",
    "@nestjs/mapped-types": "^2.1.0",
    "@nestjs/microservices": "^11.1.1",
    "@nestjs/mongoose": "^11.0.1",
    "@nestjs/passport": "^11.0.5",
    "@nestjs/platform-express": "^11.1.1",
    "@nestjs/platform-socket.io": "^11.1.1",
    "@nestjs/swagger": "^11.0.4",
    "@nestjs/typeorm": "^11.0.0",
    "@nestjs/websockets": "^11.1.1",
    "@types/mongodb": "^4.0.7",
    "amqp-connection-manager": "^4.1.10",
    "amqplib": "^0.10.3",
    "axios": "^1.5.0",
    "cache-manager-redis-yet": "^4.1.2",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.14.0",
    "eureka-js-client": "^4.5.0",
    "jwks-rsa": "^3.1.0",
    "kafkajs": "^2.2.4",
    "liquibase": "^4.28.1",
    "mongodb": "^5.8.5",
    "mongoose": "^8.1.3",
    "npm-check-updates": "^17.1.14",
    "passport": "^0.6.0",
    "passport-jwt": "^4.0.1",
    "pg": "^8.9.0",
    "postgresql": "^0.0.1",
    "reflect-metadata": "^0.2.0",
    "rxjs": "^7.2.0",
    "socket.io": "^4.7.5",
    "typeorm": "^0.3.24",
    "uuid": "^9.0.1"
  },
  "devDependencies": {
    "@nestjs/cli": "^11.0.4",
    "@nestjs/schematics": "^11.0.1",
    "@nestjs/testing": "^11.1.1",
    "@types/cache-manager": "^4.0.6",
    "@types/express": "^4.17.13",
    "@types/jest": "29.2.4",
    "@types/js-yaml": "^4.0.5",
    "@types/node": "18.11.18",
    "@types/passport-jwt": "^3.0.10",
    "@types/supertest": "^2.0.11",
    "@types/uuid": "^9.0.8",
    "@typescript-eslint/eslint-plugin": "^5.0.0",
    "@typescript-eslint/parser": "^5.0.0",
    "eslint": "^8.0.1",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "jest": "29.3.1",
    "keyv": "^5.2.3",
    "prettier": "^2.3.2",
    "source-map-support": "^0.5.20",
    "supertest": "^6.1.3",
    "ts-jest": "29.0.3",
    "ts-loader": "^9.2.3",
    "ts-node": "^10.0.0",
    "tsconfig-paths": "4.1.1",
    "typescript": "^4.9.5"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": ".",
    "testRegex": ".*\.spec\.ts$",
    "transform": {
      "^.+\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "./coverage",
    "testEnvironment": "node",
    "roots": [
      "<rootDir>/apps/",
      "<rootDir>/libs/"
    ],
    "moduleNameMapper": {
      "^@app/shared(|/.*)$": "<rootDir>/libs/shared/src/$1"
    }
  }
}

and here is my tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "paths": {
      "@app/shared": [
        "libs/shared/src"
      ],
      "@app/shared/*": [
        "libs/shared/src/*"
      ]
    }
  }
}

Any help to fix this problem would be highly appreciated

Why Do Transformed Child Elements Show Bounding Box Offsets in Chrome?

When an element has a transformation applied, its child elements will have different computed values (e.g., from getBoundingClientRect()) compared to what is actually rendered on the screen. This issue isn’t limited to retrieving these values via JavaScript; you can also observe it using browser DevTools. For example, when you hover over an element with bilt-node=”rectangle” in DevTools, the overlay shown on the screen has a slight offset from the actual rendered element. This behavior has been tested in Chrome and may be browser-specific. Does anyone know the cause of this issue? Is it a bug or an expected behavior? If this is expected, does anyone know how to obtain the exact bounding values of the element?

You can see from the image, the blue overlay is not on top of the actual rendered element

html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  overflow: hidden
}


.zoom-canvas {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  user-select: none;
  touch-action: none;
  /* Prevent default touch behaviors */
}

.canvas {
  position: absolute;
  width: 100%;
  height: 100%;
}
<div style="position: fixed; left: 0; top: 0;     width: 489px;
    height: 618px;">
  <div data-v-36c7ab2d="" class="zoom-canvas" style="background-color: #1e1e1e;">
    <div data-v-36c7ab2d="" class="canvas" style="display: flex;justify-content: center;align-items: center;transform: translate(77.2px, -2915px) scale(11.72593);transform-origin: 0px 0px;">
      <div data-v-36c7ab2d="" class="relative" style="
    position: relative;
">
        <div bilt-node="rectangle" class="cursor-cell" style="left: -326px; top: -42.4445px; position: absolute; width: 100px; height: 100px; background-color: white;"></div>
      </div>
    </div>
</div>

How to rotate a 2d circle around another?

I’m trying to rotate a circle around another circle in 2d.

I have the following code implemented, which rotates the circle on its axis, however, I want to rotate the circle around the other one.

var w = window.innerWidth;
var h = window.innerHeight;

var canvas = document.createElement('canvas');

document.body.appendChild(canvas);

canvas.width = w;
canvas.height = h;

var ctx = canvas.getContext('2d');

var point = function(x,y,z,rgb) {this.x=x;this.y=y;this.z=z;this.rgb=rgb;}

class Circle {
    constructor(x,y,z,radius) {
        this.x=x;
        this.y=y;
        this.z=z;
        this.radius=radius;
        this.points = [];

         for(let i =0; i<360; i++) {
            let angle = Math.PI / 180 * i;
            let cos = this.x + Math.cos(angle) * this.radius;
            let sin = this.y + Math.sin(angle) * this.radius;
            this.points.push(new point(cos, sin, this.z, `rgb(${i}, ${i}, ${i})`));
    
    }
    }

    rotate() {
    for(let i =0; i<this.points.length; i++) {
        let p = this.points[i];
        let dx = Math.cos(Math.PI / 180) * (p.x - this.x) - Math.sin(Math.PI / 180) * (p.y - this.y);
        let dy = Math.sin(Math.PI / 180) * (p.x - this.x) + Math.cos(Math.PI / 180) * (p.y - this.y);

        p.x = dx + this.x;
        p.y = dy + this.y;
    }
}


drawX(points, i) {
    let p = points[i];
    ctx.beginPath();
    ctx.strokeStyle = p.rgb; 
    ctx.moveTo(p.x, p.y);
    ctx.lineTo(p.x + 1, p.y + 1);
    ctx.stroke();
}

draw(ctx) {
    for(let i =0; i<this.points.length; i++) {
       this.drawX(this.points, i);
    }
}

}

circle1 = new Circle(w/2, h/2, 10, 50); 
circle2 = new Circle(w/2+200, h/2, 10, 50);

function rotateAround(p1, p2) {
    for(let i =0; i<p1.length; i++) {
        for(let j =0; j<p2.length; j++) {
            let dx = Math.cos(Math.PI / 180) * (p1[i].x - p2[j].x) - Math.sin(Math.PI / 180) * (p1[i].y - p2[j].y);
            let dy = Math.sin(Math.PI / 180) * (p1[i].x - p2[j].x) + Math.cos(Math.PI / 180) * (p1[i].y - p2[j].y);

            p1[i].x = dx + p2[j].x;
            p1[i].y = dy + p2[j].y;
        }   
    }
}

function render(now) {
    //now *= 0.001;

    circle1.draw(ctx);
    circle1.rotate();

    circle2.draw(ctx);
    circle2.rotate();

    //rotateAround(circle1.points, circle2.points);       
    requestAnimationFrame(render);
}
render();

Unfortunately, the circles rotate but not around one another. What I have tried can be seen in the rotateAround method.

How do I go about solving this?

Any help would be muchly appreciated

How to autocomplete on 400,000 items in a database?

I have large dataset of 400,00 records in a mysql database, accessed by a java api to a hibernate repo. There is an Autocomplete component in Material UI that works nice for relately small datasets in memory. That won’t work for 400K records since I don’t have that much RAM.
How do I access just the data needed as the user types?

I have the database indexed, similar to this example.

import javax.persistence.*;
import org.hibernate.annotations.Index;

@Entity
@Table(name = "users", indexes = {
    @Index(name = "idx_email", columnList = "email"),
    @Index(name = "idx_lastname_firstname", columnList = "lastName, firstName")
})
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    private String email;

    private String firstName;
    private String lastName;

    // Add Getters and setters
}

That makes queries faster, but RAM still can’t hold it all. I presume I will need to limit the query to the first 100 records or so that match the input subset and replace the autocomplete list with that data. I haven’t tried that yet but it probably will be too slow for a good user experience.

Before I spend weeks experimenting, I thought I’d get suggestions here first, since it seems like it’s probably a common use case. All the examples I’ve googled so far have loaded all the data in RAM, even the “virtualized” ones.

How can I better code the replace text in this JavaScript using Google AppScript?

Below is the code and I’ve edited it so many times. The copy of the template is made and put into the corresponding folder, but the text isn’t being replaced. Now there is an error message for the replace text function.

function BeeSafePopInvoiceFromBookARideForm(e) {
    var timestamp = e.values[0];
    var emailaddress = e.values[1];
    var passengername = e.values[2];
    var phonenumber = e.values[3];
    var date = e.values[4];
    var time = e.values[5];
    var thisrideisfor = e.values[6];
    var billtoname = e.values[16];

    var templatefile = DriveApp.getFileById("13AyC4fpLo-iLDN_CeRmmlgLzJVx2Qj3ZSyLj1XQW2hU");
    var popinvoicefolder = DriveApp.getFolderById("1X__Ph7vxabpxdgbYABMe3W5RqFjYswnA");

    // fix is here 
    var copy = templatefile.makeCopy(passengername + "_" + date, popinvoicefolder);
    var copiedTemplateId = copy.getId();

    let doc = DocumentApp.openById(copiedTemplateId);
    
    const body = DocumentApp.getActiveDocument().getActiveTab().asDocumentTab().getBody();

    // body.replaceText() var body = doc.getBody()
    body.replacetext("{{Timestamp}}", timestamp);
    body.replacetext("{{Email Address}}", emailaddress);
    body.replacetext("{{Name}}", passengername);
    body.replacetext("{{Phone Number}}", phonenumber);
    body.replacetext("{{Date}}", date);
    body.replacetext("{{Time}}", time);
    body.replacetext("{{This ride is for}}", thisrideisfor);
    body.replaceText("{{Bill To Name}}", billtoname);

    doc.saveAndClose();
}

Why are these 2 different blocks of JavaScript code deployed in a Shiny App UI section conflicting with each other?

In running the below R Shiny code, the 2 sections of JavaScript appear to be conflicting with each other. One section of JS is in the tooltipFun() function and the other is in the module UI section; the JS in the module UI section allows the modal dialog to be dragged by the user. The modal dialog is triggered by clicking the single action button in this example.

Basically, commenting out this following block of module UI code for draggable-modal allows the tooltip to render correctly, but the modal can no longer be dragged.

tags$head(
  tags$script(src = "jquery-ui.min.js"),
  tags$style(HTML(".draggable-modal .modal-header { cursor: move; }")),
  tags$script(HTML("
    $(document).on('shown.bs.modal', '.draggable-modal', function () {
      var $dialog = $(this).find('.modal-dialog');
      if (!$dialog.hasClass('ui-draggable')) {
        $dialog.draggable({ handle: '.modal-header', containment: 'window' });
      }
    });
  "))
),

Activating that same block of module UI code allows the modal to be dragged, but the tooltip no longer renders.

Why do these 2 sections of JS collide with each other and how can this be corrected, so both the tooltip renders (as formatted currently including bullets) and the modal remains draggable?

In working with R Shiny I am very carefully making modules as independent as possible and locally scoping objects wherever I can. I am unsure of how to carefully scope JS code.

Some images help explain. This next image shows what happens when the draggable-modal JS is activated:

enter image description here

And this next image shows what happens when the draggable-modal JS is deactivated:

enter image description here

Here is the code:

library(shiny)

numInputFun <- function(inputId, value = 10, label_text = "", label_tooltip = NULL, ns = identity) {
  label <- if (!is.null(label_tooltip)) {
    tooltipFun(ns(inputId), label_text, label_tooltip, ns = ns)
  } else {
    label_text
  }
  tagList(
    tags$label(label),
    shinyWidgets::autonumericInput(
      inputId = ns(inputId),
      label = NULL,
      value = value,
      options = list(caretPositionOnFocus = "start")
    )
  )
}

tooltipFun <- function(id, label, tooltip_html, placement = "bottom", ns = identity) {
  tagList(
    tags$span(label, id = ns(id), title = ""),
    tags$script(HTML(sprintf(
      "$(document).ready(function() {
         $('#%s').attr('title', `%s`).tooltip({html: true, placement: '%s'});
       });",
      ns(id), tooltip_html, placement
    )))
  )
}

mod30_A_ui <- function(id) {
  ns <- NS(id)
  tagList(
    tags$head(
      tags$script(src = "jquery-ui.min.js"),
      tags$style(HTML(".draggable-modal .modal-header { cursor: move; }")),
      tags$script(HTML("
        $(document).on('shown.bs.modal', '.draggable-modal', function () {
          var $dialog = $(this).find('.modal-dialog');
          if (!$dialog.hasClass('ui-draggable')) {
            $dialog.draggable({ handle: '.modal-header', containment: 'window' });
          }
        });
      "))
    ),
    numInputFun(
      inputId = "periods",
      label_text = "Periods (x-axis)",
      label_tooltip = "TEST <ul><li>Point 1</li><li>Point 2</li></ul>",
      ns = ns
    ),
    br(),
    actionButton(ns("delSeries"), "Delete series"),
    br(),
    tableOutput(ns("seriesTable"))
  )
}

mod30_A_server <- function(id, mod10_data = NULL) {
  moduleServer(id, function(input, output, session) {
    ns <- session$ns
    seriesTbl_1 <- reactiveVal(data.frame(
      `Series 1` = c(1, 2, 3),
      `Series 2` = c(4, 5, 6),
      check.names = FALSE
    ))
    
    output$seriesTable <- renderTable(seriesTbl_1(), rownames = TRUE, bordered = TRUE)
    
    observeEvent(input$delSeries, {
      showModal(
        tags$div(class = "draggable-modal",
                 modalDialog(
                   title = "Delete Series (drag from here)",
                   selectInput(ns("delSelect"), "", choices = colnames(seriesTbl_1()))
                 )
        )
      )
    })
  })
}

# Dummy parent App
ui <- fluidPage(mod30_A_ui("mod30_A"))
server <- function(input, output, session) { mod30_A_server("mod30_A") }
shinyApp(ui, server)

Click Events of JSX Elements rendered programatically in the dom not setting state right

This is a weird one but I’m a major novice when it comes to React, I’m probably just doing this completely wrong but I’m trying to dynamically render a content tree. It starts with a single node and when the user clicks the +, it calls an API to get all the children of that node (if it hasn’t been already loaded) and add the children as inner nodes, which can then also be clicked to load those children, etc. The reason it’s done incrementally is to improve performance by only loading each necessary piece at a time rather than trying to load the whole tree at once, which can have thousands of items.

enter image description here

Here are the relevant parts of my code:

const [currentSelections, setCurrentSelections] = useState<any[]>();
const [contentMainRoot, setContentMainRoot] = useState<Root>();

const resetTree = () => {
  if (contentMainRoot) {
    contentMainRoot.render(<ul id={sitecoreRootId}></ul>);
  }
};

useEffect(() => {
  const rootElem = document.getElementById(sitecoreRootId);
  if (!rootElem) return;
  setContentMainRoot(createRoot(rootElem));
  resetTree();
}, [activeInstance]);

const toggleNode = async (e: any) => {
  if (!activeInstance) return;
  if (!e.target.classList.contains('loaded')) {
    const id = e.target.parentElement.getAttribute('data-id');
    const results = await GetItemChildren(activeInstance, id);
    const children = results.children;
    console.log(children);

    // append ul root
    let root = null;
    if (id + '-root' === sitecoreRootId && contentMainRoot) {
      root = contentMainRoot;
    } else {
      const rootElem = document.getElementById(id + '-root');
      if (!rootElem) return;
      root = createRoot(rootElem);
    }
    const innerTree = getInnerBrowseTree(id, children);
    root?.render(innerTree);

    e.target.classList.add('loaded');
    e.target.classList.add('open');
  } else {
    if (e.target.classList.contains('open')) {
      e.target.classList.remove('open');
    } else {
      e.target.classList.add('open');
    }
  }
};

const selectNode = (e: any) => {
  const id = e.target.parentElement
    .getAttribute('data-id')
    .replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5');
  const name = e.target.parentElement.getAttribute('data-name');
  console.log(id);

  if (e.target.classList.contains('selected')) {
    e.target.classList.remove('selected');
    // remove id
  } else {
    let selectedItem = { itemId: id, name: name };
    let selectedItems: any[] =
      currentSelections === undefined ? [selectedItem] : currentSelections?.concat(selectedItem);
    setCurrentSelections(selectedItems);

    e.target.classList.add('selected');
  }
};

const getInnerBrowseTree = (id: string, children: any[]) => {
  return (
    <ul id={id}>
      {children.map((child, index) => (
        <li key={index} data-name={child.name} data-id={child.itemId}>
          {child.hasChildren && <a className="browse-expand" onClick={(e) => toggleNode(e)}></a>}
          <a className="sitecore-node" onDoubleClick={(e) => selectNode(e)}>
            {child.name}
          </a>
          <ul id={child.itemId + '-root'}></ul>
        </li>
      ))}
    </ul>
  );
};

return (
  <>
    {browseContentOpen && (
      <div id="content-tree" className="content-tree">
        <div className="inner">
          <div className="flex items-center gap-2 mt-4">
            <ul>
              <li data-name="sitecore" data-id="{11111111-1111-1111-1111-111111111111}">
                <a className="browse-expand" onClick={(e) => toggleNode(e)}></a>
                <a className="sitecore-node" onDoubleClick={(e) => selectNode(e)}>
                  sitecore
                </a>
                <ul id={sitecoreRootId}></ul>
              </li>
            </ul>
            <ul>
              {currentSelections &&
                currentSelections?.map((item, index) => (
                  <li data-id={item.itemId} data-name={item.name} key={index}>
                    {item.name}
                  </li>
                ))}
            </ul>
            <Button variant="ghost" size="sm" onClick={() => setBrowseContentOpen(false)}>
              Close
            </Button>
          </div>
        </div>
      </div>
    )}
</>
)

The issue:
All the code to expand my tree nodes works right, but selectNode doesn’t work right because it always resets currentSelections to just the item I just clicked on. Within that code, when it checks currentSelections it is always undefined, even when I just set it previously. Even though I can see currentSelections actively updating where it’s displayed, when it’s accessed in the selectNode code it’s undefined so whenever I click an item, instead of getting [content] -> [content, media library] -> [content, media library, layout], I get [content] -> [media lirbary] -> [layout]

BUT if I select a node, CLOSE the modal (click the Close button), then reopen it, the previously selected value of currentSelections is still there, and the next thing i click gets ADDED to it rather than overwriting it; but again, when i click another item, it keeps the original item from before but overwrite the new one rather than adding to it.

I keep getting the error “TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))” How do I fix this? [closed]

I’m in the process of coding this FPS shooter game on Vercel but everytime I try to run a match in the game it gives me the error “TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))” How can I fix this?

I tried restarting and reloading the game, even debugging it but nothing works.