completion-logger.ts 900 B

12345678910111213141516171819202122232425262728
  1. import { ViewPlugin } from '@codemirror/view'
  2. import { pickedCompletion } from '@codemirror/autocomplete'
  3. import { emitCompletionEvent } from './toolbar/utils/analytics'
  4. /**
  5. * A custom view plugin that watches for transactions with the `pickedCompletion` annotation.
  6. * If the completion label starts with a command, log that command for analytics.
  7. */
  8. export const completionLogger = ViewPlugin.define(view => {
  9. return {
  10. update(update) {
  11. for (const tr of update.transactions) {
  12. const completion = tr.annotation(pickedCompletion)
  13. if (completion) {
  14. const command = completionCommand(completion.label)
  15. if (command) {
  16. emitCompletionEvent(view, command)
  17. }
  18. }
  19. }
  20. },
  21. }
  22. })
  23. const completionCommand = (label: string): string | null => {
  24. const matches = label.match(/^\\(\w+)/)
  25. return matches ? matches[1] : null
  26. }