Hook card_is_being_flushed

It often arrives that I want to know when a card is going to be
flushed and in this case change it.

This could be the case if I want to change the scheduler without
implementing a whole scheduler. It simply reads the card history and
change interval and due date.

It's also the case for the "'trigger -> action' rules", which apply
some coded actions when some event occurs. E.g. suspend/unsuspend a
sibling when card become mature/is forgotten.
This commit is contained in:
Arthur Milchior 2020-02-11 16:23:20 -08:00
parent 81daad878e
commit fcfa78bba3
3 changed files with 33 additions and 1 deletions

View file

@ -84,7 +84,8 @@ class Card:
self._render_output = None self._render_output = None
self._note = None self._note = None
def _preFlush(self) -> none: def _preFlush(self) -> None:
hooks.card_will_flush(self)
self.mod = intTime() self.mod = intTime()
self.usn = self.col.usn() self.usn = self.col.usn()
# bug check # bug check

View file

@ -134,6 +134,32 @@ class _CardOdueWasInvalidHook:
card_odue_was_invalid = _CardOdueWasInvalidHook() card_odue_was_invalid = _CardOdueWasInvalidHook()
class _CardWillFlushHook:
"""Allow to change a card before it is added/updated in the database."""
_hooks: List[Callable[[Card], None]] = []
def append(self, cb: Callable[[Card], None]) -> None:
"""(card: Card)"""
self._hooks.append(cb)
def remove(self, cb: Callable[[Card], None]) -> None:
if cb in self._hooks:
self._hooks.remove(cb)
def __call__(self, card: Card) -> None:
for hook in self._hooks:
try:
hook(card)
except:
# if the hook fails, remove it
self._hooks.remove(hook)
raise
card_will_flush = _CardWillFlushHook()
class _DeckAddedHook: class _DeckAddedHook:
_hooks: List[Callable[[Dict[str, Any]], None]] = [] _hooks: List[Callable[[Dict[str, Any]], None]] = []

View file

@ -72,6 +72,11 @@ hooks = [
args=["note: Note"], args=["note: Note"],
doc="Allow to change a note before it is added/updated in the database.", doc="Allow to change a note before it is added/updated in the database.",
), ),
Hook(
name="card_will_flush",
args=["card: Card"],
doc="Allow to change a card before it is added/updated in the database.",
),
Hook( Hook(
name="card_did_render", name="card_did_render",
args=[ args=[