Görsel üzerinde bazı alanları belirgin hale getirmek [closed]

websitemin arka plan resminin üzerinde 4 farklı alanı belirgin hale getirmek ve link vermek istiyorum bi kaç yöntem denedim fakat sonuç alamadım bunula ilgili önerileriniz nedir benimle paylaşabilir misiniz ?

görselde istediğim alanı map ile yaptım fakat bu sefer belirginlik veya hover katamadım ve map özelliğini her alan için de seçemiyorum maalesef

Not able to print one backslash in Java Script

I am making a random password-generation app using JS.

Following is an array of special characters which I am using to generate random special characters:

const specialChars = ['!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', ']', '^', '_', '`', '{', '|', '}', '~', '\'];

In the app, I get two backslashes when I try to add a backslash to the password during generation using the above array:

specialChars[genRandNum(0, specialChars.length-1)];

genRandNum() function generates a random number b/w given range.
In this case, it generates a random number b/w 0 and last index of specialChars i.e. specialChars.length-1

So whenever a backslash \ is chosen randomly from specialChars array it should have printed only 1 backslash but it is printing the backslash twice.

Following is the code for the genRandChar() function for generating a random character:

const genRandChar = (choice) => {
    switch(choice) {
        case 1:
            return genRandAscii(65, 90); //For generating Capital letters
        case 2:
            return genRandAscii(97, 122); //For generating Small letters
        case 3:
            return genRandNum(0, 9); //For generating random number b/w 0 to 9
        case 4:
            return specialChars[genRandNum(0, specialChars.length-1)]; // for special chars
    }
}

genRandAscii() generates a random character bw given Ascii values

Following is the code for generating random password using capital letters, small letters, numbers(0 to 9) and special characters using genRandChar() function:

const genPassword = (filter) => {
    let password = "";
    const length = genRandNum(filter.min, filter.max);
    for(let i=1; i<=length; i++) {
        password += genRandChar(genRandNum(1, 4));
    }
    return {password: password, length: length, actualLength: password.length};
}

Sample Output of genPassword() function:

{ password: "OZ'Wl\p6", length: 8, actualLength: 8 }

In the above sample output as you can see that it was supposed to print only one backslash but it is printing twice due to which the actual length became 9 (count it) which should be 8 if only one backslash was printed.

The length which was chosen randomly i.e. length and actualLength i.e. equal to password.length is 8 only. So on counting also it should be 8 but it is 9.

Please tell me how to solve the problem.

Using two layouts simultaneously in Nuxt 3

I have a /profile page that includes common elements like sidebar, which I handle with a profile layout. The /profile page also has a sub-page at /profile/favorite. I want to use both the default layout (which includes a header and a footer) and the profile layout (which includes the sidebar and other common parts) at the same time for both /profile and /profile/favorite.

However, when I set the /profile page to use the profile layout, the default layout elements (header and footer) disappear, and my transitions break.

Question:

How can I make the /profile and /profile/favorite pages share the same sidebar while maintaining the default layout (header and footer) without duplicating the code? Is there any other recommended approach to solve this problem?

I appreciate any advice or solution.

Taiga UI select not working in angular 16

I have a problem when using select from taiga ui. The project uses Angular 16 and taiga ui 3.87ю

When opening the select the following error occurs

    ERROR Error: Portals cannot be used without TuiPortalHostComponent
    at get safeHost (taiga-ui-cdk-abstract.js:390:19)
    at TuiDropdownPortalService.add (taiga-ui-cdk-abstract.js:398:21)
    at TuiDropdownDirective.toggle (taiga-ui-core-directives-dropdown.js:109:56)
    at Object.next (taiga-ui-core-abstract.js:41:71)
    at ConsumerObserver.next (Subscriber.js:91:33)
    at SafeSubscriber._next (Subscriber.js:60:26)
    at SafeSubscriber.next (Subscriber.js:31:18)
    at distinctUntilChanged.js:14:28
    at OperatorSubscriber._next (OperatorSubscriber.js:13:21)
    at OperatorSubscriber.next (Subscriber.js:31:18)

I used the official documentation to install taiga ui and for used selecet.`

Project Dependencies:

"dependencies": {
    "@angular/animations": "^16.2.0",
    "@angular/cdk": "^16.0.0",
    "@angular/common": "^16.2.0",
    "@angular/compiler": "^16.2.0",
    "@angular/core": "^16.2.0",
    "@angular/forms": "^16.2.0",
    "@angular/platform-browser": "^16.2.0",
    "@angular/platform-browser-dynamic": "^16.2.0",
    "@angular/router": "^16.2.0",
    "@taiga-ui/cdk": "^3.87.0",
    "@taiga-ui/core": "^3.87.0",
    "@taiga-ui/icons": "^3.87.0",
    "@taiga-ui/kit": "^3.87.0",
    "@taiga-ui/styles": "^3.87.0",
    "@tinkoff/ng-dompurify": "^4.0.0",
    "rxjs": "~7.8.0",
    "taiga-ui": "^3.87.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.13.0"
 }

App.module

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    FormsModule,
    ReactiveFormsModule,
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    TuiRootModule,
    TuiDialogModule,
    TuiAlertModule,
    TuiSelectModule,
    TuiDataListWrapperModule
  ],
  providers: [{provide: TUI_SANITIZER, useClass: NgDompurifySanitizer}],
  bootstrap: [AppComponent]
})
export class AppModule { }

Template with select

<form [formGroup]="testForm">
  <tui-select formControlName="testValue">
    <tui-data-list-wrapper
      *tuiDataList
      [items]="items"
    ></tui-data-list-wrapper>
  </tui-select>
</form>

Component with select


export class AppComponent {
  testForm = new FormGroup({
    testValue: new FormControl(),
  });

  items = ['1', '2'];
}

What could be the problem?

Make a ticking javascript clock inside an ajax request that does not flicker

I am trying to make a ticking clock that updates every second (or every new minute is acceptable).

My problem arises because I am using ajax request.

A new ajax request is sent every time I choose a different timezone from a scroll down menu.

Ajax request is executing below code.

If I reload the page with for example $timezone = ‘Asia/Tokyo’, then everything is fine. The problem arises when I do an ajax request through a drop down menu with a different timezone, like $timezone = ‘Europe/Berlin’.

The result will be an output on the website that is flickering between the two different times.

So: when I select a different timezone, like timezone for Europe/Berlin from the drop down menu, an ajax request is sent and code below is executed, and setInterval(showTime, 1000); updates the time every second, meaning, the website will show new output every second when the JavaScript function will execute. But between the JavaScript updates the time on the website will fall back to the time and timezone before the ajax request, showing time for $timezone = ‘Asia/Tokyo’! So the displayed time will be a flickering time alternating: Europe/Berlin>Asia/Tokyo>Europe/Berlin>Asia/Tokyo…changing every second.

(Also, in the output I also get a “GMT+0200 (Central European Summer Time)”-ending. But that is not important, I want to discard it from my output).

Flickering clock between timezones every second because of setInterval(showTime, 1000); https://imgur.com/a/yX0yMj0

You will most probably NOT be able to recreate the error, since my $timezone comes from an ajax request (drop down menu) and not by setting it like $timezone = ‘Asia/Tokyo’.

<?php
$timezone = 'Asia/Tokyo';
//  $timezone = 'America/New_York';
//  $timezone = 'Europe/Berlin';
//  $timezone = 'Asia/Singapore';
        
$datetime = new DateTime('now', new DateTimeZone($timezone));
$formattedDate = $datetime->format('Y-m-d H:i:s');
        
echo '$timezone = ' . $timezone;
echo '<br>';
echo '<pre>';
print_r($datetime);
echo '</pre>';
echo '$formattedDate Shows Static Time in ' . $timezone . ' = ' .  $formattedDate;
echo '<br><br>';
        
echo '
<script>
(function() {
    var serverTime = new Date("' . $formattedDate . '");
    var serverOffset = serverTime.getTime() - new Date().getTime();
        
    function showTime() {
        var now = new Date();
        var correctTime = new Date(now.getTime() + serverOffset);
        
        var formattedTime = correctTime.getFullYear() + "-" +
                            String(correctTime.getMonth() + 1).padStart(2, "0") + "-" +
                            String(correctTime.getDate()).padStart(2, "0") + " " +
                            String(correctTime.getHours()).padStart(2, "0") + ":" +
                            String(correctTime.getMinutes()).padStart(2, "0") + ":" +
                            String(correctTime.getSeconds()).padStart(2, "0");
        
        
        document.getElementById("current-time9").textContent = correctTime;
    }
        
    setInterval(showTime, 1000); // Update every second
})();
</script>
      
<span>current-time9  </span><span id="current-time9"></span><br><br>
';
?>

Something to look into according to chat gpt:

1. Avoid Conflicts Between AJAX Requests and Clock Updates

2. Approach to Solve the Problem

Step 1: Store the Current Timezone

Use JavaScript to store the current timezone selected by the user. This way, you can ensure that the clock updates according to the correct timezone.

Step 2: Fetch Time Only Once Per Update

Fetch the new timezone and time information only when a change is made in the dropdown menu, rather than on every clock update.

Step 3: Use a Separate Function for Updating Time

Why connectionState property of RTCPeerConnection object is not accesssible?

According to manual, RTCPeerConnection has a property connectionState (Indicates the current state
of the peer connection by returning one of the strings).
Link to the manual = https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection

But my program (javascript) does not see it.
Developer tools (console in Firefox) do not show this property too – see curPeerConnection variable in the screenshot.

Why I do not see it ?

React Native HTTP request with FormData including an image

My goal is to send a photo from the local device to server.

I used import { launchImageLibrary } from "react-native-image-picker"; to select an asset called photo and used

const resp = await fetch(photo.uri);
const blob = resp.blob();
formData.append('regPhoto', blob);
registerUser(formData);

to append this as a blob to the form data. I checked that the await fetch call is returnin 200 with meaningful data. Then this formData sent with XMLHttpRequest API:

function registerUser(formData: FormData) {
  cl("registerUser");
  return new Promise((resolve) => {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", url + "registerUser");
    xhr.onreadystatechange = () => {
      const resObj = onReadyStateChange(xhr);
      if (resObj) {
        resolve(resObj);
      }
    };

    xhr.send(formData);
  });
}

Two things happen, the server receives the request without the image and processes it without the image. Which is success to some degree. At the same time, there is a JSON response at the client (android emulator) that reads: Unrecognized formdata part. I am not sure where this is coming from actually.

Does anybody have an idea whats going on here? Just wanted to upload an image to my server via formData.

I tried other methods of appending the photo to the formData but I get the same error.

Context is not accessible in function component – React

I have this page:

'use client';
import { useSearchParams } from 'next/navigation';

import StravaConnection from '@/features/editor/strava-connection';

const EditorProjectIdPage = () => {
  const params = useSearchParams();
  const authToken = params.get('code');

  useEffect( () => {
      console.log("----------------");
      StravaConnection(authToken!);
  }, []);
  redirect("/editor");
};

export default EditorProjectIdPage;

The StravaConnection file looks like this:

'use client';

import { useAuth } from '../../context/AuthContext';

import useSWR from "swr";

const StravaConnection = async (authToken: String) => {
  const { setTokens } = useAuth();

  const fetcher = (url) => fetch(url, { method: "POST" }).then((res) => res.json());

  const { data, error, isLoading } = useSWR(
    "https://www.example.com/oauth/token?client_id=123456&client_secret=abc&code=${authToken}&grant_type=authorization_code",
    fetcher
  );

  console.log(data);
  setTokens(data['access_token']);

  return (
    <div>
      Connecting to Strava...
    </div>
  );
};

export default StravaConnection;

The access token should be returned in the api call. This access token should be stored in the AuthContext using the useAuth method. However, the following error is shown in the console after the “————” has been logged:

Error: Invalid hook call. Hooks can only be called inside of the body
of a function component. This could happen for one of the following
reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

I do not get what I did wrong here. I suppose the error is about the useAuth and useSWR methods in the StravaConnection file, but that one is inside the body of a function component.

How to replace selected text with new text in any textbox?

Say for example the user selected this:
enter image description here

How can a chrome extension replace the selected text with something else? The tricky thing is that this is a universal script, not targeted towards a specific website. And dealing with iframes in google docs, for example, can make things even trickier. I’ve tried existing solutions, but they don’t work or are not complete.

In addition, I’ve tried:

function replaceSelectedText(correctedText, activeElementTagName, selectionStart, selectionEnd) {
  const activeElement = document.activeElement;

  if (activeElement.tagName === activeElementTagName) {
    if (activeElement.tagName === 'TEXTAREA' || activeElement.tagName === 'INPUT' && activeElement.type === 'text') {
      const value = activeElement.value;
      activeElement.value = value.slice(0, selectionStart) + correctedText + value.slice(selectionEnd);
    }
  }
}

and

function replaceSelectedText(correctedText, activeElementTagName, selectionStart, selectionEnd) {
  const activeElement = document.activeElement;
  console.log(activeElement);

  if (activeElement.tagName === activeElementTagName) {
    if (activeElement.tagName === 'TEXTAREA' || (activeElement.tagName === 'INPUT' && activeElement.type === 'text')) {
      const value = activeElement.value;
      activeElement.value = value.slice(0, selectionStart) + correctedText + value.slice(selectionEnd);
      activeElement.setSelectionRange(selectionStart, selectionStart + correctedText.length);
      activeElement.focus();
    } else {
      const selection = window.getSelection();
      if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        range.deleteContents();
        range.insertNode(document.createTextNode(correctedText));
        selection.removeAllRanges();
        range.setStart(range.startContainer, range.startOffset + correctedText.length);
        selection.addRange(range);
      }
    }
  }
}

But perhaps I’m doing things wrong.

Get access to children numeric position within parent component(#1, #2,…) | Reactjs

I’m looking for a way to get access to position of each child component within it’s parent

I have a component called Slider which can have multiple child components. lets call them SliderSection and each SliderSection can have multiple SliderStep components.

It looks something like this:

   <Slider>
      <SliderSection>
        <SliderStep>step 1</SliderStep>
        <SliderStep>step 2</SliderStep>
        <SliderStep>step 3</SliderStep>
      </SliderSection>
      <SliderSection>
        <SliderStep>step 1</SliderStep>
      </SliderSection>
      <SliderSection>
        <SliderStep>step 1</SliderStep>
        <SliderStep>step 2</SliderStep>
      </SliderSection>
   </Slider>

there is a functionality inside both SliderSection and SliderStep which rely on the position of them inside the parent component(Slider)

i used to pass down their position number as a prop to each component like this:

by using props called sectionNum and stepNum

 <Slider>
      <SliderSection sectionNum={1}>
        <SliderStep stepNum={1}></SliderStep>
        <SliderStep stepNum={2}></SliderStep>
        <SliderStep stepNum={3}></SliderStep>
      </SliderSection>
      <SliderSection sectionNum={2}>
        <SliderStep stepNum={1}></SliderStep>
      </SliderSection>
      <SliderSection sectionNum={3}>
        <SliderStep stepNum={1}></SliderStep>
        <SliderStep stepNum={2}></SliderStep>
      </SliderSection>
    </Slider>

notice how sectionNum starts from 1 and goes up for each SliderSection, sliderNum also starts from 1 and goes up for each SliderStep inside SliderSection and resets to 1 when SliderSection changes and goes up.(basically first step of each section stepNum is 1)

but this has some consequences beside not being automatic.

how can i get access to positions without manually passing props down?

why do i need this info inside SliderStep and SliderSection components?:

I want to be able to return null depending on some values(ex, don’t render step 2 if x is true) but since the sectionNum and stepNum props are hardcoded it will mess up the indexing of the slider so i need a way to handle this even if for example section#1-step#2 is not rendered internationally section#1-step#3 should change to section#1-step#2

Applying default layout to Nuxt.js error page while preserving route transitions

I have set up a default layout that includes a header and footer. This layout works fine for all of my pages since they are inside the pages directory and because I have a <NuxtPage/> wrapped in <NuxtLayout/> in app.vue.

However, I’ve encountered an issue with the error page. It is located outside the pages directory and as a result, the default layout will never be applied.

I’ve considered adding a <NuxtLayout/> component in error.vue, but this approach causes conflicts with the <NuxtLayout/> in app.vue – it re-renders it and breaks the transition. I have both pageTransition and layoutTransition set up in nuxt.config.ts.

How can I make sure that the default layout is applied to the error page while maintaining a transition?

How can account for variable timing of adding words in this Javascript+CSS message animation?

I’m writing an animation for a streaming text response in a messaging service. Each word drops in to the bubble, which resizes dynamically.

It looks good with the right timing values, but try setting the delay variable in addMessage() to different numbers like 25 or 150, and the bubble will jerk and wobble. I need it to handle variable timing of adding words more gracefully.

I think I needed to do something different with a sibling element to the chat-text element that would serve as the blue background, but I couldn’t quite figure it out. Any suggestions are appreciated.

Codepen: https://codepen.io/goldenjoe/pen/yLdVXjY

const chatContainer = document.getElementById('chat-container');
const chatText = document.getElementById('chat-text');

// const messages = ["Hello", "How are you?", "I'm a chatbot.", "I can help you with various tasks."];
const messages = ["Hello, how are you? I'm a chatbot. I can help you with various tasks."];
let index = 0;

function addWord(word) {
  const wordSpan = document.createElement('span');
  wordSpan.classList.add('word');
  wordSpan.textContent = word.trim();
  chatText.appendChild(wordSpan);

  const spaceSpan = document.createElement('span');
  spaceSpan.textContent = ' ';
  chatText.appendChild(spaceSpan);

  resizeContainer();
}

function resizeContainer() {
  const chatBoxRect = chatText.getBoundingClientRect();
  const containerAutoRect = chatContainer.getBoundingClientRect();

  // This is a bit weird, we want the width of the container, but the height of the text.
  chatContainer.style.width = containerAutoRect.width + 0 + 'px';
  chatContainer.style.height = chatBoxRect.height + 0 + 'px';
}

function addMessage() {
  if (index < messages.length) {
    const words = messages[index].split(" ");
    let delay = 50;
    words.forEach((word, i) => {
      setTimeout(() => {
        addWord(word + ' ');
      }, i * delay);
    });
    index++;
  }
}

setInterval(addMessage, 500);

// Initial resize to fit the first message
resizeContainer();
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f0f0f0;
  margin: 0;
}

#chat-container {
  background-color: #000ff0ff;
  color: white;
  padding: 10px 20px;
  border-radius: 10px;
  font-family: Arial, sans-serif;
  font-size: 1.5em;
  transition: width 0.08s linear, height 0.08s linear;
  max-width: 300px;
}


/* Just an empty container for now...couldn't find a use for a style here. */

#chat-text {}

.word {
  display: inline-block;
  /* this allows the offset to work */
  opacity: 0;
  /* if it doesn't start this way the animation won't fade in */
  transform: scale(1.2) translateY(-16px);
  animation: textIn 0.3s forwards;
  animation-delay: 0.25s;
  /* 
         HACK: There's a timing issue...if the container doesn't finish changing its size to be wide enough for the text, the text will "jump" between lines.
         The delay gives the container time to expand, preventing the text from "snapping" to the correct line.
         The correct solution is probably to have a sibling span that is just the background, and animate it matching the text size.
         */
}

@keyframes textIn {
  from {
    opacity: 0;
    transform: scale(1.2) translateY(-16px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}
<div id="chat-container">
  <span id="chat-text"></span>
</div>

Why am I getting compile error in JavaScript when extending a class with a default constructor?

I’m trying to create a subclass in JavaScript and am encountering an error related to the use of this in the subclass constructor. Here’s the code I’m working with:

class Mammals {
  // No constructor defined explicitly
}

class Humans extends Mammals {
  constructor(name) {
    this.name = name;
  }
}

const jimmy = new Humans("Jimmy");
console.log(jimmy.name);

I understand that if a base class has a default no-argument constructor, JavaScript should allow the subclass constructor to run without explicitly calling super(). I thought that since Mammals has a default constructor (as it’s not explicitly defined), the Humans constructor should not need to call super().

However, I am still encountering the error message:

Must call super constructor in derived class before accessing ‘this’
or returning from derived constructor

Can someone explain why

Thank you for your help!

localStorage not working on iOS captive portal mini browser (CPMB)

I tried to save data on iOS Captive Portal Mini Browser (Hotspot WiFi)
window.localStorage.setItem("my_data", "data");
but when I try to reconnect to CPMB
var my_data = window.localStorage.getItem("my_data");
my_data is null

I have the same problem using Cookies, it works fine on Android, Windows,…

is there any alternative to backup data to iOS device using CPMB ?

Thanks