-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.tsx
113 lines (92 loc) · 2.88 KB
/
popup.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { Button, Checkbox, Group, Stack, Text } from "@mantine/core"
import { useEffect, useState } from "react"
import { ThemeProvider } from "~theme"
import "@mantine/core/styles.css"
enum Settings {
IncludeSubdomains = "includeSubdomains",
FromAllWindows = "fromAllWindows"
}
function IndexPopup() {
const [settings, setSettings] = useState<string[]>([])
const [tabGroups, setTabGroups] = useState({})
function getTabs(): Promise<chrome.tabs.Tab[]> {
const queryInfo = settings.includes(Settings.FromAllWindows)
? {}
: { currentWindow: true }
return chrome.tabs.query(queryInfo)
}
function getTabGroups(tabs: chrome.tabs.Tab[]) {
const domains = {}
const includeSubdomains = settings.includes(Settings.IncludeSubdomains)
for (const tab of tabs) {
if (
tab.url.startsWith("chrome:") ||
tab.url.startsWith("chrome-extension://")
)
continue
const url = new URL(tab.url)
const hostname = includeSubdomains
? url.hostname
: url.hostname.split(".").slice(-2).join(".")
if (!domains[hostname]) domains[hostname] = []
domains[hostname].push(tab.id)
}
return domains
}
function groupTabs(domain: string) {
const tabsToGroup = tabGroups[domain]
chrome.tabs.group({ tabIds: tabsToGroup }).then((tabGroupId) => {
chrome.tabGroups.update(tabGroupId, { title: domain }).then(() => {
if (chrome.runtime.lastError) {
console.error(chrome.runtime.lastError)
}
})
})
}
useEffect(() => {
getTabs().then((tabs) => setTabGroups(getTabGroups(tabs)))
}, [settings])
function ButtonList(props) {
const { items } = props
const sortedItems = items.sort((a, b) => {
const aCount = tabGroups[a] ? tabGroups[a].length : 0
const bCount = tabGroups[b] ? tabGroups[b].length : 0
return bCount - aCount
})
const listItems = sortedItems.map((item, i) => (
<Button
key={i}
variant="default"
onClick={(event) => {
event.preventDefault()
groupTabs(item)
}}>
{item}
</Button>
))
return <Button.Group orientation="vertical">{listItems}</Button.Group>
}
return (
<ThemeProvider withNormalizeCSS withGlobalStyles>
<Stack miw={240} p="lg">
<Text fw="bold" size="xl">
Tab organizer ✨
</Text>
<Checkbox.Group label="Options" value={settings} onChange={setSettings}>
<Group mt="xs">
<Checkbox
value={Settings.IncludeSubdomains}
label="Include subdomains"
/>
<Checkbox
value={Settings.FromAllWindows}
label="From all windows"
/>
</Group>
</Checkbox.Group>
<ButtonList items={Object.keys(tabGroups)} />
</Stack>
</ThemeProvider>
)
}
export default IndexPopup