from enum import auto, IntEnum from typing import Optional from PySide6.QtCore import QAbstractListModel, QByteArray, QModelIndex, QObject, QPersistentModelIndex, QStandardPaths, QUrl, Qt, Signal, Slot, Property from PySide6.QtQml import QmlElement from kodereviewer.data import Comment, PullRequest QML_IMPORT_NAME = "org.deprecated.kodereviewer" QML_IMPORT_MAJOR_VERSION = 1 @QmlElement class CommentModel(QAbstractListModel): _pull_request: Optional[PullRequest] class Roles(IntEnum): Body = Qt.ItemDataRole.UserRole + 1 CreatedAt = auto() UpdatedAt = auto() Username = auto() AvatarUrl = auto() def __init__(self): super().__init__() self._pull_request = None def get_pull_request(self) -> Optional[PullRequest]: return self._pull_request def set_pull_request(self, pull_request: Optional[PullRequest]) -> None: if pull_request is None: return if self._pull_request is not None and self._pull_request == pull_request: return self.beginResetModel() self._pull_request = pull_request self._pull_request.commentsLoaded.connect(self._reset_model) self.endResetModel() self.pullRequestChanged.emit() pullRequestChanged = Signal() pullRequest = Property(PullRequest, fget=get_pull_request, fset=set_pull_request, notify=pullRequestChanged) def _reset_model(self) -> None: self.beginResetModel() self.endResetModel() def data(self, index: QModelIndex | QPersistentModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> object: if self._pull_request is None: return None comment: Comment = self._pull_request._comments[index.row()] if role == self.Roles.Body: return comment._body if role == self.Roles.CreatedAt: return comment._created_at.strftime("%Y-%M-%d %H:%m") if role == self.Roles.UpdatedAt: return comment._updated_at.strftime("%Y-%M-%d %H:%m") if role == self.Roles.Username: return comment._user._username if role == self.Roles.AvatarUrl: return comment._user._avatar_url if role == Qt.ItemDataRole.DisplayRole: return comment._body return None def rowCount(self, parent: QModelIndex | QPersistentModelIndex = QModelIndex()) -> int: if self._pull_request is None: return 0 return len(self._pull_request._comments) def roleNames(self) -> dict[int, QByteArray]: return { self.Roles.Body: QByteArray(b'body'), self.Roles.CreatedAt: QByteArray(b'createdAt'), self.Roles.UpdatedAt: QByteArray(b'updatedAt'), self.Roles.Username: QByteArray(b'username'), self.Roles.AvatarUrl: QByteArray(b'avatarUrl'), }