view src/ltpdarepo/pagination.py @ 154:2429e9db4f34

Fix activity view.
author Daniele Nicolodi <nicolodi@science.unitn.it>
date Wed, 26 Oct 2011 20:13:12 +0200
parents 90c1fa07f6a7
children fbab144c296c
line wrap: on
line source

from math import ceil, floor

class Pagination(object):
    def __init__(self, page=1, count=10, size=10, items=7):
        self.current = page
        self.size = size
        self.count = count
        self.items = items

    @property
    def pages(self):
        return int(ceil(self.count / float(self.size)))

    @property
    def has_prev(self):
        return self.current > 1

    @property
    def has_next(self):
        return self.current < self.pages

    @property
    def limits(self):
        start = (self.current - 1) * self.size
        return start, self.size

    def __iter__(self):
        # cache number of pages
        npages = self.pages
        
        # return early if no ellipsization is needed
        if npages < self.items:
            return iter(range(1, npages + 1))
        
        # begin and end of range surrounding the current page
        surrounding = float(self.items - 3) / 2
        begin = self.current - int(floor(surrounding))
        end = self.current + int(ceil(surrounding))

        # shift right within bounds
        if begin <= 2:
            offset = 2 - begin
            begin += offset
            end += offset

        # shift left within bounds
        elif end >= npages - 1:
            offset = npages - end - 1
            begin += offset
            end += offset

        # number range augmented with first and last page
        pages = range(begin, end + 1)
        pages.insert(0, 1)
        pages.append(npages)

        # left ellipsization if needed (with size of gap as negative number)
        if pages[1] != 2:
            pages[1] = 2 - pages[2]

        # right ellipsization if needed (with size of gap as negative number)
        if pages[-2] != npages - 1:
            pages[-2] = 1 + pages[-3] - npages
            
        return iter(pages)