add(web): basic layout and ui

This commit is contained in:
maotovisk 2025-08-07 11:15:56 -03:00
parent fd14d22fed
commit 80df48284c
17 changed files with 9288 additions and 4 deletions

View file

@ -0,0 +1,147 @@
// templui component button - version: v0.85.0 installed by templui v0.85.0
package button
import (
"maot-shortner/web/resources/utils"
"strings"
)
type Variant string
type Size string
type Type string
const (
VariantDefault Variant = "default"
VariantDestructive Variant = "destructive"
VariantOutline Variant = "outline"
VariantSecondary Variant = "secondary"
VariantGhost Variant = "ghost"
VariantLink Variant = "link"
)
const (
TypeButton Type = "button"
TypeReset Type = "reset"
TypeSubmit Type = "submit"
)
const (
SizeDefault Size = "default"
SizeSm Size = "sm"
SizeLg Size = "lg"
SizeIcon Size = "icon"
)
type Props struct {
ID string
Class string
Attributes templ.Attributes
Variant Variant
Size Size
FullWidth bool
Href string
Target string
Disabled bool
Type Type
}
templ Button(props ...Props) {
{{ var p Props }}
if len(props) > 0 {
{{ p = props[0] }}
}
if p.Type == "" {
{{ p.Type = TypeButton }}
}
if p.Href != "" && !p.Disabled {
<a
if p.ID != "" {
id={ p.ID }
}
href={ templ.SafeURL(p.Href) }
if p.Target != "" {
target={ p.Target }
}
class={
utils.TwMerge(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all",
"disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0",
"outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
"cursor-pointer",
p.variantClasses(),
p.sizeClasses(),
p.modifierClasses(),
p.Class,
),
}
{ p.Attributes... }
>
{ children... }
</a>
} else {
<button
if p.ID != "" {
id={ p.ID }
}
class={
utils.TwMerge(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all",
"disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0",
"outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
"cursor-pointer",
p.variantClasses(),
p.sizeClasses(),
p.modifierClasses(),
p.Class,
),
}
if p.Type != "" {
type={ string(p.Type) }
}
disabled?={ p.Disabled }
{ p.Attributes... }
>
{ children... }
</button>
}
}
func (b Props) variantClasses() string {
switch b.Variant {
case VariantDestructive:
return "bg-destructive text-destructive-foreground shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60"
case VariantOutline:
return "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50"
case VariantSecondary:
return "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80"
case VariantGhost:
return "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50"
case VariantLink:
return "text-primary underline-offset-4 hover:underline"
default:
return "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90"
}
}
func (b Props) sizeClasses() string {
switch b.Size {
case SizeSm:
return "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5"
case SizeLg:
return "h-10 rounded-md px-6 has-[>svg]:px-4"
case SizeIcon:
return "size-9"
default: // SizeDefault
return "h-9 px-4 py-2 has-[>svg]:px-3"
}
}
func (b Props) modifierClasses() string {
classes := []string{}
if b.FullWidth {
classes = append(classes, "w-full")
}
return strings.Join(classes, " ")
}

View file

@ -0,0 +1,117 @@
// templui component icon - version: v0.85.0 installed by templui v0.85.0
package icon
import (
"context"
"fmt"
"io"
"sync"
"github.com/a-h/templ"
)
// iconContents caches the fully generated SVG strings for icons that have been used,
// keyed by a composite key of name and props to handle different stylings.
var (
iconContents = make(map[string]string)
iconMutex sync.RWMutex
)
// Props defines the properties that can be set for an icon.
type Props struct {
Size int
Color string
Fill string
Stroke string
StrokeWidth string // Stroke Width of Icon, Usage: "2.5"
Class string
}
// Icon returns a function that generates a templ.Component for the specified icon name.
func Icon(name string) func(...Props) templ.Component {
return func(props ...Props) templ.Component {
var p Props
if len(props) > 0 {
p = props[0]
}
// Create a unique key for the cache based on icon name and all relevant props.
// This ensures different stylings of the same icon are cached separately.
cacheKey := fmt.Sprintf("%s|s:%d|c:%s|f:%s|sk:%s|sw:%s|cl:%s",
name, p.Size, p.Color, p.Fill, p.Stroke, p.StrokeWidth, p.Class)
return templ.ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
iconMutex.RLock()
svg, cached := iconContents[cacheKey]
iconMutex.RUnlock()
if cached {
_, err = w.Write([]byte(svg))
return err
}
// Not cached, generate it
// The actual generation now happens once and is cached.
generatedSvg, err := generateSVG(name, p) // p (Props) is passed to generateSVG
if err != nil {
// Provide more context in the error message
return fmt.Errorf("failed to generate svg for icon '%s' with props %+v: %w", name, p, err)
}
iconMutex.Lock()
iconContents[cacheKey] = generatedSvg
iconMutex.Unlock()
_, err = w.Write([]byte(generatedSvg))
return err
})
}
}
// generateSVG creates an SVG string for the specified icon with the given properties.
// This function is called when an icon-prop combination is not yet in the cache.
func generateSVG(name string, props Props) (string, error) {
// Get the raw, inner SVG content for the icon name from our internal data map.
content, err := getIconContent(name) // This now reads from internalSvgData
if err != nil {
return "", err // Error from getIconContent already includes icon name
}
size := props.Size
if size <= 0 {
size = 24 // Default size
}
fill := props.Fill
if fill == "" {
fill = "none" // Default fill
}
stroke := props.Stroke
if stroke == "" {
stroke = props.Color // Fallback to Color if Stroke is not set
}
if stroke == "" {
stroke = "currentColor" // Default stroke color
}
strokeWidth := props.StrokeWidth
if strokeWidth == "" {
strokeWidth = "2" // Default stroke width
}
// Construct the final SVG string.
// The data-lucide attribute helps identify these as Lucide icons if needed.
return fmt.Sprintf("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"%d\" height=\"%d\" viewBox=\"0 0 24 24\" fill=\"%s\" stroke=\"%s\" stroke-width=\"%s\" stroke-linecap=\"round\" stroke-linejoin=\"round\" class=\"%s\" data-lucide=\"icon\">%s</svg>",
size, size, fill, stroke, strokeWidth, props.Class, content), nil
}
// getIconContent retrieves the raw inner SVG content for a given icon name.
// It reads from the pre-generated internalSvgData map from icon_data.go.
func getIconContent(name string) (string, error) {
content, exists := internalSvgData[name]
if !exists {
return "", fmt.Errorf("icon '%s' not found in internalSvgData map", name)
}
return content, nil
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,123 @@
// templui component input - version: v0.85.0 installed by templui v0.85.0
package input
import (
"maot-shortner/web/templates/components/button"
"maot-shortner/web/templates/components/icon"
"maot-shortner/web/resources/utils"
)
type Type string
const (
TypeText Type = "text"
TypePassword Type = "password"
TypeEmail Type = "email"
TypeNumber Type = "number"
TypeTel Type = "tel"
TypeURL Type = "url"
TypeSearch Type = "search"
TypeDate Type = "date"
TypeTime Type = "time"
TypeFile Type = "file"
)
type Props struct {
ID string
Class string
Attributes templ.Attributes
Name string
Type Type
Placeholder string
Value string
Disabled bool
Readonly bool
Required bool
FileAccept string
HasError bool
NoTogglePassword bool
}
templ Input(props ...Props) {
{{ var p Props }}
if len(props) > 0 {
{{ p = props[0] }}
}
if p.Type == "" {
{{ p.Type = TypeText }}
}
if p.ID == "" {
{{ p.ID = utils.RandomID() }}
}
<div class="relative w-full">
<input
id={ p.ID }
type={ string(p.Type) }
if p.Name != "" {
name={ p.Name }
}
if p.Placeholder != "" {
placeholder={ p.Placeholder }
}
if p.Value != "" {
value={ p.Value }
}
if p.Type == TypeFile && p.FileAccept != "" {
accept={ p.FileAccept }
}
disabled?={ p.Disabled }
readonly?={ p.Readonly }
required?={ p.Required }
if p.HasError {
aria-invalid="true"
}
class={
utils.TwMerge(
// Base styles
"flex h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none md:text-sm",
// Dark mode background
"dark:bg-input/30",
// Selection styles
"selection:bg-primary selection:text-primary-foreground",
// Placeholder
"placeholder:text-muted-foreground",
// File input styles
"file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground",
// Focus styles
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
// Disabled styles
"disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50",
// Error/Invalid styles
"aria-invalid:ring-destructive/20 aria-invalid:border-destructive dark:aria-invalid:ring-destructive/40",
utils.If(p.HasError, "border-destructive ring-destructive/20 dark:ring-destructive/40"),
utils.If(p.Type == TypePassword && !p.NoTogglePassword, "pr-8"),
p.Class,
),
}
{ p.Attributes... }
/>
if p.Type == TypePassword && !p.NoTogglePassword {
@button.Button(button.Props{
Size: button.SizeIcon,
Variant: button.VariantGhost,
Class: "absolute right-0 top-1/2 -translate-y-1/2 opacity-50 cursor-pointer",
Attributes: templ.Attributes{"data-tui-input-toggle-password": p.ID},
}) {
<span class="icon-open block">
@icon.Eye(icon.Props{
Size: 18,
})
</span>
<span class="icon-closed hidden">
@icon.EyeOff(icon.Props{
Size: 18,
})
</span>
}
}
</div>
}
templ Script() {
<script defer src="/web/static/js/input.min.js"></script>
}

View file

@ -0,0 +1,42 @@
// templui component label - version: v0.85.0 installed by templui v0.85.0
package label
import "maot-shortner/web/resources/utils"
type Props struct {
ID string
Class string
Attributes templ.Attributes
For string
Error string
}
templ Label(props ...Props) {
{{ var p Props }}
if len(props) > 0 {
{{ p = props[0] }}
}
<label
if p.ID != "" {
id={ p.ID }
}
if p.For != "" {
for={ p.For }
}
class={
utils.TwMerge(
"text-sm font-medium leading-none inline-block",
utils.If(len(p.Error) > 0, "text-destructive"),
p.Class,
),
}
data-tui-label-disabled-style="opacity-50 cursor-not-allowed"
{ p.Attributes... }
>
{ children... }
</label>
}
templ Script() {
<script defer src="/web/static/js/label.min.js"></script>
}

View file

@ -0,0 +1,29 @@
package layouts
import (
"maot-shortner/web/templates/components/input"
"maot-shortner/web/templates/components/label"
"maot-shortner/web/templates/modules"
)
templ MainLayout() {
<!DOCTYPE html>
<html lang="en" class="h-full dark">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link href="/static/css/output.css" rel="stylesheet"/>
<link rel="icon" type="image/x-icon" href="/static/img/favicon.ico"/>
@input.Script()
@label.Script()
</head>
<body class="h-full">
<div class="h-full flex flex-col">
@modules.Navbar()
<main class="flex-1">
{ children... }
</main>
</div>
</body>
</html>
}

View file

@ -0,0 +1,34 @@
package modules
import "maot-shortner/web/templates/components/icon"
import "maot-shortner/web/templates/components/button"
templ Github() {
@button.Button(button.Props{
Variant: button.VariantGhost,
Href: "https://git.maot.dev/maot/maot-shortner",
}) {
<span class="font-bold">
repo
</span>
@icon.GitMerge(icon.Props{Class: "w-6 h-6"})
}
}
templ Navbar() {
<nav class="py-1">
<div class="px-6 flex justify-between items-center relative">
<div class="flex items-center">
<a href="/" class="flex items-center gap-1.5">
@icon.Link(icon.Props{Class: "w-6 h-6"})
<span class="text-xl font-bold">s.maot.dev</span>
</a>
</div>
<div class="flex gap-1 items-center justify-center">
@ThemeSwitcher()
@Github()
</div>
</div>
</nav>
}

View file

@ -0,0 +1,91 @@
package modules
import (
"maot-shortner/web/templates/components/button"
"maot-shortner/web/templates/components/icon"
)
type ThemeSwitcherProps struct {
Class string
}
templ ThemeSwitcher(props ...ThemeSwitcherProps) {
{{ var p ThemeSwitcherProps }}
if len(props) > 0 {
{{ p = props[0] }}
}
<script nonce={ templ.GetNonce(ctx) }>
(function() {
// Get current theme preference (system, light, or dark)
function getThemePreference() {
return localStorage.getItem('themePreference') || 'system';
}
// Apply theme based on preference
function applyTheme() {
const preference = getThemePreference();
let isDark = false;
if (preference === 'system') {
// Use system preference
isDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
} else {
// Use explicit preference
isDark = preference === 'dark';
}
document.documentElement.classList.toggle('dark', isDark);
// Dispatch event for compatibility
document.dispatchEvent(new CustomEvent('theme-changed'));
}
// Toggle between light and dark (system only on initial state)
function cycleTheme() {
const current = getThemePreference();
let next;
if (current === 'system') {
// First click from system state - determine based on current appearance
const isDarkNow = window.matchMedia('(prefers-color-scheme: dark)').matches;
next = isDarkNow ? 'light' : 'dark';
} else {
// Toggle between light and dark
next = current === 'light' ? 'dark' : 'light';
}
localStorage.setItem('themePreference', next);
applyTheme();
}
// Initialize theme
applyTheme();
// Listen for system theme changes
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (getThemePreference() === 'system') {
applyTheme();
}
});
// Use event delegation for click handling
document.addEventListener('click', (e) => {
const themeSwitcher = e.target.closest('[data-theme-switcher]');
if (themeSwitcher) {
e.preventDefault();
cycleTheme();
}
});
})();
</script>
@button.Button(button.Props{
Size: button.SizeIcon,
Variant: button.VariantGhost,
Class: p.Class,
Attributes: templ.Attributes{
"data-theme-switcher": "true",
},
}) {
@icon.Eclipse(icon.Props{Size: 20})
}
}

View file

@ -0,0 +1,31 @@
package pages
import (
"maot-shortner/web/templates/components/button"
"maot-shortner/web/templates/components/icon"
"maot-shortner/web/templates/components/input"
"maot-shortner/web/templates/layouts"
)
templ Home() {
@layouts.MainLayout() {
<div class="h-full flex justify-center items-center flex-col">
@icon.Link(icon.Props{Class: "w-24 h-24"})
<h2 class="text-4xl font-bold py">shorten your urls...</h2>
<div class="flex gap-4 items-center justify-center mt-4 px-4 w-full max-w-2xl">
@input.Input(input.Props{
ID: "URL",
Type: input.TypeURL,
Placeholder: "https://very-long-url.com/",
})
@button.Button(button.Props{
ID: "Shorten",
Variant: button.VariantGhost,
Type: button.TypeSubmit,
}) {
@icon.Send(icon.Props{Size: 20})
}
</div>
</div>
}
}