gregorias / anki-code-highlighter

Anki plugin for code syntax highlighting.
GNU Affero General Public License v3.0
59 stars 3 forks source link

web_editor_html can sometimes be None due to surroundContents() faili… #35

Closed dhiren2 closed 1 year ago

dhiren2 commented 1 year ago

There are cases where surroundContents() will fail. In this case, web_editor_html will be None, and then the regular expression search will throw an exception:

JS error /_anki/legacyPageData?id=5842112864:9 Uncaught InvalidStateError: Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.
Caught exception:
Traceback (most recent call last):
  File "aqt.webview", line 562, in handler
  File "/Users/dhiren/Library/Application Support/Anki2/addons21/112228974/ankieditorextra.py", line 77, in transform_field
    field = extract_field_from_web_editor(web_editor_html)
  File "/Users/dhiren/Library/Application Support/Anki2/addons21/112228974/ankieditorextra.py", line 40, in extract_field_from_web_editor
    result = re.search('<anki-editable[^>]*>(.*)</anki-editable>',
  File "re", line 201, in search
TypeError: expected string or bytes-like object

This minor patch makes it fail silently so you don't get the exception.

gregorias commented 1 year ago

Thank you.

  1. Do you have a way to reproduce this or know why range.surroundContents would fail? I would like remain intellectual control over what's happening in my software.
  2. Rather than handle missing input deeper into the stack, the error should be handled close to where it's detected and type hints should model it. Could you modify transform_field instead, so that handling a JS failure is explicit: a. Add Optional to the argument's type hint. b. Add a guard clause that returns early.
gregorias commented 1 year ago

Re 1.: I just saw https://github.com/gregorias/anki-code-highlighter/issues/34#issuecomment-1402698972. No need to answer that.

gregorias commented 1 year ago

This PR is made obsolete by https://github.com/gregorias/anki-code-highlighter/commit/f92ba2c21c39c4d1e496e4ba54da639b5a5e388e.