popup.js (2611B)
1 const popup = document.querySelector('#popup'); 2 3 const $store = Alpine.$data(popup); 4 5 function pp_get_current_data() { 6 return new Promise((resolve) => { 7 browser.tabs.query({ active: true }, (tabs) => { 8 const tab = tabs[0]; 9 browser.tabs.executeScript(tab.id, { file: 'content.js' }, () => { 10 browser.tabs.sendMessage(tab.id, { action: 'getPageData' }, resolve); 11 }); 12 }); 13 }) 14 } 15 16 async function pp_get_list() { 17 const ret = await fetch('https://soophie.de/api/pinpot/list'); 18 return await ret.json(); 19 } 20 21 async function pp_do_create(item) { 22 await fetch('https://soophie.de/api/pinpot/create', { 23 method: 'POST', 24 body: JSON.stringify(item), 25 }); 26 $store.list = await pp_get_list(); 27 $store.data = $store.list[0]; 28 pp_do_open($store.data); 29 } 30 31 async function pp_do_update(id, is_pinned) { 32 await fetch('https://soophie.de/api/pinpot/update', { 33 method: 'POST', 34 body: JSON.stringify({ id, is_pinned }), 35 }); 36 $store.list = await pp_get_list(); 37 for (const item of $store.list) { 38 if (item.id === id) { 39 pp_do_open(item); 40 break; 41 } 42 } 43 } 44 45 async function pp_do_delete(id) { 46 await fetch('https://soophie.de/api/pinpot/delete', { 47 method: 'POST', 48 body: JSON.stringify({ id }), 49 }); 50 $store.list = await pp_get_list(); 51 await pp_do_view_data(); 52 pp_sort_list(); 53 } 54 55 function pp_do_open(item) { 56 if ($store.current?.image !== item?.image) { 57 const image = popup.querySelector('.preview-image'); 58 if (image) { 59 image.classList.remove('visible'); 60 } 61 } 62 $store.current = item; 63 } 64 65 async function pp_do_close() { 66 await pp_do_view_data(); 67 pp_sort_list(); 68 } 69 70 function pp_load_image(event) { 71 const { target } = event; 72 const image = target.parentNode.parentNode; 73 if (target.naturalWidth < target.offsetWidth) { 74 image.classList.add('centered'); 75 } 76 else { 77 image.classList.remove('centered'); 78 } 79 image.classList.add('visible'); 80 } 81 82 async function pp_do_view_data() { 83 $store.data = await pp_get_current_data(); 84 for (const item of $store.list) { 85 if ($store.data?.url === item.url) { 86 $store.data.id = item.id; 87 break; 88 } 89 } 90 if (!$store.data?.id) { 91 pp_do_open($store.data); 92 } 93 else { 94 pp_do_open(null); 95 } 96 } 97 98 function pp_sort_list() { 99 if ($store.list) { 100 const idx = $store.list.findIndex((item) => $store.data?.id === item.id); 101 if (idx !== -1) { 102 $store.list = [$store.list[idx], ...$store.list.filter((item) => $store.data?.id !== item.id)]; 103 } 104 } 105 } 106 107 (async () => { 108 $store.list = await pp_get_list(); 109 await pp_do_view_data(); 110 pp_sort_list(); 111 })();