Skip to content

Commit

Permalink
feat: terminal.clear()
Browse files Browse the repository at this point in the history
  • Loading branch information
patak-dev committed Feb 18, 2022
1 parent 33d7dc2 commit 3b8ecbd
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 3 deletions.
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -53,6 +53,7 @@ Supported methods:
- `terminal.time(id)`
- `terminal.timeLog(id, obj1 [, obj2, ..., objN])`
- `terminal.timeEnd(id)`
- `terminal.clear()`

## Redirect `console` logs to the terminal

Expand Down
1 change: 1 addition & 0 deletions client.d.ts
Expand Up @@ -11,6 +11,7 @@ declare module 'virtual:terminal' {
time: (obj: string) => void
timeLog: (obj: string) => void
timeEnd: (obj: string) => void
clear: () => void
}
export default terminal
}
24 changes: 21 additions & 3 deletions src/index.ts
@@ -1,3 +1,4 @@
import readline from 'readline'
import { lightGray, lightMagenta, lightRed, lightYellow } from 'kolorist'
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite'
import { parseURL } from 'ufo'
Expand Down Expand Up @@ -38,7 +39,7 @@ export interface Options {
exclude?: FilterPattern
}

const methods = ['assert', 'error', 'info', 'log', 'table', 'warn'] as const
const methods = ['assert', 'error', 'info', 'log', 'table', 'warn', 'clear'] as const
type Method = typeof methods[number]

const colors = {
Expand Down Expand Up @@ -110,6 +111,19 @@ function pluginTerminal(options: Options = {}) {
if (methods.includes(method)) {
let run
switch (method) {
case 'clear': {
// Use same logic as in Vite
run = () => {
if (process.stdout.isTTY && !process.env.CI) {
const repeatCount = process.stdout.rows - 2
const blank = repeatCount > 0 ? '\n'.repeat(repeatCount) : ''
console.log(blank)
readline.cursorTo(process.stdout, 0, 0)
readline.clearScreenDown(process.stdout)
}
}
break
}
case 'table': {
const obj = JSON.parse(message)
const indent = 2 * (groupLevel + 1)
Expand Down Expand Up @@ -171,8 +185,9 @@ function createTerminal() {
return typeof obj === 'object' ? `${prettyPrint(obj)}` : obj.toString()
}

function send(type: string, message: string) {
fetch(`/__terminal/${type}?m=${encodeURI(message)}&t=${Date.now()}&c=${count++}&g=${groupLevel}`)
function send(type: string, message?: string) {
const encodedMessage = message ? `&m=${encodeURI(message)}` : ''
fetch(`/__terminal/${type}?t=${Date.now()}&c=${count++}&g=${groupLevel}${encodedMessage}`)
}

return {
Expand Down Expand Up @@ -201,6 +216,9 @@ function createTerminal() {
send('log', getTimer(id))
timers.delete(id)
},
clear() {
send('clear')
},
}
}

Expand Down

0 comments on commit 3b8ecbd

Please sign in to comment.