-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweb_creator.py
More file actions
1816 lines (1694 loc) · 104 KB
/
Copy pathweb_creator.py
File metadata and controls
1816 lines (1694 loc) · 104 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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
aiseed web creator — ホームページ生成ツール
依存: Python のみ(Flet + claude-agent-sdk + requests)
認証: Claude Pro/Max(claude login)
Node.js 不要。ANTHROPIC_API_KEY 不要。
Usage:
python web_creator.py
"""
import asyncio, json, os, shutil, threading, webbrowser, xml.etree.ElementTree as ET, re, html as html_mod
from pathlib import Path
from datetime import datetime
from typing import Any
import flet as ft
import requests
import digikam_bridge as dkb
from image_utils import (BASE_DIR, TEMPLATES_DIR, CONFIG_FILE, PROJECTS_DIR,
default_projects_dir,
load_json, save_json, list_templates, optimize_image)
from digikam_dialog import open_digikam_browser
from generators import generate_sitemap, generate_feed, sync_to_hub, generate_qr_codes
from cloudflare_r2 import upload_images_to_r2
from wordpress_import import import_wordpress_xml
from mcp_server import create_tools, build_system_prompt
from static_generator import render_site
from admin_dashboard import build_admin_tab
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
# メインアプリ
# ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
RECENT_FILE = BASE_DIR / "recent_projects.json"
MAX_RECENT = 20
def _load_recent():
if RECENT_FILE.exists():
try: return json.loads(RECENT_FILE.read_text("utf-8"))
except Exception: pass
return []
def _record_recent(proj_dir):
"""プロジェクトの保存・読込時に履歴を記録する"""
entries = _load_recent()
path_str = str(Path(proj_dir).resolve())
now = datetime.now().strftime("%Y-%m-%d %H:%M")
# 既存エントリを除去して先頭に追加
entries = [e for e in entries if e.get("path") != path_str]
entries.insert(0, {"path": path_str, "name": Path(proj_dir).name, "last_saved": now})
entries = entries[:MAX_RECENT]
RECENT_FILE.write_text(json.dumps(entries, ensure_ascii=False, indent=2), "utf-8")
async def main(page: ft.Page):
page.title = "aiseed web creator"
page.theme_mode = ft.ThemeMode.DARK
page.bgcolor = "#141418"
page.padding = 0
page.window.width = 1100
page.window.height = 800
# ── State ──
current_template = {"ref": None} # mutable container
current_project_dir = {"ref": None}
data = {}
config = load_json(CONFIG_FILE, {})
is_building = False
log_list = ft.ListView(expand=True, spacing=2, auto_scroll=True)
content_area = ft.Column(expand=True)
# デフォルトテンプレート構造(テンプレートなしプロジェクト用)
DEFAULT_TPL = {
"template_id": "_default", "template_name": "カスタム",
"icon": "🌐",
"theme": {"dark":"#141418","mid":"#1e1e2a","accent":"#6c8ee0","green":"#4a9",
"text":"#e0e0e0","text2":"#888","surface":"#1e1e2a","border":"#333"},
"data_sections": [], "default_data": {},
"default_pages": [{"filename": "index.html", "title": "トップ", "description": "メインページ"}],
"site_styles": [], "color_themes": [], "system_prompt_context": "",
}
def C(key):
t = current_template["ref"]
if t and "theme" in t: return t["theme"].get(key, "#888")
return DEFAULT_TPL["theme"].get(key, "#888")
def add_log(text, color=None):
log_list.controls.append(ft.Text(f"[{datetime.now():%H:%M:%S}] {text}", size=12,
color=color or C("text2"), selectable=True))
page.update()
def _change_projects_dir(new_path):
"""PROJECTS_DIR を変更して config.json に保存する"""
nonlocal config
resolved = Path(new_path).expanduser().resolve()
resolved.mkdir(parents=True, exist_ok=True)
config["projects_dir"] = str(resolved)
save_json(CONFIG_FILE, config)
global PROJECTS_DIR
PROJECTS_DIR = resolved
# ━━━ Start screen ━━━
def _build_projects_dir_setting():
"""プロジェクト保存先の表示・変更ウィジェットを返す"""
dir_label = ft.Text(str(PROJECTS_DIR), size=12, color=C("text2"), selectable=True)
async def _browse_dir(e):
path = await ft.FilePicker().get_directory_path(
dialog_title="プロジェクト保存先を変更",
initial_directory=str(PROJECTS_DIR))
if path:
_change_projects_dir(path)
dir_label.value = str(PROJECTS_DIR)
show_start_screen()
return ft.Column([
ft.Text("プロジェクト保存先", size=14, weight=ft.FontWeight.W_600, color=C("text")),
ft.Container(height=4),
ft.Row([
ft.Icon(ft.Icons.FOLDER, color=C("accent"), size=18),
dir_label,
ft.TextButton("変更...", on_click=_browse_dir,
style=ft.ButtonStyle(color=C("accent"))),
], spacing=8, vertical_alignment=ft.CrossAxisAlignment.CENTER),
], spacing=0)
def show_start_screen():
content_area.controls.clear()
# ── 新規プロジェクト ──
new_proj_name = ft.TextField(label="プロジェクト名",
hint_text="例: my-cafe-site",
border_color=C("border"), focused_border_color=C("accent"),
bgcolor=C("surface"), text_style=ft.TextStyle(color=C("text"), size=14),
label_style=ft.TextStyle(color=C("text2"), size=12), border_radius=8, expand=True)
new_parent_label = ft.Text(str(PROJECTS_DIR), size=12, color=C("text2"))
# 親フォルダ選択用の状態
new_parent_dir = {"ref": PROJECTS_DIR}
# FilePicker: 新規プロジェクトの親フォルダ選択
async def _browse_new_parent(e):
path = await ft.FilePicker().get_directory_path(
dialog_title="作成先フォルダを選択",
initial_directory=str(new_parent_dir["ref"]))
if path:
new_parent_dir["ref"] = Path(path)
new_parent_label.value = str(path)
page.update()
def _create(e):
name = new_proj_name.value.strip()
if not name: return
proj_dir = Path(new_parent_dir["ref"]) / name
proj_dir.mkdir(parents=True, exist_ok=True)
(proj_dir / "output").mkdir(exist_ok=True)
d = {"pages": list(DEFAULT_TPL["default_pages"]),
"site": {"style": "", "color_theme": "", "extra_request": ""}}
save_json(proj_dir / "site_data.json", d)
load_project(proj_dir)
# ── 既存プロジェクトを開く (FilePicker) ──
async def _browse_open(e):
path = await ft.FilePicker().get_directory_path(
dialog_title="プロジェクトフォルダを選択",
initial_directory=str(PROJECTS_DIR))
if path:
proj_dir = Path(path)
if proj_dir.is_dir():
load_project(proj_dir)
# ── 最近のプロジェクト(履歴ベース) ──
recent_entries = _load_recent()
existing = []
for entry in recent_entries:
p = Path(entry["path"])
if not p.is_dir(): continue
last_saved = entry.get("last_saved", "")
def _open(e, path=p):
load_project(path)
existing.append(ft.Container(
content=ft.Row([
ft.Icon(ft.Icons.FOLDER_OUTLINED, color=C("accent"), size=20),
ft.Column([
ft.Text(p.name, size=14, weight=ft.FontWeight.W_600, color=C("text")),
ft.Text(str(p), size=11, color=C("text2")),
], spacing=2, expand=True),
ft.Text(last_saved, size=11, color=C("text2")),
], spacing=10),
bgcolor=C("surface"), border_radius=8, padding=ft.Padding.all(14),
border=ft.Border.all(1, C("border")), on_click=_open, ink=True,
))
content_area.controls.append(ft.Container(
content=ft.Column([
ft.Container(height=40),
ft.Text("aiseed web creator", size=28, weight=ft.FontWeight.W_700, color=C("text"),
text_align=ft.TextAlign.CENTER),
ft.Container(height=32),
# 新規プロジェクト
ft.Text("新規プロジェクト", size=14, weight=ft.FontWeight.W_600, color=C("text")),
ft.Container(height=8),
new_proj_name,
ft.Container(height=8),
ft.Row([
ft.Text("作成先:", size=12, color=C("text2")),
new_parent_label,
ft.TextButton("変更...", on_click=_browse_new_parent,
style=ft.ButtonStyle(color=C("accent"))),
], spacing=8, vertical_alignment=ft.CrossAxisAlignment.CENTER),
ft.Container(height=8),
ft.Button(content=ft.Text("新規作成"), bgcolor=C("accent"),
color="white", height=44, on_click=_create),
ft.Container(height=32),
ft.Divider(color=C("border")),
ft.Container(height=16),
# 既存プロジェクトを開く
ft.Text("プロジェクトを開く", size=14, weight=ft.FontWeight.W_600, color=C("text")),
ft.Container(height=8),
ft.Button(content=ft.Row([
ft.Icon(ft.Icons.FOLDER_OPEN, color=C("text"), size=18),
ft.Text("フォルダを選択...", color=C("text")),
], spacing=8), bgcolor=C("surface"), height=44, on_click=_browse_open,
style=ft.ButtonStyle(side=ft.BorderSide(1, C("border")))),
# 既存プロジェクト一覧
*([ ft.Container(height=16),
ft.Text("最近のプロジェクト", size=12, color=C("text2")),
ft.Container(height=8),
*existing ] if existing else []),
# プロジェクト保存先の設定
ft.Container(height=32),
ft.Divider(color=C("border")),
ft.Container(height=16),
_build_projects_dir_setting(),
], horizontal_alignment=ft.CrossAxisAlignment.CENTER,
scroll=ft.ScrollMode.AUTO, width=500),
expand=True, padding=ft.Padding.all(40),
alignment=ft.Alignment.TOP_CENTER,
))
page.update()
def _save_data():
"""site_data.json を保存し、最近のプロジェクト履歴を更新する"""
proj_dir = current_project_dir["ref"]
if proj_dir:
_save_data()
_record_recent(proj_dir)
def load_project(proj_dir):
nonlocal data, is_building
current_project_dir["ref"] = proj_dir
data_file = proj_dir / "site_data.json"
data.clear()
data.update(load_json(data_file, {}))
_record_recent(proj_dir)
# テンプレートがあれば読む、なければデフォルト
tpl = None
local_tpl = proj_dir / "template.json"
if local_tpl.exists():
tpl = load_json(local_tpl)
else:
tpl_id = data.get("_template_id", "")
if tpl_id:
for f in TEMPLATES_DIR.glob("*.json"):
t = json.loads(f.read_text("utf-8"))
if t.get("template_id") == tpl_id:
tpl = t; break
if tpl:
save_json(local_tpl, tpl)
if not tpl:
tpl = dict(DEFAULT_TPL)
current_template["ref"] = tpl
is_building = False
show_editor(proj_dir, tpl, initial_tab=1)
# ━━━ Editor UI (dynamic from template) ━━━
def show_editor(proj_dir, tpl, initial_tab=0):
content_area.controls.clear()
output_dir = proj_dir / "output"
site_file = output_dir / "index.html"
theme = tpl["theme"]
def _field(lbl, val="", hint="", multiline=False, expand=False):
return ft.TextField(label=lbl, value=val, hint_text=hint, multiline=multiline,
min_lines=3 if multiline else 1, max_lines=6 if multiline else 1,
border_color=theme["border"], focused_border_color=theme["accent"],
label_style=ft.TextStyle(color=theme["text2"], size=12),
text_style=ft.TextStyle(color=theme["text"], size=13),
bgcolor=theme["surface"], border_radius=8,
content_padding=ft.Padding.symmetric(horizontal=12, vertical=10), expand=expand)
def _sec(title, controls):
return ft.Container(content=ft.Column([
ft.Text(title, size=13, weight=ft.FontWeight.W_700, color=theme["accent"]),
ft.Divider(height=1, color=theme["border"]), *controls
], spacing=10), padding=ft.Padding.only(bottom=16))
# ── Dynamic form generation ──
field_refs = {} # section_id -> {key: widget}
list_containers = {} # section_id -> ft.Column
def _make_widget(f, val, theme, expand=False):
"""フィールド定義からウィジェットを生成(date/datetime/markdown対応)"""
ftype = f.get("type", "")
if ftype == "checkbox":
return ft.Checkbox(label=f["label"], value=bool(val),
check_color=theme["accent"], active_color=theme["accent"])
elif ftype == "date":
# 日付フィールド: TextField + DatePicker
tf = _field(f["label"], str(val) if val else "", f.get("hint","今日の日付"), expand=expand)
def _pick_date(e, tf=tf):
def _on_pick(e2):
if e2.control.value:
tf.value = e2.control.value.strftime("%Y-%m-%d")
page.update()
dp = ft.DatePicker(on_change=_on_pick)
page.show_dialog(dp)
page.update()
return ft.Row([tf, ft.IconButton(icon=ft.Icons.CALENDAR_MONTH,
icon_color=theme["accent"], icon_size=20, on_click=_pick_date)], spacing=4, expand=expand)
elif ftype == "datetime":
tf = _field(f["label"], str(val) if val else "", f.get("hint","2026-04-01 10:00"), expand=expand)
def _pick_dt(e, tf=tf):
def _on_pick(e2):
if e2.control.value:
tf.value = e2.control.value.strftime("%Y-%m-%d") + " " + (tf.value.split(" ")[-1] if " " in tf.value else "10:00")
page.update()
dp = ft.DatePicker(on_change=_on_pick)
page.show_dialog(dp)
page.update()
return ft.Row([tf, ft.IconButton(icon=ft.Icons.CALENDAR_MONTH,
icon_color=theme["accent"], icon_size=20, on_click=_pick_dt)], spacing=4, expand=expand)
elif ftype == "image":
# 画像フィールド: digiKam から選択 + プレビュー
img_path_field = ft.TextField(value=str(val) if val else "", visible=False)
img_preview = ft.Image(src=str(val) if val else "", width=160, height=120,
fit=ft.BoxFit.COVER, border_radius=8, visible=bool(val))
img_label = ft.Text(
os.path.basename(str(val)) if val else "digiKam から選択",
size=11, color=theme["text2"], max_lines=1, overflow=ft.TextOverflow.ELLIPSIS)
multiple = f.get("multiple", False)
def _open_dk(e, ipf=img_path_field, ip=img_preview, il=img_label, mult=multiple):
def _on_dk_select(paths, dk_images):
if mult:
ipf.value = ",".join(paths)
ip.src = str(output_dir / paths[0])
ip.visible = True
il.value = f"{len(paths)}枚選択済み"
# 全画像のキャプションを保存
captions = [im.get("caption", "") for im in dk_images if im.get("caption")]
if captions:
ipf.data = captions
else:
ipf.value = paths[0]
ip.src = str(output_dir / paths[0])
ip.visible = True
il.value = os.path.basename(paths[0])
if dk_images and dk_images[0].get("caption"):
ipf.data = dk_images[0]["caption"]
page.update()
open_digikam_browser(page, theme, output_dir, mult, _on_dk_select)
dk_btn = ft.IconButton(icon=ft.Icons.PHOTO_LIBRARY,
icon_color=theme["accent"], icon_size=24, tooltip="digiKam から選択",
on_click=_open_dk)
def _clear_img(e, ipf=img_path_field, ip=img_preview, il=img_label):
ipf.value = ""; ip.visible = False; il.value = "digiKam から選択"; page.update()
clear_btn = ft.IconButton(icon=ft.Icons.CLEAR, icon_color=theme["text2"],
icon_size=16, tooltip="クリア", on_click=_clear_img)
return ft.Column([
ft.Text(f["label"], size=12, color=theme["text2"]),
img_preview,
ft.Row([dk_btn, il, clear_btn], spacing=4),
img_path_field,
], spacing=4, expand=expand)
elif ftype == "markdown":
# マークダウンエディタ: 大きめテキストエリア + プレビュートグル
tf = ft.TextField(label=f["label"], value=str(val) if val else "",
hint_text=f.get("hint","マークダウン記法で記述できます"),
multiline=True, min_lines=8, max_lines=20,
border_color=theme["border"], focused_border_color=theme["accent"],
label_style=ft.TextStyle(color=theme["text2"], size=12),
text_style=ft.TextStyle(color=theme["text"], size=13, font_family="monospace"),
bgcolor=theme["surface"], border_radius=8,
content_padding=ft.Padding.symmetric(horizontal=12, vertical=10), expand=expand)
md_preview = ft.Markdown(value="", selectable=True,
extension_set=ft.MarkdownExtensionSet.GITHUB_WEB, expand=expand)
md_container = ft.Container(content=md_preview, bgcolor=theme["surface"],
border_radius=8, padding=ft.Padding.all(12), border=ft.Border.all(1, theme["border"]),
visible=False, expand=expand)
def _toggle_preview(e, tf=tf, md_preview=md_preview, mc=md_container):
mc.visible = not mc.visible
if mc.visible:
md_preview.value = tf.value or "*プレビューする内容がありません*"
page.update()
preview_btn = ft.TextButton(content=ft.Text("👁 プレビュー", size=11, color=theme["text2"]),
on_click=_toggle_preview)
return ft.Column([ft.Row([ft.Text(f["label"], size=12, color=theme["text2"]), preview_btn],
alignment=ft.MainAxisAlignment.SPACE_BETWEEN), tf, md_container], spacing=4, expand=expand)
elif "choices" in f:
return ft.Dropdown(label=f["label"], value=str(val) if val else f["choices"][0],
options=[ft.dropdown.Option(c) for c in f["choices"]],
border_color=theme["border"], bgcolor=theme["surface"],
text_style=ft.TextStyle(color=theme["text"], size=13),
label_style=ft.TextStyle(color=theme["text2"], size=12),
width=250, border_radius=8)
else:
return _field(f["label"], str(val) if val else "", f.get("hint",""), f.get("multiline",False), expand=expand)
def _get_widget_value(w):
"""ウィジェットから値を取得(Rowラップ等を考慮)"""
if isinstance(w, ft.Row) and w.controls:
# date/datetime: Row[TextField, IconButton]
return w.controls[0].value if hasattr(w.controls[0], 'value') else ""
elif isinstance(w, ft.Column) and len(w.controls) >= 2:
# image: Column[Text, Image, Row, TextField(hidden)] — last control is hidden TextField
last = w.controls[-1]
if isinstance(last, ft.TextField) and not last.visible:
return last.value or ""
# markdown: Column[Row, TextField, Container]
return w.controls[1].value if hasattr(w.controls[1], 'value') else ""
elif hasattr(w, 'value'):
return w.value
return ""
# ── プラグインの data_sections をマージ ──
all_sections = list(tpl.get("data_sections", []))
plugins_dir = proj_dir / "plugins"
_loaded_plugins = []
if plugins_dir.exists():
for pd in sorted(plugins_dir.iterdir()):
pj = pd / "plugin.json"
if pj.exists():
try:
pdata = json.loads(pj.read_text("utf-8"))
_loaded_plugins.append(pdata)
for ps in pdata.get("data_sections", []):
# 重複チェック
if not any(s["id"] == ps["id"] for s in all_sections):
all_sections.append(ps)
except Exception:
pass
# グローバル plugins/ もチェック
global_plugins_dir = BASE_DIR / "plugins"
if global_plugins_dir.exists() and global_plugins_dir != plugins_dir:
for pd in sorted(global_plugins_dir.iterdir()):
pj = pd / "plugin.json"
if pj.exists():
try:
pdata = json.loads(pj.read_text("utf-8"))
if not any(lp.get("plugin_id") == pdata.get("plugin_id") for lp in _loaded_plugins):
_loaded_plugins.append(pdata)
for ps in pdata.get("data_sections", []):
if not any(s["id"] == ps["id"] for s in all_sections):
all_sections.append(ps)
except Exception:
pass
sections_ui = []
for sec in all_sections:
sid = sec["id"]
if sec["type"] == "fields":
refs = {}
controls = []
for f in sec["fields"]:
k = f["key"]
val = data.get(sid, {}).get(k, f.get("default", ""))
w = _make_widget(f, val, theme)
refs[k] = w
controls.append(w)
field_refs[sid] = refs
sections_ui.append(_sec(sec["title"], controls))
elif sec["type"] == "list":
lc = ft.Column(spacing=6)
list_containers[sid] = lc
def _rebuild_list(sid=sid, lc=lc, sec=sec):
lc.controls.clear()
items = data.get(sid, [])
for i, item in enumerate(items):
idx = i
def _del(e, sid=sid, idx=idx):
data[sid].pop(idx)
_save_data()
_rebuild_list(sid, list_containers[sid], sec)
page.update()
def _edit(e, sid=sid, idx=idx, sec=sec):
_open_edit_dlg(sid, idx, sec)
title = item.get(sec.get("item_label_key","name"), "?")
sub_tpl = sec.get("item_subtitle_template","")
try: sub = sub_tpl.format(**{k: item.get(k,"") for k in [f["key"] for f in sec["fields"]]})
except: sub = ""
# 日付があれば表示
date_val = ""
for f in sec["fields"]:
if f.get("type") in ("date","datetime") and item.get(f["key"]):
date_val = f"📅 {item[f['key']]} "
break
lc.controls.append(ft.Container(
content=ft.Row([ft.Column([
ft.Text(f"{date_val}{title}", size=13, weight=ft.FontWeight.W_600, color=theme["text"]),
ft.Text(sub, size=11, color=theme["text2"]),
], expand=True, spacing=2),
ft.Row([
ft.IconButton(icon=ft.Icons.EDIT_OUTLINED, icon_color=theme["text2"], icon_size=16, on_click=_edit),
ft.IconButton(icon=ft.Icons.DELETE_OUTLINE, icon_color=theme["text2"], icon_size=16, on_click=_del),
], spacing=0)]),
bgcolor=theme["surface"], border_radius=8, padding=ft.Padding.all(10),
border=ft.Border.all(1, theme["border"])))
_rebuild_list()
# 追加/編集ダイアログ生成
def _make_item_dlg(sid, sec, lc, edit_idx=None):
"""追加 or 編集ダイアログを生成"""
existing = data.get(sid, [])[edit_idx] if edit_idx is not None else {}
is_edit = edit_idx is not None
dlg_fields = {}
dlg_controls = []
for f in sec["fields"]:
val = existing.get(f["key"], f.get("default","")) if is_edit else ""
w = _make_widget(f, val, theme, expand=True)
dlg_fields[f["key"]] = w
dlg_controls.append(w)
def _save(e):
item = {}
for f in sec["fields"]:
item[f["key"]] = _get_widget_value(dlg_fields[f["key"]])
label_key = sec.get("item_label_key","name")
if not item.get(label_key,""): return
if is_edit:
data[sid][edit_idx] = item
else:
data.setdefault(sid, []).append(item)
_save_data()
_rebuild_list(sid, list_containers[sid], sec)
action = "更新" if is_edit else "追加"
add_log(f"✅ {action}: {item.get(label_key,'')}", theme["green"])
page.pop_dialog(); page.update()
title_text = f"{sec['title']}を{'編集' if is_edit else '追加'}"
h = min(len(sec["fields"])*65, 500)
# markdown フィールドがあればダイアログを大きく
if any(f.get("type")=="markdown" for f in sec["fields"]): h = min(h + 200, 600)
dlg = ft.AlertDialog(
title=ft.Text(title_text, size=16, weight=ft.FontWeight.W_600),
content=ft.Container(width=520, content=ft.Column(dlg_controls, spacing=10,
scroll=ft.ScrollMode.AUTO, height=h)),
actions=[
ft.TextButton(content=ft.Text("キャンセル"),
on_click=lambda e: (page.pop_dialog(), page.update())),
ft.Button(content=ft.Text("保存" if is_edit else "追加"),
bgcolor=theme["accent"], color="white", on_click=_save)])
return dlg
def _open_add_dlg(e, sid=sid, sec=sec, lc=lc):
dlg = _make_item_dlg(sid, sec, lc)
page.show_dialog(dlg); page.update()
def _open_edit_dlg(sid, idx, sec):
dlg = _make_item_dlg(sid, sec, list_containers[sid], edit_idx=idx)
page.show_dialog(dlg); page.update()
# digiKam 一括インポートボタン(画像フィールドを持つリストのみ)
has_photo_field = any(f.get("type") == "image" and not f.get("multiple") for f in sec["fields"])
list_btns = [ft.Button(content=ft.Text(f"+ {sec['title']}を追加"),
bgcolor=theme["surface"], color=theme["text"], on_click=_open_add_dlg)]
if has_photo_field:
def _dk_bulk_import(e, sid=sid, sec=sec, lc=lc):
"""digiKam から複数写真を選択し、各画像をリストアイテムとして一括追加"""
def _on_bulk_select(paths, dk_images):
# digiKam メタデータからギャラリーアイテムを自動生成
db_path_str = load_json(CONFIG_FILE, {}).get("digikam_db_path", "") or os.environ.get("DIGIKAM_DB_HINT", "")
db_path = dkb.find_digikam_db(db_path_str)
if db_path:
gallery_items = dkb.export_for_gallery(db_path, [im["id"] for im in dk_images])
else:
gallery_items = [{"caption": im.get("caption", im["name"]), "tags": ", ".join(im.get("tags", []))} for im in dk_images]
# パスを対応付けてデータに追加
photo_key = next((f["key"] for f in sec["fields"] if f.get("type") == "image" and not f.get("multiple")), "photo")
for i, path in enumerate(paths):
if i < len(gallery_items):
item = gallery_items[i]
item[photo_key] = path
# _source_path と _image_id は内部用なので削除
item.pop("_source_path", None)
item.pop("_image_id", None)
else:
item = {photo_key: path}
# sec のフィールドにないキーは除去
valid_keys = {f["key"] for f in sec["fields"]}
item = {k: v for k, v in item.items() if k in valid_keys}
data.setdefault(sid, []).append(item)
_save_data()
_rebuild_list(sid, list_containers[sid], sec)
add_log(f"📸 digiKam から {len(paths)}枚を一括インポート", theme["green"])
page.update()
open_digikam_browser(page, theme, output_dir, True, _on_bulk_select)
list_btns.append(ft.Button(
content=ft.Row([ft.Icon(ft.Icons.PHOTO_LIBRARY, size=16), ft.Text("digiKam 一括インポート")], spacing=4),
bgcolor=theme["accent"], color="white", on_click=_dk_bulk_import))
# WordPress XML インポート(blog セクションのみ)
if sid == "blog":
wp_xml_path = ft.TextField(label="WordPress XMLファイルパス", hint_text="例: /home/user/export.xml",
border_color=theme["border"], focused_border_color=theme["accent"],
bgcolor=theme["surface"], text_style=ft.TextStyle(color=theme["text"], size=13),
label_style=ft.TextStyle(color=theme["text2"], size=12), border_radius=8, expand=True)
def _wp_import(e, sid=sid, sec=sec, lc=lc, path_field=wp_xml_path):
xml_path = path_field.value.strip() if path_field.value else ""
if not xml_path: return
p = Path(xml_path).expanduser().resolve()
if not p.is_file():
add_log(f"⚠ ファイルが見つかりません: {p}", "#eab308"); return
try:
posts = import_wordpress_xml(str(p))
if not posts:
add_log("⚠ 記事が見つかりません", "#eab308"); return
existing = data.get(sid, [])
existing_slugs = {p.get("slug") for p in existing}
added = 0
for post in posts:
if post["slug"] not in existing_slugs:
existing.append(post)
added += 1
data[sid] = existing
_save_data()
_rebuild_list(sid, list_containers[sid], sec)
add_log(f"✅ WordPress インポート: {added}件追加({len(posts)}件中)", theme["green"])
except Exception as ex:
add_log(f"❌ インポートエラー: {ex}", "#ef4444")
page.update()
list_btns.append(ft.Row([wp_xml_path,
ft.Button(
content=ft.Row([ft.Icon(ft.Icons.UPLOAD_FILE, size=16), ft.Text("WP インポート")], spacing=4),
bgcolor=theme["surface"], color=theme["text"], on_click=_wp_import)
], spacing=8, expand=True))
sections_ui.append(_sec(sec["title"], [lc, ft.Row(list_btns, spacing=8, wrap=True)]))
# ── Pages UI ──
page_cards = ft.Column(spacing=6)
def _rebuild_pages():
page_cards.controls.clear()
for i, pg in enumerate(data.get("pages",[])):
idx=i
def _del_pg(e, idx=idx):
data["pages"].pop(idx); _save_data(); _rebuild_pages(); page.update()
page_cards.controls.append(ft.Container(
content=ft.Row([
ft.Container(content=ft.Text(f"{i+1}",size=11,color=theme["text2"]),
width=24,height=24,border_radius=12,bgcolor=theme["border"],alignment=ft.Alignment.CENTER),
ft.Column([
ft.Text(f"{pg['title']} ({pg['filename']})",size=13,weight=ft.FontWeight.W_600,color=theme["text"]),
ft.Text(pg.get("description",""),size=11,color=theme["text2"]),
],expand=True,spacing=2),
ft.IconButton(icon=ft.Icons.DELETE_OUTLINE,icon_color=theme["text2"],icon_size=16,on_click=_del_pg),
],spacing=8),bgcolor=theme["surface"],border_radius=8,
padding=ft.Padding.symmetric(horizontal=12,vertical=8),border=ft.Border.all(1,theme["border"])))
_rebuild_pages()
pg_fn=_field("ファイル名",hint="例: gallery.html"); pg_title=_field("タイトル"); pg_desc=_field("内容の説明")
pg_dlg=ft.AlertDialog(title=ft.Text("ページ追加"),
content=ft.Container(width=400,content=ft.Column([pg_fn,pg_title,pg_desc],spacing=10,height=200)),
actions=[ft.TextButton(content=ft.Text("キャンセル"),on_click=lambda e:(page.pop_dialog(),page.update())),
ft.Button(content=ft.Text("追加"),bgcolor=theme["accent"],color="white",
on_click=lambda e:_add_page())])
def _add_page():
fn=pg_fn.value.strip(); t=pg_title.value.strip()
if not fn or not t: return
if not fn.endswith(".html"): fn+=".html"
data.setdefault("pages",[]).append({"filename":fn,"title":t,"description":pg_desc.value})
_save_data(); _rebuild_pages()
pg_fn.value="";pg_title.value="";pg_desc.value=""; page.pop_dialog(); page.update()
# ── Site settings ──
st = data.get("site",{})
s_url=_field("サイトURL",st.get("url",""),"例: https://example.com(サイトマップ・OGP生成に使用)",expand=True)
s_style=ft.Dropdown(label="デザイン",value=st.get("style",""),
options=[ft.dropdown.Option(s) for s in tpl.get("site_styles",["デフォルト"])],
border_color=theme["border"],bgcolor=theme["surface"],text_style=ft.TextStyle(color=theme["text"],size=13),
label_style=ft.TextStyle(color=theme["text2"],size=12),width=220,border_radius=8)
s_color=ft.Dropdown(label="カラーテーマ",value=st.get("color_theme",""),
options=[ft.dropdown.Option(c) for c in tpl.get("color_themes",["デフォルト"])],
border_color=theme["border"],bgcolor=theme["surface"],text_style=ft.TextStyle(color=theme["text"],size=13),
label_style=ft.TextStyle(color=theme["text2"],size=12),width=220,border_radius=8)
s_extra=_field("追加リクエスト",st.get("extra_request",""),"自由にリクエスト",multiline=True)
# ── WordPress Theme Browser ──
wp_search=ft.TextField(label="WPテーマ検索",hint_text="例: farm, restaurant, business",
border_color=theme["border"],focused_border_color=theme["accent"],
bgcolor=theme["surface"],text_style=ft.TextStyle(color=theme["text"],size=13),
label_style=ft.TextStyle(color=theme["text2"],size=12),border_radius=8,expand=True,
on_submit=lambda e:_search_wp_themes(e))
wp_results=ft.Column(spacing=8)
wp_selected_info=ft.Text(
f"選択中: {data.get('wp_theme_ref',{}).get('name','なし')}" if data.get('wp_theme_ref') else "テーマ未選択(検索してデザイン参考を選べます)",
size=12,color=theme["text2"])
def _search_wp_themes(e):
q=wp_search.value.strip()
if not q: return
wp_results.controls.clear()
wp_results.controls.append(ft.Text("検索中...",size=12,color=theme["text2"]))
page.update()
def _fetch():
try:
url=f"https://api.wordpress.org/themes/info/1.2/?action=query_themes&request[search]={q}&request[per_page]=12"
r=requests.get(url,timeout=15)
themes=r.json().get("themes",[]) if r.ok else []
wp_results.controls.clear()
if not themes:
wp_results.controls.append(ft.Text("テーマが見つかりませんでした",size=12,color=theme["text2"]))
page.update(); return
# グリッド表示
row_items=[]
for t in themes[:12]:
screenshot=t.get("screenshot_url","")
name=t.get("name","")
slug=t.get("slug","")
desc=t.get("description","")[:100]
tags=", ".join(list(t.get("tags",{}).values())[:5]) if isinstance(t.get("tags"),dict) else ""
def _select_theme(e, t=t):
ref={"name":t.get("name",""),"slug":t.get("slug",""),
"screenshot_url":t.get("screenshot_url",""),
"description":t.get("description","")[:300],
"tags":list(t.get("tags",{}).values())[:10] if isinstance(t.get("tags"),dict) else [],
"homepage":t.get("homepage",""),
"preview_url":t.get("preview_url","")}
data["wp_theme_ref"]=ref
_save_data()
wp_selected_info.value=f"✅ 選択: {ref['name']}(Claudeがこのデザインを参考にします)"
wp_selected_info.color=theme["green"]
add_log(f"🎨 WPテーマ参照: {ref['name']}",theme["green"])
page.update()
card=ft.Container(
content=ft.Column([
ft.Image(src=screenshot,width=200,height=150,fit=ft.BoxFit.COVER,
border_radius=ft.border_radius.only(top_left=8,top_right=8)) if screenshot else ft.Container(height=150,bgcolor=theme["border"]),
ft.Container(content=ft.Column([
ft.Text(name,size=12,weight=ft.FontWeight.W_600,color=theme["text"],
max_lines=1,overflow=ft.TextOverflow.ELLIPSIS),
ft.Text(tags[:40] if tags else desc[:40],size=10,color=theme["text2"],
max_lines=1,overflow=ft.TextOverflow.ELLIPSIS),
],spacing=2),padding=ft.Padding.symmetric(horizontal=8,vertical=6)),
],spacing=0),
width=210,border_radius=8,bgcolor=theme["surface"],
border=ft.Border.all(1,theme["border"]),
on_click=_select_theme,ink=True)
row_items.append(card)
wp_results.controls.append(ft.Row(row_items,wrap=True,spacing=10,run_spacing=10))
except Exception as ex:
wp_results.controls.clear()
wp_results.controls.append(ft.Text(f"エラー: {ex}",size=12,color="#ef4444"))
page.update()
threading.Thread(target=_fetch,daemon=True).start()
def _clear_wp_theme(e):
data.pop("wp_theme_ref",None)
_save_data()
wp_selected_info.value="テーマ未選択"
wp_selected_info.color=theme["text2"]
page.update()
# ── Save ──
def save_data(e=None):
for sid, refs in field_refs.items():
sec_data = {}
for k, w in refs.items():
sec_data[k] = _get_widget_value(w)
data[sid] = sec_data
data["site"] = {"url":s_url.value.strip(),"style":s_style.value,"color_theme":s_color.value,"extra_request":s_extra.value}
_save_data()
add_log("✅ 保存しました", theme["green"])
sb = ft.SnackBar(content=ft.Text("保存しました"), bgcolor=theme["green"])
page.overlay.append(sb); sb.open=True; page.update()
# ── Data Tab ──
tab_data = ft.Container(content=ft.Column([
*sections_ui,
_sec("ページ構成",[
ft.Text("生成するHTMLページを自由に追加・削除",size=11,color=theme["text2"]),
page_cards,
ft.Button(content=ft.Text("+ ページ追加"),bgcolor=theme["surface"],color=theme["text"],
on_click=lambda e:(page.show_dialog(pg_dlg),page.update()))]),
_sec("デザイン参照(WordPressテーマ)",[
ft.Text("世界中のデザイナーが作ったWPテーマからデザインの参考を選べます(WordPress自体は不要)",
size=11,color=theme["text2"]),
wp_selected_info,
ft.Row([wp_search,
ft.IconButton(icon=ft.Icons.SEARCH,icon_color=theme["accent"],on_click=_search_wp_themes),
ft.TextButton(content=ft.Text("クリア",size=11),on_click=_clear_wp_theme),
],spacing=4),
wp_results]),
_sec("サイト設定",[s_url,ft.Row([s_style,s_color],spacing=12),s_extra]),
ft.Container(content=ft.Button(content=ft.Text("💾 保存"),
bgcolor=theme["accent"],color="white",width=200,height=44,on_click=save_data),
alignment=ft.Alignment.CENTER,padding=ft.Padding.symmetric(vertical=16)),
],spacing=6,scroll=ft.ScrollMode.AUTO),expand=True,padding=ft.Padding.all(20))
# ── Build Tab ──
chat_input=ft.TextField(hint_text="修正指示を入力...",border_color=theme["border"],
focused_border_color=theme["accent"],bgcolor=theme["surface"],
text_style=ft.TextStyle(color=theme["text"],size=13),border_radius=8,expand=True,
on_submit=lambda e:send_msg(e))
build_prog=ft.ProgressBar(visible=False,color=theme["accent"],bgcolor=theme["border"])
def _agent(prompt,initial=False,mode="direct"):
nonlocal is_building
async def _run():
nonlocal is_building
try:
from claude_agent_sdk import ClaudeSDKClient,ClaudeAgentOptions,AssistantMessage,ResultMessage,TextBlock,ToolUseBlock
srv=create_tools(proj_dir)
# プラグイン指示を system_prompt_context に追加
_ctx = tpl.get("system_prompt_context","")
for _plg in _loaded_plugins:
instr = _plg.get("instructions","")
if instr:
_ctx += f"\n\n## プラグイン: {_plg.get('plugin_name','')}\n{instr}"
sys_prompt=build_system_prompt(str(output_dir.resolve()),data.get("pages",[]),
_ctx, data.get("wp_theme_ref"),
site_url=data.get("site",{}).get("url",""),
seo_data=data.get("seo",{}),mode=mode)
opts=ClaudeAgentOptions(system_prompt=sys_prompt,
allowed_tools=["Read","Write","Edit","Bash",
"mcp__aiseed__get_site_data","mcp__aiseed__get_deploy_config",
"mcp__aiseed__save_deploy_config","mcp__aiseed__log_action"],
permission_mode="acceptEdits",mcp_servers={"aiseed":srv},
cwd=str(proj_dir),max_turns=40)
async with ClaudeSDKClient(options=opts) as client:
await client.query(prompt)
async for msg in client.receive_response():
if isinstance(msg,AssistantMessage):
for b in msg.content:
if isinstance(b,TextBlock): add_log(f"Claude: {b.text}",theme["text"])
elif isinstance(b,ToolUseBlock):
l=b.name
if b.name=="Write": l=f"Write → {b.input.get('file_path','')}"
elif b.name=="Edit": l=f"Edit → {b.input.get('file_path','')}"
elif b.name.startswith("mcp__aiseed__"): l="🔧 "+b.name.replace("mcp__aiseed__","")
add_log(f" ⚙ {l}",theme["text2"])
elif isinstance(msg,ResultMessage):
p=[]
if msg.total_cost_usd is not None: p.append(f"${msg.total_cost_usd:.4f}")
if msg.num_turns: p.append(f"{msg.num_turns}ターン")
if p: add_log(f"📊 {' / '.join(p)}",theme["text2"])
add_log("✅ 完了",theme["green"])
# サイトマップ・フィード自動生成
site_url=data.get("site",{}).get("url","")
if site_url:
generate_sitemap(output_dir,site_url,data.get("pages",[]),data.get("blog",[]))
add_log("📋 sitemap.xml / robots.txt 生成",theme["text2"])
generate_feed(output_dir,site_url,data)
add_log("📡 feed.json 生成",theme["text2"])
except ImportError: add_log("❌ claude-agent-sdk未インストール","#ef4444")
except Exception as ex: add_log(f"❌ {ex}","#ef4444")
finally: is_building=False; build_prog.visible=False; page.update()
asyncio.run(_run())
def _build_prompt_direct():
pages=data.get("pages",[])
if not pages:
pages=[{"filename":"index.html","title":"トップページ","description":"メインページ"}]
pl=", ".join(f"{p.get('filename','index.html')}({p.get('title','無題')})" for p in pages)
return f"サイトを複数ページで作成。\n1.get_site_dataでデータ取得(pages配列あり)\n2.css/style.css→Write\n3.以下をWrite: {pl}\n4.全ページ共通ナビ\n5.log_action\nデータが空欄の項目はプレースホルダーテキストで補完してください。\n生成後ページ構成を報告。"
def _build_prompt_jinja2():
pages=data.get("pages",[])
if not pages:
pages=[{"filename":"index.html","title":"トップページ","description":"メインページ"}]
pl=", ".join(f"_templates/{p.get('filename','index.html')}.j2" for p in pages)
md_files=", ".join(f"content/{p.get('filename','index.html').replace('.html','.md')}" for p in pages)
return f"Jinja2テンプレートとサンプルMarkdownを生成。\n1.get_site_dataでデータ構造を確認\n2._templates/base.j2→Write(共通レイアウト)\n3.css/style.css→Write(静的CSSの場合)またはcss/style.css.j2\n4.以下をWrite: {pl}\n5.content/にサンプルMarkdown生成: {md_files}\n6.log_action\nデータが空欄の項目はプレースホルダーテキストで補完してください。\n生成後テンプレート構成とcontent/構成を報告。"
# ── Claude 直接生成 ──
def start_build(e):
nonlocal is_building
if is_building: return
is_building=True;build_prog.visible=True;page.update();save_data()
add_log("▶ サイト生成開始(Claude 直接生成)...",theme["accent"])
threading.Thread(target=_agent,args=(_build_prompt_direct(),True,"direct"),daemon=True).start()
def auto_build(e):
nonlocal is_building
if is_building: return
is_building=True;build_prog.visible=True;page.update();save_data()
add_log("▶ 自動ビルド開始(Claude 直接生成)...",theme["accent"])
p=_build_prompt_direct()+"\n\nさらに:Readで全ページ品質チェック(リンク整合性、データ反映)。問題あればEdit。"
threading.Thread(target=_agent,args=(p,True,"direct"),daemon=True).start()
# ── 静的ジェネレータ ──
def ssg_create_templates(e):
nonlocal is_building
if is_building: return
is_building=True;build_prog.visible=True;page.update();save_data()
add_log("▶ テンプレート生成開始(静的ジェネレータ)...",theme["accent"])
threading.Thread(target=_agent,args=(_build_prompt_jinja2(),True,"jinja2"),daemon=True).start()
def ssg_render(e):
nonlocal is_building
if is_building: return
save_data()
templates_dir=output_dir/"_templates"
if not templates_dir.exists() or not list(templates_dir.rglob("*.j2")):
add_log("テンプレート未生成。先に「テンプレート生成」を実行してください","#eab308");return
is_building=True;build_prog.visible=True;page.update()
add_log("▶ サイト生成開始(静的ジェネレータ)...","#d97706")
def _run():
nonlocal is_building
try:
files=render_site(proj_dir,log_fn=lambda m:add_log(m,theme["text2"]))
add_log(f"{len(files)}ファイル生成完了",theme["green"])
site_url=data.get("site",{}).get("url","")
if site_url:
generate_sitemap(output_dir,site_url,data.get("pages",[]),data.get("blog",[]))
generate_feed(output_dir,site_url,data)
add_log("sitemap.xml / feed.json 更新",theme["text2"])
except FileNotFoundError as ex:
add_log(f"{ex}","#eab308")
except Exception as ex:
add_log(f"エラー: {ex}","#ef4444")
finally:
is_building=False;build_prog.visible=False;page.update()
threading.Thread(target=_run,daemon=True).start()
# ── 共通 ──
def send_msg(e):
nonlocal is_building
msg=chat_input.value.strip()
if not msg or is_building: return
chat_input.value="";is_building=True;build_prog.visible=True;page.update()
add_log(f"あなた: {msg}",theme["accent"])
threading.Thread(target=_agent,args=(msg,),daemon=True).start()
def preview(e):
if not site_file.exists(): add_log("⚠ サイト未生成","#eab308"); return
import http.server,functools; port=8080
def _s():
h=functools.partial(http.server.SimpleHTTPRequestHandler,directory=str(output_dir))
try: s=http.server.HTTPServer(("",port),h); add_log(f"🌐 http://localhost:{port}",theme["green"]); webbrowser.open(f"http://localhost:{port}"); s.serve_forever()
except OSError: webbrowser.open(f"http://localhost:{port}"); add_log(f"🌐 http://localhost:{port}",theme["green"])
threading.Thread(target=_s,daemon=True).start()
# ── ビルドタブ UI ──
direct_row = ft.Row([
ft.Button(content=ft.Text("⚡ 生成"),bgcolor=theme["accent"],color="white",height=38,on_click=start_build),
ft.Button(content=ft.Text("🔄 自動ビルド"),bgcolor=theme["green"],color="white",height=38,on_click=auto_build),
],spacing=8)
ssg_row = ft.Row([
ft.Button(content=ft.Text("⚡ テンプレート生成"),bgcolor=theme["accent"],color="white",height=38,on_click=ssg_create_templates),
ft.Button(content=ft.Text("📋 サイト生成"),bgcolor="#d97706",color="white",height=38,
tooltip="Jinja2テンプレートからサイトを生成(API不使用)",on_click=ssg_render),
],spacing=8)
def _on_mode_change(e):
is_ssg = e.control.value == "ssg"
direct_row.visible = not is_ssg
ssg_row.visible = is_ssg
page.update()
build_mode = ft.RadioGroup(
value="direct",on_change=_on_mode_change,
content=ft.Row([
ft.Radio(value="direct",label="Claude 直接生成"),
ft.Radio(value="ssg",label="静的ジェネレータ"),
],spacing=16))
ssg_row.visible = False
tab_build=ft.Container(content=ft.Column([
ft.Container(content=ft.Column([
build_mode,
direct_row,
ssg_row,
ft.Row([ft.Button(content=ft.Text("👁 プレビュー"),bgcolor=theme["surface"],color=theme["text"],height=38,on_click=preview)]),
],spacing=8),padding=ft.Padding.only(bottom=8)),
build_prog,
ft.Container(content=log_list,bgcolor=theme["surface"],border_radius=8,
border=ft.Border.all(1,theme["border"]),padding=ft.Padding.all(12),expand=True),
ft.Row([chat_input,ft.IconButton(icon=ft.Icons.SEND,icon_color=theme["accent"],on_click=send_msg)],spacing=8),
],spacing=8),expand=True,padding=ft.Padding.all(20))
# ── Deploy Tab ──
proj_config=load_json(proj_dir/"config.json",{})
d_result=ft.Text("",size=13,selectable=True)
deploy_content=ft.Column(spacing=10)
# -- Cloudflare fields --
cf_proj=_field("サイト名(英数字・ハイフン)",proj_config.get("cf_project_name",""),"例: my-farm-site(公開URLになります)")
cf_acct=_field("Account ID(32文字の英数字)",proj_config.get("cf_account_id",""),"上の手順でコピーした値を貼り付け")