-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbutton_layout.py
More file actions
287 lines (249 loc) · 9.9 KB
/
button_layout.py
File metadata and controls
287 lines (249 loc) · 9.9 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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
#!/usr/bin/env python3
"""
Button Layout Designer - Calcula dimensiones y espaciado de botones
en un contenedor de tamaño fijo.
Dado un area de AxB pixeles, numero de filas/columnas y gaps deseados,
calcula el tamaño optimo de cada boton y genera CSS/HTML de preview.
"""
import argparse
import math
import webbrowser
import tempfile
from dataclasses import dataclass
from pathlib import Path
@dataclass
class LayoutResult:
container_width: int
container_height: int
rows: int
cols: int
gap: int
padding: int
border_width: int
border_radius: int
button_width: float
button_height: float
@property
def total_buttons(self) -> int:
return self.rows * self.cols
@property
def button_area(self) -> float:
return self.button_width * self.button_height
@property
def total_button_area(self) -> float:
return self.button_area * self.total_buttons
@property
def container_area(self) -> int:
return self.container_width * self.container_height
@property
def fill_ratio(self) -> float:
return self.total_button_area / self.container_area * 100
def calculate_layout(
width: int,
height: int,
rows: int,
cols: int,
gap: int = 8,
padding: int = 16,
border_width: int = 1,
border_radius: int = 4,
) -> LayoutResult:
"""Calcula las dimensiones de cada boton dado el contenedor y la grid."""
usable_width = width - 2 * padding - (cols - 1) * gap
usable_height = height - 2 * padding - (rows - 1) * gap
btn_w = usable_width / cols
btn_h = usable_height / rows
if btn_w <= 0 or btn_h <= 0:
raise ValueError(
f"No hay espacio suficiente. Espacio disponible por boton: "
f"{btn_w:.1f}x{btn_h:.1f}px. Reduce gap/padding o filas/columnas."
)
return LayoutResult(
container_width=width,
container_height=height,
rows=rows,
cols=cols,
gap=gap,
padding=padding,
border_width=border_width,
border_radius=border_radius,
button_width=btn_w,
button_height=btn_h,
)
def print_summary(layout: LayoutResult) -> None:
"""Imprime un resumen del layout calculado."""
print("\n=== Layout de Botones ===\n")
print(f"Contenedor: {layout.container_width} x {layout.container_height} px")
print(f"Grid: {layout.rows} filas x {layout.cols} columnas ({layout.total_buttons} botones)")
print(f"Padding: {layout.padding} px")
print(f"Gap: {layout.gap} px")
print(f"Border: {layout.border_width} px")
print(f"Border radius: {layout.border_radius} px")
print(f"\nBoton: {layout.button_width:.1f} x {layout.button_height:.1f} px")
print(f"Area por boton: {layout.button_area:.0f} px²")
print(f"Fill ratio: {layout.fill_ratio:.1f}%")
# Recomendaciones
print("\n--- Recomendaciones ---")
if layout.button_width < 44 or layout.button_height < 44:
print("AVISO: Botones menores a 44px. Problemas de accesibilidad en movil (min recomendado: 44x44px).")
if layout.gap < 4:
print("AVISO: Gap muy pequeno. Los botones pueden parecer pegados.")
if layout.button_width / layout.button_height > 4:
print("NOTA: Botones muy anchos. Considera mas columnas o menos ancho de contenedor.")
if layout.button_height / layout.button_width > 4:
print("NOTA: Botones muy altos. Considera mas filas o menos alto de contenedor.")
aspect = layout.button_width / layout.button_height
if 0.8 <= aspect <= 1.2:
print(f"OK: Botones casi cuadrados (aspect ratio {aspect:.2f}).")
else:
print(f"INFO: Aspect ratio {aspect:.2f}:1.")
font_size = min(layout.button_width, layout.button_height) * 0.35
font_size = max(10, min(font_size, 24))
print(f"Font size sugerido: {font_size:.0f}px")
def generate_css(layout: LayoutResult) -> str:
"""Genera CSS para el layout."""
return f""".button-container {{
width: {layout.container_width}px;
height: {layout.container_height}px;
display: grid;
grid-template-columns: repeat({layout.cols}, 1fr);
grid-template-rows: repeat({layout.rows}, 1fr);
gap: {layout.gap}px;
padding: {layout.padding}px;
box-sizing: border-box;
}}
.button-container button {{
/* Calculado: {layout.button_width:.1f} x {layout.button_height:.1f} px */
width: 100%;
height: 100%;
border: {layout.border_width}px solid #333;
border-radius: {layout.border_radius}px;
background: #4a90d9;
color: white;
font-size: {max(10, min(min(layout.button_width, layout.button_height) * 0.35, 24)):.0f}px;
cursor: pointer;
transition: background 0.2s;
}}
.button-container button:hover {{
background: #357abd;
}}"""
def generate_html_preview(layout: LayoutResult) -> str:
"""Genera un HTML completo de preview."""
css = generate_css(layout)
buttons = ""
for i in range(1, layout.total_buttons + 1):
buttons += f" <button>{i}</button>\n"
return f"""<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Button Layout Preview</title>
<style>
body {{
font-family: system-ui, sans-serif;
background: #1a1a2e;
display: flex;
flex-direction: column;
align-items: center;
padding: 40px;
color: #eee;
}}
h1 {{ font-size: 1.2rem; margin-bottom: 8px; }}
.info {{
font-size: 0.85rem;
color: #aaa;
margin-bottom: 20px;
}}
.button-container {{
background: #16213e;
border: 2px dashed #555;
}}
{css}
</style>
</head>
<body>
<h1>Button Layout: {layout.rows}x{layout.cols} en {layout.container_width}x{layout.container_height}px</h1>
<p class="info">Boton: {layout.button_width:.1f}x{layout.button_height:.1f}px | Gap: {layout.gap}px | Padding: {layout.padding}px | Fill: {layout.fill_ratio:.1f}%</p>
<div class="button-container">
{buttons} </div>
</body>
</html>"""
def suggest_layouts(width: int, height: int, max_buttons: int = 30) -> None:
"""Sugiere varias configuraciones de grid para el contenedor dado."""
print(f"\n=== Sugerencias para {width}x{height}px (max {max_buttons} botones) ===\n")
print(f"{'Grid':<10} {'Botones':<9} {'Tam boton':<16} {'Fill %':<8} {'Accesible'}")
print("-" * 60)
for total in range(2, max_buttons + 1):
for r in range(1, total + 1):
if total % r != 0:
continue
c = total // r
if r > c:
break
try:
layout = calculate_layout(width, height, r, c)
accessible = "Si" if layout.button_width >= 44 and layout.button_height >= 44 else "No"
print(
f"{r}x{c:<7} {total:<9} "
f"{layout.button_width:.0f}x{layout.button_height:.0f} px{'':<5} "
f"{layout.fill_ratio:<8.1f} {accessible}"
)
except ValueError:
pass
def main():
parser = argparse.ArgumentParser(
description="Calcula layout optimo de botones en un contenedor.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Ejemplos:
%(prog)s 800 600 3 4 Layout 3x4 en 800x600px
%(prog)s 400 300 2 3 --gap 12 Con gap de 12px
%(prog)s 800 600 3 4 --preview Abre preview en navegador
%(prog)s 800 600 3 4 --css Genera solo CSS
%(prog)s 800 600 --suggest Sugiere configuraciones
""",
)
parser.add_argument("width", type=int, help="Ancho del contenedor en px")
parser.add_argument("height", type=int, help="Alto del contenedor en px")
parser.add_argument("rows", type=int, nargs="?", help="Numero de filas")
parser.add_argument("cols", type=int, nargs="?", help="Numero de columnas")
parser.add_argument("--gap", type=int, default=8, help="Espacio entre botones en px (default: 8)")
parser.add_argument("--padding", type=int, default=16, help="Padding del contenedor en px (default: 16)")
parser.add_argument("--border", type=int, default=1, help="Grosor del borde del boton en px (default: 1)")
parser.add_argument("--radius", type=int, default=4, help="Border radius en px (default: 4)")
parser.add_argument("--css", action="store_true", help="Imprimir CSS generado")
parser.add_argument("--preview", action="store_true", help="Abrir preview HTML en navegador")
parser.add_argument("--save", type=str, metavar="FILE", help="Guardar preview HTML a archivo")
parser.add_argument("--suggest", action="store_true", help="Sugerir configuraciones de grid")
parser.add_argument("--max-buttons", type=int, default=30, help="Max botones para sugerencias (default: 30)")
args = parser.parse_args()
if args.suggest:
suggest_layouts(args.width, args.height, args.max_buttons)
return
if args.rows is None or args.cols is None:
parser.error("Se requieren filas y columnas (o usa --suggest)")
try:
layout = calculate_layout(
args.width, args.height, args.rows, args.cols,
gap=args.gap, padding=args.padding,
border_width=args.border, border_radius=args.radius,
)
except ValueError as e:
print(f"Error: {e}")
return
print_summary(layout)
if args.css:
print(f"\n=== CSS ===\n")
print(generate_css(layout))
if args.preview or args.save:
html = generate_html_preview(layout)
if args.save:
Path(args.save).write_text(html)
print(f"\nPreview guardada en: {args.save}")
if args.preview:
with tempfile.NamedTemporaryFile("w", suffix=".html", delete=False) as f:
f.write(html)
print(f"\nAbriendo preview: {f.name}")
webbrowser.open(f"file://{f.name}")
if __name__ == "__main__":
main()