forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselection.ts
More file actions
65 lines (51 loc) · 1.59 KB
/
selection.ts
File metadata and controls
65 lines (51 loc) · 1.59 KB
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
import * as Clipboard from "./clipboard"
type Toast = {
show: (input: { message: string; variant: "info" | "success" | "warning" | "error" }) => void
error: (err: unknown) => void
}
type FocusableSelectionTarget = {
hasSelection: () => boolean
}
type Renderer = {
getSelection: () => { getSelectedText: () => string; selectedRenderables: FocusableSelectionTarget[] } | null
clearSelection: () => void
currentFocusedRenderable?: FocusableSelectionTarget | null
}
type SelectionKeyEvent = {
ctrl?: boolean
name: string
preventDefault: () => void
stopPropagation: () => void
}
export function copy(renderer: Renderer, toast: Toast): boolean {
const text = renderer.getSelection()?.getSelectedText()
if (!text) return false
Clipboard.copy(text)
.then(() => toast.show({ message: "Copied to clipboard", variant: "info" }))
.catch(toast.error)
renderer.clearSelection()
return true
}
export function handleSelectionKey(renderer: Renderer, toast: Toast, event: SelectionKeyEvent) {
const selection = renderer.getSelection()
if (!selection) return
if (event.ctrl && event.name === "c") {
if (!copy(renderer, toast)) {
renderer.clearSelection()
return
}
event.preventDefault()
event.stopPropagation()
return
}
if (event.name === "escape") {
renderer.clearSelection()
event.preventDefault()
event.stopPropagation()
return
}
const focus = renderer.currentFocusedRenderable
if (focus?.hasSelection() && selection.selectedRenderables.includes(focus)) return
renderer.clearSelection()
}
export * as Selection from "./selection"