File size: 2,241 Bytes
ded98ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// main.js

function sendValue(value) {
  Streamlit.setComponentValue(value);
}

function onRender(event) {
  if (!window.rendered) {
    const { image, button_coords, text_list, before_copy_label, after_copy_label } = event.detail.args;

    // Set the image source
    const imageElement = document.getElementById("image-element");
    imageElement.src = image;

    // Wait for the image to load to adjust frame height and width
    imageElement.onload = function () {
      const imageWidth = imageElement.naturalWidth;
      const imageHeight = imageElement.naturalHeight;

      // Set the container size to match the image
      const imageContainer = document.getElementById("image-container");
      imageContainer.style.width = `${imageWidth}px`;
      imageContainer.style.height = `${imageHeight}px`;

      // Dynamically set the frame height based on the image size
      Streamlit.setFrameHeight(imageHeight + 50);  // Add some extra space for buttons

      // Place buttons based on provided coordinates and sizes
      button_coords.forEach((coords, index) => {
        const [topLeft, bottomRight] = coords;
        const button = document.createElement("button");
        button.textContent = before_copy_label;
        button.className = "st-copy-to-clipboard-btn";

        // Calculate button position and size
        const buttonWidth = bottomRight[0] - topLeft[0];
        const buttonHeight = bottomRight[1] - topLeft[1];
        button.style.position = "absolute";
        button.style.left = `${topLeft[0]}px`;
        button.style.top = `${topLeft[1]}px`;
        button.style.width = `${buttonWidth}px`;
        button.style.height = `${buttonHeight}px`;

        // Define copy function for each button
        button.addEventListener("click", () => {
          navigator.clipboard.writeText(text_list[index]);
          button.textContent = after_copy_label;
          setTimeout(() => {
            button.textContent = before_copy_label;
          }, 1000);
        });

        imageContainer.appendChild(button);
      });
    };

    window.rendered = true;
  }
}

// Register Streamlit event listeners
Streamlit.events.addEventListener(Streamlit.RENDER_EVENT, onRender);
Streamlit.setComponentReady();