import React, { useState } from "react"; import PropTypes from "prop-types"; import { useDispatch } from "react-redux"; import { prettySize } from "../../utils"; import { addTorrent } from "../../actions/torrents"; import Dropdown from "react-bootstrap/Dropdown"; const buildMenuItems = (torrents) => { if (!torrents || torrents.length === 0) { return []; } // Build the array of entries let entries = []; let dividerCount = torrents.size - 1; torrents.forEach((torrentsBySource, source) => { // Push the title entries.push({ type: "header", value: source, }); torrentsBySource.forEach((torrent) => { entries.push({ type: "entry", quality: torrent.quality, size: torrent.result.size, torrent: torrent, }); }); // Push the divider if (dividerCount > 0) { dividerCount--; entries.push({ type: "divider" }); } }); return entries; }; const countEntries = (torrents) => { if (!torrents || torrents.length === 0) { return 0; } let count = 0; torrents.forEach((source) => { count = count + source.size; }); return count; }; export const TorrentsButton = ({ torrents, search, searching, url }) => { const dispatch = useDispatch(); const [show, setShow] = useState(false); const entries = buildMenuItems(torrents); const count = countEntries(torrents); const onSelect = (eventKey) => { // Close the dropdown if the eventkey is not specified if (eventKey === null) { setShow(false); } }; const onToggle = (isOpen, event, metadata) => { // Don't close on select if (metadata && metadata.source !== "select") { setShow(isOpen); } }; return ( Torrents {count} Automatic search Manual search {entries.length > 0 && } {entries.map((e, index) => { switch (e.type) { case "header": return ( {e.value} ); case "divider": return ; case "entry": return ( { event.preventDefault(); dispatch(addTorrent(e.torrent)); }} > {e.quality} {e.size !== 0 && ( ({prettySize(e.size)}) )} ); } })} ); }; TorrentsButton.propTypes = { torrents: PropTypes.object, searching: PropTypes.bool, search: PropTypes.func.isRequired, url: PropTypes.string, };