Skip to content

Commit

Permalink
feat(Script): add withRoot()
Browse files Browse the repository at this point in the history
  • Loading branch information
meszaros-lajos-gyorgy committed Oct 21, 2023
1 parent 4e43b92 commit 400b5e8
Showing 1 changed file with 54 additions and 10 deletions.
64 changes: 54 additions & 10 deletions src/Script.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { eventNames } from 'node:process'
import { Settings } from '@src/Settings.js'
import { ScriptCommand } from '@scripting/ScriptCommand.js'
import { ScriptProperty } from '@scripting/ScriptProperty.js'
Expand All @@ -24,10 +25,6 @@ export class Script {
eventHandlers: Record<string, ScriptHandler[]> = {
init: [],
}
rawScripts: { before: ScriptHandler[]; after: ScriptHandler[] } = {
before: [],
after: [],
}

constructor(props: ScriptConstructorProps) {
this.filename = props.filename
Expand All @@ -38,6 +35,10 @@ export class Script {

const eventHandlerPairs = Object.entries(this.eventHandlers)
for (let [eventName, handlers] of eventHandlerPairs) {
if (eventName === '::before' || eventName === '::after') {
continue
}

let eventString = ''

if (eventName === 'init') {
Expand All @@ -58,11 +59,14 @@ export class Script {
subroutines.push(subroutine.toString())
}

const beforeScripts = this.eventHandlers['::before'].map((script) => Script.handlerToString(script))
const afterScripts = this.eventHandlers['::after'].map((script) => Script.handlerToString(script))

const scriptSections = [
this.rawScripts.before.map((script) => Script.handlerToString(script)).join('\n'),
beforeScripts.join('\n'),
eventStrings.join('\n'),
subroutines.join('\n'),
this.rawScripts.after.map((script) => Script.handlerToString(script)).join('\n'),
afterScripts.join('\n'),
]

return scriptSections.filter((section) => section !== '').join('\n\n')
Expand Down Expand Up @@ -96,12 +100,12 @@ export class Script {
return this
}

appendRaw(script: ScriptHandler) {
this.rawScripts.after.push(script)
prependRaw(handler: ScriptHandler) {
this.on('::before', handler)
}

prependRaw(script: ScriptHandler) {
this.rawScripts.before.push(script)
appendRaw(handler: ScriptHandler) {
this.on('::after', handler)
}

static handlerToString(handler: ScriptHandler) {
Expand All @@ -121,4 +125,44 @@ export class Script {

return result
}

whenRoot() {
const preparedObject = {
on: (eventName: string, handler: ScriptHandler) => {
this.on(eventName, () => {
if (!this.isRoot) {
return ''
}

return Script.handlerToString(handler)
})

return preparedObject
},
prependRaw: (handler: ScriptHandler) => {
this.prependRaw(() => {
if (!this.isRoot) {
return ''
}

return Script.handlerToString(handler)
})

return preparedObject
},
appendRaw: (handler: ScriptHandler) => {
this.appendRaw(() => {
if (!this.isRoot) {
return ''
}

return Script.handlerToString(handler)
})

return preparedObject
},
}

return preparedObject
}
}

0 comments on commit 400b5e8

Please sign in to comment.