Skip to content

Instantly share code, notes, and snippets.

@loilo
Last active August 27, 2023 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save loilo/4105105db7c9da74d1a37a1ac658a783 to your computer and use it in GitHub Desktop.
Save loilo/4105105db7c9da74d1a37a1ac658a783 to your computer and use it in GitHub Desktop.
Draftlog with Vue Reactivity

Draftlog with Vue Reactivity

Draftlog is a great tool for creating rich terminal logging experiences. However, using it feels kind of imperative when coming from a data-driven frontend world (insofar as you have to decide on your own when to re-apply data and call the draft function again).

This little code snippet marries Draftlog with the @vue/reactivity (one of the earlier implementation of the signals pattern in the web development world).

You basically keep using console.draft() just as before, but you can pass it reactive data which will cause the draft to update automatically when that data changes.

// Set up console.draft()
import './draftlog-vue'

// Get reactive primitives
import { ref, computed } from '@vue/reactivity'

// Get the current time in a reactive way
const date = ref(new Date())
const clock = computed(() => date.value.toLocaleTimeString())

// Update the current date every second
setInterval(() => date.value = new Date(), 1000)

console.draft('Current time:', clock)

Side note: Calling console.draft() will still return an function which you can use to update the draft. However, you will see yourself doing this way less often.

import { effect, shallowRef, toValue } from '@vue/reactivity'
import draftlog from 'draftlog'
// Initialize console.wrap with Draftlog
draftlog(console)
// Save the original console.draft
const originalDraft = console.draft
// Override console.draft
console.draft = function draft(...args: any[]) {
const reactiveArgs = shallowRef(args)
const update = originalDraft.call(console)
// Update the console output whenever the reactive arguments change
effect(() => {
update(...reactiveArgs.value.map(arg => toValue(arg)))
})
// Return a callback that can be used to update the reactive arguments
return (...args: any[]) => {
reactiveArgs.value = args
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment