How to set and get Telegram Web App CloudStorage key value?

Can anyone explain how to?

const student = JSON.stringify(Telegram.WebApp.initDataUnsafe);
const key = 'user_data';
Telegram.WebApp.CloudStorage.setItem(key, student, (error, success) => {
               if (error) {
                   alert('Error storing JSON string:', error);
               } else if (success) {
                   alert('JSON string stored successfully');

   Telegram.WebApp.CloudStorage.getItem(key, (error, value) => {
        if (error) {
            alert('Error retrieving JSON string:', error);
                    } else {
            alert('Retrieved JSON string:', value);
        }
    });
        }
        });

Did it according to https://core.telegram.org/bots/webapps#cloudstorage
but receive empty value and no errors every attempt. Shall I init CloudStorage on a server side?

Need to capture the value from a specific field on the standard record edit page in real-time, before the Save button is clicked on Salesforce

I need to capture the value from a specific field on the standard record edit page in real-time, before the Save button is clicked, validate it, and then display the corresponding alert in the custom LWC component.

I try to capture the value from the “Amount” field on the standard record edit page in real-time, validate it, and then display the appropriate alert in the custom LWC component.
Opportunity standard record edit page

SharePoint Content Editor like Functionality

I need help to achieve Sharepoint’s Content Editor like functionality (SharePoint basically allows users to add their custom script + HTML or HTML file to import on the Sharepoint’s page). I want to do some customisation in my Angular SPA and want to further customize the app using external HTML + JS Code for different environment as this is SaaS application and every environment is different. I am try to do this by using following code but I did not get any success.

Basic Idea is external HTML will have code which can interact with the app and further customize it

<html>
<script>
const promiseOfSomeData = fetch("https://....somesite/Test.html").then(r=>r.text()).then(data => {
    console.log('in async');
    return data;
});
window.onload = async () => {
    let someData = await promiseOfSomeJsonData;
    document.querySelector('#some.selector').innerHTML = body;
    console.log("onload");
};
</script>

This is Native Code and HTML here

I’m trying to make an outline/sketch (as in the pictures) of a three js 3d model

Hello everyone, please tell me, I want to achieve the effect of tracing the model and highlighting its lines, as in the picture, but the object remains blue. How can you make such an effect, I don’t understand anything, thank you!

project codecode

Примеры как должно быть:

enter image description here

enter image description here

enter image description here

My Model and Project:

model index

I tried this option and got this result: enter image description here

code:

   // Uploading your model (.glb or .gltf)
    const loader = new GLTFLoader();
    loader.load(
      '/models/825001.glb', // The path to your model
      (gltf) => {
        const model = gltf.scene;

        // We change the materials of the model to white
        replaceMaterialsWithWhite(model);

        //Adding a model to the scene
        scene.add(model);

        // Updating OutlinePass after loading the model
        outlinePass.selectedObjects = [model];
      },
      undefined,
      (error) => {
        console.error('Model loading error:', error);
      }
    );

    // Post-processing with stroke effect
    const composer = new EffectComposer(renderer);
    const renderPass = new RenderPass(scene, currentCamera);
    composer.addPass(renderPass);

    const outlinePass = new OutlinePass(new THREE.Vector2(window.innerWidth, window.innerHeight), scene, currentCamera);
    outlinePass.edgeStrength = 5.0;    // The strength of the visible stroke (increase the value for a thicker stroke)
    outlinePass.edgeGlow = 0.0;        // Светящийся эффект (0 - отключен)
    outlinePass.edgeThickness = 2.0;   // Stroke thickness
    outlinePass.pulsePeriod = 0;       // Ripple animation (0 - disabled)
    outlinePass.visibleEdgeColor.set(0x000000);  // black outline color
    outlinePass.hiddenEdgeColor.set(0x000000);   // Black outline color for hidden parts
    composer.addPass(outlinePass);

How to achieve advanced autocompletion in React CodeMirror?

I’m trying to implement a code editor on my react site, I need to implement a pretty good autocompletion for Python. I ran into a problem, which is that I haven’t figured out how to add some ready-made solutions here (to be honest, I haven’t even found any yet). Speaking of my own attempts, I tried to solve this by adding my provider: autocompletion({ override: [customCompletionProvider] }),.
Also its code:


    const customCompletionProvider = (context) => {
      const word = context.matchBefore(/w*/);
    
      const code = context.state.doc.toString();
    
      // detect variables in code
      const variableDeclarationPattern = /(w+)s*=s*(.+)/g;
      let match;
      while ((match = variableDeclarationPattern.exec(code)) !== null) {
        const [_, varName, varValue] = match;
        if (/['"]/.test(varValue)) variables[varName] = "str";
        else if (/[.*]/.test(varValue)) variables[varName] = "list";
        else if (/(.*)/.test(varValue)) variables[varName] = "tuple";
        else if (/{.*}/.test(varValue)) variables[varName] = "dict";
        else if (/[-+]?d+/.test(varValue)) variables[varName] = "int";
        else if (/[-+]?d*.d+/.test(varValue)) variables[varName] = "float";
      }
    
      // method call through dot? =>
      const dotMatch = context.matchBefore(/w+.w*/);
      if (dotMatch) {
        const [variable, methodStart] = dotMatch.text.split(".");
    
        if (variables[variable]) {
          const methods = getMethodsForType(variables[variable]);
          return {
            from: dotMatch.from + variable.length + 1,
            options: methods.map((method) => ({
              label: method,
              type: "method",
            })),
          };
        }
      }
    
      const letterMatch = context.matchBefore(/[a-z]|[A-Z]/);
      console.log(letterMatch);
    
      if (!letterMatch) {
        return null;
      }
    
      const basicSuggestions = [
        { label: "print", type: "function" },
        { label: "len", type: "function" },
        { label: "str", type: "type" },
        { label: "int", type: "type" },
        { label: "list", type: "type" },
        { label: "dict", type: "type" },
        { label: "tuple", type: "type" },
        { label: "def", type: "function" },
        { label: "class", type: "class" },
        { label: "async", type: "keyword" },
        { label: "return", type: "keyword" },
        { label: "yield", type: "keyword" },
      ];
    
      return {
        from: word.from,
        options: basicSuggestions.filter((suggestion) =>
          suggestion.label.startsWith(word.text)
        ),
      };
    };

Besides the fact that my version doesn’t work very well, to put it mildly, it also overrides the basic autocompletion, which I wouldn’t want to lose.
Also code of component:


    <CodeMirror
      value={value}
      height="330px"
      width="1000px"
      extensions={[
        python(),
        indentUnit.of("    "),
        autocompletion({ override: [customCompletionProvider] }),
        onUpdateExtension,
      ]}
      onChange={onChange}
      theme={Theme}
    />;

Also i’m using onUpdateExtension:


    const onUpdateExtension = EditorView.updateListener.of((update) => {
      if (update.docChanged) {
        const { state } = update.view;
        const doc = state.doc.toString();
        const lastChar = doc[doc.length - 1];
    
        if (lastChar === ".") {
          startCompletion(update.view);
        }
      }
    });

PS: my main goal is to add hints for variable methods, right after typing the dot

How should I handle a Control+Click on an unfocused browser window?

I can’t find a way to detect that a key is down at the time when the window comes into focus: Javascript event listeners fail because they cannot trigger when the window is not in focus.

This results on jarring behavior, as my web page handles standalone clicks very differently from the Control+Click combination.

My idea for how to mitigate this problem is to ignore the click that brings the window into focus, but I’m not entirely happy with this.

(I’m also considering doing nothing about it because I imagine this problem is a lot less common in production, but I’m even less happy with this)

Comment lier un cookie a un bouton radio pour le disabled [closed]

Voila mon probleme: j’ai des boutons radio dans une boucle, dans un formulaire (en spring boot) et j’aimerai que le bouton radio qui a ete coche reste coche apres soumission du form et surtout quand on reviens sur la page de choix, histoire de ne pas pouvoir recoche le meme choix(en JS). En gros, je fais un choix, je submit =>ca m’envoie sur une autre page mais quand je reviens sur ma page de choix, le choix precedent devra etre disabled. J’arrive a disabled le bouton, a save le form, a creer un cookie mais je n’arrive pas a faire les 3 en meme temps…
Je vous mets mon form :

<form action="#" th:action="@{/piece}" modelAttribute="piece"  method="post"
     name="formP" onsubmit="saveform()">
        <tr th:each="piece: ${pieces}">
            <input type="submit" name="submit" value="${piece.nom}" th:value="'Valider : '+ ${piece.nom}"
             onsubmit="" />
            <label class="radio-image">
                <input type="radio" name="img" th:value="${piece.img}" onclick="check()"  required>
                <img th:src="@{${'/images/'+ piece.img}}" />
            </label>
            <br>
        </tr>
    </form>

Merci de votre aide

Ma fonction js pour rendre mon bouton non cochable et recupere mon cookie:

function check() {
    var btnPieceRad = document.getElementsByName('img');
    for (i = 0; i < btnPieceRad.length; i++) {
        if ((btnPieceRad[i].checked )) {
            var valeur = btnPieceRad[i].value;
 
            btnPieceRad[i].disabled = true;
            document.cookie = 'cdtest=' + valeur + ';path=/piece;';
        }
    }

Voila je ne trouve pas comment faire pour que en revenant sur la page le 1er choix soit deja coche.

Get filtered data only from SapUi 5 Table

I have an application using a table of type sap.ui.table.Table.
The table is setup using data binding using a local sap.ui.model.json.JSONModel and calling setModel() on the table itself. Sorting and filtering is also enabled so the user can easily show the data he needs. So far this works great.

My issue now is, is there a way to get the data based on the ordering and filter the user applied to the table? I would like to create a sum of values based on the current view.

I tried to call getRows() on the table, but it only returns the visible rows on screen. If there are more, those values are not returned. Other than that I don’t find a matching method on table or the model that could return that data.

So is there a way to get that data or do I have to read the filter values and filter the data myself manually?

Prevent dragging image over container boundaries in React JS

In my react js application i am trying to create a zoomable image with the possibility to drag image in zoom mode.

import "./styles.css";
import React, { useState, useRef, useEffect } from "react";

export default function App() {
  const [isDragging, setIsDragging] = useState(false);
  const [zoomLevel, setZoomLevel] = useState(1);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
  const imgRef = useRef(null);
  const containerRef = useRef(null);

  useEffect(() => {
    if (zoomLevel === 1) {
      setPosition({ x: 0, y: 0 }); // Reset position when zoom level is 1
    }
  }, [zoomLevel]);

  const handleWheel = (e) => {
    e.preventDefault();
    const zoomAmount = e.deltaY * -0.001;
    setZoomLevel((prevZoom) => Math.min(Math.max(prevZoom + zoomAmount, 1), 5));
  };

  const handleZoomIn = () => {
    setZoomLevel((prevZoom) => Math.min(prevZoom + 0.1, 5));
  };

  const handleZoomOut = () => {
    setZoomLevel((prevZoom) => Math.max(prevZoom - 0.1, 1));
  };

  const calculateBoundaries = () => {
    if (!imgRef.current || !containerRef.current) return;

    // Get bounding rects
    const containerRect = containerRef.current.getBoundingClientRect();
    const imageRect = imgRef.current.getBoundingClientRect();

    // Calculate boundaries
    const minX = containerRect.left - imageRect.width + position.x; // Allow dragging to the left edge
    const maxX = containerRect.right - position.x; // Prevent dragging past the right edge
    const minY = containerRect.top - imageRect.height + position.y; // Allow dragging to the top edge
    const maxY = containerRect.bottom - position.y; // Prevent dragging past the bottom edge

    return { minX, maxX, minY, maxY };
  };

  const handleMouseDown = (e) => {
    if (zoomLevel === 1) return; // Disable dragging if not zoomed
    e.preventDefault();
    setIsDragging(true);
    setDragStart({
      x: e.clientX - position.x,
      y: e.clientY - position.y,
    });
  };

  const handleMouseMove = (e) => {
    if (!isDragging) return;
    e.preventDefault();
    // Calculate the distance dragged

    const { minX, maxX, minY, maxY } = calculateBoundaries();
    const newX = e.clientX - dragStart.x;
    const newY = e.clientY - dragStart.y;

    // Apply boundaries to the new position
    const updatedX = Math.min(Math.max(newX, minX), maxX);
    const updatedY = Math.min(Math.max(newY, minY), maxY);

    setPosition({
      x: updatedX,
      y: updatedY,
    });

    // Change cursor based on position
    if (
      updatedX === minX ||
      updatedX === maxX ||
      updatedY === minY ||
      updatedY === maxY
    ) {
      document.body.style.cursor = "not-allowed"; // Change cursor to not-allowed if at boundary
    } else {
      document.body.style.cursor = isDragging ? "grabbing" : "grab"; // Default cursor
    }
  };

  const handleMouseUp = () => {
    setIsDragging(false);
    document.body.style.cursor = "default"; // Reset cursor when dragging stops
  };

  return (
    <div>
      <div className="zoom-controls">
        <button onClick={handleZoomIn}>Zoom In</button>
        <button onClick={handleZoomOut}>Zoom Out</button>
      </div>
      <div
        className="zoom-container"
        ref={containerRef}
        onWheel={handleWheel}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseUp}
      >
        <img
          ref={imgRef}
          src="https://asset.gecdesigns.com/img/wallpapers/beautiful-fantasy-wallpaper-ultra-hd-wallpaper-4k-sr10012418-1706506236698-cover.webp"
          alt="Zoomable"
          style={{
            transform: `translate(${position.x}px, ${position.y}px) scale(${zoomLevel})`,
            cursor:
              zoomLevel > 1 ? (isDragging ? "grabbing" : "grab") : "default",
          }}
          className="zoom-image"
        />
      </div>
    </div>
  );
}

.zoom-container {
  overflow: hidden;
  width: 100%;
  height: 400px;
  position: relative;
  border: 1px solid #ddd;
  background-repeat: no-repeat;
  background-position: cover;
  cursor: default; /* Default cursor when not interacting */
}

.zoom-image {
  transform-origin: center center;
  transition: transform 0.1s ease-out;
  background-position: contain;
  width: 100%;
  height: 400px;
}


The component works, zoom works fine. The only issue what i am trying to solve is to prevent dragging the image more than its boundaries.

Expected result:

When user will zoom and will start dragging the image in any direction then he should be stopped to drag more and to appear these white spaces between image and container like is now. So, as example if user will drag from top to bottom, the maximum allowed dragging effect should be when the user will drag until the image edge, not more..
demo: https://codesandbox.io/p/sandbox/pedantic-bose-ywk35n

macOS React Native .xcode.env.local node path not being correctly assigned

.xcode.env

# This `.xcode.env` file is versioned and is used to source the environment
# used when running script phases inside Xcode.
# To customize your local environment, you can create an `.xcode.env.local`
# file that is not versioned.

# NODE_BINARY variable contains the PATH to the node executable.
#
# Customize the NODE_BINARY variable here.
# For example, to use nvm with brew, add the following line
# . "$(brew --prefix nvm)/nvm.sh" --no-use
export NODE_BINARY=$(command -v node)

We have a react native project. Our node installation is managed with asdf-vm. When I run the command as a user command -v node and which node I get the correct path returned to me as follows:

> which node
/Users/devboi/.asdf/shims/node
> command -v node
/Users/devboi/.asdf/shims/node

But when run the same commands as a yarn script

"scripts": {
    "nodePath": "which node",
    "nodepath": "command -v node"
  },

➜ yarn nodePath
/private/var/folders/gs/hrtylh996mv147w1xqzdm2fm0000gn/T/xfs-407a6ad6/node

➜ yarn nodepath
/private/var/folders/gs/hrtylh996mv147w1xqzdm2fm0000gn/T/xfs-5833b283/node

The reason I ask about this is that when we generate our .xcode.env.local from the config set up by the .xcode.env file the temporary paths with private are the ones being written to the .xcode.env.local files. I have seen people using nvm has run into the same issues, but I haven’t seen any clear solutions.

What am I missing? Some config of yarn? Or an export somewhere?

Handling Promise.race better

Trying to write the flow logic for a drawing tool where user can enter keyboard input to draw on a cavas let’s say, to achieve this I’m trying to chain event listeners in a way that they remove themselves once done. I would rather do this than keeping track of a global state that manages which listeners are active etc. I’m making progress but I’m stuck on recusive calls to Promise.race not sure if there’s a better way to achieve this.

Using Promise.race in a recusive loop means that alot of the promises do not get resolved.
Is there a better way for me to do this?

export function startCount(node) {
  const counter = Object.create(counterMethods);
  counter.node = node;
  counter.number = 0;
  counter.exitloopflag = false;
  return counter;
}

const counterMethods = {
  doCounter: function () {
    return new Promise((resolve) => {
      let handler = () => {
        console.log("click");
        this.node.removeEventListener("click", handler);
        resolve();
      };
      this.node.addEventListener("click", handler);
    });
  },
  quit: function () {
    return new Promise((resolve) => {
      let handler = (e) => {
        if (e.key === "Escape") {
          this.node.removeEventListener("keydown", handler);
          resolve("exit");
        }
      };
      this.node.addEventListener("keydown", handler);
    });
  },
  counterFlow: function () {
    if (this.exit) return;
    Promise.race([this.doCounter(), this.quit()]).then((value) => { //<-- not confident about this
      console.log(`The value is !!!: ${value}`);
      if (value === "exit") {
        this.exit = true;
      } else {
        this.number += 1;
        console.log(`you have clicked ${this.number} times`);
        this.counterFlow();  //<-- recursive call, means I'm leaving a lot of unresolved promises.
      }
    });
  },
};


let obj = new startCount(document);
obj.counterFlow();

Leaflet.js as Web Component – Impossible to Display Map Properly because Shadow Dom

This simple Leaflet example works perfectly with vanilla JavaScript but does not when using Web Components (tiles show up all messed up https://imgur.com/a/ZicDrRQ).

My best guess is the way the Shadow DOM behaves with the #map element sizing, oddly enough if we change #map to display: flex slightly more tiles show up but still many are missing.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leaflet.js with OpenStreetMap and Geolocation as Web Component</title>

    <!-- Leaflet CSS -->
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css"
        integrity="sha256-p4NxAoJBhIIN+hmNHrzRCf9tD/miZyoHS5obTRR9BMY=" crossorigin="" />

    <!-- Leaflet JS -->
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"
        integrity="sha256-20nQCchB9co0qIjJZRGuk2/Z9VM+kNiyxNV1lvTlZBo=" crossorigin=""></script>

</head>
<style>
    html,
    body {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
    }
</style>

<body>

    <geo-map></geo-map>

    <script>
        class GeoMap extends HTMLElement {
            constructor() {
                super();
                this.attachShadow({ mode: 'open' });

                this.shadowRoot.innerHTML = `
                    <style>
                        :host {
                            display: inline-block;
                            width: 100%;
                            height: 100%;
                        }

                        #map {
                            display: inline-block;
                            width: 100%;
                            height: 100%;
                        }
                    </style>
                    <div id="map"></div>
                `;
            }

            connectedCallback() {
                const mapDiv = this.shadowRoot.querySelector('#map');
                const map = L.map(mapDiv);
                L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                }).addTo(map);
                map.setView([34.42696537699258, -119.7175455093384], 13);
            }
        }

        customElements.define('geo-map', GeoMap);
    </script>

</body>

</html>

How to check array length whilst coping with the fact that the array maybe undefined

I have an application that allows users to write javascript for custom tasks on a set of files, it works on metadata in the files and the metadata is bound to the javascript. The metadata for different files can be different and a field defined in one file may not exist in another. When a particular piece of metadata contains multiple values for a file it is returned as an array.

What I wanted was create a function that checked the length of an array whilst coping with the fact that the array may not be defined so that the user could use this without having to check if the array is undefined making their scripting easier. However the function below fails for undefined arrays because it cant pass an undefined varaible to the function in the first place.

function arrayLength(indexedScriptField)
{
    if(typeof indexedScriptField !== 'undefined')
    {
         return indexedScriptField.length;
    }
    return 0;
}

Is there another way to achieve what I want ?