Skip to content
The Chat Archive
claude-opus-4-20250514-thinking-16k· Anthropic LMArena Human Preference 140K

Untitled conversation

  1. User
    class Section(BaseModel):
        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 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)
    

    Python 3.12+, Flet 0.28.3. この構造をGUIからD&Dで編集できるようなものを作って。

  2. Assistant

    FletでSectionクラスの階層構造をドラッグ&ドロップで編集できるGUIアプリケーションを作成します。

    import flet as ft
    from typing import Optional, List
    from pydantic import BaseModel, Field
    import uuid
    
    class Section(BaseModel):
        id: str = Field(default_factory=lambda: str(uuid.uuid4()))
        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,
                    bgcolor=ft.colors.BLUE_50,
                    border_radius=5,
                    padding=ft.padding.all(8),
                    on_click=on_click,
                ),
                content_feedback=ft.Container(
                    content=ft.Text(section.title, size=12),
                    bgcolor=ft.colors.BLUE_100,
                    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,
                bgcolor=ft.colors.GREY_50,
                border_radius=10,
                padding=10,
            )
            
            # エディターコンテナ
            self.editor_container = ft.Container(
                expand=True,
                bgcolor=ft.colors.WHITE,
                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,
                        bgcolor=ft.colors.GREY_100,
                        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())
    
    ft.app(target=main)
    

    このアプリケーションの主な機能:

    1. ドラッグ&ドロップ: セクションをドラッグして他のセクションの子要素として配置できます
    2. セクション編集: セクションをクリックして、タイトルとコンテンツを編集
    3. セクション追加: +ボタンで新しいセクションを追加
    4. セクション削除: 選択したセクションを削除ボタンで削除
    5. リアルタイムプレビュー: 右側にMarkdown形式でプレビュー表示
    6. 階層構造の視覚化: インデントでセクションの階層を表現

    使い方:

    • 左側のツリーでセクションをドラッグして構造を変更
    • セクションをクリックして編集
    • +ボタンで新規セクション追加
    • 編集後は「保存」ボタンで変更を反映
  3. User

    D&Dがうまく機能しない。微調整して。

  4. Assistant

    ドラッグ&ドロップの動作を改善したバージョンです:

    import flet as ft
    from typing import Optional, List
    from pydantic import BaseModel, Field
    import uuid
    
    class Section(BaseModel):
        id: str = Field(default_factory=lambda: str(uuid.uuid4()))
        title: str
        content: str = ""
        sub_sections: List['Section'] = Field(default_factory=list)
    
        def find(self, title: str) -> Optional['Section']:
            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']:
            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 find_parent(self, section_id: str) -> Optional['Section']:
            """指定されたIDのセクションの親を検索"""
            for sub in self.sub_sections:
                if sub.id == section_id:
                    return self
                parent = sub.find_parent(section_id)
                if parent:
                    return parent
            return None
    
        def remove_by_id(self, section_id: str) -> bool:
            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:
            title = self.title
            if auto_format:
                if level <= 2:
                    title = title.title()
                else:
                    words = title.lower().split()
                    if words:
                        words[0] = words[0].capitalize()
                        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.dragging_section_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."))
            
            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_click(e):
                self.selected_section = section
                self.update_editor()
    
            def on_drag_start(e: ft.DragStartEvent):
                self.dragging_section_id = section.id
                self.page.update()
    
            def on_drag_complete(e: ft.DragEndEvent):
                self.dragging_section_id = None
                self.page.update()
    
            def on_will_accept(e: ft.DragTargetAcceptEvent):
                # ドラッグ中の要素が自分自身でないことを確認
                if self.dragging_section_id and self.dragging_section_id != section.id:
                    e.control.content.border = ft.border.all(2, ft.colors.BLUE_400)
                    e.control.update()
    
            def on_leave(e: ft.DragTargetLeaveEvent):
                e.control.content.border = ft.border.all(1, ft.colors.GREY_300)
                e.control.update()
    
            def on_accept(e: ft.DragTargetAcceptEvent):
                e.control.content.border = ft.border.all(1, ft.colors.GREY_300)
                
                src_id = e.data
                if src_id == section.id:
                    return
                
                # ドラッグされたセクションを探す
                dragged_section = self.root_section.find_by_id(src_id)
                if not dragged_section:
                    return
                
                # 元の場所から削除
                self.root_section.remove_by_id(src_id)
                
                # ターゲットセクションに追加
                section.sub_sections.append(dragged_section)
                
                self.update_tree()
                self.update_preview()
    
            # セクションコンテンツ
            content = ft.Container(
                content=ft.Row([
                    ft.Icon(
                        ft.icons.FOLDER_OPEN if section.sub_sections else ft.icons.ARTICLE,
                        size=16,
                        color=ft.colors.BLUE_700,
                    ),
                    ft.Text(
                        section.title,
                        size=14,
                        weight=ft.FontWeight.W_500,
                        color=ft.colors.BLACK87,
                    ),
                ], spacing=5),
                bgcolor=ft.colors.BLUE_50 if self.selected_section and self.selected_section.id == section.id else ft.colors.WHITE,
                border=ft.border.all(1, ft.colors.GREY_300),
                border_radius=5,
                padding=ft.padding.all(8),
                on_click=on_click,
            )
    
            # ドラッグ可能な要素
            draggable = ft.Draggable(
                group="section",
                content=content,
                content_when_dragging=ft.Container(
                    content=ft.Text(f"Moving: {section.title}", size=12),
                    bgcolor=ft.colors.GREY_300,
                    padding=5,
                    border_radius=3,
                ),
                data=section.id,
                on_drag_start=on_drag_start,
                on_drag_complete=on_drag_complete,
            )
    
            # ドロップターゲット
            drop_target = ft.DragTarget(
                group="section",
                content=draggable,
                on_will_accept=on_will_accept,
                on_leave=on_leave,
                on_accept=on_accept,
            )
    
            # サブセクションのコンテナ
            items = [drop_target]
            if section.sub_sections:
                sub_items = []
                for sub in section.sub_sections:
                    sub_items.append(self.create_section_tile(sub, level + 1))
                
                items.append(
                    ft.Container(
                        content=ft.Column(sub_items, spacing=3),
                        padding=ft.padding.only(left=20),
                    )
                )
    
            return ft.Container(
                content=ft.Column(items, spacing=3),
                padding=ft.padding.only(left=level * 20),
            )
    
        def create_root_drop_zone(self):
            """ルートレベルへのドロップゾーン"""
            def on_will_accept(e):
                e.control.bgcolor = ft.colors.BLUE_100
                e.control.update()
    
            def on_leave(e):
                e.control.bgcolor = ft.colors.GREY_100
                e.control.update()
    
            def on_accept(e):
                e.control.bgcolor = ft.colors.GREY_100
                
                src_id = e.data
                dragged_section = self.root_section.find_by_id(src_id)
                if not dragged_section:
                    return
                
                # 元の場所から削除
                self.root_section.remove_by_id(src_id)
                
                # ルートに追加
                self.root_section.sub_sections.append(dragged_section)
                
                self.update_tree()
                self.update_preview()
    
            return ft.DragTarget(
                group="section",
                content=ft.Container(
                    content=ft.Row([
                        ft.Icon(ft.icons.HOME, size=14),
                        ft.Text("ここにドロップしてルートレベルに配置", size=12, italic=True),
                    ], spacing=5),
                    bgcolor=ft.colors.GREY_100,
                    border=ft.border.all(1, ft.colors.GREY_400, ft.BorderStyle.DASHED),
                    border_radius=5,
                    padding=10,
                    height=40,
                ),
                on_will_accept=on_will_accept,
                on_leave=on_leave,
                on_accept=on_accept,
            )
    
        def update_tree(self):
            tree_items = []
            
            # ルートドロップゾーン
            tree_items.append(self.create_root_drop_zone())
            
            # セクションタイル
            for section in self.root_section.sub_sections:
                tree_items.append(self.create_section_tile(section))
            
            self.tree_container.content = ft.Column(
                tree_items,
                spacing=5,
                scroll=ft.ScrollMode.AUTO,
            )
            self.page.update()
    
        def update_editor(self):
            if not self.selected_section:
                self.editor_container.content = ft.Container(
                    content=ft.Text("セクションを選択してください", color=ft.colors.GREY_600),
                    alignment=ft.alignment.center,
                )
            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_text = ""
            for section in self.root_section.sub_sections:
                markdown_text += section.to_markdown() + "\n\n"
            self.preview_text.value = markdown_text.strip()
            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()
                
                # 保存完了のスナックバー
                self.page.show_snack_bar(
                    ft.SnackBar(ft.Text("変更を保存しました"), bgcolor=ft.colors.GREEN_400)
                )
    
        def add_section(self, e):
            new_section = Section(title="新しいセクション", 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()
                
                self.page.show_snack_bar(
                    ft.SnackBar(ft.Text("セクションを削除しました"), bgcolor=ft.colors.RED_400)
                )
    
        def build(self):
            # 編集フォーム
            self.title_field = ft.TextField(
                label="タイトル",
                expand=True,
                border_color=ft.colors.BLUE_400,
            )
            self.content_field = ft.TextField(
                label="コンテンツ",
                multiline=True,
                min_lines=5,
                max_lines=10,
                expand=True,
                border_color=ft.colors.BLUE_400,
            )
            
            self.editor_form = ft.Column([
                self.title_field,
                self.content_field,
                ft.Row([
                    ft.ElevatedButton(
                        "保存",
                        on_click=self.save_changes,
                        icon=ft.icons.SAVE,
                        color=ft.colors.WHITE,
                        bgcolor=ft.colors.BLUE_600,
                    ),
                    ft.ElevatedButton(
                        "削除",
                        on_click=self.delete_section,
                        icon=ft.icons.DELETE,
                        color=ft.colors.WHITE,
                        bgcolor=ft.colors.RED_600,
                    ),
                ], spacing=10),
            ], spacing=15)
            
            # コンテナ
            self.tree_container = ft.Container(
                expand=True,
                bgcolor=ft.colors.GREY_50,
                border_radius=10,
                padding=15,
            )
            
            self.editor_container = ft.Container(
                expand=True,
                bgcolor=ft.colors.WHITE,
                border_radius=10,
                padding=20,
            )
            
            self.preview_text = ft.Text(
                selectable=True,
                expand=True,
                color=ft.colors.BLACK87,
            )
            
            # パネル
            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="新規セクション追加",
                            icon_color=ft.colors.BLUE_600,
                        ),
                    ]),
                    ft.Divider(height=1),
                    self.tree_container,
                ], expand=True),
                width=350,
                padding=10,
            )
            
            center_panel = ft.Container(
                content=ft.Column([
                    ft.Text("セクション編集", size=18, weight=ft.FontWeight.BOLD),
                    ft.Divider(height=1),
                    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.Divider(height=1),
                    ft.Container(
                        content=self.preview_text,
                        bgcolor=ft.colors.GREY_100,
                        border_radius=10,
                        padding=20,
                        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 = 1400
        page.window_height = 800
        page.padding = 0
        
        editor = SectionEditor(page)
        page.add(editor.build())
    
    ft.app(target=main)
    

    主な改善点:

    1. ドラッグ状態の管理: dragging_section_idで現在ドラッグ中のセクションを追跡
    2. 視覚的フィードバック: ドロップ可能な領域にホバーすると青い枠線が表示
    3. ルートレベルドロップゾーン: 最上部に専用のドロップエリアを追加
    4. ドラッグ中の表示: ドラッグ中は「Moving: [タイトル]」というラベルを表示
    5. 選択状態の視覚化: 選択中のセクションは背景色で強調表示
    6. スナックバー: 保存・削除時にフィードバックを表示

    使い方のヒント:

    • セクションをドラッグすると、ドロップ可能な場所が青い枠で表示されます
    • 最上部の「ここにドロップしてルートレベルに配置」にドロップすると、最上位階層に移動します
    • 他のセクションの上にドロップすると、そのセクションの子要素になります

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.