Line data Source code
1 : package pagination
2 :
3 : import "fmt"
4 :
5 : // Pagination はペジネーション状態を管理する
6 : type Pagination struct {
7 : ItemIndex int // 現在選択中のアイテムインデックス(全体での位置)
8 : Page int // 現在のページ(0ベース)
9 : ItemCount int // アイテム総数
10 : ItemsPerPage int // 1ページあたりのアイテム数
11 : }
12 :
13 : // New はPaginationを作成する
14 : // pageはitemIndexから自動計算される。
15 : // カーソルを持たない一覧は負の itemIndex を渡す。どのページにも属さないので先頭ページを返す
16 : func New(itemIndex, itemCount, itemsPerPage int) Pagination {
17 1 : page := 0
18 1 : if itemsPerPage > 0 && itemCount > 0 && itemIndex > 0 {
19 1 : page = itemIndex / itemsPerPage
20 1 : }
21 1 : return Pagination{
22 1 : ItemIndex: itemIndex,
23 1 : Page: page,
24 1 : ItemCount: itemCount,
25 1 : ItemsPerPage: itemsPerPage,
26 1 : }
27 : }
28 :
29 : // GetCurrentPage は現在のページ番号を返す(表示用なので1ベース)
30 : func (p Pagination) GetCurrentPage() int {
31 1 : return p.Page + 1
32 1 : }
33 :
34 : // GetTotalPages は総ページ数を返す
35 : func (p Pagination) GetTotalPages() int {
36 : // アイテムが無いか負数のときは1ページに丸める。負数は総数として不正だが、
37 : // 呼び出し側にガードを書かせず、ページ計算の所有者であるここで吸収する
38 1 : if p.ItemsPerPage <= 0 || p.ItemCount <= 0 {
39 1 : return 1
40 1 : }
41 1 : return (p.ItemCount + p.ItemsPerPage - 1) / p.ItemsPerPage
42 : }
43 :
44 : // GetVisibleRange は現在のページで表示するアイテムの範囲を返す(start, end)
45 : func (p Pagination) GetVisibleRange() (start, end int) {
46 1 : if p.ItemsPerPage <= 0 {
47 1 : return 0, p.ItemCount
48 1 : }
49 1 : start = p.Page * p.ItemsPerPage
50 1 : end = min(start+p.ItemsPerPage, p.ItemCount)
51 1 : if start >= p.ItemCount {
52 1 : return 0, 0
53 1 : }
54 1 : return start, end
55 : }
56 :
57 : // IsEnabled はペジネーションが有効か(複数ページあるか)を返す
58 : func (p Pagination) IsEnabled() bool {
59 1 : return p.GetTotalPages() > 1
60 1 : }
61 :
62 : // IsSelectedInPage は指定インデックスが現在のページ内で選択中かを返す
63 : func (p Pagination) IsSelectedInPage(index int) bool {
64 1 : return index == p.ItemIndex
65 1 : }
66 :
67 : // GetPageText はシンプルなページテキストを返す
68 : // 例: "2/5"
69 : func (p Pagination) GetPageText() string {
70 1 : if !p.IsEnabled() {
71 1 : return ""
72 1 : }
73 1 : return fmt.Sprintf("%d/%d", p.GetCurrentPage(), p.GetTotalPages())
74 : }
75 :
76 : // IndexedItem は元のインデックスを保持したアイテム
77 : type IndexedItem[T any] struct {
78 : Index int
79 : Item T
80 : }
81 :
82 : // VisibleEntries は現在ページの要素と元のインデックスを返す
83 : func VisibleEntries[T any](items []T, p Pagination) []IndexedItem[T] {
84 1 : start, end := p.GetVisibleRange()
85 1 : if start >= len(items) {
86 1 : return nil
87 1 : }
88 1 : if end > len(items) {
89 1 : end = len(items)
90 1 : }
91 :
92 1 : result := make([]IndexedItem[T], end-start)
93 1 : for i := start; i < end; i++ {
94 1 : result[i-start] = IndexedItem[T]{
95 1 : Index: i,
96 1 : Item: items[i],
97 1 : }
98 : }
99 :
100 1 : return result
101 : }
|