clipboard.go RawHistoryFolder
1package handlers
2
3import (
4 "context"
5 "encoding/json"
6
7 "github.com/bnema/dumber/internal/application/port"
8 "github.com/bnema/dumber/internal/infrastructure/config"
9 "github.com/bnema/dumber/internal/infrastructure/webkit"
10 "github.com/bnema/dumber/internal/logging"
11)
12
13// ClipboardHandler handles clipboard-related messages from webviews.
14type ClipboardHandler struct {
15 clipboard port.Clipboard
16 configGetter func() *config.Config
17 onCopied func(textLen int) // Called after successful auto-copy (for toast notification)
18}
19
20// NewClipboardHandler creates a new ClipboardHandler.
21func NewClipboardHandler(clipboard port.Clipboard, configGetter func() *config.Config, onCopied func(textLen int)) *ClipboardHandler {
22 return &ClipboardHandler{
23 clipboard: clipboard,
24 configGetter: configGetter,
25 onCopied: onCopied,
26 }
27}
28
29// autoCopyRequest represents the payload for auto-copy selection messages.
30type autoCopyRequest struct {
31 Text string `json:"text"`
32}
33
34// HandleAutoCopySelection handles the auto_copy_selection message from JS.
35// It copies the selected text to the clipboard if the feature is enabled.
36func (h *ClipboardHandler) HandleAutoCopySelection() webkit.MessageHandler {
37 return webkit.MessageHandlerFunc(func(ctx context.Context, _ webkit.WebViewID, payload json.RawMessage) (any, error) {
38 log := logging.FromContext(ctx)
39
40 // Check if feature is enabled
41 cfg := h.configGetter()
42 if cfg == nil || !cfg.Clipboard.AutoCopyOnSelection {
43 return nil, nil
44 }
45
46 var req autoCopyRequest
47 if err := json.Unmarshal(payload, &req); err != nil {
48 log.Debug().Err(err).Msg("failed to unmarshal auto-copy payload")
49 return nil, nil // Silently ignore malformed requests
50 }
51
52 // Skip empty or very short selections (< 2 chars)
53 if len(req.Text) < 2 {
54 return nil, nil
55 }
56
57 if err := h.clipboard.WriteText(ctx, req.Text); err != nil {
58 log.Debug().Err(err).Msg("failed to write selection to clipboard")
59 return nil, nil // Don't propagate error to JS
60 }
61
62 log.Debug().Int("length", len(req.Text)).Msg("auto-copied selection to clipboard")
63
64 // Notify UI for toast feedback (if callback is set)
65 if h.onCopied != nil {
66 h.onCopied(len(req.Text))
67 }
68
69 return nil, nil
70 })
71}
72
73// RegisterClipboardHandlers registers clipboard handlers with the router.
74func RegisterClipboardHandlers(
75 ctx context.Context,
76 router *webkit.MessageRouter,
77 clipboard port.Clipboard,
78 configGetter func() *config.Config,
79 onCopied func(textLen int),
80) error {
81 handler := NewClipboardHandler(clipboard, configGetter, onCopied)
82
83 // Register auto_copy_selection handler
84 if err := router.RegisterHandler("auto_copy_selection", handler.HandleAutoCopySelection()); err != nil {
85 return err
86 }
87
88 log := logging.FromContext(ctx)
89 log.Info().Msg("registered clipboard handlers")
90
91 return nil
92}