Chrome extension Service Worker not connecting to port when inactive

I’m making a Chrome extension, in which I have a service worker, which accesses an IndexedDB. When opening the popup I need to exchange data from the service to the popup and vice versa, I do this by opening a port:
let port = chrome.runtime.connect({ name: "popup" });
When the service worker shows it’s active, it works perfectly fine. But when the service worker shows it’s inactive, it gives off this error:
Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

I’ve tried everything, trying to wake it up based events, which didn’t work, switching browsers to Chrome to see if it’s an issue with Brave, also didn’t change anything.
I’ve tried try catch, still showed error, and didn’t work.
Tried to set a timeout to let the service worker wake up, also didn’t work.
I also don’t want to use a background server, as I heard it was deprecated in manifest V3

How to display answer descriptions in a coding quiz application when the user gives a wrong answer? [closed]

I’m developing a coding quiz application where users are presented with multiple-choice questions. If a user selects the wrong answer, I want to display a detailed description of the correct answer to help them learn from their mistakes.

I’m currently using Javascript to develop Front end for my application. What would be the best approach to implement this functionality? Should I store the answer descriptions in a database or use a separate file? How can I link each description to its corresponding question and display it dynamically?

I would appreciate any insights or sample code snippets on how to achieve this functionality effectively and efficiently. Thank you in advance for your help!

this is what i got on internet i want to make similar like this
demo image

not tried anything so please guide me.

How to create a pan & zoom effect for an image with different proportions to its container?

I have the following simple code that pans and zooms an image (slightly modified from [here]:(https://www.cssscript.com/image-zoom-hover-effect/)

    function imageZoom(container, img) {

      container.addEventListener("mousemove", onZoom);
      container.addEventListener("mouseover", onZoom);
      container.addEventListener("mouseleave", offZoom);
      function onZoom(e) {
    
        let offset = container.getBoundingClientRect();
          const x = e.clientX - offset.left;
          const y = e.clientY - offset.top;
          img.style.transformOrigin = `${x}px ${y}px`;
          img.style.transform = "scale(2.5)";
      }
      function offZoom(e) {
          img.style.transformOrigin = `center center`;
          img.style.transform = "scale(1)";
      }
    }

This works well when the image is proportional to container. I need it to work with random-sized images inside square containers, with the ability to show the entire image via pan & zoom.

I’ve tried multiplying X and Y by

        let coefX= img.naturalWidth / container.offsetWidth
        let coefY= img.naturalHeight / container.offsetHeight

respectively, but that resulted in the image leaving the container altogether. I feel like the math is simple and obvious, but I can’t seem to grasp it – other attempts I’ve made resulted in similar problems.

Swiper continous auto scroll stops and starts and pause on mouse over not immediate

I’m having an issue with Swiper and the slides not continuously scrolling in a linear smooth motion. Instead the slides pause and slow down and then start to speed up slightly before slowing again.

Demo here.

I’d like the slides to loop in a continuous smooth motion, only pausing on mouse over. Similar to this example.

I’ve seen from this post here this functionality was requested previously and its stated that this functionality has been added in since V9, but I cannot seeing any working examples since V9.

I’m using swiper version 10.0.2

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

<head>
  <meta charset="utf-8" />
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />
  <!-- Link Swiper's CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css" />

  <!-- Demo styles -->
  <style>
    html,
    body {
      position: relative;
      height: 100%;
    }

    body {
      background: #eee;
      font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
      font-size: 14px;
      color: #000;
      margin: 0;
      padding: 0;
    }

    .swiper {
      width: 100%;
      height: 100%;
    transition-timing-function: linear!important;
    }

    .swiper-slide {
      text-align: center;
      font-size: 18px;
      background: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 660px;
      background: red;
    }

    .swiper-slide img {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  </style>
</head>

<body>
  <!-- Swiper -->
  <div class="swiper mySwiper">
    <div class="swiper-wrapper">
      <div class="swiper-slide">Slide 1</div>
      <div class="swiper-slide">Slide 2</div>
      <div class="swiper-slide">Slide 3</div>
      <div class="swiper-slide">Slide 4</div>
      <div class="swiper-slide">Slide 5</div>
      <div class="swiper-slide">Slide 6</div>
      <div class="swiper-slide">Slide 7</div>
      <div class="swiper-slide">Slide 8</div>
      <div class="swiper-slide">Slide 9</div>
    </div>
  </div>

  <!-- Swiper JS -->
  <script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>

  <!-- Initialize Swiper -->
  <script>
    var swiper = new Swiper(".mySwiper", {
      spaceBetween: 40,
        effect: 'slide',
        loop: true,
        freeMode: true,
        slidesPerView: "auto",
        speed: 5000,
        autoplay: {
            delay: 1,
            pauseOnMouseEnter: true,
            disableOnInteraction: false,
            waitForTransition: true,
            stopOnLastSlide: false,

        }
    });
  </script>
</body>

</html>

React functional component behaviour question

I’m starting to learn React and its components, specifically the functional components.
While playing around with the code i found out a behavior that left me with a doubt/question (i don’t know if it’s a basic behaviour or not). I’m using React18, React-dom18 and Babel through CDN.
My IDE is “Webstorm”.
I deliberately writed the code like this just to test out this behaviour, i know it’s probably not optimal.

The code i used is all inside an HTML file and i have not used any additional setup or configuration:

<script type="text/babel">

  const RecipeTitle = ({test = 0}) => {
    const [title, setTitle] = React.useState(test);

     function onChangeHandler(){
      setTitle(1);
      console.log("onChange event! title: " + title);
    }

    console.log("Functional component executing. title: " + title);
    console.log("------------------------");

    return <input type="text" value={title} onChange={onChangeHandler} />
  };

  const container = document.querySelector("#root");
  const rootElement = ReactDOM.createRoot(container);
  rootElement.render(<RecipeTitle />);
</script>

I have a RecipeTitle component that gets rendered the first time when the application runs. This component have a state(title) and generate an “input” element in the DOM in which you can insert text; This element will always show the state value(title) in the web page because of the “value” prop setted on the element.
When the user try to change the text inside the input element(no matter what he press on his keyboard) the onChange event will trigger that will execute the “onChangeHandler” function, in this function i set the state value(title) always to “1”(this cause the text showed in the input element to be always “1” no matter what but this is not my concern). I added 3 “console.log()” to show better my doubt.
My doubt is happening when the user try to change the text inside the input element from the web page the second time.

The first time the “setTitle” method gets called he sets the state value from “0” to “1” so he re-runs the whole function to update the value showed in the input element in the web page (and that’s okay).

The second time the “setTitle” method gets called he sets the state value from “1” to “1”, so it didn’t changed at all, even so the whole function get re-executed again (i know this by the logs, printed in the browser console, that are outside of “onChangeHandler” method) but the “input” element dosen’t get re-rendered again (i know this by using “React Developer Tools”, specifically the “profiler” tab that highlights the elements when they get re-rendered)(this is the unexpected behaviour, because i was expecting he behaves like the third and all the times after the second one which i explain just below).

The third and all the times after the second one that the “setTitle” method gets called, he sets the state value from “1” to “1”, so it didn’t changed at all, the whole function DOSEN’T get re-executed again(he executes only the “onChangeHandler” method and that’s it, and also the “input” element dosen’t get re-rendered again (this is the behaviour i was expecting to happen from the second time already and not starting from the third time moving fowards).

So for summarizing, my question is: why he starts to ignore the execution of the whole functional component STARTING FROM the third time that the “onChange” event get triggered if it’s, instead, from the second time already that state value starts to be setted to always the same value as before(it didn’t change)? It is some kind of React internal optimization that he do? if yes: how it works explained in a brief way? any clarification about this can be helpful for me.

Here i leave a screenshot that show my doubt:

doubt screenshot

Thank you very much for any help, i already tried to search for this behaviour online but without result.

P.S: I know about hooks.

How To trigger a function in my React Native app from my Node.js app

How To trigger a function in my React Native app from my Node.js app without using web sockets, I have a specific purpose: I am developing a call feature for my React Native app and I need to listen for incoming calls by calling a function. When a user initiates a call, I want to trigger the incoming call function on another user’s device. While Firebase Cloud Messaging (FCM) can be a viable approach, it requires user notification permission on iOS, and it won’t work if the user declines the permission, as most users tend to do.

Considering this limitation, what alternative solutions can I explore?

Express JS writeFile then spawn Python script

I’m trying to setup an express router that takes a post request, write to a JSON file, and spawn a Python script to do something with the JSON file. However, the router will write the file, spawn the Python script but ‘exit with child code 0’ before the Python script is completed.

The router only run with either just the spawn function or with the writeFile function but not both in sequential call. I already tried breaking the function into middleware as well but still doesn’t work. Not sure what is missing here…

sampleRouter.post('/:fileName', (req, res) => {
  let fileName = req.params.fileName;
  let data = JSON.stringify(req.body);
    
  fs.writeFile(fileName, data, function (err) {
    if(err) {
      res.send(err);
    }
    console.log("Write Success");

    const Python = spawn('python', [sample.py]);
  });

  res.send("Write Success");
});

Floating label from chakra-ui and react-select

As a noobie, I have ReactSelect as a defalut component and I’m having troble implemnting a floating label with chakra-ui as is demonstrated here.

Tryed to add a className=”identifier” so themecan find my component. It kind of worked using extendTheme over component/index.

'input:not(:placeholder-shown) + label, .identifier input:not(:placeholder-shown) + label,

Happens that label its always active, floating top left and not transitioning back center when there is no option is selected.

Same doen’t happen with date or text imput.

Anys sugestions?
https://codesandbox.io/embed/eager-darkness-3nh94z?fontsize=14&hidenavigation=1&theme=dark

Strange behavior with Bootstrap 5 Tooltips & Popovers

I have a Chrome extension that is built using Bootstrap 5.3 that uses several components like Collapse, Tooltips, Popovers and others. I’m having a strange problem with Tooltips and Popovers though.

The main view of the popup/sidepanel is a div with the id of resultsPanel and the extension flow goes like this

If storage contains a result insert into results panel and (exit) ->
Enter data and hit search ->
api call ->
results are added inside resultsPanel ->
"controls are enabled ->
html inside resultsPanel is written to storage

In the event that there was a result it’s inserted into the view like this

if (lastResult !== null) {
    $('#resultsPanel').html(lastResult);
    enableControls();
}

After the UI is finished being updated or we have just loaded the previous result this is how the controls are enabled

function enableControls() {
   const collapseElementList = [].slice.call(
      document.querySelectorAll('.collapse'),
   );
   const _collapseList = collapseElementList.map(function (collapseEl) {
      return new Collapse(collapseEl, {
         toggle: false,
      });
   });

   const popoverTriggerList = document.querySelectorAll(
      '[data-bs-toggle="popover"]',
   );
   const _popoverList = [...popoverTriggerList].map(
      (popoverTriggerEl) => new Popover(popoverTriggerEl),
   );
}

This is where the problem begins…

If we did not load a previous result

The collapse elements work as expected, but tooltips and popovers do NOT work.

If did load a previous result

The UI looks like I expect it too and all controls, including popovers/tooltips, work as intended.

Any clue why this is happening?

Add elements to a page and link them

I need to create a button that lets me add several types of fields to my form.

For example if I want to add a skill, I need to add an input for the skill title, another for the number of resources required and another for the solution. I should be able to add as many as I want.

I also need to be able to link skills together if they follow one another visually on the page and I need to be able to delete an item from the list.

I’ve tried to do this with parentElements but my file is 1000 lines of code long and very complicated to read. What’s more, every time I’m asked to add a new feature, nothing works.

next = input1.parentElement.parentElement.parentElement.parentElement.nextElementSibling.firstChild.firstChild.lastChild.children[1];
nextsol = input1.parentElement.parentElement.parentElement.parentElement.nextElementSibling.firstChild.nextSibling.children[1];
nextlink = input1.parentElement.parentElement.parentElement.parentElement.nextElementSibling.firstChild;

if (next.parentElement.parentElement.parentElement.children[1].childElementCount < 2 && next.classList.length < 3) {
  const inputNext = document.createElement("input");
  inputNext.value = 1;
  inputNext.classList.add("width-50px");
  next.parentElement.parentElement.parentElement.children[1].appendChild(inputNext);
  next.style.border = "1px solid gray";

Getting the error “Warning: Prop `dangerouslySetInnerHTML` did not match.” while trying to use script tags in Remix

I try to run some code for initialising and preload some code in my Remix app. I get this error: “Warning: Prop dangerouslySetInnerHTML did not match. Server:…”. I’ve set my script tag in head, and it seems I always get this error when running my script tag.. Is there something obvious I’m missing here?

<head>
  <script
  key="initialising"
  dangerouslySetInnerHTML={{
    __html: `... some code`,
  }}
  />
</head>

Most of the other threads I see are not using the script tag, so I’m not sure where to look for an answer

I’ve tried to add it to the handle function using remix-utils, but it seems like it loads the script too late.. when this is a script I wanna run as the very first thing

Why mongoose model .create() is missing out properties on the record

I’m trying to save an object to a collection, but I’m missing properties when I try to save a document with it. See the schema below

const ordersScheme = new Schema(
  {
    userId: {
      type: String,
      required: true,
      trim: true
    },

    Delivery: {
      type: Boolean,
      required: true,
      trim: true
    },
    Address: {
      address_line_1: {
        type: String,
        required: false,
        trim: true
      },
      coordinates: {
        type: String,
        required: false,
        trim: true
      }
    },
    line_items: []
  },
  { timestamps: true }
);

now when I try to push a product, the saved document is missing properties for the object inside line_items array.

So this is the exact same payload:

{
    "userId": "649ba737f4c1f0c385d7c5a2",
    "Delivery": false,
    "Address": {
        "address_line_1": "No Address",
        "coordinates": "No Coords"
    },
    "line_items": [
        {
            "_id": 1688390766597,
            "product": {
                "Type_field": "Product",
                "Product_Category": "ACCESSORY UNPAINTED",
                "Product_Image": "https://somewebsites.dddd.net/static/1678120139378_1_main__2___2_.jpg",
                "Category": {
                    "display_value": "Fence Accessory Unpainted",
                    "ID": "5"
                },
                "Product_Name": "READY CONCRETE - 15KG",
                "Item_Size_Attribute": "15KG",
                "ProductNumber": "100015",
                "Parent_Product": "",
                "Variation_Type": "",
                "Colours_Available": [],
                "Price_GST": "11.22",
                "Item_Width": "0",
                "Price": "9.29",
                "Item_Material_Attribute": "Concrete",
                "Item_Height": "0",
                "ID": "601",
                "Length_Type": "Standard"
            },
            "colours": [],
            "relations": [],
            "image": "https://somewebsites.dddd.net/static/1678120139378_1_main__2___2_.jpg",
            "ID": 601,
            "quantity": 1,
            "customSize": 0,
            "selectedColour": null,
            "IDD": "6493e09761dc1406da49adea"
        }
    ],
    "total_cost": "9.29"
}

I don’t understand what’s the issue, when I try to specify every property in the Schema, I don’t get even a quarter of the information. With line_items: [], I’m getting most of them with missing a few.

This is what I’m getting saved in the DB with the Schema and Payload above. See how quantity, customSize and other properties are missing from line_items objects.

{
    "type": "success",
    "message": "Order created successfully",
    "data": {
        "message": {
            "userId": "649ba737f4c1f0c385d7c5a2",
            "Delivery": true,
            "Address": {
                "address_line_1": "No Address",
                "coordinates": "No Coords"
            },
            "line_items": [
                [
                    {
                        "_id": "6493e09761dc1406da49adea",
                        "product": {
                            "Type_field": "Product",
                            "Product_Category": "ACCESSORY UNPAINTED",
                            "Product_Image": "https://d213123.dddd.net/static/1678170139378_1_main__2___2_.jpg",
                            "Category": {
                                "display_value": "Fence Accessory Unpainted",
                                "ID": "5"
                            },
                            "Product_Name": "READY CONCRETE - 15KG",
                            "Item_Size_Attribute": "15KG",
                            "ProductNumber": "100015",
                            "Parent_Product": "",
                            "Variation_Type": "",
                            "Colours_Available": [],
                            "Price_GST": "11.22",
                            "Item_Width": "0",
                            "Price": "9.29",
                            "Item_Material_Attribute": "Concrete",
                            "Item_Height": "0",
                            "ID": "601",
                            "Length_Type": "Standard"
                        },
                        "colours": [],
                        "relations": [],
                        "image": "https://d213123.dddd.net/static/1678170139378_1_main__2___2_.jpg",
                        "ID": 601
                    }
                ]
            ],
            "_id": "64a2ce30b4faf7b52b564bbb",
            "createdAt": "2023-07-03T13:33:36.839Z",
            "updatedAt": "2023-07-03T13:33:36.839Z",
            "__v": 0
        }
    }
}

how can i use the returned value in the global scope? [duplicate]

i would like to be able to use the entered date of the datepicker in the global scope to then add it to an object….

 $( "#datepicker" ).datepicker({

        onSelect: function () { 
            let dateObject = $(this).datepicker('getDate'); 
            let day = dateObject.getDate();
 

            let month = dateObject.getMonth();
  

            let year = dateObject.getFullYear();


            let birthDate = `${day}-${month+1}-${year}`

            // nutze diesen Geburtstag!!!
            console.log(birthDate)

            let datess = $(this).val();

            console.log(datess)
         
            return birthDate;
            
        },

        changeYear: true,
        changeMonth: true,
        minDate: 0,
        maxDate: "+1Y",
        currentDate: $("#datepicker").val(),

    });

How do I send notifications to a specific device using fcm-node package for firebase?

I’m trying to send notifications to a specific device using fcm-node package but I don’t know how as it’s not clear in the docs

this is my code:

let firbaseNotification = {
                notification: {
                    title: content.title,
                    body: content.message,
                    // content_available: true,
                    priority: 'high',
                    click_action: 'FLUTTER_NOTIFICATION_CLICK',
                    requestTime,
                    sound: 'default'
                },
                data: {
                    content,
                    action_loc_key: null,
                    content_available: true,
                    priority: 'high'
                }
            };

            var message = {
                notification: firbaseNotification.notification,
                data: firbaseNotification.data
            };

            firbaseNotification['registration_ids'] = deviceIds; // Device IDS

            fcm.send(firbaseNotification, function (err, response) {
                if (err) {
                    status = 400;
                    console.log("Something has gone wrong!", err);
                } else {
                    console.log("Successfully sent with response: ", response);
                }

                res.send({ status, errorMessge: err });
            });
        } catch (error) {
            console.log('error', error)
            res.send({ status: 400, errorMessge: error });
        }
    });
};

deviceIds is supposed to be the id of target devices in my db, how do I send to a specific user?

how to allow the user to resize image according to its preference to drag and resize the image in react native expo

the problem i faceing is that i have screen and there is an option for attachments so the user can attach an image on the screen and the image can be movable and resizable , i have already achieved the functionality for moving the image on with in the view but i stuck in also making it resizable, so please let me know the solution for this project i am using expo cli and there is no library i found till now for the desired functionality.

import { View, ImageBackground, TextInput, Text, TouchableOpacity, PanResponder, Animated, StyleSheet, Modal, Alert, ToastAndroid, Button, Dimensions, Image } from 'react-native'
import React, { useRef, useEffect, useState } from 'react'
import { ReactNativeZoomableView } from '@openspacelabs/react-native-zoomable-view';
import { useAuth } from "../context/auth";
import clientApi from '../api/clientApi';
import { useTasks } from '../context/Task';
import * as ImagePicker from 'expo-image-picker';
import { Audio } from 'expo-av';

import {
    DrawWithOptions,
} from '@archireport/react-native-svg-draw';
import { LinearGradient } from 'expo-linear-gradient';
import * as MediaLibrary from 'expo-media-library';
import * as Sharing from 'expo-sharing';
import { MaterialIcons } from '@expo/vector-icons';
import { FontAwesome } from '@expo/vector-icons';
import { FontAwesome5 } from '@expo/vector-icons';

const DailyTasks = ({ route }) => {
    const Data = route.params;

    const [text, setText] = useState('');

    const [modalVisible, setModalVisible] = useState(false);
    const [title, setTitle] = useState('');

    const [category, setCategory] = useState('DailyTasks');
    const [auth] = useAuth();
    const { userId, token } = auth;
    const [recording, setRecording] = useState();
    const [recordings, setRecordings] = useState([]);
    const [message, setMessage] = useState("");
    const pan = useRef(new Animated.ValueXY()).current;
    const [image, setImage] = useState(null);
    const [isTextInputEnabled, setIsTextInputEnabled] = useState(false);

    const { updateTasks } = useTasks();
    const handleSave = async () => {
        try {
            if (!userId) {
                console.log('userId is null', userId);
                setModalVisible(false)
                ToastAndroid.show("User ID is missing", ToastAndroid.SHORT);
                return;
            } else {
                const headers = {
                    Authorization: token
                };
                const res = await clientApi.post('/api/v1/tasks/create',
                    { title, category, text, userId },
                    { headers }
                );
                setModalVisible(!modalVisible)
                if (res && res.data.success) {
                    const updatedRes = await clientApi.get(`/api/v1/tasks/user-tasks/${userId}`);
                    const updatedTasks = updatedRes.data;
                    ToastAndroid.show(res.data.message, ToastAndroid.SHORT);
                    updateTasks(updatedTasks);
                } else {
                    ToastAndroid.show(res.data.message, ToastAndroid.SHORT);
                }
            }
            setModalVisible(false)
        } catch (error) {
            setModalVisible(!modalVisible)
            console.log(error);
            ToastAndroid.show("Something went wrong");
            setModalVisible(false)

        }
    }
    const saveSnapshot = async (uri) => {
        const permission = await MediaLibrary.requestPermissionsAsync();
        if (permission.granted) {
            await MediaLibrary.saveToLibraryAsync(uri); // Save the snapshot to the device's photo library on Android
            console.log('Snapshot saved successfully:', uri);
        } else {
            console.log('Permission to access media library not granted.');
        }
    };


    const handleToggleInput = () => {
        setIsTextInputEnabled((prevIsTextInputEnabled) => !prevIsTextInputEnabled);
    };
    const pickImage = async () => {
        // No permissions request is necessary for launching the image library
        let result = await ImagePicker.launchImageLibraryAsync({
            mediaTypes: ImagePicker.MediaTypeOptions.All,
            allowsEditing: true,
            aspect: [4, 3],
            quality: 1,
        });

        console.log(result);

        if (!result.canceled) {
            setImage(result.assets[0].uri);
        }
    };
    const removeImage = () => {
        setImage(null);
    };

    async function startRecording() {
        try {
            const permission = await Audio.requestPermissionsAsync();

            if (permission.status === "granted") {
                await Audio.setAudioModeAsync({
                    allowsRecordingIOS: true,
                    playsInSilentModeIOS: true
                });

                const { recording } = await Audio.Recording.createAsync(
                    Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
                );

                setRecording(recording);
            } else {
                setMessage("Please grant permission to app to access microphone");
            }
        } catch (err) {
            console.error('Failed to start recording', err);
        }
    }
    async function stopRecording() {
        setRecording(undefined);
        await recording.stopAndUnloadAsync();

        let updatedRecordings = [...recordings];
        const { sound, status } = await recording.createNewLoadedSoundAsync();
        updatedRecordings.push({
            sound: sound,
            duration: getDurationFormatted(status.durationMillis),
            file: recording.getURI()
        });

        setRecordings(updatedRecordings);
    }

    function getDurationFormatted(millis) {
        const minutes = millis / 1000 / 60;
        const minutesDisplay = Math.floor(minutes);
        const seconds = Math.round((minutes - minutesDisplay) * 60);
        const secondsDisplay = seconds < 10 ? `0${seconds}` : seconds;
        return `${minutesDisplay}:${secondsDisplay}`;
    }
    function RecordingLine({ recordingLine, index }) {
        const [isPlaying, setIsPlaying] = useState(false);
        const sound = recordingLine.sound;

        const handlePlaybackToggle = async () => {
            if (isPlaying) {
                // Pause the playback
                await sound.pauseAsync();
            } else {
                // Start or resume the playback
                await sound.playAsync();
            }
            setIsPlaying(!isPlaying);
        };

        return (
            <View style={styles.row}>
                <Text>Recording {index + 1} - {recordingLine.duration}</Text>
                <Button style={styles.button} onPress={handlePlaybackToggle} title={isPlaying ? 'Pause' : 'Play'}></Button>
                <Button style={styles.button} onPress={() => Sharing.shareAsync(recordingLine.file)} title="Share"></Button>
            </View>
        );
    }
    function getRecordingLines() {
        return recordings.map((recordingLine, index) => {
            return <RecordingLine key={index} recordingLine={recordingLine} index={index} />;
        });
    }
    useEffect(() => {
        if (route.params && route.params.desc) {
            setText(route.params.desc);
            setTitle(route.params.head)
        }
    }, [route.params]);
    const panResponder = PanResponder.create({
        onStartShouldSetPanResponder: () => true,
        onPanResponderMove: Animated.event([
            null,
            { dx: pan.x, dy: pan.y }
        ], { useNativeDriver: false }),
        onPanResponderRelease: () => {
            pan.flattenOffset(); // This will set the offset to the current value and reset value to zero
        },
        onPanResponderGrant: () => {
            pan.setOffset({
                x: pan.x._value,
                y: pan.y._value
            }); // This will set the offset to the current value when the pan starts
        }
    });

    return (
        <View style={{
            flex: 1,
        }}>
            <ReactNativeZoomableView
                disablePanOnInitialZoom={true}
                scrollEnabled={false}
                maxZoom={2}
                minZoom={1}
                zoomStep={0.5}
                initialZoom={1}
                bindToBorders={true}
                onZoomAfter={this.logOutZoomState}
                panEnabled={false}
                panBoundaryPadding={0}
                doubleTapZoomToCenter={true}
                style={{
                }}
            >
                <View style={{
                    flex: 1,
                    justifyContent: 'center',
                    alignItems: 'center'
                }} >
                    <ImageBackground source={require('../../assets/table1.png')} style={{
                        width: '100%',
                        height: Dimensions.get('window').height / 1.21,
                        position: 'absolute',
                    }}
                        resizeMode="cover" >

                        {isTextInputEnabled ? (
                            <>
                                <TextInput
                                    value={text}
                                    onChangeText={(newtext) => setText(newtext)}
                                    autoFocus
                                    multiline
                                    editable
                                    style={styles.textcontainer} />
                            </>) : (<>
                                <Text style={styles.textcontainer}>{text} </Text>
                                <DrawWithOptions
                                    linearGradient={LinearGradient}
                                    close={() => true}
                                    takeSnapshot={(snap) => {
                                        snap.then((uri) => {
                                            saveSnapshot(uri);
                                            ToastAndroid.show(uri, ToastAndroid.SHORT);
                                        });
                                    }}
                                /></>)}
                        <Animated.View {...panResponder.panHandlers} style={[pan.getLayout(), styles.btncontainer, { width: 200, height: 200 }]}>
                            <View style={{ flexDirection: 'column' }} >
                                {image && (
                                    <>
                                        <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />
                                        <TouchableOpacity onPress={removeImage} style={styles.removebtn}>
                                            <FontAwesome name="remove" size={30} color="#B9D5FF" />
                                        </TouchableOpacity>
                                    </>
                                )}
                            </View>

                        </Animated.View>
                        <View
                            style={[
                                styles.btncontainer,
                                {
                                    marginLeft: "70%"
                                },
                            ]}
                        >

                            <View style={{ flexDirection: 'column', justifyContent: 'flex-end' }}>
                                {getRecordingLines()}
                            </View>
                        </View>
                        <View>
                            <Modal
                                animationType="slide"
                                transparent={true}
                                visible={modalVisible}
                                onRequestClose={() => {
                                    Alert.alert('Modal has been closed.');
                                    setModalVisible(!modalVisible);
                                }}>
                                <View style={styles.centeredView}>
                                    <View style={styles.modalView}>
                                        <TextInput
                                            placeholder='Title'
                                            style={styles.modalText}
                                            onChangeText={(title) => setTitle(title)}
                                            value={title}
                                        />

                                        <TouchableOpacity
                                            style={[styles.button, styles.buttonClose]}
                                            onPress={handleSave}>
                                            <Text style={styles.textStyle}>Save</Text>
                                        </TouchableOpacity>
                                    </View>
                                </View>
                            </Modal>
                        </View>
                    </ImageBackground>
                </View>
            </ReactNativeZoomableView>
            <View style={{ alignItems: 'center' }}>
                <View style={styles.buttonview}>
                    <TouchableOpacity onPress={pickImage} style={styles.Touchablebutton} >
                        {/* <Text style={{ fontSize: 15, marginRight: 10, color: 'white' }}>Attachment</Text> */}
                        <MaterialIcons name="attachment" size={24} color="#B9D5FF" />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.Touchablebutton} onPress={handleToggleInput}>
                        {/* <Text style={{ fontSize: 20, marginRight: 10, color: 'white' }}>{isTextInputEnabled ? 'Drawing' : 'Text'}</Text> */}
                        {isTextInputEnabled ? <FontAwesome5 name="pen" size={24} color="#B9D5FF" /> : <MaterialIcons name="text-fields" size={24} color="#B9D5FF" />}
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.Touchablebutton} onPress={() => setModalVisible(true)} >
                        {/* <Text style={{ fontSize: 20, marginRight: 10, color: 'white' }}>Save</Text> */}
                        <FontAwesome name="save" size={24} color="#B9D5FF" />
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.Touchablebutton} onPress={recording ? stopRecording : startRecording}>
                        {/* <Text style={{ fontSize: 15, marginRight: 10, color: 'white' }}>{recording ? 'Stop Recording' : 'Start Recording'}</Text> */}
                        {recording ? <FontAwesome5 name="stop" size={24} color="#B9D5FF" /> : <MaterialIcons name="multitrack-audio" size={24} color="#B9D5FF" />}

                    </TouchableOpacity>
                </View>
            </View>
        </View>
    )
}

export default DailyTasks

const styles = StyleSheet.create({
    buttonview: {
        flexDirection: 'row',
        justifyContent: 'center',
        marginBottom: '1%',
        backgroundColor: 'black',
        borderRadius: 10,
        width: Dimensions.get('window').width / 3,
    },
    Touchablebutton: {
        // backgroundColor: 'grey',
        width: Dimensions.get('window').width / 10,
        justifyContent: 'center',
        alignItems: 'center',
        // borderWidth: 2,
        borderColor: 'white',
        borderRadius: 10,
        height: 30
    },
    removebtn: {

        width: Dimensions.get('window').width / 10,
        alignSelf: "flex-start",
        borderRadius: 10,
        height: 30
    },
    centeredView: {
        flex: 1,
        justifyContent: 'center',
        // alignItems: 'flex-end',
        marginTop: 22,
        // height: 300,
        // width: '30%'
    },
    modalView: {
        margin: 20,
        backgroundColor: 'white',
        borderRadius: 20,
        padding: 35,
        alignItems: 'center',
        shadowColor: '#000',
        shadowOffset: {
            width: 0,
            height: 2,
        },
        shadowOpacity: 0.25,
        shadowRadius: 4,
        elevation: 5,
    },
    button: {
        borderRadius: 20,
        padding: 10,
        elevation: 2,
    },
    buttonOpen: {
        backgroundColor: '#F194FF',
    },
    buttonClose: {
        backgroundColor: '#2196F3',
    },
    textStyle: {
        color: 'white',
        fontWeight: 'bold',
        textAlign: 'center',
    },
    modalText: {
        marginBottom: 15,
        textAlign: 'center',
    },
    btncontainer: {
        position: 'absolute',
        flexDirection: 'row',
        marginTop: '10%'
        // top: '7%',
        // width: '100%',

    },
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        zIndex: 999999,`your text`
        paddingTop: 10
    },
    buttonnote: {
        zIndex: 9999999,
        width: '10%',
    },
    textcontainer: {
        height: '100%',
        width: '100%',
        fontSize: 15,
        position: 'absolute',
        marginTop: "0%"
    }
})
type here