gemini-2.5-flash-lite-preview-06-17-thinking· Google LMArena Human Preference 140K
[code] Python 3.12+, Flet 0.28.3. GUIによる編集が、D&Dのみうまく機能しない。ドラッグすることのみ可能で、ドロップできない。…
- User
# src/models/markdown_model.py from typing import Optional import flet as ft from pydantic import BaseModel, Field from uuid6 import uuid7 class Section(BaseModel): id: str = Field(default_factory=lambda: str(uuid7())) title: str content: str = "" sub_sections: list['Section'] = Field(default_factory=list) def find(self, title: str) -> Optional['Section']: """ 自分自身または子孫セクションの中から、title が一致する Section を返す。 見つからなければ None。 """ if self.title == title: return self for sub in self.sub_sections: found = sub.find(title) if found: return found return None def find_by_id(self, section_id: str) -> Optional['Section']: """IDでセクションを検索""" if self.id == section_id: return self for sub in self.sub_sections: found = sub.find_by_id(section_id) if found: return found return None def remove_by_id(self, section_id: str) -> bool: """IDでセクションを削除""" for i, sub in enumerate(self.sub_sections): if sub.id == section_id: self.sub_sections.pop(i) return True if sub.remove_by_id(section_id): return True return False def to_markdown(self, level: int = 1, auto_format: bool = True) -> str: """ このセクションとサブセクションを再帰的に Markdown 形式で返す。 level は見出しレベル(# の数)を指定。 """ title = self.title if auto_format: if level <= 2: title = title.title() # H1, H2: 各単語の先頭を大文字 else: words = title.lower().split() if words: words[0] = words[0].capitalize() # H3以下: 先頭の単語だけ大文字 title = ' '.join(words) md = [f"{'#' * level} {title}"] if self.content: md.append(f"{self.content}") for sub in self.sub_sections: md.append("\n" + sub.to_markdown(level + 1, auto_format)) return "\n".join(md) class SectionEditor: def __init__(self, page: ft.Page): self.page = page self.root_section = Section(title="Root", content="") self.selected_section: Optional[Section] = None # サンプルデータ self._init_sample_data() def _init_sample_data(self): """サンプルデータの初期化""" intro = Section(title="introduction", content="This is the introduction.") intro.sub_sections.append(Section(title="background", content="Background information.")) intro.sub_sections.append(Section(title="motivation", content="Why this matters.")) methods = Section(title="methods", content="Our methodology.") methods.sub_sections.append(Section(title="data collection", content="How we collected data.")) methods.sub_sections.append(Section(title="analysis", content="How we analyzed data.")) self.root_section.sub_sections.extend([intro, methods]) def create_section_tile(self, section: Section, level: int = 0) -> ft.Container: """セクションをドラッグ可能なタイルとして作成""" def on_drag_accept(e): # ドラッグされたセクションのIDを取得 dragged_id = e.src_id target_id = e.control.data if dragged_id == target_id: return # ドラッグされたセクションを探す dragged_section = self.root_section.find_by_id(dragged_id) if not dragged_section: return # 元の場所から削除 self.root_section.remove_by_id(dragged_id) # ターゲットセクションに追加 if target_id == "root": self.root_section.sub_sections.append(dragged_section) else: target_section = self.root_section.find_by_id(target_id) if target_section: target_section.sub_sections.append(dragged_section) self.update_tree() self.update_preview() def on_click(e): self.selected_section = section self.update_editor() # セクションタイトル title_row = ft.Row([ ft.Icon(ft.Icons.FOLDER_OPEN if section.sub_sections else ft.Icons.ARTICLE, size=16), ft.Text(section.title, size=14, weight=ft.FontWeight.W_500), ], spacing=5) # ドラッグ可能なコンテナ draggable = ft.Draggable( group="section", content=ft.Container( content=title_row, border_radius=5, padding=ft.padding.all(8), on_click=on_click, ), content_feedback=ft.Container( content=ft.Text(section.title, size=12), border_radius=5, padding=ft.padding.all(5), ), ) # ドロップターゲット drag_target = ft.DragTarget( group="section", content=draggable, on_accept=on_drag_accept, data=section.id, ) # サブセクションを含むコンテナ items = [drag_target] for sub in section.sub_sections: items.append(self.create_section_tile(sub, level + 1)) return ft.Container( content=ft.Column(items, spacing=2), padding=ft.padding.only(left=level * 20), ) def update_tree(self): """ツリービューを更新""" self.tree_container.content = ft.Column( [self.create_section_tile(sub) for sub in self.root_section.sub_sections], spacing=5, scroll=ft.ScrollMode.AUTO, ) self.page.update() def update_editor(self): """選択されたセクションの編集フォームを更新""" if not self.selected_section: self.editor_container.content = ft.Text("セクションを選択してください") else: self.title_field.value = self.selected_section.title self.content_field.value = self.selected_section.content self.editor_container.content = self.editor_form self.page.update() def update_preview(self): """Markdownプレビューを更新""" markdown_text = "" for section in self.root_section.sub_sections: markdown_text += section.to_markdown() + "\n\n" self.preview_text.value = markdown_text self.page.update() def save_changes(self, e): """変更を保存""" if self.selected_section: self.selected_section.title = self.title_field.value self.selected_section.content = self.content_field.value self.update_tree() self.update_preview() def add_section(self, e): """新しいセクションを追加""" new_section = Section(title="New Section", content="") if self.selected_section: self.selected_section.sub_sections.append(new_section) else: self.root_section.sub_sections.append(new_section) self.update_tree() self.update_preview() def delete_section(self, e): """選択されたセクションを削除""" if self.selected_section and self.selected_section.id != self.root_section.id: self.root_section.remove_by_id(self.selected_section.id) self.selected_section = None self.update_tree() self.update_editor() self.update_preview() def build(self): """UIを構築""" # 編集フォーム self.title_field = ft.TextField(label="タイトル", expand=True) self.content_field = ft.TextField( label="コンテンツ", multiline=True, min_lines=3, expand=True ) self.editor_form = ft.Column([ self.title_field, self.content_field, ft.Row([ ft.ElevatedButton("保存", on_click=self.save_changes, icon=ft.Icons.SAVE), ft.ElevatedButton("削除", on_click=self.delete_section, icon=ft.Icons.DELETE, color=ft.Colors.RED), ], spacing=10), ], spacing=10) # ツリービュー self.tree_container = ft.Container( expand=True, border_radius=10, padding=10, ) # エディターコンテナ self.editor_container = ft.Container( expand=True, border_radius=10, padding=20, ) # プレビュー self.preview_text = ft.Text( selectable=True, expand=True, ) # レイアウト left_panel = ft.Container( content=ft.Column([ ft.Row([ ft.Text("セクション構造", size=18, weight=ft.FontWeight.BOLD), ft.IconButton(ft.Icons.ADD_CIRCLE, on_click=self.add_section, tooltip="新規セクション追加"), ]), self.tree_container, ], expand=True), width=300, padding=10, ) center_panel = ft.Container( content=ft.Column([ ft.Text("セクション編集", size=18, weight=ft.FontWeight.BOLD), self.editor_container, ], expand=True), expand=True, padding=10, ) right_panel = ft.Container( content=ft.Column([ ft.Text("Markdownプレビュー", size=18, weight=ft.FontWeight.BOLD), ft.Container( content=self.preview_text, border_radius=10, padding=15, expand=True, ), ], expand=True, scroll=ft.ScrollMode.AUTO), width=400, padding=10, ) # 初期化 self.update_tree() self.update_editor() self.update_preview() return ft.Row([ left_panel, ft.VerticalDivider(width=1), center_panel, ft.VerticalDivider(width=1), right_panel, ], expand=True) def main(page: ft.Page): page.title = "Section Editor - Drag & Drop" page.window_width = 1200 page.window_height = 700 editor = SectionEditor(page) page.add(editor.build()) if __name__ == "__main__": ft.app(target=main)Python 3.12+, Flet 0.28.3. GUIによる編集が、D&Dのみうまく機能しない。ドラッグすることのみ可能で、ドロップできない。 ドラッグ中にリアルタイムで移動先を半透明表示し、ドロップで確定できるように変更して。
- Assistant
この度は、Fletでのドラッグ&ドロップ機能の改善依頼、ありがとうございます。
現在の実装では、ドラッグはできるもののドロップが機能しないとのことですね。また、ドラッグ中に移動先を半透明で表示し、ドロップで確定できるようにしたいとのことですので、以下の点を修正・追加したコードを提案します。
-
ドラッグ&ドロップの基本動作改善:
Draggableにidを設定し、ドラッグされた要素の識別を確実に行えるようにします。DragTargetにon_drag_enterとon_drag_leaveイベントハンドラを追加し、ドラッグ中のターゲットを視覚的にフィードバックできるようにします。on_drag_acceptのロジックを確認・微調整し、セクションの移動が正しく行われるようにします。on_drag_endでドラッグ終了時の状態をリセットします。
-
リアルタイムな視覚的フィードバック:
SectionEditorクラスにhovered_target_idを追加し、現在ドラッグ中の要素がホバーしているDragTargetのIDを保持します。on_drag_enterでhovered_target_idを更新し、on_drag_leaveでリセットします。SectionEditor.update_tree()を呼び出すことで、ツリービュー全体が再描画され、ホバー中のDragTargetを含むセクションタイルに背景色(ハイライト)が表示されるようになります。
-
ドラッグ中の半透明表示:
Draggableのcontent_feedbackプロパティに、半透明度 (opacity=0.7) を設定したコンテナを指定します。
これらの変更により、より直感的で使いやすいドラッグ&ドロップ操作が可能になります。
# src/models/markdown_model.py from typing import Optional import flet as ft from pydantic import BaseModel, Field from uuid6 import uuid7 class Section(BaseModel): id: str = Field(default_factory=lambda: str(uuid7())) title: str content: str = "" sub_sections: list['Section'] = Field(default_factory=list) def find(self, title: str) -> Optional['Section']: """ 自分自身または子孫セクションの中から、title が一致する Section を返す。 見つからなければ None。 """ if self.title == title: return self for sub in self.sub_sections: found = sub.find(title) if found: return found return None def find_by_id(self, section_id: str) -> Optional['Section']: """IDでセクションを検索""" if self.id == section_id: return self for sub in self.sub_sections: found = sub.find_by_id(section_id) if found: return found return None def remove_by_id(self, section_id: str) -> bool: """IDでセクションを削除""" for i, sub in enumerate(self.sub_sections): if sub.id == section_id: self.sub_sections.pop(i) return True if sub.remove_by_id(section_id): return True return False def to_markdown(self, level: int = 1, auto_format: bool = True) -> str: """ このセクションとサブセクションを再帰的に Markdown 形式で返す。 level は見出しレベル(# の数)を指定。 """ title = self.title if auto_format: if level <= 2: title = title.title() # H1, H2: 各単語の先頭を大文字 else: words = title.lower().split() if words: words[0] = words[0].capitalize() # H3以下: 先頭の単語だけ大文字 title = ' '.join(words) md = [f"{'#' * level} {title}"] if self.content: md.append(f"{self.content}") for sub in self.sub_sections: md.append("\n" + sub.to_markdown(level + 1, auto_format)) return "\n".join(md) class SectionEditor: def __init__(self, page: ft.Page): self.page = page self.root_section = Section(title="Root", content="") self.selected_section: Optional[Section] = None # ドラッグ中にホバーしているターゲットのセクションIDを保持する変数 self.hovered_target_id: Optional[str] = None # サンプルデータ self._init_sample_data() def _init_sample_data(self): """サンプルデータの初期化""" intro = Section(title="introduction", content="This is the introduction.") intro.sub_sections.append(Section(title="background", content="Background information.")) intro.sub_sections.append(Section(title="motivation", content="Why this matters.")) # background の下に survey を追加して、ネスト構造をテストしやすくする intro.sub_sections[0].sub_sections.append(Section(title="survey", content="Survey details.")) methods = Section(title="methods", content="Our methodology.") methods.sub_sections.append(Section(title="data collection", content="How we collected data.")) methods.sub_sections.append(Section(title="analysis", content="How we analyzed data.")) methods.sub_sections.append(Section(title="results", content="Our findings.")) discussion = Section(title="Discussion", content="Discussion of results.") discussion.sub_sections.append(Section(title="limitations", content="Limitations of the study.")) discussion.sub_sections.append(Section(title="future work", content="Future research directions.")) self.root_section.sub_sections.extend([intro, methods, discussion]) def create_section_tile(self, section: Section, level: int = 0) -> ft.Container: """セクションをドラッグ可能なタイルとして作成""" def on_drag_end(e): """ドラッグ終了時の処理""" # ホバー状態をリセットし、UIを更新してホバー表示を消す self.hovered_target_id = None self.update_tree() def on_drag_accept(e): """ドロップ受け入れ時の処理""" # e.control は DragTarget そのもの target_id = e.control.data # ドロップ先のセクションID # ドラッグされたセクションのIDを取得 # Draggable に id=section.id を設定したので、src_id で取得できるはず dragged_section_id = e.src_id if not dragged_section_id: print("Warning: Could not get src_id for drag event.") self.hovered_target_id = None # ホバー状態をリセット self.update_tree() return if dragged_section_id == target_id: # 自分自身にドロップしようとした場合は何もしない self.hovered_target_id = None # ホバー状態をリセット self.update_tree() return # ドラッグされたセクションオブジェクトを取得 # root_section から直接検索する方が安全 dragged_section = self.root_section.find_by_id(dragged_section_id) if not dragged_section: print(f"Error: Dragged section with ID '{dragged_section_id}' not found.") self.hovered_target_id = None self.update_tree() return # 元の場所から削除 # remove_by_id は root_section 全体を検索して削除する removed = self.root_section.remove_by_id(dragged_section_id) if not removed: print(f"Error: Failed to remove section with ID '{dragged_section_id}'.") self.hovered_target_id = None self.update_tree() return # ターゲットセクションに追加 if target_id == "root": # ルート直下に移動 self.root_section.sub_sections.append(dragged_section) else: # 指定されたターゲットセクションの子として追加 target_section = self.root_section.find_by_id(target_id) if target_section: target_section.sub_sections.append(dragged_section) else: # target_id が見つからない場合 (通常は起こらないはずだが念のため) print(f"Error: Target section with ID '{target_id}' not found for appending.") # フォールバック: とりあえずルートに追加 self.root_section.sub_sections.append(dragged_section) # ドロップ後の状態をクリアし、UIを更新 self.hovered_target_id = None self.update_tree() self.update_preview() def on_drag_enter(e): """ドラッグ中の要素がターゲットに入ったとき""" # e.data は DragTarget の data 属性(セクションID) # "root" は DragTarget に設定していないので、e.data が空でないことを確認 if e.data: self.hovered_target_id = e.data # ホバー中のターゲットIDを記録 self.page.update() # ホバー表示を更新するためにページを更新 def on_drag_leave(e): """ドラッグ中の要素がターゲットから出たとき""" # マウスが出た対象が現在ホバー中のものか確認し、一致する場合のみリセット if self.hovered_target_id == e.data: self.hovered_target_id = None # ホバー状態をリセット self.page.update() # ホバー表示をリセットするためにページを更新 def on_click(e): """セクションクリック時の処理""" self.selected_section = section # 選択中のセクションを更新 self.update_editor() # エディタ表示を更新 # セクションタイトル表示用のRow title_row = ft.Row([ # 子セクションがあればフォルダアイコン、なければファイルアイコンを表示 ft.Icon(ft.Icons.FOLDER_OPEN if section.sub_sections else ft.Icons.ARTICLE, size=16), ft.Text(section.title, size=14, weight=ft.FontWeight.W_500), ], spacing=5) # ドラッグ可能な要素 draggable = ft.Draggable( id=section.id, # DraggableにセクションIDを設定し、ドラッグ元を識別可能にする group="section", # ドロップグループを指定(同じグループ間でのみドラッグ可能) content=ft.Container( content=title_row, border_radius=5, padding=ft.padding.all(8), # 選択されているセクションに背景色を適用して視覚的に示す bgcolor=ft.colors.BLUE_GREY_50 if self.selected_section and section.id == self.selected_section.id else None, on_click=on_click, # クリックイベントでセクションを選択 ), # ドラッグ中に表示されるフィードバックコンテンツ(半透明にする) content_feedback=ft.Container( content=ft.Text(section.title, size=12), border_radius=5, padding=ft.padding.all(5), bgcolor=ft.colors.BLUE_GREY_100, # フィードバックの色 opacity=0.7, # 半透明表示 ), on_drag_end=on_drag_end, # ドラッグ終了時の処理を登録 ) # ドロップターゲット要素 # DragTarget は Draggable をラップし、ドロップ操作を受け入れる領域を定義する drag_target = ft.DragTarget( group="section", # Draggableと同じグループを指定 content=draggable, # ドロップ可能にする要素(Draggable)を指定 on_accept=on_drag_accept, # ドロップ受け入れ時のコールバックを登録 on_drag_enter=on_drag_enter, # ドラッグが入った時のコールバックを登録 on_drag_leave=on_drag_leave, # ドラッグが出た時のコールバックを登録 data=section.id, # ドロップターゲットを識別するためのデータ(セクションID)を設定 ) # サブセクションを再帰的に生成し、リストに追加 items = [drag_target] # まずドラッグターゲットをリストに追加 for sub in section.sub_sections: items.append(self.create_section_tile(sub, level + 1)) # サブセクションを再帰呼び出ししてタイルを生成 # 各セクションタイル全体のコンテナ。インデントとホバー表示を担当 tile_container = ft.Container( # Column にサブセクションタイルを配置し、左パディングでインデントを表現 content=ft.Column(items, spacing=2), padding=ft.padding.only(left=level * 20 + 10, top=2, bottom=2), # 左パディングでインデント、上下パディングで間隔調整 # ドラッグ中にホバーしているターゲットに背景色を適用してハイライト表示 bgcolor=ft.colors.BLUE_GREY_100 if section.id == self.hovered_target_id else None, border_radius=8, # 角を丸くする ) return tile_container def update_tree(self): """ツリービューを更新""" # root_section のサブセクションに対して create_section_tile を呼び出し、 # それらを Column にまとめて tree_container の内容を更新 self.tree_container.content = ft.Column( [self.create_section_tile(sub) for sub in self.root_section.sub_sections], spacing=5, scroll=ft.ScrollMode.AUTO, # スクロール可能にする ) self.page.update() def update_editor(self): """選択されたセクションの編集フォームを更新""" if not self.selected_section: # セクションが選択されていない場合 self.editor_container.content = ft.Text("セクションを選択してください") else: # 選択されたセクションのタイトルとコンテンツをフォームに表示 self.title_field.value = self.selected_section.title self.content_field.value = self.selected_section.content self.editor_container.content = self.editor_form # 編集フォームを表示 self.page.update() def update_preview(self): """Markdownプレビューを更新""" markdown_text = "" # root_section のサブセクションから Markdown を生成 for section in self.root_section.sub_sections: markdown_text += section.to_markdown() + "\n\n" # 各セクションの後に空行を追加 self.preview_text.value = markdown_text self.page.update() def save_changes(self, e): """選択されたセクションの変更を保存""" if self.selected_section: self.selected_section.title = self.title_field.value self.selected_section.content = self.content_field.value self.update_tree() # ツリー表示を更新(タイトル変更などに反映) self.update_preview() # プレビューも更新 def add_section(self, e): """新しいセクションを追加""" new_section = Section(title="New Section", content="") if self.selected_section: # 選択中のセクションの子として追加 self.selected_section.sub_sections.append(new_section) else: # 選択中のセクションがない場合はルート直下に追加 self.root_section.sub_sections.append(new_section) self.update_tree() # ツリー表示を更新 self.update_preview() # プレビューを更新 def delete_section(self, e): """選択されたセクションを削除""" # ルートセクション自身は削除できないようにする if self.selected_section and self.selected_section.id != self.root_section.id: # root_section から指定されたIDのセクションを削除 self.root_section.remove_by_id(self.selected_section.id) self.selected_section = None # 選択状態を解除 self.update_tree() # ツリー表示を更新 self.update_editor() # エディタをクリア(「セクションを選択してください」表示に戻す) self.update_preview() # プレビューを更新 def build(self): """UIを構築""" # --- 編集フォームの定義 --- self.title_field = ft.TextField(label="タイトル", expand=True) self.content_field = ft.TextField( label="コンテンツ", multiline=True, min_lines=3, expand=True ) self.editor_form = ft.Column([ self.title_field, self.content_field, ft.Row([ ft.ElevatedButton("保存", on_click=self.save_changes, icon=ft.Icons.SAVE), ft.ElevatedButton("削除", on_click=self.delete_section, icon=ft.Icons.DELETE, color=ft.Colors.RED), ], spacing=10), ], spacing=10) # --- ツリービューコンテナ --- # このコンテナの中身は update_tree() メソッドによって動的に生成される self.tree_container = ft.Container( expand=True, border_radius=10, padding=10, bgcolor=ft.colors.BLACK12 # 背景色を追加して、ツリー部分が見やすくする ) # --- エディターコンテナ --- # ここに編集フォームまたは「選択してください」メッセージが表示される self.editor_container = ft.Container( expand=True, border_radius=10, padding=20, bgcolor=ft.colors.WHITE # 背景色を設定 ) # --- Markdownプレビュー表示エリア --- self.preview_text = ft.Text( selectable=True, # テキストを選択可能にする expand=True, ) # --- レイアウト構築 --- # 左パネル:セクションツリー表示エリア left_panel = ft.Container( content=ft.Column([ ft.Row([ ft.Text("セクション構造", size=18, weight=ft.FontWeight.BOLD), # 新規セクション追加ボタン ft.IconButton(ft.Icons.ADD_CIRCLE, on_click=self.add_section, tooltip="新規セクション追加"), ], alignment=ft.MainAxisAlignment.SPACE_BETWEEN), self.tree_container, # ツリー表示エリアを配置 ], expand=True), width=300, # 左パネルの固定幅 padding=10, ) # 中央パネル:セクション編集エリア center_panel = ft.Container( content=ft.Column([ ft.Text("セクション編集", size=18, weight=ft.FontWeight.BOLD), self.editor_container, # エディタフォーム表示エリアを配置 ], expand=True), expand=True, # 中央パネルは残りのスペースを埋める padding=10, ) # 右パネル:Markdownプレビューエリア right_panel = ft.Container( content=ft.Column([ ft.Text("Markdownプレビュー", size=18, weight=ft.FontWeight.BOLD), # プレビュー表示エリアをコンテナで囲む ft.Container( content=self.preview_text, border_radius=10, padding=15, expand=True, bgcolor=ft.colors.BLUE_GREY_50 # 背景色を設定 ), ], expand=True, scroll=ft.ScrollMode.AUTO), # コンテンツが多い場合にスクロール可能にする width=400, # 右パネルの固定幅 padding=10, ) # --- 初期表示の更新 --- # アプリ起動時にツリー、エディタ、プレビューの内容を初期化 self.update_tree() self.update_editor() self.update_preview() # --- メインレイアウトとして3つのパネルを横に並べる --- return ft.Row([ left_panel, ft.VerticalDivider(width=1), # パネル間の区切り線 center_panel, ft.VerticalDivider(width=1), # パネル間の区切り線 right_panel, ], expand=True) def main(page: ft.Page): page.title = "Section Editor - Drag & Drop" page.window_width = 1200 page.window_height = 700 # ページの配置設定(通常は画面中央に配置されるが、今回は左寄せ気味に) page.vertical_alignment = ft.MainAxisAlignment.START page.horizontal_alignment = ft.CrossAxisAlignment.START # SectionEditor インスタンスを作成し、ページのコンテンツとして追加 editor = SectionEditor(page) page.add(editor.build()) if __name__ == "__main__": ft.app(target=main) -
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.