108 lines
3.4 KiB
Python
108 lines
3.4 KiB
Python
import asyncio
|
|
|
|
import flet as ft
|
|
|
|
from app.api.articles import list_articles
|
|
|
|
from app.state import state
|
|
|
|
def article_card(page, article):
|
|
async def go_detail(e):
|
|
await page.push_route(f"/articles/{article['id']}")
|
|
|
|
return ft.Card(
|
|
content=ft.Container(
|
|
padding=15,
|
|
content=ft.Column(
|
|
controls=[
|
|
ft.Text(article['title'], size=18, weight=ft.FontWeight.BOLD),
|
|
ft.Text(article.get('body', ''), max_lines=2),
|
|
ft.TextButton(
|
|
'อ่านต่อ',
|
|
on_click=go_detail,
|
|
)
|
|
]
|
|
)
|
|
)
|
|
)
|
|
|
|
def articles_page(page: ft.Page):
|
|
articles_column = ft.Column(expand=True, spacing=10)
|
|
search_field = ft.TextField(
|
|
hint_text="ค้นหาบทความ",
|
|
prefix_icon=ft.Icons.SEARCH,
|
|
)
|
|
|
|
current_page = {'value':1}
|
|
|
|
page_text = ft.Text(value=f"หน้า {current_page['value']}")
|
|
# สร้างปุ่ม
|
|
btn_prev = ft.OutlinedButton('ก่อนหน้า', disabled=True)
|
|
btn_next = ft.OutlinedButton('ถัดไป', disabled=True)
|
|
|
|
async def load_articles():
|
|
articles_column.controls.clear()
|
|
articles_column.controls.append(ft.ProgressRing())
|
|
|
|
btn_prev.disabled = True
|
|
btn_next.disabled = True
|
|
|
|
page.update()
|
|
|
|
try:
|
|
data = await asyncio.to_thread(
|
|
list_articles,
|
|
page=current_page['value'],
|
|
search=search_field.value,
|
|
token=state.access_token,
|
|
)
|
|
|
|
# อัปเดตสถานะปุ่มจากข้อมูล Backend
|
|
btn_prev.disabled = data.get('previous') is None
|
|
btn_next.disabled = data.get('next') is None
|
|
page_text.value = f"หน้า {current_page['value']}"
|
|
|
|
articles_column.controls.clear()
|
|
for item in data.get('results', []):
|
|
articles_column.controls.append(article_card(page, item))
|
|
|
|
if not data.get('results'):
|
|
articles_column.controls.append(ft.Text("ไม่พบบทความ"))
|
|
|
|
except Exception as e:
|
|
articles_column.controls.clear()
|
|
articles_column.controls.append(ft.Text(f"เกิดข้อผิดพลาด: {e}", color=ft.Colors.RED))
|
|
btn_prev.disabled = current_page['value'] <= 1
|
|
btn_next.disabled = True
|
|
|
|
page.update()
|
|
|
|
# Logic การเปลี่ยนหน้า
|
|
async def change_page(delta):
|
|
current_page['value'] += delta
|
|
await load_articles()
|
|
btn_prev.on_click = lambda e: asyncio.create_task(change_page(-1))
|
|
btn_next.on_click = lambda e: asyncio.create_task(change_page(1))
|
|
|
|
def on_search(e):
|
|
current_page['value'] = 1
|
|
asyncio.create_task(load_articles())
|
|
|
|
search_field.on_submit = on_search
|
|
|
|
controls = ft.Column(
|
|
controls=[
|
|
ft.Text('บทความ', size=24),
|
|
ft.Row([search_field]),
|
|
articles_column,
|
|
ft.Row(
|
|
controls=[btn_prev, page_text, btn_next],
|
|
alignment=ft.MainAxisAlignment.CENTER
|
|
)
|
|
],
|
|
expand=True,
|
|
)
|
|
|
|
asyncio.create_task(load_articles())
|
|
return controls
|