val-town / codemirror-ts

lint, hover, and autocomplete extensions for CodeMirror + TypeScript
https://val-town.github.io/codemirror-ts/
ISC License
105 stars 6 forks source link

Bug: TS server stops working after file gets emptied out #23

Closed nandorojo closed 1 month ago

nandorojo commented 1 month ago

Hey guys, thanks for the useful library here. Wanted to share a few cases where it breaks.

If you clear the text of the editor, then the autocomplete/TS server stops working. Here's a video to show it on the homepage:

https://github.com/val-town/codemirror-ts/assets/13172299/d50bb321-d858-4fba-884a-363755e4fc4e

I tried on both v1.0.0 (which is on the Stackblitz example from the docs) and on 2.1.0 locally.

nandorojo commented 1 month ago
Screenshot 2024-05-13 at 7 27 53 PM

Digging a bit deeper, it looks like, once the text has been removed, any attempt to open the suggestions throws this error from the getAutocompletion function. I'll see if I can find a solution. The issue happens here:

https://github.com/val-town/codemirror-ts/blob/4ca28461617756492721ef16d6e2b70e8dc53756/src/autocomplete/getAutocompletion.ts#L41

nandorojo commented 1 month ago

I have a hunch it may be due to this line:

https://github.com/val-town/codemirror-ts/blob/4ca28461617756492721ef16d6e2b70e8dc53756/src/sync/update.ts#L17

If I recall correctly, the TS language service might need a non-empty file. So it's possible that the fix is to pass code || ' ' where an empty string is the fallback to avoid breaking the service. I'll see if this makes a difference, though it might be something else.

nandorojo commented 1 month ago

I confirmed that that was indeed the issue. Adding a fallback here fixed it:

export function tsSync() {
  let first = true
  return EditorView.updateListener.of((update) => {
    const config = update.view.state.facet(tsFacet)
    if (!config) return
    if (!update.docChanged && !first) return
    first = false
    createOrUpdateFile(config.env, config.path, update.state.doc.toString() || ' ') // <- this is the fix
  })
}
nandorojo commented 1 month ago

PR opened: https://github.com/val-town/codemirror-ts/pull/24