How to get list of only already created groups?

I know how to get list of tabs consists in certain group:

var possible_colors = ['grey', 'blue', 'red', 'yellow', 'green', 'pink', 'purple', 'cyan', 'orange']

chrome.tabGroups.query({ color: possible_colors[1] }, function (group) {
    chrome.tabs.query({ groupId: group[0].id }, function (tabs) {
        console.log(tabs)
    })
})

But I want to get list of only created or only exists groups in current chrome window. Maybe it’s somehow possible by Chrome Extensions API and without loop through all possible_colors to check?

Get data from multiple custom checkboxes in react native

I am building a small quiz in react native. On my screen, I want the user to chose several correct answers from a choice of 4-6 options. I build a custom checkbox for that. If the correct answers are checked (and all wrong answers are unchecked) the user should get a message that the answer was correct.

Here is the custom checkbox component. I only included the code for three boxes to make the code a bit shorter:

import { TouchableOpacity, StyleSheet, View, Text } from "react-native";
import { FontAwesome } from "@expo/vector-icons";

function AnswerContainer_CheckBox(props) {

  const [userInput, setUserInput] = useState("");

  const answerHandler = () => {
    if (userInput == props.finalAnswer) {
      dispatch(answerTrue());
    }
  };

  const [checked_1, setChecked_1] = useState(false);
  const [checked_2, setChecked_2] = useState(false);
  const [checked_3, setChecked_3] = useState(false);
  
/*Visibility
if set to false via props, the checkbox won't show
*/
  const [box_1_Visibility, setBox_1_Visibility] = useState(
    props.box_1_Visibility
  );
  const [box_2_Visibility, setBox_2_Visibility] = useState(
    props.box_2_Visibility
  );
  const [box_3_Visibility, setBox_3_Visibility] = useState(
    props.box_3_Visibility
  );
 
  /* Functions to chech and uncheck ityems*/

  const checkedHandler_1 = () => {
    if (checked_1 == false) {
      setChecked_1(true);
      setUserInput(userInput + props.box_1_Letter);
      answerHandler();
    } else {
      setChecked_1(false);
      setUserInput(userInput.replace(props.box_1_Letter,""));
      answerHandler();
    }
  };
  const checkedHandler_2 = () => {
    if (checked_2 == false) {
      setChecked_2(true);
      setUserInput(userInput + props.box_2_Letter);
      answerHandler();
    } else {
      setChecked_2(false);
      setUserInput(userInput.replace(props.box_2_Letter,""));
      answerHandler();
    }
  };
  const checkedHandler_3 = () => {
    if (checked_3 == false) {
      setChecked_3(true);
      setUserInput(userInput + props.box_3_Letter);
      answerHandler();
    } else {
      setChecked_3(false);
      setUserInput(userInput.replace(props.box_4_Letter,""));
      answerHandler();
    }
  };
  
  return (
    <View>
      {/* Checkbox 1 */}
      <TouchableOpacity
        onPress={() => {
          checkedHandler_1();
        }}
      >
        <View
          style={
            (box_1_Visibility === true && styles.mainContainer) || styles.hide
          }
        >
          <View style={styles.icon}>
            <FontAwesome
              name={checked_1 == true ? "check-square" : "square-o"}
              size={24}
              color={checked_1 == true ? "#3787FF" : "#BFD3E5"}
            />
          </View>
          <Text style={styles.checkButtonText}>{props.box_1_Label}</Text>
        </View>
      </TouchableOpacity>

      {/* Checkbox 2 */}
      <TouchableOpacity
        onPress={() => {
            checkedHandler_2();
        }}
      >
        <View
          style={
            (box_2_Visibility === true && styles.mainContainer) || styles.hide
          }
        >
          <View style={styles.icon}>
            <FontAwesome
              name={checked_2 == true ? "check-square" : "square-o"}
              size={24}
              color={checked_2 == true ? "#3787FF" : "#BFD3E5"}
            />
          </View>
          <Text style={styles.checkButtonText}>{props.box_2_Label}</Text>
        </View>
      </TouchableOpacity>

      {/* Checkbox 3 */}
      <TouchableOpacity
        onPress={() => {
          checkedHandler_3();
        }}
      >
        <View
          style={
            (box_3_Visibility === true && styles.mainContainer) || styles.hide
          }
        >
          <View style={styles.icon}>
            <FontAwesome
              name={checked_3 == true ? "check-square" : "square-o"}
              size={24}
              color={checked_3 == true ? "#3787FF" : "#BFD3E5"}
            />
          </View>
          <Text style={styles.checkButtonText}>{props.box_3_Label}</Text>
        </View>
      </TouchableOpacity>

        </View>
  );
}

So what is happening here: onPress the checkedHandler-function checks the state. If “false” it will change it to “true”. If it is “true” it will change to “false”. Depending on the state, the style of the checkbox will change. The checkedHandler-function will also update the string within “userInput” depending on the state. The content of the string is catched via props from the parent component (“box_1_Letter” etc).

This is how I added the component in my screen/parent component:

       <AnswerContainer_CheckBox
              finalAnswer={"AC"}
            box_1_Visibility={true}
            box_2_Visibility={true}
            box_3_Visibility={true}
            box_4_Visibility={true}
            box_5_Visibility={false}
            box_6_Visibility={false}
            box_1_Label={"Shanghai"}
            box_1_Letter={"A"}
            box_2_Label={"Paris"}
            box_2_Letter={"B"}
            box_3_Label={"New York"}
            box_3_Letter={"C"}
            box_4_Label={"Berlin"}
            box_4_Letter={"D"}

          />

As you can see I first define how many boxes should be visible and I also add a label to each box and the associated “letter”. “finalAnswer” contains the correct answer.

Now comes my problem: let’s say in my example “Shanghai” and “New York” are the correct answers. Both boxes have to be checked while all other boxes have to be unchecked. How do I check that within the parent component/Screen?. My solution does not work. The user would have to check the boxes in the right order (and even then it somehow didn’t work). The solution would also only be available within the component, not the parent. I do not want to create a global state with redux for this.

Any help appreciated (be aware: I am pretty new to this 🙂

How can I make a flow chart interactive in a webpage?

I need to create an interactive flowchart as follows,

-> on hovering over the first box in the chart, the rest of the flowchart needs to be displayed as the gif in the link below.
https://images.app.goo.gl/q9jREMs5AtxfQ3E7A .

I’m looking for any solutions, libraries, codepen links, etc. Any leads or suggestions are welcome.

Do let me know if further clarification is required!
Thank you!

How to add a simple popup in REACT?

I am building an app using React. I am new to it. So here I want to make a popup that will pop when a button is clicked. It is basically a login/signup system. How do I add the popup? Should I install a package?

This is the code :

import React, { Component } from "react";
import "./login.css";

class Screen extends Component {
  state = {
    name: "",
    password: "",
  };
  function1 = (event) => {
    this.setState({ name: event.target.value });
  };

  function2 = (event) => {
    this.setState({ password: event.target.value });
  };
  render() {
    return (
      <div>
        <div>
          <ul>
            <li>
              <p id="logo">My website </p>
            </li>
            <li>
              <a class="active">Home</a>
            </li>
            <li>
              <a onClick={this.function1}>Page 1</a>
            </li>
            <li>
              <a>Page 2</a>
            </li>
            <li>
              <a>Page 3</a>
            </li>
            <li>
              <a id="loggedinas">Logged in as: {this.state.name}</a>
            </li>
          </ul>
        </div>
        <h1>This is the title</h1>

        <h2>Login/Sign Up</h2>
        <input type="email" onChange={this.function1} maxLength="20"></input>
        <br />
        <br />
        <input type="password" onChange={this.function2}></input>
        <h1> logged in as: {this.state.name}</h1>
      </div>
    );
  }
}

export default Screen;


Css :

button {
  background-color: aqua;
}

body {
  background-color: white;
}

/* Navbar */
ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover {
  background-color: #111;
}

#logo {
  color: white;
  padding-left: 10px;
  font-weight: bold;
}

#loggedinas {
  color: white;
  font-style: italic;
  font-weight: bold;
}

/* Navbar end */


Is there a simple way to do that?

I hope it is clear,
Thank you in advance.

Private class member with computed name [duplicate]

With modern javascript we can have private members on classes

  class someClass {
    #privateField = 'foo'
    #privateMethod() { ... }
  }

  const instance = new someClass(); // #privateField and #privateMethod are not accessible on the instance
  someClass.#privateField; // SyntaxError: Private field '#priv' must be declared in an enclosing class

For some time we’ve been able to have fields with names that are not valid identifiers (e.g. contains spaces, symbols, start with a number, etc.) by using computed values e.g.

  class someClass {
    ["member name that would otherwise be invalid"](){ ... } 
  }

Is it possible to mix the 2 and have private members with computed names?

e.g.

  class someClass {
    ["#private Member with invalid name"]() { ... } // this is not actually private
    #["private Member with invalid name"]() { ... } // this is not valid syntax
  }

I am writing code that generates other code (yes, I am aware of injection risks. Rest assured that I will handle them appropriately). I can be reasonably sure that the members I need to create will not have names that are valid as identifiers, hence I need to use the computed property name syntax. But I also want them to be private members.

There are numerous workarounds I could use including using symbols, mangling or obfuscating the names, or even private-by-convention.

I am hoping for a solution that is more elegant than any of these.

Access the request object after AbortController.abort() in axios response interceptor

I’m writing a (vue) webapp which is used primarily in a location where the wifi can get a bit iffy. I have set up a timeout using an AbortController which will abort the request after a set time. I would like the option to retry the request in the response interceptor, however the error object has no reference to the request config. Is there any way to retrieve the object to retry the request?

Request interceptor:

axios.interceptors.request.use(
    async config => {
        ...
        const controller = new AbortController();
        config.signal = controller.signal;
        const timeout = config.timeout || 10000;
        config.manualTimeoutId = setTimeout(async () => {
            controller.abort();
        }, timeout);
        return config;
    }
)

Response interceptor:

axios.interceptors.response.use(
    response => {
        clearTimeout(response.config.manualTimeoutId);
        return response;
    },
    async error => {
        if (axios.isCancel(error)) {
            //Maybe show retry dialog and retry? return axios(originalRequest)...
            //However error here is a simple "Error" object with no config
            
        }
        //In any other error, we can access the request here
        //using error.config
        ...
        clearTimeout(error.config.manualTimeoutId);
        throw error;
    }
)

Cannot use ${}while accessing a property inside an object

So I’m trying access the property named all like this

let lang = organizationLocales[0].locale; 

alertDetails.alertMessage.`${lang}`.all

But sadly, I’m getting an error near that dollar symbol saying that “identifier expected”, I just want to access the property in a dynamic way as the variable lang will be changing based on the user input. I’d appreciate any help, thanks in advance.

P.S organizationLocales is an array that has nothing to do with alertDetails object.

How do i use react native multiple select expo

So im trying to implement react-native-multiple-select in my expo. I’m getting this errror. Could it be that it doesnt work with expo??

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

Check the render method of Body.

import React, { useEffect, useState, useContext } from 'react'
import MultiSelect from 'react-native-multiple-select';
import { StyleSheet, Text, View } from 'react-native'
const items = [{
  id: '92iijs7yta',
  name: 'Ondo'
}, {
  id: 'a0s0a8ssbsd',
  name: 'Ogun'
}, {
  id: '16hbajsabsd',
  name: 'Calabar'
}, {
  id: 'nahs75a5sg',
  name: 'Lagos'
}, {
  id: '667atsas',
  name: 'Maiduguri'
}, {
  id: 'hsyasajs',
  name: 'Anambra'
}, {
  id: 'djsjudksjd',
  name: 'Benue'
}, {
  id: 'sdhyaysdj',
  name: 'Kaduna'
}, {
  id: 'suudydjsjd',
  name: 'Abuja'
}
];

const Body = ({ navigation, route }) => {

  const [selectedItems, setSelectedItems] = useState([]);
  const onSelectedItemsChange = (selectedItems) => {   setSelectedItems(selectedItems)};
<View>
        <MultiSelect
          hideTags
          items={items}
          uniqueKey="id"
          onSelectedItemsChange={onSelectedItemsChange}
          selectedItems={selectedItems}
          selectText="Pick Items"
          searchInputPlaceholderText="Search Items..."
          onChangeInput={(text) => console.log(text)}         
          tagRemoveIconColor="#CCC"
          tagBorderColor="#CCC"
          tagTextColor="#CCC"
          selectedItemTextColor="#CCC"
          selectedItemIconColor="#CCC"
          itemTextColor="#000"
          displayKey="name"
          searchInputStyle={{ color: '#CCC' }}
          submitButtonColor="#CCC"
          submitButtonText="Submit"
        />
     
      </View>

  )
}

export default Body``` 

How to place InputButtons in the Header of R shinydashboard (using may be CSS,JS)

I have the below proto-type of my shiny app with two pages and two selectInput buttons in each page.

ui <- dashboardPage(
  dashboardHeader(title = "Header"),
  dashboardSidebar( sidebarMenu(id = "tabs",
                                menuItem("Page1", tabName = "page1"),
                                menuItem("Page2", tabName = "page2"))),
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "page1",
    fluidRow(column(2,
      selectInput("count1", "Select a category", c("1", "2"))),
    column(2,selectInput("count2", "Select a subcategory1",       
                      c("cat1", "cat2", "cat3", "cat4")))),
      fluidRow(infoBoxOutput("ibox1")),
      fluidRow(valueBoxOutput("vbox1"))
    )
  ,
    tabItem(
      tabName = "page2",
      fluidRow(column(2,
        selectInput("count3", "Select a category", c("1", "2"))),
        column(2, selectInput("count4", "Select a subcategory2",       
                                   c("sub1", "sub2", "sub3", "sub4")))),
        fluidRow(infoBoxOutput("ibox2")),
        fluidRow(valueBoxOutput("vbox2")
      )
)
)
)
)


server <- function(input, output) {
  output$ibox1 <- renderInfoBox({
    infoBox(
      "Title",
      input$count1,
      icon = icon("credit-card")
    )
  })
  output$vbox1 <- renderValueBox({
    valueBox(
      "Title",
      input$count2,
      icon = icon("credit-card")
    )
  })
  output$ibox2 <- renderInfoBox({
    infoBox(
      "Title",
      input$count3,
      icon = icon("credit-card")
    )
  })
  output$vbox2 <- renderValueBox({
    valueBox(
      "Title",
      input$count4,
      icon = icon("credit-card")
    )
  })
  
}

shinyApp(ui, server)

If the app is run, we will see two selectInput buttons in the body of each page. Is it possible to move the selectInput buttons in each page to the header so that it looks like:

page 1:

enter image description here

page 2:

enter image description here

The inputButtons should be placed in the header and should show the corresponding inputs of each page. Can someone help if it could be done in shiny application making use of any custom CSS or javascript?

how to select an image, resize it, change the file format to .jpg and upload it with other json data

For my frontend I need the function where the client can select an image. This is then resized to a uniform size and should be converted to jpg format. Then the image should be sent with other json data to an api. What is the best way to do this?

I know from Python that I can resize the image with Pillow and save it in a different format. Then I would use something like base64 to send as as a value in the JSON. How do I do this in javascript or should I solve this in a completely different way?

Tasks

  • resizing
  • conveting to .jpg
  • sending together with other (json) information

More data

  • Frontend: React

How do I sync my search state with Url and connect it to next.js router?

I am following the react instant search example here – https://www.algolia.com/doc/guides/building-search-ui/going-further/routing-urls/react/

const createURL = state => `?${qs.stringify(state)}`;

const searchStateToUrl = searchState =>
  searchState ? createURL(searchState) : '';

const urlToSearchState = ({ search }) => qs.parse(search.slice(1));

An I’m having difficulty understanding how this would work in next js, because how can I connect the searchStateToUrl function to my next router, since I am not accepting any props in next js?

export function App({ location, history }) {
  const [searchState, setSearchState] = useState(urlToSearchState(location));
  const debouncedSetStateRef = useRef(null);

  function onSearchStateChange(updatedSearchState) {
    clearTimeout(debouncedSetStateRef.current);

    debouncedSetStateRef.current = setTimeout(() => {
      history.push(searchStateToUrl(location, updatedSearchState));
    }, DEBOUNCE_TIME);

    setSearchState(updatedSearchState);
  }

  useEffect(() => {
    setSearchState(urlToSearchState(location));
  }, [location]);

What is the preferred way of organizing and exporting/importing vanilla JS components?

I’m building a simple framework using only SCSS and vanilla JS for use on various small or medium projects. It comprises components mostly, housed in dedicated folders:

accordion/
  accordion.js
  accordion.scss
  index.js
  index.scss
dialog/
  dialog.js
  dialog.scss
  index.js
  index.scss
...

Component definition JavaScript files typically look like this:

accordion.js
---
import toggleCollapsible from "../../helpers/toggle-collapsible";

const SELECTOR_ACCORDION = ".accordion";
const SELECTOR_SLAT = ".accordion-slat";

function Accordion(accordion) {
  function handleSlatClick(event) {
    const targetSlat = event.target.closest(SELECTOR_SLAT);

    if (targetSlat) {
      toggleCollapsible(targetSlat);
    }
  }

  accordion.addEventListener("click", handleSlatClick);
}

export { Accordion as default, SELECTOR_ACCORDION };

Index files are used for forwarding in order to simplify imports (so I can use import Accordion from "./components/accordion/" instead of import Accordion from "./components/accordion/accordion")

All components are imported into a main file that is bundled using esbuild.

main.js
---
import Accordion, { SELECTOR_ACCORDION } from "./components/accordion";
import Dialog, { SELECTOR_DIALOG } from "./components/dialog";
...

import initializeComponent from "./helpers/initialize-component";

initializeComponent(Accordion, SELECTOR_ACCORDION);
initializeComponent(Accordion, SELECTOR_DIALOG);

Is this approach of organizing components solid and easy to scale? Should component selectors be defined alongside the corresponding components or inside the main file (I’ve seen that other projects use this approach)? Are there any drawbacks?

Google chrome extension. Paste image data and upload it to server

First of all, for better undestanding, I want to discribe what exactly functionality i need to from my extension:

  1. I open some site [stackoverflow.com || github.com || some else forum] then i need to write text with images as illustrations.
  2. I open some other window from what I need to do screenshot.
  3. I create screenshot with Snipping Tool (which place image data to clipboard after screenshoting)
  4. I`m back to previously opened site
  5. I [open context menu and choose my custom item in it || click on icon of my browser extension and click on button in it || just use ctrl+v hotkeys]
  6. My extension now must go to work and upload image data from clipboard to my own server and paste ready formatted for markdown or bbcode text with url to image.
  7. In options i will can choose what kind of formated text I need to paste.

At this moment, I have this files on my server:
index.html

<button id="pastenupload" type="button" onclick="pastenupload()">SEND FROM CLIPBOARD</button>
<script>
function pastenupload() {
    navigator.permissions.query({ name: "clipboard-read" }).then((result) => {
        if (result.state == "granted" || result.state == "prompt") {
            navigator.clipboard.read().then((data) => {
                for (let i = 0; i < data.length; i++) {
                 if (!data[i].types.includes("image/png")) {
                        alert("Clipboard contains non-image data. Unable to access it.");
                    } else {            
                        data[i].getType("image/png").then((blob) => {
                        fetch(`pastenupload.php`, {method:"POST", body:blob})
                            .then(response => console.log(response.text()))  
                        });
                    }
                }
            });
        }
    });
}
</script>

pastenupload.php

<?php
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, DELETE, PUT, PATCH, OPTIONS');
    header("Access-Control-Allow-Headers: X-Requested-With");
    // gets entire POST body
    $data = file_get_contents('php://input');
    // write the data out to the file
    $fp = fopen("/path/to/my/file/myfile.png", "wb");

    fwrite($fp, $data);
    fclose($fp);
    echo 'Good Done!';
?>

This work as expected. If image data in clipboard, after press button image stores in selected folder on my server.

Now I try to create chrome browser extension based on the “Getting Started Example” with this files:

manifest.json

{
  "name": "Paste&Upload",
  "description": "Paste copied image direct into server!",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": ["storage", "activeTab", "scripting", "clipboardRead", "tabs"],
  "host_permissions": ["<all_urls>"],
  "action": {
    "default_popup": "pu_popup.html",
    "default_icon": {
      "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
  },
  "icons": {
    "16": "/images/get_started16.png",
    "32": "/images/get_started32.png",
    "48": "/images/get_started48.png",
    "128": "/images/get_started128.png"
  }
}

pu_popup.html

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="pu_button.css">
  </head>
  <body>
    <button id="changeColor"></button>
    <script src="pu_popup.js"></script>
  </body>
</html>

pu_popup.js

let changeColor = document.getElementById("changeColor");

changeColor.addEventListener("click", async () => {
  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: pastenupload,
  });
});

function pastenupload() {
  navigator.permissions.query({ name: "clipboard-read" }).then((result) => {
    if (result.state == "granted" || result.state == "prompt") {
      navigator.clipboard.read().then((data) => {
        for (let i = 0; i < data.length; i++) {
         if (!data[i].types.includes("image/png")) {
            alert("Clipboard contains non-image data. Unable to access it.");
          } else {           
            data[i].getType("image/png").then((blob) => {
            fetch(`https://myserver/pasteupload.php`, {method:"POST", body:blob})
              .then(response => console.log(response.text()))  
            });
          }
        }
      });
    }
  });
}

I click on icon of my extension, click on changeColor button, and in dev.tools I see

forms.html:1 Uncaught (in promise) DOMException: Document is not focused.

What I need to change to Document became is focused?
Or do I need to look for another approach to solving my problem?

As for the my 6th point, I think I won’t have any problems with it, I indicated it simply for a more accessible understanding of the functionality of the extension that I want to make.

In general, the only thing that interests me is how to properly organize the transfer of image data to my server?

Thanks!