reenabled @typescript-eslint/no-unnecessary-condition

This commit is contained in:
Eugene Pankov
2021-01-02 20:10:00 +01:00
parent 946f4292ef
commit 4d9cc91e91
36 changed files with 197 additions and 164 deletions

View File

@@ -35,8 +35,8 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
]),
])]
session: BaseSession
savedState: any
session?: BaseSession
savedState?: any
@Input() zoom = 0
@@ -51,7 +51,7 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
/** @hidden */
@HostBinding('class.top-padded') topPadded: boolean
frontend: Frontend
frontend?: Frontend
/** @hidden */
frontendIsReady = false
@@ -83,7 +83,7 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
protected terminalContainersService: TerminalFrontendService
protected toastr: ToastrServiceProxy
protected log: LogService
protected decorators: TerminalDecorator[]
protected decorators: TerminalDecorator[] = []
protected contextMenuProviders: TabContextMenuItemProvider[]
// Deps end
@@ -95,10 +95,29 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
private termContainerSubscriptions: Subscription[] = []
private allFocusModeSubscription: Subscription|null = null
get input$ (): Observable<Buffer> { return this.frontend.input$ }
get input$ (): Observable<Buffer> {
if (!this.frontend) {
throw new Error('Frontend not ready')
}
return this.frontend.input$
}
get output$ (): Observable<string> { return this.output }
get resize$ (): Observable<ResizeEvent> { return this.frontend.resize$ }
get alternateScreenActive$ (): Observable<boolean> { return this.frontend.alternateScreenActive$ }
get resize$ (): Observable<ResizeEvent> {
if (!this.frontend) {
throw new Error('Frontend not ready')
}
return this.frontend.resize$
}
get alternateScreenActive$ (): Observable<boolean> {
if (!this.frontend) {
throw new Error('Frontend not ready')
}
return this.frontend.alternateScreenActive$
}
get frontendReady$ (): Observable<void> { return this.frontendReady }
constructor (protected injector: Injector) {
@@ -119,7 +138,6 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
this.contextMenuProviders = injector.get<any>(TabContextMenuItemProvider, null, InjectFlags.Optional) as TabContextMenuItemProvider[]
this.logger = this.log.create('baseTerminalTab')
this.decorators = this.decorators || []
this.setTitle('Terminal')
this.hotkeysSubscription = this.hotkeys.matchedHotkey.subscribe(hotkey => {
@@ -128,7 +146,7 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
}
switch (hotkey) {
case 'ctrl-c':
if (this.frontend.getSelection()) {
if (this.frontend?.getSelection()) {
this.frontend.copySelection()
this.frontend.clearSelection()
this.toastr.info('Copied')
@@ -137,15 +155,15 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
}
break
case 'copy':
this.frontend.copySelection()
this.frontend.clearSelection()
this.frontend?.copySelection()
this.frontend?.clearSelection()
this.toastr.info('Copied')
break
case 'paste':
this.paste()
break
case 'clear':
this.frontend.clear()
this.frontend?.clear()
break
case 'zoom-in':
this.zoomIn()
@@ -199,9 +217,13 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
/** @hidden */
ngOnInit (): void {
if (!this.session) {
throw new Error('No session set on the tab object by the time ngOnInit is called')
}
this.focused$.subscribe(() => {
this.configure()
this.frontend.focus()
this.frontend?.focus()
})
this.frontend = this.terminalContainersService.getFrontend(this.session)
@@ -223,10 +245,10 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
})
setTimeout(() => {
this.session.resize(columns, rows)
this.session?.resize(columns, rows)
}, 1000)
this.session.releaseInitialDataBuffer()
this.session?.releaseInitialDataBuffer()
})
this.alternateScreenActive$.subscribe(x => {
@@ -242,12 +264,12 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
setImmediate(() => {
if (this.hasFocus) {
this.frontend.attach(this.content.nativeElement)
this.frontend.configure()
this.frontend!.attach(this.content.nativeElement)
this.frontend!.configure()
} else {
this.focused$.pipe(first()).subscribe(() => {
this.frontend.attach(this.content.nativeElement)
this.frontend.configure()
this.frontend!.attach(this.content.nativeElement)
this.frontend!.configure()
})
}
})
@@ -264,7 +286,7 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
this.frontend.bell$.subscribe(() => {
if (this.config.store.terminal.bell === 'visual') {
this.frontend.visualBell()
this.frontend?.visualBell()
}
if (this.config.store.terminal.bell === 'audible') {
this.bellPlayer.play()
@@ -295,9 +317,9 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
if (!(data instanceof Buffer)) {
data = Buffer.from(data, 'utf-8')
}
this.session.write(data)
this.session?.write(data)
if (this.config.store.terminal.scrollOnInput) {
this.frontend.scrollToBottom()
this.frontend?.scrollToBottom()
}
}
@@ -305,6 +327,10 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
* Feeds input into the terminal frontend
*/
write (data: string): void {
if (!this.frontend) {
throw new Error('Frontend not ready')
}
const percentageMatch = /(^|[^\d])(\d+(\.\d+)?)%([^\d]|$)/.exec(data)
if (!this.alternateScreenActive && percentageMatch) {
const percentage = percentageMatch[3] ? parseFloat(percentageMatch[2]) : parseInt(percentageMatch[2])
@@ -357,7 +383,7 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
* Applies the user settings to the terminal
*/
configure (): void {
this.frontend.configure()
this.frontend?.configure()
this.topPadded = this.hostApp.platform === Platform.macOS
&& this.config.store.appearance.frame === 'thin'
@@ -374,17 +400,17 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
zoomIn (): void {
this.zoom++
this.frontend.setZoom(this.zoom)
this.frontend?.setZoom(this.zoom)
}
zoomOut (): void {
this.zoom--
this.frontend.setZoom(this.zoom)
this.frontend?.setZoom(this.zoom)
}
resetZoom (): void {
this.zoom = 0
this.frontend.setZoom(this.zoom)
this.frontend?.setZoom(this.zoom)
}
focusAllPanes (): void {
@@ -394,13 +420,13 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
if (this.parent instanceof SplitTabComponent) {
this.parent._allFocusMode = true
this.parent.layout()
this.allFocusModeSubscription = this.frontend.input$.subscribe(data => {
this.allFocusModeSubscription = this.frontend?.input$.subscribe(data => {
for (const tab of (this.parent as SplitTabComponent).getAllTabs()) {
if (tab !== this && tab instanceof BaseTerminalTabComponent) {
tab.sendInput(data)
}
}
})
}) ?? null
}
}
@@ -418,7 +444,7 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
/** @hidden */
ngOnDestroy (): void {
this.frontend.detach(this.content.nativeElement)
this.frontend?.detach(this.content.nativeElement)
this.detachTermContainerHandlers()
this.config.enabledServices(this.decorators).forEach(decorator => {
try {
@@ -451,6 +477,10 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
protected attachTermContainerHandlers (): void {
this.detachTermContainerHandlers()
if (!this.frontend) {
throw new Error('Frontend not ready')
}
const maybeConfigure = () => {
if (this.hasFocus) {
setTimeout(() => this.configure(), 250)
@@ -464,8 +494,8 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
}
})),
this.focused$.subscribe(() => this.frontend.enableResizing = true),
this.blurred$.subscribe(() => this.frontend.enableResizing = false),
this.focused$.subscribe(() => this.frontend && (this.frontend.enableResizing = true)),
this.blurred$.subscribe(() => this.frontend && (this.frontend.enableResizing = false)),
this.frontend.mouseEvent$.subscribe(async event => {
if (event.type === 'mousedown') {
@@ -525,6 +555,10 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
}
protected attachSessionHandlers (destroyOnSessionClose = false): void {
if (!this.session) {
throw new Error('Session not set')
}
// this.session.output$.bufferTime(10).subscribe((datas) => {
this.session.output$.subscribe(data => {
if (this.enablePassthrough) {
@@ -537,7 +571,7 @@ export class BaseTerminalTabComponent extends BaseTabComponent implements OnInit
if (destroyOnSessionClose) {
this.sessionCloseSubscription = this.session.closed$.subscribe(() => {
this.frontend.destroy()
this.frontend?.destroy()
this.destroy()
})
}

View File

@@ -26,7 +26,10 @@ export abstract class TerminalDecorator {
/**
* Automatically cancel @subscription once detached from @terminal
*/
protected subscribeUntilDetached (terminal: BaseTerminalTabComponent, subscription: Subscription): void {
protected subscribeUntilDetached (terminal: BaseTerminalTabComponent, subscription?: Subscription): void {
if (!subscription) {
return
}
if (!this.smartSubscriptions.has(terminal)) {
this.smartSubscriptions.set(terminal, [])
}

View File

@@ -6,7 +6,7 @@ export interface ResizeEvent {
export interface SessionOptions {
name?: string
command: string
args: string[]
args?: string[]
cwd?: string
env?: Record<string, string>
width?: number

View File

@@ -60,9 +60,7 @@ export class ShellSettingsTabComponent {
properties: ['openDirectory', 'showHiddenFiles'],
}
)).filePaths
if (paths) {
this.config.store.terminal.workingDirectory = paths[0]
}
this.config.store.terminal.workingDirectory = paths[0]
}
newProfile (shell: Shell): void {

View File

@@ -53,7 +53,7 @@ export class TerminalTabComponent extends BaseTerminalTabComponent {
initializeSession (columns: number, rows: number): void {
this.sessions.addSession(
this.session,
this.session!,
Object.assign({}, this.sessionOptions, {
width: columns,
height: rows,
@@ -76,8 +76,8 @@ export class TerminalTabComponent extends BaseTerminalTabComponent {
}
async getCurrentProcess (): Promise<BaseTabProcess|null> {
const children = await this.session.getChildProcesses()
if (!children.length) {
const children = await this.session?.getChildProcesses()
if (!children?.length) {
return null
}
return {
@@ -86,8 +86,8 @@ export class TerminalTabComponent extends BaseTerminalTabComponent {
}
async canClose (): Promise<boolean> {
const children = await this.session.getChildProcesses()
if (children.length === 0) {
const children = await this.session?.getChildProcesses()
if (!children?.length) {
return true
}
return (await this.electron.showMessageBox(
@@ -104,6 +104,6 @@ export class TerminalTabComponent extends BaseTerminalTabComponent {
ngOnDestroy (): void {
this.homeEndSubscription.unsubscribe()
super.ngOnDestroy()
this.session.destroy()
this.session?.destroy()
}
}

View File

@@ -18,7 +18,7 @@ export class DebugDecorator extends TerminalDecorator {
let sessionOutputBuffer = ''
const bufferLength = 8192
this.subscribeUntilDetached(terminal, terminal.session.output$.subscribe(data => {
this.subscribeUntilDetached(terminal, terminal.session!.output$.subscribe(data => {
sessionOutputBuffer += data
if (sessionOutputBuffer.length > bufferLength) {
sessionOutputBuffer = sessionOutputBuffer.substring(sessionOutputBuffer.length - bufferLength)
@@ -88,18 +88,18 @@ export class DebugDecorator extends TerminalDecorator {
}
private doSaveState (terminal: TerminalTabComponent) {
this.saveFile(terminal.frontend.saveState(), 'state.txt')
this.saveFile(terminal.frontend!.saveState(), 'state.txt')
}
private async doCopyState (terminal: TerminalTabComponent) {
const data = '```' + JSON.stringify(terminal.frontend.saveState()) + '```'
const data = '```' + JSON.stringify(terminal.frontend!.saveState()) + '```'
this.electron.clipboard.writeText(data)
}
private async doLoadState (terminal: TerminalTabComponent) {
const data = await this.loadFile()
if (data) {
terminal.frontend.restoreState(data)
terminal.frontend!.restoreState(data)
}
}
@@ -109,7 +109,7 @@ export class DebugDecorator extends TerminalDecorator {
if (data.startsWith('`')) {
data = data.substring(3, data.length - 3)
}
terminal.frontend.restoreState(JSON.parse(data))
terminal.frontend!.restoreState(JSON.parse(data))
}
}
@@ -125,7 +125,7 @@ export class DebugDecorator extends TerminalDecorator {
private async doLoadOutput (terminal: TerminalTabComponent) {
const data = await this.loadFile()
if (data) {
terminal.frontend.write(data)
terminal.frontend?.write(data)
}
}
@@ -135,7 +135,7 @@ export class DebugDecorator extends TerminalDecorator {
if (data.startsWith('`')) {
data = data.substring(3, data.length - 3)
}
terminal.frontend.write(JSON.parse(data))
terminal.frontend?.write(JSON.parse(data))
}
}
}

View File

@@ -7,10 +7,10 @@ import { TerminalTabComponent } from '../components/terminalTab.component'
export class PathDropDecorator extends TerminalDecorator {
attach (terminal: TerminalTabComponent): void {
setTimeout(() => {
this.subscribeUntilDetached(terminal, terminal.frontend.dragOver$.subscribe(event => {
this.subscribeUntilDetached(terminal, terminal.frontend?.dragOver$.subscribe(event => {
event.preventDefault()
}))
this.subscribeUntilDetached(terminal, terminal.frontend.drop$.subscribe(event => {
this.subscribeUntilDetached(terminal, terminal.frontend?.drop$.subscribe(event => {
for (const file of event.dataTransfer!.files as any) {
this.injectPath(terminal, file.path)
}

View File

@@ -36,7 +36,7 @@ export class ZModemDecorator extends TerminalDecorator {
terminal.write(data)
}
},
sender: data => terminal.session.write(Buffer.from(data)),
sender: data => terminal.session!.write(Buffer.from(data)),
on_detect: async detection => {
try {
terminal.enablePassthrough = false
@@ -50,7 +50,7 @@ export class ZModemDecorator extends TerminalDecorator {
},
})
setTimeout(() => {
this.subscribeUntilDetached(terminal, terminal.session.binaryOutput$.subscribe(data => {
this.subscribeUntilDetached(terminal, terminal.session!.binaryOutput$.subscribe(data => {
const chunkSize = 1024
for (let i = 0; i <= Math.floor(data.length / chunkSize); i++) {
try {
@@ -153,6 +153,7 @@ export class ZModemDecorator extends TerminalDecorator {
this.cancelEvent.toPromise(),
])
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (canceled) {
this.showMessage(terminal, colors.bgRed.black(' Canceled ') + ' ' + details.name)
} else {
@@ -207,6 +208,7 @@ export class ZModemDecorator extends TerminalDecorator {
await xfer.end()
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
if (canceled) {
this.showMessage(terminal, colors.bgRed.black(' Canceled ') + ' ' + offer.name)
} else {

View File

@@ -33,7 +33,7 @@ export class XTermFrontend extends Frontend {
private search = new SearchAddon()
private fitAddon = new FitAddon()
private serializeAddon = new SerializeAddon()
private ligaturesAddon: LigaturesAddon
private ligaturesAddon?: LigaturesAddon
private opened = false
constructor () {

View File

@@ -7,7 +7,7 @@ import { TerminalTabComponent } from './components/terminalTab.component'
@Injectable()
export class RecoveryProvider extends TabRecoveryProvider {
async recover (recoveryToken: RecoveryToken): Promise<RecoveredTab|null> {
if (recoveryToken?.type === 'app:terminal-tab') {
if (recoveryToken.type === 'app:terminal-tab') {
return {
type: TerminalTabComponent,
options: {

View File

@@ -53,16 +53,16 @@ export class TerminalService {
return slugify(profile.name, { remove: /[:.]/g }).toLowerCase()
}
async getProfileByID (id: string): Promise<Profile> {
async getProfileByID (id: string): Promise<Profile|null> {
const profiles = await this.getProfiles({ includeHidden: true })
return profiles.find(x => this.getProfileID(x) === id) ?? profiles[0]
return profiles.find(x => this.getProfileID(x) === id) ?? null
}
/**
* Launches a new terminal with a specific shell and CWD
* @param pause Wait for a keypress when the shell exits
*/
async openTab (profile?: Profile, cwd?: string|null, pause?: boolean): Promise<TerminalTabComponent> {
async openTab (profile?: Profile|null, cwd?: string|null, pause?: boolean): Promise<TerminalTabComponent> {
if (!profile) {
profile = await this.getProfileByID(this.config.store.terminal.profile)
if (!profile) {
@@ -101,7 +101,7 @@ export class TerminalService {
}
const tab = this.openTabWithOptions(sessionOptions)
if (profile?.color) {
if (profile.color) {
(this.app.getParentTab(tab) ?? tab).color = profile.color
}
return tab

View File

@@ -32,7 +32,7 @@ export class UACService {
}
const options = { ...sessionOptions }
options.args = [options.command, ...options.args]
options.args = [options.command, ...options.args ?? []]
options.command = helperPath
return options
}

View File

@@ -30,7 +30,7 @@ export class SaveAsProfileContextMenu extends TabContextMenuItemProvider {
const profile = {
sessionOptions: {
...tab.sessionOptions,
cwd: await tab.session.getWorkingDirectory() ?? tab.sessionOptions.cwd,
cwd: await tab.session?.getWorkingDirectory() ?? tab.sessionOptions.cwd,
},
name: tab.sessionOptions.command,
}
@@ -79,7 +79,7 @@ export class NewTabContextMenu extends TabContextMenuItemProvider {
click: () => this.zone.run(async () => {
let workingDirectory = this.config.store.terminal.workingDirectory
if (this.config.store.terminal.alwaysUseWorkingDirectory !== true && tab instanceof TerminalTabComponent) {
workingDirectory = await tab.session.getWorkingDirectory()
workingDirectory = await tab.session?.getWorkingDirectory()
}
await this.terminalService.openTab(profile, workingDirectory)
}),
@@ -150,7 +150,7 @@ export class CopyPasteContextMenu extends TabContextMenuItemProvider {
click: (): void => {
this.zone.run(() => {
setTimeout(() => {
tab.frontend.copySelection()
tab.frontend?.copySelection()
this.toastr.info('Copied')
})
})
@@ -174,7 +174,7 @@ export class LegacyContextMenu extends TabContextMenuItemProvider {
weight = 1
constructor (
@Optional() @Inject(TerminalContextMenuItemProvider) protected contextMenuProviders: TerminalContextMenuItemProvider[],
@Optional() @Inject(TerminalContextMenuItemProvider) protected contextMenuProviders: TerminalContextMenuItemProvider[]|null,
) {
super()
}