diff --git a/main.js b/main.js index c27de25..19af9a9 100644 --- a/main.js +++ b/main.js @@ -1,5 +1,32 @@ "use strict"; +function dataItemFromBI(bi) { + var link_in_title = bi.querySelector('.basket-item__title a'); + var abs_url = link_in_title.href; + var wine_desc = link_in_title.text; + var stock_status_span = bi.querySelector('.badge-label'); + try { + var quantity_value_sel = bi.querySelector('.basket-item__quantity-select select'); + var quantity_value = quantity_value_sel.value; + var quantity_unit_sel = bi.querySelector('.basket-item__type select'); + var quantity_unit = quantity_unit_sel.value; + } catch (err) { + var quantity_value = '?'; + var quantity_unit = '?'; + } + var item = { + wine: wine_desc, + url: abs_url, + stock: stock_status_span.innerText, + qty_val: quantity_value, + qty_unit: quantity_unit + }; + return item; +} + +function formatItemAsStr(item) { + return `| ${item.wine} | ${item.url} | ${item.stock} | ${item.qty_val} | ${item.qty_unit} |`; +} function makeCopyButtons() { // shopping basket items are in li tags with class "basket-item" @@ -20,9 +47,13 @@ function makeCopyButtons() { var all_butt = document.createElement('BUTTON'); all_butt.className = copy_all_button_class; all_butt.onclick = () => { - - let copyStr = '| wine | url | stock | qty_val | qty_unit |' - + '| --- | --- | --- | --- | --- |'; + let copyStr = '| wine | url | stock | qty_val | qty_unit |\n' + + '| --- | --- | --- | --- | --- |\n'; + var basket_items = document.querySelectorAll('li.basket-item'); + for (let bi of basket_items) { + var item = dataItemFromBI(bi); + copyStr += formatItemAsStr(item) + '\n'; + } navigator.clipboard.writeText(copyStr); } all_butt.innerHTML = 'Copy all items'; @@ -41,26 +72,7 @@ function makeCopyButtons() { num_created++; console.log('hello bi ' + bi); - var link_in_title = bi.querySelector('.basket-item__title a'); - var abs_url = link_in_title.href; - var wine_desc = link_in_title.text; - var stock_status_span = bi.querySelector('.badge-label'); - try { - var quantity_value_sel = bi.querySelector('.basket-item__quantity-select select'); - var quantity_value = quantity_value_sel.value; - var quantity_unit_sel = bi.querySelector('.basket-item__type select'); - var quantity_unit = quantity_unit_sel.value; - } catch (err) { - var quantity_value = '?'; - var quantity_unit = '?'; - } - var item = { - wine: wine_desc, - url: abs_url, - stock: stock_status_span.text, - qty_val: quantity_value, - qty_unit: quantity_unit - }; + var item = dataItemFromBI(bi); var butt = document.createElement('BUTTON'); butt.className = copy_button_class; // I'm not sure why this mess is needed, but I was previously getting @@ -71,7 +83,7 @@ function makeCopyButtons() { } return onclickinner; } - let copyString = `| ${item.wine} | ${item.url} | ${item.stock} | ${item.qty_val} | ${item.qty_unit} |`; + let copyString = formatItemAsStr(item); butt.onclick = onclickgen(copyString); butt.innerHTML = 'Copy'; bi.prepend(butt);