aboutsummaryrefslogtreecommitdiff
path: root/internal/theme/theme.go
blob: 1fc6600c6c06ba19262049467816fa1ca08edccc (plain) (blame)
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
package theme

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"
)

// OpenCodeTheme represents an OpenCode-compatible theme JSON structure
type OpenCodeTheme struct {
	Schema string                     `json:"$schema"`
	Defs   map[string]string          `json:"defs"`
	Theme  map[string]json.RawMessage `json:"theme"` // Can be string or object
}

// OpenCodeThemeMode represents dark/light mode values for a theme property
type OpenCodeThemeMode struct {
	Dark  string `json:"dark"`
	Light string `json:"light"`
}

// ResolvedTheme contains the resolved color values for both modes
type ResolvedTheme struct {
	Dark  map[string]string
	Light map[string]string
}

// LoadTheme fetches and parses an OpenCode theme from a URL
func LoadTheme(themeURL string) (*ResolvedTheme, error) {
	if themeURL == "" {
		return nil, nil // No theme specified, use default
	}

	// Fetch the theme JSON
	client := &http.Client{
		Timeout: 10 * time.Second,
	}

	resp, err := client.Get(themeURL)
	if err != nil {
		return nil, fmt.Errorf("failed to fetch theme from %s: %w", themeURL, err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("failed to fetch theme: HTTP %d", resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read theme response: %w", err)
	}

	// Parse the theme JSON
	var ocTheme OpenCodeTheme
	if err := json.Unmarshal(body, &ocTheme); err != nil {
		return nil, fmt.Errorf("failed to parse theme JSON: %w", err)
	}

	// Resolve color references
	resolved := &ResolvedTheme{
		Dark:  make(map[string]string),
		Light: make(map[string]string),
	}

	for key, rawValue := range ocTheme.Theme {
		// Try to parse as object first (light/dark mode)
		var mode OpenCodeThemeMode
		if err := json.Unmarshal(rawValue, &mode); err == nil && (mode.Dark != "" || mode.Light != "") {
			// It's an object with dark/light properties
			darkColor := resolveColor(mode.Dark, ocTheme.Defs)
			resolved.Dark[key] = darkColor

			lightColor := resolveColor(mode.Light, ocTheme.Defs)
			resolved.Light[key] = lightColor
		} else {
			// It's a simple string (dark-only theme)
			var colorRef string
			if err := json.Unmarshal(rawValue, &colorRef); err != nil {
				continue // Skip invalid values
			}

			// Use the same color for both light and dark
			color := resolveColor(colorRef, ocTheme.Defs)
			resolved.Dark[key] = color
			resolved.Light[key] = color
		}
	}

	return resolved, nil
}

// resolveColor resolves a color value, handling references to defs
func resolveColor(value string, defs map[string]string) string {
	// If it starts with #, it's already a color
	if strings.HasPrefix(value, "#") {
		return value
	}

	// Otherwise, look it up in defs
	if color, ok := defs[value]; ok {
		return color
	}

	// Fallback to the value itself
	return value
}

// GenerateCSS generates CSS custom properties from a resolved theme
func (t *ResolvedTheme) GenerateCSS() string {
	if t == nil {
		return ""
	}

	var css strings.Builder

	// Generate CSS variables for dark mode (default)
	css.WriteString(":root {\n")
	for key, color := range t.Dark {
		cssVar := toCSSVariableName(key)
		css.WriteString(fmt.Sprintf("  %s: %s;\n", cssVar, color))
	}
	css.WriteString("}\n\n")

	// Generate CSS variables for light mode
	css.WriteString("@media (prefers-color-scheme: light) {\n  :root {\n")
	for key, color := range t.Light {
		cssVar := toCSSVariableName(key)
		css.WriteString(fmt.Sprintf("    %s: %s;\n", cssVar, color))
	}
	css.WriteString("  }\n}\n")

	return css.String()
}

// toCSSVariableName converts a theme key to a CSS variable name
// e.g., "background" -> "--theme-background"
func toCSSVariableName(key string) string {
	// Convert camelCase to kebab-case
	var result strings.Builder
	result.WriteString("--theme-")

	for i, c := range key {
		if i > 0 && c >= 'A' && c <= 'Z' {
			result.WriteRune('-')
			result.WriteRune(c + 32) // Convert to lowercase
		} else {
			result.WriteRune(c)
		}
	}

	return result.String()
}

// GetColorMapping returns a mapping of semantic names to CSS variable names
func GetColorMapping() map[string]string {
	return map[string]string{
		// Status colors
		"status-up":       "var(--theme-success)",
		"status-degraded": "var(--theme-warning)",
		"status-down":     "var(--theme-error)",

		// Text colors
		"text-primary":   "var(--theme-text)",
		"text-secondary": "var(--theme-text-muted)",

		// Background colors
		"bg-primary":   "var(--theme-background)",
		"bg-secondary": "var(--theme-background-panel)",
		"bg-tertiary":  "var(--theme-background-element)",

		// Border colors
		"border-primary": "var(--theme-border)",
		"border-subtle":  "var(--theme-border-subtle)",
		"border-active":  "var(--theme-border-active)",

		// Accent colors
		"accent-primary":   "var(--theme-primary)",
		"accent-secondary": "var(--theme-secondary)",
	}
}

// GenerateVariableOverrides generates CSS that maps OpenCode theme to Kaze's CSS variables
// This is the proper approach - override the root CSS variables that style.css uses
// Uses !important to ensure theme overrides take precedence over external CSS
func (t *ResolvedTheme) GenerateVariableOverrides() string {
	if t == nil {
		return ""
	}

	return `
/* OpenCode Theme - Override Kaze CSS Variables */
/* Uses !important to prevent flash when external CSS loads */

/* Dark mode (default) - uses theme's dark colors */
:root {
	/* Background colors */
	--bg-primary: var(--theme-background) !important;
	--bg-secondary: var(--theme-background-panel) !important;
	--bg-tertiary: var(--theme-background-element) !important;
	
	/* Border color */
	--border-color: var(--theme-border) !important;
	
	/* Text colors */
	--text-primary: var(--theme-text) !important;
	--text-secondary: var(--theme-text-muted) !important;
	--text-tertiary: var(--theme-text-muted) !important;
	--text-dim: var(--theme-border) !important;
	
	/* Status colors */
	--status-ok: var(--theme-success) !important;
	--status-warn: var(--theme-warning) !important;
	--status-error: var(--theme-error) !important;
	--status-unknown: var(--theme-text-muted) !important;
}

/* Light mode - uses theme's light colors */
@media (prefers-color-scheme: light) {
	:root {
		/* Background colors */
		--bg-primary: var(--theme-background) !important;
		--bg-secondary: var(--theme-background-panel) !important;
		--bg-tertiary: var(--theme-background-element) !important;
		
		/* Border color */
		--border-color: var(--theme-border) !important;
		
		/* Text colors */
		--text-primary: var(--theme-text) !important;
		--text-secondary: var(--theme-text-muted) !important;
		--text-tertiary: var(--theme-text-muted) !important;
		--text-dim: var(--theme-border) !important;
		
		/* Status colors */
		--status-ok: var(--theme-success) !important;
		--status-warn: var(--theme-warning) !important;
		--status-error: var(--theme-error) !important;
		--status-unknown: var(--theme-text-muted) !important;
	}
}
`
}