Signal to track CellModel state change not working

I am trying to have a callback function called when the active cell in the notebook changes its cell type (code, raw, markdown). I am retrieving the currently active cell using the signal NotebookPanel.content.activeCellChanged (and it works).

Then in am hooking to the Cell returned by signal callback with Cell.model.contentChanged but it never fires (I also tried using Cell.model.stateChanged, but it does not work either - and I actually did not understand the difference between the two).

What am I doing wrong?

Hi @Stefano_Fioravanzo, great question.

I agree that the stateChanged signal is confusing, and I have actually been advocating that we remove it. That is fired only in a few specific circumstances, like when the trusted or readonly state changes. Normally, contentChanged would be what you want except in this instance. This is because we internally implement changing a cell type by removing the old cell and inserting a new one with the same text content. So you can’t listen to change signals on the old one as it is not really the same cell.

I can’t think of a super clean way to do what you are describing, but a hack like the following could work:

  1. Listen to the model.cells.changed signal.
  2. If a cell is deleted, cache the text content and type of the cell.
  3. If a cell is subsequently inserted, check to see if it is a new cell type with the same text content. That is your changed cell.
  4. If there is any other action, clear the cache.

Again, not super clean, but I think it could do what you describe. Hope this helps!

Thank you @ian-r-rose. Yes I was suspecting something like this. I will experiment with your suggested approach.
Just out of curiosity, is there a specific reason(s) for creating a new cell when changing the type, instead of mutating the existing one?