select which country to load

This commit is contained in:
Greg 2025-06-11 00:24:03 +03:00
parent cbdb829c67
commit 982800821b
9 changed files with 306 additions and 165 deletions

View file

@ -1,8 +1,20 @@
import { COUNTRIES } from "./countries";
const CACHE_PREFIX = "KOBOPRICE";
const initCountries = () =>
COUNTRIES.reduce(
(acc, { countryCode }) => ({ ...acc, [countryCode]: true }),
{},
);
export const initCache = () => {
if (!localStorage.getItem(CACHE_PREFIX)) {
setState({ books: {}, rates: null });
setState({
books: {},
rates: null,
countries: initCountries(),
});
}
};
export const getState = () => JSON.parse(localStorage.getItem(CACHE_PREFIX));
@ -16,3 +28,10 @@ export const cacheBookPrice = (price, url) => {
state.books[url] = price;
setState(state);
};
export const getSelectedCountries = () =>
getState().countries || initCountries();
export const cacheSelectedCountries = (countries) => {
const state = getState();
state.countries = countries;
setState(state);
};

View file

@ -17,7 +17,6 @@ const observePriceOnPage = (page) =>
});
observer.observe(page, {
attributes: true,
childList: true,
characterData: true,
subtree: true,
@ -40,7 +39,7 @@ export const extractPrice = async (url) => {
l("starting observing price on", url);
const price = await observePriceOnPage(iframe.contentDocument.body, url);
const price = await observePriceOnPage(iframe.contentDocument.body);
document.body.removeChild(iframe);

View file

@ -1,8 +1,10 @@
import { useSelectedCountries } from "./useCountries";
import "./logger";
import { initCache } from "./cache";
import { createElement, h, render } from "preact";
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { bookUrl } from "./bookUrl";
import { initCache } from "./cache";
import { usePrices } from "./usePrices";
import { useCallback, useState } from "preact/hooks";
/*
TODO:
@ -32,19 +34,22 @@ const createPricesContainer = () => {
const isInLibrary = () => document.querySelectorAll(".read-now").length;
const formatPrice = (countryPrice, convertedPrice) => {
const formatPrice = (countryPrice, convertedPrice, isSelected) => {
if (!isSelected) return "SKIP";
if (countryPrice == undefined) {
return `LOADING`;
return "NOT LOADED";
}
if (convertedPrice) {
return `${countryPrice} => ${convertedPrice?.formatted}`;
}
return `NOT FOUND`;
return "NOT FOUND";
};
const Price = ({ props }) => {
const { convertedPrice, countryCode, countryPrice, url } = props;
const Price = ({ price, toggleCountry, isSelected }) => {
const { convertedPrice, countryCode, countryPrice } = price;
const [isHovered, setHover] = useState(false);
const hover = useCallback(() => setHover(true));
@ -54,27 +59,38 @@ const Price = ({ props }) => {
display: "flex",
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
backgroundColor: isHovered ? "#d7d7d7" : "",
padding: "10px 10px 0 10px",
padding: "0 10px",
};
return h(
const link = h(
"a",
{
style,
href: url,
style: { textDecoration: "underline" },
href: bookUrl(countryCode),
target: "_blank",
onMouseEnter: hover,
onMouseLeave: leave,
},
[
h("p", null, countryCode.toUpperCase()),
h(
countryCode.toUpperCase(),
);
const checkbox = h("input", {
type: "checkbox",
checked: isSelected,
onChange: () => toggleCountry(),
});
const priceLabel = h(
"p",
{ style: { fontWeight: "bold" } },
formatPrice(countryPrice, convertedPrice),
),
],
formatPrice(countryPrice, convertedPrice, isSelected),
);
return h(
"label",
{ style, onMouseEnter: hover, onMouseLeave: leave },
h("div", { style: { display: "flex" } }, checkbox, link),
priceLabel,
);
};
@ -93,16 +109,74 @@ const InLibrary = () =>
);
const Percent = (percent) => {
const spinner = useRef();
useEffect(() => {
spinner.current.animate(
[{ transform: "rotate(0deg)" }, { transform: "rotate(360deg)" }],
{ iterations: Infinity, duration: 1000 },
);
}, []);
const style = { padding: "10px 10px 0 10px", textAlign: "center" };
if (percent == 100) return h("h2", { style }, "all prices are loaded!");
return h("h2", { style }, `${percent}%`);
return h(
"h2",
{ style },
`${percent}%`,
h("span", {
ref: spinner,
style: {
width: "16px",
height: "16px",
borderRadius: "50%",
display: "inline-block",
borderTop: "3px solid black",
borderRight: "3px solid transparent",
boxSizing: "border-box",
marginLeft: "15px",
},
}),
);
};
const Header = (state, percentChecked) => {
if (state === "loading") return Percent(percentChecked);
if (state === "done")
return h(
"h2",
{ style: { textAlign: "center" } },
"All prices are loaded!",
);
return h(
"h2",
{ style: { textAlign: "center" } },
'Select countries or leave as is and press "load"',
);
};
const Load = (state, load) => {
return h(
"button",
{
disabled: state === "loading",
onClick: load,
type: "button",
style: { backgroundColor: "#91ff91" },
},
state === "loading" ? "Loading..." : "Load prices",
);
};
const App = () => {
const [prices, percentChecked] = usePrices();
const { isSelected, toggleCountry, selected } = useSelectedCountries();
const { prices, percentChecked, state, load } = usePrices(selected);
l(selected);
const style = {
display: "flex",
flexDirection: "column",
@ -113,10 +187,20 @@ const App = () => {
return InLibrary();
}
return h("div", { style }, [
Percent(percentChecked),
...prices.map((price) => h(Price, { props: price })),
]);
return h(
"div",
{ style },
Header(state, percentChecked),
...prices.map((price) =>
h(Price, {
price,
toggleCountry: () => toggleCountry(price.countryCode),
isSelected: isSelected(price.countryCode),
isLoading: state,
}),
),
Load(state, load),
);
};
l("starting...");

22
lib/useCountries.js Normal file
View file

@ -0,0 +1,22 @@
import "./logger";
import { useCallback, useEffect, useState } from "preact/hooks";
import { cacheSelectedCountries, getSelectedCountries } from "./cache";
export const useSelectedCountries = () => {
const [selected, setSelected] = useState(() => getSelectedCountries());
useEffect(() => cacheSelectedCountries(selected), [selected]);
const toggleCountry = useCallback((countryCode) =>
setSelected({ ...selected, [countryCode]: !selected[countryCode] }),
);
const isSelected = useCallback((countryCode) => !!selected[countryCode]);
return {
selected,
toggleCountry,
isSelected,
};
};

View file

@ -1,19 +1,27 @@
import { useEffect, useState } from "preact/hooks";
import { COUNTRIES } from "./countries";
import { useCallback, useState } from "preact/hooks";
import { bookPriceFor } from "./bookPriceFor";
import { COUNTRIES } from "./countries";
const sortPrices = (prices) =>
prices.sort(
(a, b) =>
const sortPrices = (prices, selectedCountries) =>
prices.sort((a, b) => {
if (!selectedCountries[a.countryCode]) return 1;
if (!selectedCountries[b.countryCode]) return -1;
return (
(a?.convertedPrice?.intValue || Infinity) -
(b?.convertedPrice?.intValue || Infinity),
(b?.convertedPrice?.intValue || Infinity)
);
});
export const usePrices = () => {
export const usePrices = (selectedCountries) => {
const [prices, setPrices] = useState(COUNTRIES);
useEffect(() => {
const fetchAll = async () => {
const [state, setState] = useState("init");
const load = useCallback(async () => {
setState("loading");
for (let index = 0; index < prices.length; index += 2) {
if (!selectedCountries[prices[index].countryCode]) continue;
// intentionally blocking execution
// to resolve sequentially.
// It should prevent DOS and triggering captcha
@ -28,17 +36,26 @@ export const usePrices = () => {
prices[index] = await bookPriceFor(prices[index]);
}
sortPrices(prices);
setPrices([...prices]);
}
setState("done");
l("DONE");
}, [selectedCountries]);
const selectedCount = Object.entries(selectedCountries)
.map(([_, selected]) => selected)
.filter(Boolean).length;
const alreadyLoaded = prices.filter(
(p) => p.countryPrice != undefined && selectedCountries[p.countryCode],
).length;
const percentChecked = (alreadyLoaded / selectedCount) * 100;
return {
prices: sortPrices(prices, selectedCountries),
percentChecked: percentChecked.toFixed(2),
load,
state,
};
fetchAll();
}, []);
const percentChecked =
(prices.filter((p) => p.countryPrice != undefined).length / prices.length) *
100;
return [prices, percentChecked.toFixed(0)];
};

View file

@ -1,7 +1,7 @@
{
"name": "Kobo Price",
"description": "Find lowest book price on kobo.com",
"version": "1.2.3",
"version": "1.3.0",
"manifest_version": 3,
"content_scripts": [
{

View file

@ -13,7 +13,7 @@
"watch": "concurrently npm:watch-bundle npm:watch-ext",
"build-userscript": "cat userscript/koboprice.meta.js dist/index.js > userscript/koboprice.user.js",
"build-ext": "web-ext build",
"build-all": "npm run bundle && npm run build-userscript && npm run build-ext"
"build-all": "npm run bundle && npm run build-userscript && rm -rf web-ext-artifacts && npm run build-ext"
},
"author": "",
"license": "ISC",

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long