My script doesn´t let me add contributors to my github repositorys

I have 15 repositorys, all of them with the name “21-051-(numberOfTheGroup)” where numberOfTheGroup is a number that depends of the number of the group. I have an .xlsx document that have gmail and number of the group of the members of each group.

I made this script, i want to take the emails of the .xlsx and the number of group, and add that emails as contributors of each repositorys (obviusly, only add the email to the repository of his group).

I made the script in Javascript with node.js and other version in python, but it doesn´t work in any of two options. In both cases send me the error 404 {“message”: “Not Found”, “documentation_url”: “docs.github.com/rest/collaborators/…”}. All the configurations in github and in the script are okay for me, i saw the documentation in github and other posts to do the script and all of them do the same thing i did, but it doesn´t work.

I will let the code here if somebody knowns what is the problem.

Python code:

import pandas as pd
from github import Github

# Token de acceso a GitHub
token = "Here i put my github token"

# Autenticación en GitHub con el token de acceso
g = Github(token)

# Leer el archivo Excel (.xlsx)
datos = pd.read_excel("Lista_Mails.xlsx")

# Iterar sobre cada fila del archivo CSV
for index, fila in datos.iterrows():
    grupo = fila["Grupo"]
    correo = fila["Correo"]

    # Obtener el nombre del repositorio correspondiente al grupo
    nombre_repositorio = f"24-051-{grupo}"
    
    try:
        # Obtener el repositorio
        repositorio = g.get_repo(f"SantiBoero1/{nombre_repositorio}")

        # Añadir al correo electrónico como colaborador
        try:
            repositorio.add_to_collaborators(correo, "maintain")
            print(f"Correo {correo} añadido al grupo {grupo} en el repositorio {nombre_repositorio}")
        except Exception as e:
            print(f"Error al añadir colaborador {correo} al repositorio {nombre_repositorio}: {str(e)}")
    except Exception as e:
        print(f"Error al acceder al repositorio {nombre_repositorio}: {str(e)}")

Javascript code:

const { Octokit } = require('@octokit/rest');
const fs = require('fs');
const xlsx = require('xlsx');

// Token de acceso a GitHub
const token = 'Here i put my github token';

// Crear una instancia de Octokit con el token de acceso
const octokit = new Octokit({
  auth: token,
});

// Leer el archivo Excel (.xlsx)
const workbook = xlsx.readFile('Lista_Mails.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const datos = xlsx.utils.sheet_to_json(worksheet);

// Iterar sobre cada fila del archivo Excel
datos.forEach(async (fila) => {
  const grupo = fila.Grupo;
  const correo = fila.Correo;

  // Obtener el nombre del repositorio correspondiente al grupo
  const nombreRepositorio = `24-051-${grupo}`;

  try {
    // Añadir al correo electrónico como colaborador
    await octokit.repos.addCollaborator({
      owner: 'SantiBoero1',
      repo: nombreRepositorio,
      username: correo,
      permission: 'maintain', // Cambiar a 'pull' si se desea un rol de solo lectura
    });

    console.log(`Correo ${correo} añadido al grupo ${grupo} en el repositorio ${nombreRepositorio}`);
  } catch (error) {
    console.error(`Error al añadir colaborador ${correo} al repositorio ${nombreRepositorio}: ${error.message}`);
  }
});

I read all the documentation of Github, see other post here in stack overflow but i could´t find what is the problem

Why can I still proceed to next step even though the form is not complete yet?

so I’m almost finish with my multi-step-form but the problem I’m encountering right now is, I can still proceed to the next step even though the form in not yet complete on the 3rd step.

I’ll send an image first as an example.

In this first Image, I can’t press the next button since I didn’t fill the rest of the field.

enter image description here

Now, I’m at the 3rd step

enter image description here

At you can see, I didn’t fill the field, but I can still press the next button.

This image shows since this is my 4th step. I will press the back button and the warning will show.

enter image description here
enter image description here

CalendarPicker.tsx

function CalendarPicker() {
  const [currentFormPage, setCurrentFormPage] = useState(0);
  const [previousStep, setPreviousStep] = useState(0);

  type Inputs = z.infer<typeof formSchemaData>;
  const form = useForm<Inputs>({
    resolver: zodResolver(formSchemaData),
    defaultValues: {
      title: "",
      email: "",
      fullName: "",
      department: "",
      dateOfEvent: "",
      purpose: "",
      startingTime: "",
      endingTime: "",
      type: 'no',
      dryRunDate: '',
      dryRunStart: '',
      dryRunEnd: '',
    },
  });

  const goToNextPage = async () => {
    const fields = steps[currentFormPage].fields;
    const output = await form.trigger(fields as FieldName[], {
      shouldFocus: true,
    });

    if (!output) return;

    if (currentFormPage !== 3) {
      const watch = form.watch([
        "title",
        "email",
        "fullName",
        "department",
        "dateOfEvent",
        "startingTime",
        "endingTime",
        "purpose",
        "type",
        "dryRunDate",
        "dryRunStart",
        "dryRunEnd",
      ]);

      setPreviousStep(currentFormPage);
      setCurrentFormPage((step) => step + 1);
    }
  };
}

return(
{
  currentFormPage === 1 && <>.../form field</>;
}

{
  currentFormPage === 2 && (
    <>
      <DialogHeader>
        <DialogTitle>Purpose, Date and Time</DialogTitle>
      </DialogHeader>

      <FormField
        control={form.control}
        name="type"
        render={({ field }) => (
          <FormItem className="space-y-3">
            <FormLabel>Optional;</FormLabel>
            <FormControl>
              <RadioGroup
                onValueChange={field.onChange}
                defaultValue={field.value}
                className="flex flex-col space-y-1"
              >
                <FormItem className="flex items-center space-x-3 space-y-0">
                  <FormControl>
                    <RadioGroupItem value="yes" />
                  </FormControl>
                  <FormLabel className="font-normal">yes</FormLabel>
                </FormItem>
                <FormItem className="flex items-center space-x-3 space-y-0">
                  <FormControl>
                    <RadioGroupItem onClick={handleClick} value="no" />
                  </FormControl>
                  <FormLabel className="font-normal">no</FormLabel>
                </FormItem>

                {hasDryRun === "yes" && (
                  <>
                    <FormField
                      control={form.control}
                      name="dryRunDate"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>dryRunDate</FormLabel>
                          <FormControl>
                            <Input type="text" placeholder="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="dryRunStart"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>dryRunDate</FormLabel>
                          <FormControl>
                            <Input type="time" placeholder="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />

                    <FormField
                      control={form.control}
                      name="dryRunEnd"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>dryRunDate</FormLabel>
                          <FormControl>
                            <Input type="time" placeholder="date" {...field} />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  </>
                )}
              </RadioGroup>
            </FormControl>
            <FormMessage />
          </FormItem>
        )}
      />

      
    </>
  );
}
)

schema.ts

export const formSchemaData = z.object({
    title: z.string().min(2, {
      message: "title must be at least 2 characters.",
    }),
    email: z.string().min(2, {
      message: "email must be at least 2 characters.",
    }).email(),
    fullName: z.string().min(2, {
      message: "full name must be at least 2 characters.",
    }),
    department: z.string().min(2, {
      message: "department  must be at least 2 characters.",
    }),
  
  
    // set 2 
    dateOfEvent: z.string(), // Assuming dateOfEvent is a string in the desired format
    startingTime: z.string().min(2, {
      message: "staring time must be set.",
    }),
    endingTime: z.string().min(2, {
      message: "ending time must be set.",
    }),
  
    purpose: z.string().min(2,{
      message: "Please choose a purpose of the meeting.",
    }),
  
    // Set 3
    type: z.enum(["yes", "no"], {
      required_error: "You need to select a notification type.",
    }),
    dryRunDate: z.string().optional(),
    dryRunStart: z.string().optional(),
    dryRunEnd: z.string().optional(),
  }).superRefine(({ type, dryRunDate, dryRunStart, dryRunEnd }, ctx) => {
    if (type === 'yes') {
      if (!dryRunDate) {
        ctx.addIssue({
          code: 'custom',
          message: 'dryRunDate is required to fill up if you choose yes.',
          path: ['dryRunDate']
        })
      }
      if (!dryRunStart) {
        ctx.addIssue({
          code: 'custom',
          message: 'dryRunStart is required to fill up if you choose yes.',
          path: ['dryRunStart']
        })
      }
      if (!dryRunEnd) {
        ctx.addIssue({
          code: 'custom',
          message: 'dryRunEnd is required to fill up if you choose yes.',
          path: ['dryRunEnd']
        })
      }
    }
  });
  


           

How can I disable the onClick event when the dropdown plaeholder is selected?

I’ve tried various ways to prevent the onClick event when either placeholder is selected but have been unable to get this to work. Here’s what I have so far:

    <div class="choosesign">
  <div class="zodiacs">
    <select id="zodiac-me" class="zodiac-me" name="zodiac1">
        <option value="none">Your Sign</option>
        <option value="1">Aries</option>
        <option value="2">Aquarius</option>
        <option value="3">Cancer</option>
        <option value="4">Capricorn</option>
        <option value="5">Gemini</option>
        <option value="6">Leo</option>
        <option value="7">Libra</option>
        <option value="8">Pisces</option>
        <option value="9">Sagittarius</option>
        <option value="10">Scorpio</option>
        <option value="11">Taurus</option>
        <option value="12">Virgo</option>
    </select>
</div>
<div class="zodiacs">
    <select id="zodiac-them" class="zodiac-them" name="zodiac2">
        <option value="none">Their Sign</option>
        <option value="1">Aries</option>
        <option value="2">Aquarius</option>
        <option value="3">Cancer</option>
        <option value="4">Capricorn</option>
        <option value="5">Gemini</option>
        <option value="6">Leo</option>
        <option value="7">Libra</option>
        <option value="8">Pisces</option>
        <option value="9">Sagittarius</option>
        <option value="10">Scorpio</option>
        <option value="11">Taurus</option>
        <option value="12">Virgo</option>
    </select>
</div>
<div class="zodiacs" id="gobutton">
<a id="zodiacchoice" href="#" onclick='GotoLink()'> <h1>
  GO</h1> </a>
</div>
</div>

<script>function GotoLink(){
  var sel = $('.zodiac-me option:selected').text();
    var sel2 = $('.zodiac-them option:selected').text();
    if (sel=='Your Sign') {
    document.getElementById("zodiacchoice").disabled = true;
  } else {
    document.getElementById("zodiacchoice").href = '/' + sel + '/' + sel + '-vs-' + sel2;
  }
}</script>

I tried using the if statement to clarify, but the onClick isn’t disabled. The link still works correctly.

Doughnut chart with only top corners rounded

I have been trying for a few hours to accomplish the following Chart with D3.js:

enter image description here

It’s easy to accomplish a similar result following the default examples, and getting something like this:

enter image description here

The problem is when I try to just round the corners on top of each segment (like first screenshot) because the default cornerRadius method will apply it radius to all the corners.

I tried a few approaches suggested by using the amazing D3.js Assistant (Chat GPT) but none of them helped me to do it because it’s failing on calculating the correct values for the Arcs, and I’m super noob when talking about manual making an SVG (even after reading the docs).

Some approaches I tried:

  • Remove existing rounded corners by using a custom method to create the d path.
  • Creating each segment “by hand” with a custom method
  • Hitting my head on the keyboard

Useful links I found:

Lottie: Is there a method from any lottie player libraries to validate the lottie JSON file

I would like the users to upload Lottie JSON. But, before they could upload the file, I would like to validate if it’s a valid Lottie JSON. Is there any method to do so with the exitsing lottie player library or would I have to write it myself based on their docs?

I tried the Lottie Player which crashes abrupty when we pass an incorrect JSON. But, it’s the component that crashes. I am looking for a method that trying some work around to verify if the component crashes

Button text won’t update to ‘Finish’ when i get to the last question for my VUE 3 quiz app

Building a quiz app in vue 3 and everything works as its suppose to til i get to the last question, where the button text is suppose to say ‘Finish’ as soon as the question is loaded. new to vue and been looking into this for hours even copilot cant find an error. how do i get the button text to update once the last question has been reached?

<script setup>
import { ref, computed } from 'vue'

const questions = ref([
  {
    question: 'How many books are in the kjva bible?',
    answer: 0,
    options: [
      '80',
      '32',
      '60',
    ],
    selected: null
  },
  {
    question: "What is the name of Israel's first king?",
    answer: 2,
    options: [
      'David',
      'Asa',
      'Saul',
    ],
    selected: null
  },
  {
    question: 'Salvation is of the...?',
    answer: 1,
    options: [
      'Egyptians',
      'Jews',
      'Edomites',
    ],
    selected: null
  }
])

const quizCompleted = ref(false)
const currentQuestion = ref(0)
const score = computed(() => {
  let value = 0
  questions.value.map(q => {
    if(q.selected == q.answer) {
      value++
    }
  })
  return value
})

const getCurrentQuestion = computed(() => {
  let question = questions.value[currentQuestion.value]
  questions.index = question.value
  return question 
})

const setAnswer = evt => {
  questions.value[currentQuestion.value].selected = evt.target.value
  evt.target.value = null
}

const nextQuestion = () => {
  if(currentQuestion.value < questions.value.length -1) {
    currentQuestion.value++
    console.log('currentQuestion.value type:', typeof currentQuestion.value);
console.log('questions.value.length type:', typeof questions.value.length);
console.log(currentQuestion.index, value);

  } else {
    quizCompleted.value = true
    console.log('Quiz Completed')
  }
}
</script>

<template>
  <main class="app">
    <h1>The Quiz</h1>

    <section class="quiz">
      <div class="quiz-info">
        <div class="question">{{ getCurrentQuestion.question }}</div>
        <div class="score">Score {{ score }}/{{ questions.length }}</div>
      </div>
      
      <div class="options">
        <label v-for="(option, index) in getCurrentQuestion.options" 
          :key="index"
          :class="`option ${
            getCurrentQuestion.selected == index
              ? index == getCurrentQuestion.answer
                ? 'correct'
                : 'wrong'
                : ''
          } ${
            getCurrentQuestion.selected != null &&
            index != getCurrentQuestion.selected
            ? 'disabled'
            : ''
          }`">
          <input 
            type="radio" name="options"
            :name="getCurrentQuestion.index"
            :value="index"
            v-model="getCurrentQuestion.selected"
            :disabled="getCurrentQuestion.selected"
            @change="setAnswer" />
            <div>{{ option }}</div>  
        </label>
      </div>

      <button
        @click="nextQuestion"
        :disabled="!getCurrentQuestion.selected">
        {{ 
          getCurrentQuestion.index == questions.length - 1
            ? 'Finish'
            : getCurrentQuestion.selected == null
              ? 'Select an option'
              : 'Next Question'
         }}
        </button>
    </section>
  </main>

</template>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Montserrat', sans-serif;
}

body {
  background-color: #271C36;
  color: #fff;
}
</style>


i tried to console log the nextquestion function to find an issue and couldnt…
also i think the error lies in the button logic button im not sure

Invalid Property Value on CSS styling using Javascript

I’m trying to create and style an element using Javascript:

var div_html = document.createElement("div");
var div = document.createElement("div");
div.setAttribute("class", "div_class");
div.style.height = 50 + "px";
div_html.appendChild(div);
document.body.innerHTML = div_html.innerHTML;
.div_class {
width: 200px;
background-color: black;
}

Now this snippet works on here, but for my code, when I load this on the browser, the

div.style.height = 50 + “px”;

css style is not applied i.e. in the developer tools they are crossed out and it says “Invalid property value”. Given it works here, I don’t think the syntax of my css styling is wrong.

Also I’ve got code in the same js file that is basically doing exactly the same thing further up and it works fine. The only difference I can see is that in the block that works, I’ve created the div as an element in an array, whereas in this case it’s just a variable.

I’ve tried re-writing code as follows:

document.body.innerHTML = '<div class="div_class" style="height: 50px"></div>';
.div_class {
width: 200px;
background-color: black;
}

Again, this will work on here but when I load this on the browser I get exactly the same problem as before.

Use a function from one .astro file in another .astro file

enter image description hereHola alguien sabe cómo puedo usar mi función setHTMLcontent desde mi layout en el archivo fondo.astro, había buscado que tenía que importarla pero no funcionan las formas que intente, estoy usando astro

Hello, does anyone know how I can use my setHTMLcontent function from my layout in the Fondo.astro file, I had searched that I had to import it but the ways I tried don’t work, I’m using astro

Try with import {setHTMLcontent} from “./Layout.astro”

Drag items dissapear/wont move when trying to move them

I’m trying to make a 3×3 grid with the grid items beeing each a part of 1 image. These items I want to be able to drag and drop them inside another 3×3 grid.(In any order i want).

I’ve encountered a roadblock and been trying to solve it for a while now.

Directory tree:

.
├── Project/
│   └── Res/
│       ├── Media/
│       │   └── Images/
│       │       └── image.jpg
│       ├── Scripts/
│       │   └── anim3.js
│       ├── Styles/
│       │   └── anim3.css
│       └── Pages/
│           └── animPage3.html
└── index.html(not relevant)

animPage3.html:

<body>
<head>
<link 
rel="stylesheet" href="Res/Styles/anim3.css">
</head>

<div class="draggable-grid">
  <div class="box" draggable="true"></div>
  ...There's a total of 9 these...
</div>

<div class="droppable-grid">

<div class="droppable-box"></div> 
<!--There's a total of 9 of these "droppable-box" divs-->

</div>
<script src="Res/Scripts/anim3.js">
</body>

anim3.css:

.grid-cont {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px;
}
.draggable-grid, .droppable-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  gap: 10px;
}
.box {
  width: 100px; 
  height: 100px; 
  background-image: url('../Media/Images/image.jpg');
  background-size: 300% 300%;
}
.droppable-box {
  border: 2px dashed #ccc;
  height: 100px; 
}

anim3.js:

const draggableBoxes = document.querySelectorAll('.draggable-grid .box');
const droppableBoxes = document.querySelectorAll('.droppable-grid .droppable-box');
draggableBoxes.forEach(box => {
  box.addEventListener('dragstart', dragStart);
});
droppableBoxes.forEach(droppableBox => {
  droppableBox.addEventListener('dragover', dragOver);
  droppableBox.addEventListener('dragenter', dragEnter);
  droppableBox.addEventListener('dragleave', dragLeave);
  droppableBox.addEventListener('drop', drop);
});
let draggedItem = null;
function dragStart() {
  draggedItem = this;
  setTimeout(() => this.style.display = 'none', 0);
}
function dragOver(e) {
  e.preventDefault();
}
function dragEnter(e) {
  e.preventDefault();
  this.classList.add('hovered');
}
function dragLeave() {
  this.classList.remove('hovered');
}
function drop() {
  this.classList.remove('hovered');
  this.append(draggedItem);
  draggedItem.style.display = 'block';
  draggedItem = null;
}

I tried to comment out
//setTimeout(() => this.style.display = 'none', 0);
Wich didn’t make the drag work.

What i want the code to do:
Make two 3×3 grids.
1st grid has dragable items and the items background is each a part of “1 image*.
“2nd grid* is were I want to be able to drop the items, at any of the 9 boxes.

parseInt works in JavaScript, but not in C#

I’m trying to convert this JavaScript code to C#. It is a hexadecimal string that is the value of a crypto token.

Here is what works in JavaScript:

parseInt("0x0000000000000000000000000000000000000000000000056bc75e2d63100000", 16)

Here is what I have tried in C#:

var result = Int16.Parse("0x0000000000000000000000000000000000000000000000056bc75e2d63100000");

I get the error Input string was not in a correct format. What am I doing wrong?

multipart/mixed with blob using axios

The curl command below works for the API call.

curl -k –user “un:$PASSWORD” -X POST -H “Content-type: multipart/mixed” -F “blob=@binaryfile” -F ‘metadata={“prop1″:”v1″,”prop2″:”v2”};type=application/json’ https:///api/v2.0/entity

How could I achieve the same using nodejs ?

        formData.append('blob', fs.createReadStream(binaryfile))
        formData.append('metadata', fs.createReadStream(jsonfile))
        const config = {
            method: 'POST',
            url: 'https://<host>/api/v2.0/entity',
            headers: {
                'Content-Type': 'multipart/mixed',
                'Accept': 'application/json'
            },
            data: formData
        }

        return await axios(config).then(function (response) {
            return response.data
        }).catch(error => {
            return error
        })

Get URL Image From Firebase Storage

i have already stored the image in the firebase storage with the path is “Avatar/Assists/0654234.jpg”. and i use this code from chat gpt. But the problem i have is it’s said “firebase.storage is not a function”. IS there another way that i can get URL image from storage?

 const express = require('express')
     const bodyParser = require('body-parser')
     const admin = require('firebase-admin')
     const serviceAccount = require("./serviceAccountKey.json")
     const functions = require('firebase-functions')
        const path = require('path')
        const firebase = require('firebase/app');
     require('firebase/storage');

const firebaseConfig = {
  apiKey: "AIzaSyDioYAzvJooHpspr8Z58bImI0s2jaIRU90",
  authDomain: "testlogin-c11b6.firebaseapp.com",
  projectId: "testlogin-c11b6",
  storageBucket: "testlogin-c11b6.appspot.com",
  messagingSenderId: "598921663451",
  appId: "1:598921663451:web:8bc05bbb07d312f1650dfe",
  measurementId: "G-4N0GNYZQ8J"
};

firebase.initializeApp(firebaseConfig);


admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL : "https://testlogin-c11b6-defaultrtdb.firebaseio.com/"
})


const app = express()
const db = admin.database();
const PORT = 80

let paths = "Avatar/Assist/0654234.jpg"
const storageRef = firebase.storage().ref().child(paths);
storageRef.getDownloadURL()
  .then((url) => {
console.log( url);

  })
  .catch((error) => {
   console.error(error);
 });

How to Dynamically Update Multiselect Dropdown Options in AngularJS?

I’m working on a project where I have two multiselect dropdowns using AngularJS’s ui-select. The options available in the second dropdown are filtered based on the selection made in the first dropdown. However, I’m facing an issue when I try to dynamically update the options in the second dropdown upon removing a selection from the first dropdown.

I want to remove the corresponding selected options in the second dropdown when any option selected in the first dropdown is removed. However, setting undefined or [] to the selectedCalyxCode model doesn’t seem to work as expected.

<ui-select multiple theme="bootstrap" id="calyxCode" refresh="search($select.search)"
            class="form-control" close-on-select="false" title="Select Code"
            ng-model="selectedCalyxCode" style="width: 100%; height: 34px;">
    <ui-select-match allow-clear="true"
        placeholder="Select Code">{{$item}}</ui-select-match>
    <ui-select-choices repeat="calyxCode in calyxCodeList | filter: $select.search">
        <div ng-bind-html="region | highlight: $select.search"></div>
    </ui-select-choices>
</ui-select>

<ui-select multiple theme="bootstrap" id="region-ui-select" refresh="search($select.search)"
            class="form-control" close-on-select="false" title="Choose Region"
            ng-model="regionInput" style="width: 100%; height: 34px;">
    <ui-select-match allow-clear="true"
        placeholder="Select Region">{{$item}}</ui-select-match>
    <ui-select-choices repeat="region in regionList | filter: $select.search">
        <div ng-bind-html="region | highlight: $select.search"></div>
    </ui-select-choices>
</ui-select>

Can someone guide me on how to achieve this functionality in AngularJS? I’m relatively new to AngularJS, so any simplified explanations or examples would be highly appreciated.

Change styled-component percentage transform animation according to useState value

I have an component that makes a transition of a span inside a div, whenever the span content changes I need to change the percentage of the transform in styled-component based on the span width, so the transition always fit the size of its parent before it starts again. But when the state percentage changes, the value of the property “props.percent” doesn`t reflect in the DOM element, even if the state is updated correctly. It works sometimes, but suddenly stop working after some updates.

import React, { useEffect, useState } from 'react'
import { StyledEvent } from './styles'

export const Event = ({ panelwidth, children, events }) => {
  const [percentage, setPercentage] = useState(100)

  const calculaenter image description heretePercentage = (panelwidth) => {
    const locationsPanel = document.getElementById('eventsLocations');
    
    if (locationsPanel?.offsetWidth) {
      return Math.abs(panelwidth / locationsPanel?.offsetWidth * 100 - 100).toFixed(2);
    }

    return 0;
  }
  
  useEffect(() => {
    const newPercentage = calculatePercentage(panelwidth);

    console.log('panelWidth =>', panelwidth)
    console.log('percent =>', newPercentage)

    setPercentage(newPercentage);
  }, [events]);

  return (
    <StyledEvent 
      id="eventsLocations" 
      percent={percentage}
    >
      {children}
    </StyledEvent>
  )
}
import { styled } from 'styled-components'

const duration = '60s'

export const StyledEvent = styled.span`
    display: flex;
    align-items: center;
    font-size: 1.625rem;
    font-weight: 400;
    margin: 0 auto;
    animation-name: slide;
    animation-delay: 1s;
    animation-duration: ${duration};
    animation-timing-function: linear;
    animation-iteration-count: infinite;
    color: ${(props) => props.theme['white']};

    @keyframes slide {
    0% {
      transform: translate(0, 0);
    }
    100% {
      transform: translate(${(props) => `-${props.percent}%`}, 0);
    }
  }

  p {
    font-weight: 600;
  }
`

Whenever the state changes based on the calc of components width, I need the transition to change.