code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
getReadmeTemplate = async templatePath => {
const spinner = ora('Loading README template').start()
try {
const template = await promisify(fs.readFile)(templatePath, 'utf8')
spinner.succeed('README template loaded')
return template
} catch (err) {
spinner.fail('README template loading fail')
throw err
}
}
|
Get README template content from the given templatePath
@param {string} templatePath
|
getReadmeTemplate
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
buildReadmeContent = async (context, templatePath) => {
const currentYear = getYear(new Date())
const template = await getReadmeTemplate(templatePath)
return ejs.render(template, {
filename: templatePath,
currentYear,
...context
})
}
|
Build README content with the given context and templatePath
@param {Object} context
@param {string} templatePath
|
buildReadmeContent
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
buildReadmeContent = async (context, templatePath) => {
const currentYear = getYear(new Date())
const template = await getReadmeTemplate(templatePath)
return ejs.render(template, {
filename: templatePath,
currentYear,
...context
})
}
|
Build README content with the given context and templatePath
@param {Object} context
@param {string} templatePath
|
buildReadmeContent
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
validateReadmeTemplatePath = templatePath => {
const spinner = ora('Resolving README template path').start()
try {
fs.lstatSync(templatePath).isFile()
} catch (err) {
spinner.fail(`The template path '${templatePath}' is not valid.`)
throw err
}
spinner.succeed('README template path resolved')
}
|
Validate template path
@param {string} templatePath
|
validateReadmeTemplatePath
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
validateReadmeTemplatePath = templatePath => {
const spinner = ora('Resolving README template path').start()
try {
fs.lstatSync(templatePath).isFile()
} catch (err) {
spinner.fail(`The template path '${templatePath}' is not valid.`)
throw err
}
spinner.succeed('README template path resolved')
}
|
Validate template path
@param {string} templatePath
|
validateReadmeTemplatePath
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
getReadmeTemplatePath = async (customTemplate, useDefaultAnswers) => {
const templatePath = isNil(customTemplate)
? await chooseTemplate(useDefaultAnswers)
: customTemplate
validateReadmeTemplatePath(templatePath)
return templatePath
}
|
Get readme template path
(either a custom template, or a template that user will choose from prompt)
@param {String} customTemplate
|
getReadmeTemplatePath
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
getReadmeTemplatePath = async (customTemplate, useDefaultAnswers) => {
const templatePath = isNil(customTemplate)
? await chooseTemplate(useDefaultAnswers)
: customTemplate
validateReadmeTemplatePath(templatePath)
return templatePath
}
|
Get readme template path
(either a custom template, or a template that user will choose from prompt)
@param {String} customTemplate
|
getReadmeTemplatePath
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
checkOverwriteReadme = () =>
!fs.existsSync(README_PATH) || askOverwriteReadme()
|
Check if readme generator can overwrite the existed readme
|
checkOverwriteReadme
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
checkOverwriteReadme = () =>
!fs.existsSync(README_PATH) || askOverwriteReadme()
|
Check if readme generator can overwrite the existed readme
|
checkOverwriteReadme
|
javascript
|
kefranabg/readme-md-generator
|
src/readme.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/readme.js
|
MIT
|
getGitRepositoryName = cwd => {
try {
return getReposName.sync({ cwd })
// eslint-disable-next-line no-empty
} catch (err) {
return undefined
}
}
|
Get git repository name
@param {String} cwd
|
getGitRepositoryName
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getGitRepositoryName = cwd => {
try {
return getReposName.sync({ cwd })
// eslint-disable-next-line no-empty
} catch (err) {
return undefined
}
}
|
Get git repository name
@param {String} cwd
|
getGitRepositoryName
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getDefaultAnswer = async (question, answersContext) => {
if (question.when && !question.when(answersContext)) return undefined
switch (question.type) {
case 'input':
return typeof question.default === 'function'
? question.default(answersContext)
: question.default || ''
case 'checkbox':
return question.choices
.filter(choice => choice.checked)
.map(choice => choice.value)
default:
return undefined
}
}
|
Get the default answer depending on the question type
@param {Object} question
|
getDefaultAnswer
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getDefaultAnswer = async (question, answersContext) => {
if (question.when && !question.when(answersContext)) return undefined
switch (question.type) {
case 'input':
return typeof question.default === 'function'
? question.default(answersContext)
: question.default || ''
case 'checkbox':
return question.choices
.filter(choice => choice.checked)
.map(choice => choice.value)
default:
return undefined
}
}
|
Get the default answer depending on the question type
@param {Object} question
|
getDefaultAnswer
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
isProjectAvailableOnNpm = projectName => {
try {
execSync(`npm view ${projectName}`, { stdio: 'ignore' })
return true
} catch (err) {
return false
}
}
|
Return true if the project is available on NPM, return false otherwise.
@param projectName
@returns boolean
|
isProjectAvailableOnNpm
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
isProjectAvailableOnNpm = projectName => {
try {
execSync(`npm view ${projectName}`, { stdio: 'ignore' })
return true
} catch (err) {
return false
}
}
|
Return true if the project is available on NPM, return false otherwise.
@param projectName
@returns boolean
|
isProjectAvailableOnNpm
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getDefaultAnswers = questions =>
questions.reduce(async (answersContextProm, question) => {
const answersContext = await answersContextProm
return {
...answersContext,
[question.name]: await getDefaultAnswer(question, answersContext)
}
}, Promise.resolve({}))
|
Get default question's answers
@param {Array} questions
|
getDefaultAnswers
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getDefaultAnswers = questions =>
questions.reduce(async (answersContextProm, question) => {
const answersContext = await answersContextProm
return {
...answersContext,
[question.name]: await getDefaultAnswer(question, answersContext)
}
}, Promise.resolve({}))
|
Get default question's answers
@param {Array} questions
|
getDefaultAnswers
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getAuthorWebsiteFromGithubAPI = async githubUsername => {
try {
const userData = await fetch(
`${GITHUB_API_URL}/users/${githubUsername}`
).then(res => res.json())
const authorWebsite = userData.blog
return isNil(authorWebsite) || isEmpty(authorWebsite)
? undefined
: authorWebsite
} catch (err) {
return undefined
}
}
|
Get author's website from Github API
@param {string} githubUsername
@returns {string} authorWebsite
|
getAuthorWebsiteFromGithubAPI
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getAuthorWebsiteFromGithubAPI = async githubUsername => {
try {
const userData = await fetch(
`${GITHUB_API_URL}/users/${githubUsername}`
).then(res => res.json())
const authorWebsite = userData.blog
return isNil(authorWebsite) || isEmpty(authorWebsite)
? undefined
: authorWebsite
} catch (err) {
return undefined
}
}
|
Get author's website from Github API
@param {string} githubUsername
@returns {string} authorWebsite
|
getAuthorWebsiteFromGithubAPI
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
doesFileExist = filepath => {
try {
return fs.existsSync(filepath)
} catch (err) {
return false
}
}
|
Returns a boolean whether a file exists or not
@param {String} filepath
@returns {Boolean}
|
doesFileExist
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
doesFileExist = filepath => {
try {
return fs.existsSync(filepath)
} catch (err) {
return false
}
}
|
Returns a boolean whether a file exists or not
@param {String} filepath
@returns {Boolean}
|
doesFileExist
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getPackageManagerFromLockFile = () => {
const packageLockExists = doesFileExist('package-lock.json')
const yarnLockExists = doesFileExist('yarn.lock')
if (packageLockExists && yarnLockExists) return undefined
if (packageLockExists) return 'npm'
if (yarnLockExists) return 'yarn'
return undefined
}
|
Returns the package manager from the lock file
@returns {String} packageManger or undefined
|
getPackageManagerFromLockFile
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
getPackageManagerFromLockFile = () => {
const packageLockExists = doesFileExist('package-lock.json')
const yarnLockExists = doesFileExist('yarn.lock')
if (packageLockExists && yarnLockExists) return undefined
if (packageLockExists) return 'npm'
if (yarnLockExists) return 'yarn'
return undefined
}
|
Returns the package manager from the lock file
@returns {String} packageManger or undefined
|
getPackageManagerFromLockFile
|
javascript
|
kefranabg/readme-md-generator
|
src/utils.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/utils.js
|
MIT
|
buildFormattedChoices = engines =>
isNil(engines)
? null
: Object.keys(engines).map(key => ({
name: `${key} ${engines[key]}`,
value: {
name: key,
value: engines[key]
},
checked: true
}))
|
Return engines as formatted choices
@param {Object} engines
|
buildFormattedChoices
|
javascript
|
kefranabg/readme-md-generator
|
src/questions/project-prerequisites.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/questions/project-prerequisites.js
|
MIT
|
buildFormattedChoices = engines =>
isNil(engines)
? null
: Object.keys(engines).map(key => ({
name: `${key} ${engines[key]}`,
value: {
name: key,
value: engines[key]
},
checked: true
}))
|
Return engines as formatted choices
@param {Object} engines
|
buildFormattedChoices
|
javascript
|
kefranabg/readme-md-generator
|
src/questions/project-prerequisites.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/questions/project-prerequisites.js
|
MIT
|
hasProjectInfosEngines = projectInfos =>
!isNil(projectInfos.engines) && !isEmpty(projectInfos.engines)
|
Check if projectInfos has engines properties
@param {Object} projectInfos
|
hasProjectInfosEngines
|
javascript
|
kefranabg/readme-md-generator
|
src/questions/project-prerequisites.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/questions/project-prerequisites.js
|
MIT
|
hasProjectInfosEngines = projectInfos =>
!isNil(projectInfos.engines) && !isEmpty(projectInfos.engines)
|
Check if projectInfos has engines properties
@param {Object} projectInfos
|
hasProjectInfosEngines
|
javascript
|
kefranabg/readme-md-generator
|
src/questions/project-prerequisites.js
|
https://github.com/kefranabg/readme-md-generator/blob/master/src/questions/project-prerequisites.js
|
MIT
|
async function saveVueggProject (project, owner, repo, token) {
try {
return await axios.post('/api/project', { project, owner, repo, token })
} catch (e) {
console.error(e)
return false
}
}
|
Saves the current vuegg project definition in the specify repository
@param {object} project : Project definition to be saved in the repository (as vue.gg)
@param {string} owner : Repository owner
@param {string} repo : Repository where to save the project definition
@param {string} token : Authentication token
@return {object|false} : returns a JSON of the created file of false is something goes wrong
|
saveVueggProject
|
javascript
|
alxpez/vuegg
|
client/src/api/index.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/api/index.js
|
MIT
|
async function getVueggProject (owner, repo, token) {
try {
return await axios.get('/api/project', { params: { owner, repo, token } })
} catch (e) {
console.error(e)
return false
}
}
|
Retrieves the base64 vue.gg project definition from the especified repository.
@param {string} owner : owner of the repository
@param {string} repo : repository to get the vue.gg project definition from
@param {string} [token] : oauth2 token (for access private repos) [unused for now]
@return {string} : base64 string of the vue.gg file of the repository
|
getVueggProject
|
javascript
|
alxpez/vuegg
|
client/src/api/index.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/api/index.js
|
MIT
|
async function generateVueSources (project) {
try {
return await axios.post('/api/generate', project, {responseType: 'blob'})
} catch (e) {
console.error(e)
return false
}
}
|
Generated vuejs sources from a vuegg project definition
@param {object} project : current project
@return {blob} : A zip file containing the vuejs sources of the passed project
|
generateVueSources
|
javascript
|
alxpez/vuegg
|
client/src/api/index.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/api/index.js
|
MIT
|
async function authorizeUser () {
const oauthOpen = promisify(open)
const STATE = shortid.generate()
const authUrl = 'https://github.com/login/oauth/authorize'
.concat('?client_id=').concat(CLIENT_ID)
.concat('&redirect_uri=').concat(REDIRECT_URL)
.concat('&state=').concat(STATE)
.concat('&scope=').concat(SCOPE)
try {
let resp = await oauthOpen(authUrl)
if (resp.state === STATE) {
return await _getAccessToken(resp.code)
} else {
console.error('The states do not match, this request could be compromised')
return false
}
} catch (e) {
console.error(e)
return false
}
}
|
Displays the login with GitHub screen to the user (as a popup or new tab),
if everything ok, closes the login screen and retrieves an authentication token for the logged user.
If something goes wrong in the process returns false.
@return {string|false} : Returns the authentication token or false if something goes wrong
|
authorizeUser
|
javascript
|
alxpez/vuegg
|
client/src/auth/index.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/auth/index.js
|
MIT
|
async function _getAccessToken (code) {
try {
let resp = await axios.post('/api/get-access-token', { code: code })
return resp.data
} catch (e) {
console.error(e)
return false
}
}
|
Displays the login with GitHub screen to the user (as a popup or new tab),
if everything ok, closes the login screen and retrieves an authentication token for the logged user.
If something goes wrong in the process returns false.
@return {string|false} : Returns the authentication token or false if something goes wrong
|
_getAccessToken
|
javascript
|
alxpez/vuegg
|
client/src/auth/index.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/auth/index.js
|
MIT
|
async function getAuthenticatedUser (token) {
try {
let resp = await axios.get('https://api.github.com/user', {
headers: {
'Authorization': 'bearer '.concat(token)
}
})
return resp.data
} catch (e) {
console.error(e)
return false
}
}
|
Retrieves the current authenticated user info
@param {string} token : Authentication token for the logged user
@return {object} Authenticated user
|
getAuthenticatedUser
|
javascript
|
alxpez/vuegg
|
client/src/auth/index.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/auth/index.js
|
MIT
|
function compInst (component) {
return {
global: true,
name: component.name,
top: component.top,
left: component.left,
bottom: component.bottom,
right: component.right,
componegg: component.componegg,
egglement: component.egglement,
containegg: component.containegg
}
}
|
Returns the component instance from the base component provided
@param {object} component : base component to generate the instance
@return {object} : Component instance
@see {@link [types.registerElement]}
@see {@link [types.duplicatePage]}
|
compInst
|
javascript
|
alxpez/vuegg
|
client/src/factories/componentFactory.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/factories/componentFactory.js
|
MIT
|
function compRef (component) {
return {
usageCount: 1,
name: component.name,
height: component.height,
width: component.width,
type: component.type,
text: component.text,
attrs: component.attrs,
styles: component.styles,
classes: component.classes,
children: component.children,
dependencies: component.dependencies || []
}
}
|
Returns the component reference from the base component provided
@param {object} component : base component to generate the instance
@return {object} : Component reference
@see {@link [types.registerElement]}
@see {@link [types.duplicatePage]}
|
compRef
|
javascript
|
alxpez/vuegg
|
client/src/factories/componentFactory.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/factories/componentFactory.js
|
MIT
|
function fixElementToParentBounds (element, parent) {
const parentH = getComputedProp('height', parent)
const parentW = getComputedProp('width', parent)
let height = getComputedProp('height', element, parent)
let width = getComputedProp('width', element, parent)
let top = element.top
let left = element.left
// Checks if position + size gets out-of-bounds (TOO FAR), if so, reposition...
if ((top + height) > parentH) {
top -= (top + height) - parentH
}
if ((left + width) > parentW) {
left -= (left + width) - parentW
}
// Checks if position is out-of-bounds (NEGATIVE), if so reposition...
if (top <= 0) top = 0
if (left <= 0) left = 0
// Checks if, with a 0 position, the element is still out-of-bounds (TOO BIG), if so, resize
if (top === 0 && (height > parentH)) height = parentH
if (left === 0 && (width > parentW)) width = parentW
return {left, top, height, width}
}
|
Fixes the properties (top, left, height, width) of an element,
based on the parent container
@param {object} element : The element to which fix its props
@param {object} parent : Parent element of the 'element'
@return {object} : Object with clean/fixed top, left, height, width properties for the element
|
fixElementToParentBounds
|
javascript
|
alxpez/vuegg
|
client/src/helpers/positionDimension.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/helpers/positionDimension.js
|
MIT
|
function getComputedProp (prop, element, parent) {
if (prop === 'left' || prop === 'right' || prop === 'top' || prop === 'bottom') {
return parseInt(window.getComputedStyle(document.getElementById(element.id).parentNode)[prop])
} else {
return (
(!parent)
? parseInt(window.getComputedStyle(document.getElementById(element.id))[prop])
: (typeof element[prop] !== 'string')
? element[prop]
: (typeof parent[prop] !== 'string')
? parent[prop] * parseInt(element[prop]) / 100
: parseInt(window.getComputedStyle(document.getElementById(parent.id))[prop]) * parseInt(element[prop]) / 100
)
}
}
|
Calculates the computed prop of an element,
based on its own props and the parent props.
(Specially created to deal with percentage dimensions)
@param {object} element : The element to get the dimension for
@param {object} parent : The parent element of the 'element'
@param {string} prop : Property for which to extract the dimension (height/width)
@return {number} : The real dimension for the element (height/width)
|
getComputedProp
|
javascript
|
alxpez/vuegg
|
client/src/helpers/positionDimension.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/helpers/positionDimension.js
|
MIT
|
function setElId (el, parentId) {
let elId = shortid.generate()
if (parentId) elId = parentId.concat('.', elId)
let newElement = {...el, id: elId, children: []}
if (el.children && el.children.length > 0) {
for (let childEl of el.children) {
newElement.children.push(setElId(childEl, elId))
}
}
return newElement
}
|
Assigns a new id to the element preceded by the parentId and a dot '.'
@param {object} el : Element to register
@param {string} [parentId] : Id of the parent element
@return {object} : New element (cloned from egglement) with newly assigned ids
|
setElId
|
javascript
|
alxpez/vuegg
|
client/src/helpers/recursiveMethods.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/helpers/recursiveMethods.js
|
MIT
|
function getExtGlobComps (el, compList) {
if (!compList) compList = []
if (el.global || el.external) compList.push(el)
if (el.children && el.children.length > 0) {
for (let childEl of el.children) {
compList = getExtGlobComps(childEl, compList)
}
}
return compList
}
|
Creates an array containing all the global/external components inside.
@param {object} el : Current reviewing element
@return {object} : An array with the global/external components found inside.
|
getExtGlobComps
|
javascript
|
alxpez/vuegg
|
client/src/helpers/recursiveMethods.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/helpers/recursiveMethods.js
|
MIT
|
function getChildNode (currentNode, targetId) {
if (currentNode.id === targetId) return currentNode
for (let child of currentNode.children) {
if (targetId.indexOf(child.id) !== -1) {
return getChildNode(child, targetId)
}
}
}
|
Returns the element identified by targetId, which could be the
currentNode itself, one of its children... (and down to any depth)
@param {object} currentNode : The element being inspected
@param {string} targetId : The id of the element expected
@return {object} : The element identified by targetId
|
getChildNode
|
javascript
|
alxpez/vuegg
|
client/src/helpers/recursiveMethods.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/helpers/recursiveMethods.js
|
MIT
|
function calcRelativePoint (currentNode, targetId, currentX, currentY) {
if (currentNode.id === targetId) return {left: currentX, top: currentY}
if (currentNode.left && currentNode.top) {
currentX -= currentNode.left
currentY -= currentNode.top
}
for (let child of currentNode.children) {
if (targetId.indexOf(child.id) !== -1) {
return calcRelativePoint(child, targetId, currentX, currentY)
}
}
}
|
Returns the element --identified by targetId-- relative position,
based on its parent (and full family depth) position
and the current mouse left/top position.
This method gives positioning support for elements changing "family".
@param {object} currentNode : The element being inspected
@param {string} targetId : The id of the element expected
@param {number} currentX : Current relative left position
@param {number} currentY : Current relative top position
@return {object} : Relative point obtained from the currentX, currentY
|
calcRelativePoint
|
javascript
|
alxpez/vuegg
|
client/src/helpers/recursiveMethods.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/helpers/recursiveMethods.js
|
MIT
|
canUndo () {
// There should always be at least one state (initializeState)
return this.done.length > 1
}
|
Vue Mixin to control the State history and undo/redo functionality
@type {Vue.mixin}
@see {@link https://vuejs.org/v2/guide/mixins.html|Vue Mixins}
|
canUndo
|
javascript
|
alxpez/vuegg
|
client/src/mixins/redoundo.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/mixins/redoundo.js
|
MIT
|
canRedo () {
return this.undone.length > 0
}
|
Vue Mixin to control the State history and undo/redo functionality
@type {Vue.mixin}
@see {@link https://vuejs.org/v2/guide/mixins.html|Vue Mixins}
|
canRedo
|
javascript
|
alxpez/vuegg
|
client/src/mixins/redoundo.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/mixins/redoundo.js
|
MIT
|
undo () {
if (this.canUndo) {
this.undone.push(this.done.pop())
let undoState = this.done[this.done.length - 1]
this.$store.replaceState(cloneDeep(undoState))
this.$root.$emit('rebaseState')
this.updateCanRedoUndo()
}
}
|
Vue Mixin to control the State history and undo/redo functionality
@type {Vue.mixin}
@see {@link https://vuejs.org/v2/guide/mixins.html|Vue Mixins}
|
undo
|
javascript
|
alxpez/vuegg
|
client/src/mixins/redoundo.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/mixins/redoundo.js
|
MIT
|
redo () {
if (this.canRedo) {
let redoState = this.undone.pop()
this.done.push(redoState)
this.$store.replaceState(cloneDeep(redoState))
this.$root.$emit('rebaseState')
this.updateCanRedoUndo()
}
}
|
Vue Mixin to control the State history and undo/redo functionality
@type {Vue.mixin}
@see {@link https://vuejs.org/v2/guide/mixins.html|Vue Mixins}
|
redo
|
javascript
|
alxpez/vuegg
|
client/src/mixins/redoundo.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/mixins/redoundo.js
|
MIT
|
updateCanRedoUndo () {
this.$store.commit(_toggleCanUndo, this.canUndo)
this.$store.commit(_toggleCanRedo, this.canRedo)
}
|
Vue Mixin to control the State history and undo/redo functionality
@type {Vue.mixin}
@see {@link https://vuejs.org/v2/guide/mixins.html|Vue Mixins}
|
updateCanRedoUndo
|
javascript
|
alxpez/vuegg
|
client/src/mixins/redoundo.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/mixins/redoundo.js
|
MIT
|
function elementsFromPoint (x, y) {
return (document.elementsFromPoint) ? document.elementsFromPoint(x, y) : elementsFromPointPolyfill(x, y)
}
|
Returns an array of HTML elements located under the point specified by x, y.
If the native elementsFromPoint function does not exist, a polyfill will be used.
@param {number} x : X position
@param {number} y : Y position
@return {array} : Array of the elements under the point (x, y)
|
elementsFromPoint
|
javascript
|
alxpez/vuegg
|
client/src/polyfills/elementsFromPoint.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/polyfills/elementsFromPoint.js
|
MIT
|
function elementsFromPointPolyfill (x, y) {
var parents = []
var parent = void 0
do {
if (parent !== document.elementFromPoint(x, y)) {
parent = document.elementFromPoint(x, y)
parents.push(parent)
parent.style.pointerEvents = 'none'
} else {
parent = false
}
} while (parent)
parents.forEach(function (parent) {
return (parent.style.pointerEvents = 'all')
})
return parents
}
|
Polyfill that covers the functionality of the native document.elementsFromPoint
function, in case that the browser does not support it.
@param {number} x : X position
@param {number} y : Y position
@return {array} : Array of the elements under the point (x, y)
|
elementsFromPointPolyfill
|
javascript
|
alxpez/vuegg
|
client/src/polyfills/elementsFromPoint.js
|
https://github.com/alxpez/vuegg/blob/master/client/src/polyfills/elementsFromPoint.js
|
MIT
|
async function getAccessToken (ctx) {
try {
let resp = await auth.getAccessToken(ctx.request.body)
ctx.response.status = 200
ctx.response.type = 'text/plain'
ctx.response.body = resp
} catch (e) {
console.error('\n> Could not obtain token\n' + e)
process.exit(1)
}
}
|
[getAccessToken description]
@param {[type]} ctx [description]
@return {[type]} [description]
|
getAccessToken
|
javascript
|
alxpez/vuegg
|
server/server.js
|
https://github.com/alxpez/vuegg/blob/master/server/server.js
|
MIT
|
async function saveVueggProject (ctx) {
try {
let resp = await github.saveVueggProject(ctx.request.body)
if (resp) {
ctx.response.status = 200
ctx.response.body = resp
ctx.response.type = 'text/plain'
}
} catch (e) {
console.error('\n> Could not save the project definition\n' + e)
process.exit(1)
}
}
|
Saves a vuegg project file in Github
@param {object} ctx : KoaContext object
@param {object} ctx.request.body : Body of the POST request
@see {@link http://koajs.com/#context|Koa Context}
|
saveVueggProject
|
javascript
|
alxpez/vuegg
|
server/server.js
|
https://github.com/alxpez/vuegg/blob/master/server/server.js
|
MIT
|
async function getVueggProject (ctx) {
let params = ctx.request.query
try {
let resp = await github.getContent(params.owner, params.repo, 'vue.gg', params.token)
if (resp) {
ctx.response.status = 200
ctx.response.body = resp
ctx.response.type = 'application/json'
}
} catch (e) {
console.error('\n> Could not fetch the project definition\n' + e)
process.exit(1)
}
}
|
Retrieves a vuegg project file from Github
@param {object} ctx : KoaContext object
@param {object} ctx.request.body : Body of the POST request
@see {@link http://koajs.com/#context|Koa Context}
|
getVueggProject
|
javascript
|
alxpez/vuegg
|
server/server.js
|
https://github.com/alxpez/vuegg/blob/master/server/server.js
|
MIT
|
async function generate (ctx) {
try {
let zipFile = await generator(ctx.request.body, ROOT_DIR)
if (zipFile) {
console.log('> Download -> ' + zipFile)
ctx.response.status = 200
ctx.response.type = 'zip'
ctx.response.body = fs.createReadStream(zipFile)
}
} catch (e) {
console.error('\n> Could not complete the project generation...\n' + e)
process.exit(1)
}
}
|
Generates a full vue application from a scaffold project,
plus the app definition sent in the ctx.request.body
@param {object} ctx : KoaContext object
@param {object} ctx.request.body : Body of the POST request
@return {zipFile} : A zip file with the generated application should be served
@see {@link http://koajs.com/#context|Koa Context}
|
generate
|
javascript
|
alxpez/vuegg
|
server/server.js
|
https://github.com/alxpez/vuegg/blob/master/server/server.js
|
MIT
|
async function _generator (content, rootDir) {
const spinner = ora({spinner: 'circleHalves'})
let targetDir = path.resolve(rootDir, 'tmp', content.id)
let zippedProject = path.resolve(rootDir, 'tmp', content.id + '.zip')
try {
spinner.start('> Getting environment ready')
targetDir = await prepare(content, rootDir)
spinner.succeed()
} catch (e) {
spinner.fail('> Oh! Shit went wrong during the preparations...\n' + e)
process.exit(1)
}
console.log('> Scaffold located at -> ' + targetDir)
try {
spinner.start('> Building pages/components (' + content.title + ')')
for (const page of content.pages) {
await vueBuilder(page, content.components, targetDir)
}
spinner.succeed()
} catch (e) {
spinner.fail('> Ups! Pages/components generation failed...\n' + e)
process.exit(1)
}
try {
spinner.start('> Configuring Router')
await routerBuilder(content, targetDir)
spinner.succeed()
} catch (e) {
spinner.fail('> Ups! Router generation failed...\n' + e)
process.exit(1)
}
try {
spinner.start('> Refactoring (' + content.title + ')')
await projetRefactor(content, targetDir)
spinner.succeed()
} catch (e) {
spinner.fail('> Ups! Somethig broke during the project refactor...\n' + e)
process.exit(1)
}
try {
spinner.start('> Archiving project')
await projetZip(content, targetDir)
spinner.succeed()
} catch (e) {
spinner.fail('> Ups! Somethig broke during the zipping up...\n' + e)
process.exit(1)
}
try {
spinner.start('> Cleaning up the mess')
await cleanup(targetDir)
spinner.succeed()
} catch (e) {
spinner.fail('> Ups! Somethig broke during the cleanup...\n' + e)
process.exit(1)
}
return zippedProject
}
|
Index of the project generator libraries.
@constructor
@param {object} content : Definition of the project to be generated
@param {string} rootDir : The root folder of vuegg-server
|
_generator
|
javascript
|
alxpez/vuegg
|
server/api/generator/index.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/index.js
|
MIT
|
function _cssBuilder (el, isRoot) {
if ((!isRoot || !el.egglement) && (!el.styles || Object.keys(el.styles).length === 0)) return ''
const selector = isRoot ? '#' : '.'
const className = el.id.substr(el.id.lastIndexOf(".") + 1)
let styleDef = ''
let fullStyle = {}
if (isRoot) {
fullStyle = buildRoot(el)
} else {
fullStyle = buildNested(el)
if (el.children && el.children.length > 0 && !el.global) {
for (const child of el.children){
styleDef += _cssBuilder(child)
}
}
}
styleDef += '\n' + selector + S(className).replaceAll('.', '-').s + ' '
+ S(JSON.stringify(fullStyle, null, 2)).replaceAll('\n}',';\n}').s + '\n'
return S(styleDef).replaceAll('\\"', '\'').replaceAll('"', '').replaceAll(',\n', ';\n').s
}
|
Given an element definition, extracts the css/styles from that element
and its children (by recursive calling) and contatenates them on a sigle String object.
If the el is a componegg, its children won't be parsed.
@constructor
@param {object} el : Element from which the style definitions will be gathered
@return {string} : Style definitions for the provided element (and its children)
|
_cssBuilder
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/css.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/css.js
|
MIT
|
function buildRoot (el) {
let rootCSS = el.styles
if (typeof el.width !== 'undefined' && el.width !== null) {
rootCSS = {...rootCSS, width: isNaN(el.width) ? el.width : (el.width + 'px')}
}
if (typeof el.height !== 'undefined' && el.height !== null) {
rootCSS = {...rootCSS, height: isNaN(el.height) ? el.height : (el.height + 'px')}
}
return rootCSS
}
|
Creates the CSS for the root element
|
buildRoot
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/css.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/css.js
|
MIT
|
function buildNested (el) {
let nestedCSS = el.egglement ? {...el.styles, position: 'absolute'} : el.styles
if (typeof el.width !== 'undefined' && el.width !== null && el.width !== 'auto') {
nestedCSS = {...nestedCSS, width: isNaN(el.width) ? el.width : (el.width + 'px')}
}
if (typeof el.height !== 'undefined' && el.height !== null && el.height !== 'auto') {
nestedCSS = {...nestedCSS, height: isNaN(el.height) ? el.height : (el.height + 'px')}
}
if (typeof el.top !== 'undefined' && el.top !== null && el.top !== 'auto') {
nestedCSS = {...nestedCSS, top: isNaN(el.top) ? el.top : (el.top + 'px')}
}
if (typeof el.left !== 'undefined' && el.left !== null && el.left !== 'auto') {
nestedCSS = {...nestedCSS, left: isNaN(el.left) ? el.left : (el.left + 'px')}
}
if (typeof el.bottom !== 'undefined' && el.bottom !== null && el.bottom !== 'auto') {
nestedCSS = {...nestedCSS, bottom: isNaN(el.bottom) ? el.bottom : (el.bottom + 'px')}
}
if (typeof el.right !== 'undefined' && el.right !== null && el.right !== 'auto') {
nestedCSS = {...nestedCSS, right: isNaN(el.right) ? el.right : (el.right + 'px')}
}
if (typeof el.zIndex !== 'undefined' && el.zIndex !== null && el.zIndex !== 'auto') {
nestedCSS = {...nestedCSS, 'z-index': el.zIndex}
}
/*
* Tweak to apply the capability of defining the element dimension using
* left/right (instead of width) for elements other than <div> or <span>
*
* Depending on the browser this is not necessary but it will apply to be safe
*/
if (el.type !== 'div' || el.type !== 'span') {
if (isNaN(el.width) &&
(typeof el.right !== 'undefined' && el.right !== null && el.right !== 'auto') &&
(typeof el.left !== 'undefined' && el.left !== null && el.left !== 'auto')) {
const hHigh = Math.max(parseInt(el.left), parseInt(el.right))
let left = isNaN(el.left) ? el.left : (el.left + 'px')
let right = isNaN(el.right) ? el.right : (el.right + 'px')
nestedCSS = {...nestedCSS, width: 'calc(100% - ' + left + ' - ' + right + ')'}
nestedCSS = (hHigh === parseInt(el.left))
? {...nestedCSS, left, right: 'auto'}
: {...nestedCSS, right, left: 'auto'}
}
}
/*
* Tweak to apply the capability of defining the element dimension using
* top/bottom (instead of height), for <img> elements (there may be others)
*
* Depending on the browser this is not necessary but it will apply to be safe
*/
if (el.type === 'img') {
if (isNaN(el.height) &&
(typeof el.top !== 'undefined' && el.top !== null && el.top !== 'auto') &&
(typeof el.bottom !== 'undefined' && el.bottom !== null && el.bottom !== 'auto')) {
const vHigh = Math.max(parseInt(el.top), parseInt(el.bottom))
let top = isNaN(el.top) ? el.top : (el.top + 'px')
let bottom = isNaN(el.bottom) ? el.bottom : (el.bottom + 'px')
nestedCSS = {...nestedCSS, height: 'calc(100% - ' + top + ' - ' + bottom + ')'}
nestedCSS = (vHigh === parseInt(el.top))
? {...nestedCSS, top, bottom: 'auto'}
: {...nestedCSS, bottom, top: 'auto'}
}
}
return el.global ? nestedCSS : {...nestedCSS, ...el.styles}
}
|
Creates the CSS definition for a nested element
|
buildNested
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/css.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/css.js
|
MIT
|
function _htmlBuilder (el, level) {
const className = el.id.substr(el.id.lastIndexOf(".") + 1)
let elDef = ""
let elTag = el.type
let elProps = {'class': S(className).replaceAll('.', '-').s + parseBooleanPropsToString(el.classes)}
if (el.global) {
elTag = S(el.name).humanize().slugify().s
} else {
if (el.text && !S(el.text).isEmpty()){
elDef += el.text
}
if (el.children && el.children.length > 0) {
for (const child of el.children){
elDef += _htmlBuilder(child, level+1) + "\n" + S(' ').times(level*2).s
}
}
for (attr in el.attrs) {
if ((typeof el.attrs[attr] !== 'boolean') || ((typeof el.attrs[attr] === 'boolean') && (el.attrs[attr] === true))) {
elProps[attr] = el.attrs[attr]
}
}
}
let genHtml = "\n" + S(' ').times((level)*2).s + S(elDef).wrapHTML(elTag, elProps).replaceAll('="true"', '').s
return isSelfClosing(elTag)
? S(genHtml).replaceAll('></'.concat(elTag).concat('>'), '/>')
: genHtml
}
|
Given an egglement definition, creates a single String with the element as
a HTML-tag, its properties and nested children (by recursive calling).
If the egglement is a componegg, its props and children won't be parsed.
@constructor
@param {object} el : Element from which tag/props will be gathered
@param {number} level : Level of indentation of the element
@return {string} : HTML tags definitions for the provided element (and its children)
|
_htmlBuilder
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/html.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/html.js
|
MIT
|
function parseBooleanPropsToString (propList) {
let parsedString = ''
for (prop in propList) {
if (propList[prop] === true) parsedString += ' ' + prop
}
return parsedString
}
|
Given an egglement definition, creates a single String with the element as
a HTML-tag, its properties and nested children (by recursive calling).
If the egglement is a componegg, its props and children won't be parsed.
@constructor
@param {object} el : Element from which tag/props will be gathered
@param {number} level : Level of indentation of the element
@return {string} : HTML tags definitions for the provided element (and its children)
|
parseBooleanPropsToString
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/html.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/html.js
|
MIT
|
function isSelfClosing (tag) {
return SCT.includes(tag)
}
|
Given an egglement definition, creates a single String with the element as
a HTML-tag, its properties and nested children (by recursive calling).
If the egglement is a componegg, its props and children won't be parsed.
@constructor
@param {object} el : Element from which tag/props will be gathered
@param {number} level : Level of indentation of the element
@return {string} : HTML tags definitions for the provided element (and its children)
|
isSelfClosing
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/html.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/html.js
|
MIT
|
async function _routerBuilder (content, targetDir) {
const templateFile = path.resolve(targetDir,'templates','router','index.js')
const targetFile = path.resolve(targetDir,'src','router','index.js')
try {
await shell.cp(templateFile, targetFile)
} catch (e) {
log.error('\n > Could not copy ' + targetFile);
}
let imports = ""
let declarations = ""
for (const page of content.pages) {
const pageName = S(page.name).stripPunctuation().camelize().titleCase().s
imports += "\nimport " + pageName + " from '@/pages/" + pageName + "'"
declarations += "\n" + S(' ').times(4).s
+ "{ path: '" + page.path
+ "', name: '" + page.name
+ "', component: " + pageName + " },"
}
declarations = S(declarations).stripRight(',').s
shell.sed('-i', '{{PAGES_IMPORTS}}', imports, targetFile)
shell.sed('-i', '{{ROUTES_DECLARATIONS}}', declarations, targetFile)
}
|
Given the project's content definition, copies the router file template,
and replaces the placeholders with the information of the project's pages.
@constructor
@param {object} content : Definition of the project to be generated
@param {string} targetDir : Folder to host the generated project for the given content
|
_routerBuilder
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/router.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/router.js
|
MIT
|
async function _vueBuilder (file, componentRefs, targetDir) {
const fileName = S(file.name).stripPunctuation().camelize().titleCase().s
const fileType = file.componegg ? 'components' : 'pages'
const templateFile = path.resolve(targetDir,'templates','vue','default.vue')
const targetFile = path.resolve(targetDir,'src', fileType, fileName + '.vue')
try {
await shell.cp(templateFile, targetFile)
} catch (e) {
log.error('\n > Could not copy ' + targetFile);
}
let children = ""
let styles = ""
let imports = ""
let declarations = ""
let fileId = file.id.substr(file.id.lastIndexOf(".") + 1)
if (file.text) children += file.text
styles += cssBuilder(file, true)
for (const childEl of file.children) {
children += htmlBuilder(childEl, 1)
styles += cssBuilder(childEl)
}
for (const component of getAllGlobalComponents(file, [])) {
let compName = S(component.name).stripPunctuation().camelize().titleCase().s
let compImport = "\nimport " + compName + " from '@/components/" + compName + "'"
if(!S(imports).contains(compImport)) {
let compPath = path.resolve(targetDir,'src/components/', compName + '.vue')
let componentRef = getComponentRef(componentRefs, component.name)
if(!shell.test('-e', compPath)) {
_vueBuilder({...component, ...componentRef, id: component.id}, componentRefs, targetDir)
}
imports += compImport
declarations += compName + ", "
}
}
if (declarations !== ''){
imports += '\n'
declarations = S(declarations).ensureLeft(',\n components: { ').stripRight(', ').ensureRight(' }').s
}
shell.sed('-i', '{{PARENT_TAG}}', file.type || 'div', targetFile)
shell.sed('-i', '{{VUEGG_ID}}', S(fileId).replaceAll('.', '-').s, targetFile)
shell.sed('-i', '{{VUEGG_ATTRS}}', getFormattedAttrs(file.attrs), targetFile)
shell.sed('-i', '{{VUEGG_NAME}}', S(file.name).humanize().slugify().s, targetFile)
shell.sed('-i', '{{VUEGG_CHILDREN}}', children, targetFile)
shell.sed('-i', '{{COMPONENTS_IMPORTS}}', imports, targetFile)
shell.sed('-i', '{{COMPONENTS_DECLARATIONS}}', declarations, targetFile)
shell.sed('-i', '{{VUEGG_STYLES}}', styles, targetFile)
}
|
Given a file definition (page or component), copies the vue file template,
and replaces the placeholders with the information of the file.
Generates nested components by recursive calls to the constructor function.
@constructor
@param {object} file : Definition of vue file to be generated
@param {object} componentRefs : Array of global componentReferences used in the project
@param {string} targetDir : Folder to host the generated project for the given content
|
_vueBuilder
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/vue.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/vue.js
|
MIT
|
function getAllGlobalComponents (file, collection) {
if (file.children && file.children.length > 0) {
for (let el of file.children) {
if (el.componegg && el.global && (collection.indexOf(comp => comp.name === el.name) === -1)) {
collection.push(el)
}
collection = getAllGlobalComponents (el, collection)
}
}
return collection
}
|
Given a file definition (page or component), copies the vue file template,
and replaces the placeholders with the information of the file.
Generates nested components by recursive calls to the constructor function.
@constructor
@param {object} file : Definition of vue file to be generated
@param {object} componentRefs : Array of global componentReferences used in the project
@param {string} targetDir : Folder to host the generated project for the given content
|
getAllGlobalComponents
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/vue.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/vue.js
|
MIT
|
function getComponentRef (components, componentName) {
return components[components.findIndex(comp => comp.name === componentName)]
}
|
Given a file definition (page or component), copies the vue file template,
and replaces the placeholders with the information of the file.
Generates nested components by recursive calls to the constructor function.
@constructor
@param {object} file : Definition of vue file to be generated
@param {object} componentRefs : Array of global componentReferences used in the project
@param {string} targetDir : Folder to host the generated project for the given content
|
getComponentRef
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/vue.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/vue.js
|
MIT
|
function getFormattedAttrs (attrs) {
let formattedAttrs = ''
if (attrs) {
for (attr in attrs) {
if ((typeof attrs[attr] !== 'boolean')) {
formattedAttrs += ' ' + attr + '="' + attrs[attr] + '"'
} else if ((typeof attrs[attr] === 'boolean') && (attrs[attr] === true)) {
formattedAttrs += ' ' + attr
}
}
}
return formattedAttrs
}
|
Given a file definition (page or component), copies the vue file template,
and replaces the placeholders with the information of the file.
Generates nested components by recursive calls to the constructor function.
@constructor
@param {object} file : Definition of vue file to be generated
@param {object} componentRefs : Array of global componentReferences used in the project
@param {string} targetDir : Folder to host the generated project for the given content
|
getFormattedAttrs
|
javascript
|
alxpez/vuegg
|
server/api/generator/builder/vue.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/builder/vue.js
|
MIT
|
async function _cleanup (targetDir) {
try {
await shell.rm('-rf', targetDir)
} catch (e) {
log.error('\n > Could not remove ' + targetDir)
}
}
|
Remove the target folder for the generated project after this is been archived
@constructor
@param {string} targetDir : Folder that hosts the generated project (to remove)
|
_cleanup
|
javascript
|
alxpez/vuegg
|
server/api/generator/environment/cleanup.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/environment/cleanup.js
|
MIT
|
async function _prepare (content, rootDir) {
const tmpDir = path.resolve(rootDir, 'tmp')
const targetDir = path.resolve(tmpDir, content.id)
try {
if (!shell.test('-e', tmpDir)) {
await shell.mkdir('-p', tmpDir)
}
if (shell.test('-e', targetDir)) {
await shell.rm('-rf', targetDir)
}
await shell.mkdir('-p', targetDir)
} catch (e) {
console.error('\n> Crap, something crashed during the folder creation...\n' + e)
process.exit(1)
}
let repo = 'https://github.com/vuegg/vuegg-scaffold.git'
try {
const asyncExec = util.promisify(shell.exec)
await asyncExec('git clone '.concat(repo).concat(' ').concat(targetDir), {async:true})
} catch (e) {
console.error('\n> Ups! Could not complete the scaffolding...\n' + e)
}
return targetDir
}
|
Prepares the environment and clones the scaffold-project for the generation tasks.
Checks if the /tmp folder exists on vuegg-server root (creates it if not),
adds a new folder for the project that will be generated (based on the content)
clones a scaffold project inside the targetDir and returns its full location.
@constructor
@param {object} content : Definition of the project to be generated
@param {string} rootDir : Root folder of vuegg-server
@return {string} : Folder that will host the generated app for the given content
|
_prepare
|
javascript
|
alxpez/vuegg
|
server/api/generator/environment/prepare.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/environment/prepare.js
|
MIT
|
async function _archive (content, targetDir) {
const output = fs.createWriteStream(path.resolve(targetDir, '..', content.id + '.zip'))
const archive = archiver('zip', { zlib: { level: 9 } })
// output eventHandlers
output.on('close', () => console.log('> Archived: ' + archive.pointer() + ' total bytes'))
output.on('end', () => console.log('Data has been drained'))
// archive eventHandlers
archive.on('error', (err) => { throw err })
archive.on('warning', (err) => {
if (err.code === 'ENOENT') {
console.warn(err)
} else {
throw err
}
})
// pipe archive data to the file
archive.pipe(output)
// append files from a sub-directory, putting its contents at the root of archive
archive.directory(targetDir, false)
// finalize the archive (done appending files but streams have to finish yet)
await archive.finalize()
}
|
Archives the contens of the project located at
targetDir into a zip-file (writeStream)
@constructor
@param {object} content : Definition of the project generated
@param {string} targetDir : Folder that hosts the generated project
|
_archive
|
javascript
|
alxpez/vuegg
|
server/api/generator/project/archive.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/project/archive.js
|
MIT
|
async function _refactor (content, targetDir) {
const readmeFile = path.resolve(targetDir, 'README.md')
const indexFile = path.resolve(targetDir, 'index.html')
const packageFile = path.resolve(targetDir, 'package.json')
const mainFile = path.resolve(targetDir, 'src', 'main.js')
shell.sed('-i', '{{PROJECT_TITLE}}', content.title, readmeFile)
shell.sed('-i', '{{PROJECT_TITLE}}', content.title, indexFile)
shell.sed('-i', '{{PROJECT_NAME}}', S(content.title).slugify().s, packageFile)
let dependencies = ''
let packagesImports = ''
let indexStyleImports = ''
let indexScriptImports = ''
let packagesUse = ''
let uniqueDependencies = []
for (let component of content.components) {
if (component.dependencies) {
for (let dependency of component.dependencies) {
if (uniqueDependencies.findIndex(dep => dep.name === dependency.name) === -1) {
uniqueDependencies.push(dependency)
}
}
}
}
for (let dependency of uniqueDependencies) {
dependencies += '\n' + S(' ').times(4).s + '"' + dependency.name + '": "' + dependency.version + '",'
for (let packImport of dependency.imports) {
if (typeof packImport === 'string') {
if (packImport.indexOf('//') !== -1){
packImport.indexOf('css')
? indexStyleImports += '\n' + S(' ').times(4).s + '<link rel="stylesheet" href="' + packImport + '" type="text/css">'
: indexScriptImports += '\n' + S(' ').times(4).s + '<script src="' + packImport + '"></script>'
} else {
packagesImports += "import '" + packImport + "'\n"
}
} else {
packagesImports += "import " + packImport[0] + " from '" + packImport[1] + "'\n"
packagesUse += "Vue.use(" + packImport[0] + ")\n"
}
}
}
shell.sed('-i', '{{STYLE_IMPORTS}}', indexStyleImports, indexFile)
shell.sed('-i', '{{SCRIPT_IMPORTS}}', indexScriptImports, indexFile)
shell.sed('-i', '{{DEPENDENCIES}}', dependencies, packageFile)
shell.sed('-i', '{{PACKAGES_IMPORTS}}', packagesImports, mainFile)
shell.sed('-i', '{{PACKAGES_USE}}', packagesUse, mainFile)
try {
await shell.rm('-rf', path.resolve(targetDir, '.git'))
} catch (e) {
log.error('\n > Could not remove ' + path.resolve(targetDir, '.git'))
}
try {
await shell.rm('-rf', path.resolve(targetDir,'templates'))
} catch (e) {
log.error('\n > Could not remove ' + path.resolve(targetDir,'templates'))
}
}
|
Finishes the replacement of the project title in README.md, package.json, index.html
and removes the /templates folder from the generated project folder.
@constructor
@param {object} content : Definition of the project generated
@param {string} targetDir : Folder that hosts the generated project for the given content
|
_refactor
|
javascript
|
alxpez/vuegg
|
server/api/generator/project/refactor.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/generator/project/refactor.js
|
MIT
|
async function saveVueggProject ({project, owner, repo, token}) {
let existingRepo = await getRepo(owner, repo, token)
if (!existingRepo) { await createRepo(repo, token) }
return await saveFile(project, owner, repo, 'vue.gg', token)
}
|
Saves the current vuegg project definition in the specify repository
@param {object} project : Project definition to be saved in the repository (as vue.gg)
@param {string} owner : Repository owner
@param {string} repo : Repository where to save the project definition
@param {string} token : Authentication token
@return {object|false} : returns a JSON of the created file of false is something goes wrong
|
saveVueggProject
|
javascript
|
alxpez/vuegg
|
server/api/github/index.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/github/index.js
|
MIT
|
async function getRepo (owner, repo, token) {
// octokit.authenticate({type: 'oauth', token})
try {
return await octokit.repos.get({owner, repo})
} catch (e) {
console.log('(REPO) - ' + owner + '/' + repo + ' does not exist')
return false
}
}
|
[getRepo description]
@param {[type]} owner [description]
@param {[type]} repo [description]
@param {[type]} [token] [description]
@return {[type]} [description]
|
getRepo
|
javascript
|
alxpez/vuegg
|
server/api/github/index.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/github/index.js
|
MIT
|
async function createRepo (name, token) {
octokit.authenticate({type: 'oauth', token})
try {
return await octokit.repos.create({name, license_template: 'mit'})
} catch (e) {
console.error('(REPO) - Failed to create: ' + owner + '/' + name)
console.error(e)
return false
}
}
|
[createRepo description]
@param {[type]} name [description]
@param {[type]} token [description]
@return {[type]} [description]
|
createRepo
|
javascript
|
alxpez/vuegg
|
server/api/github/index.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/github/index.js
|
MIT
|
async function getContent (owner, repo, path, token) {
// octokit.authenticate({type: 'oauth', token})
try {
return await octokit.repos.getContent({owner, repo, path})
} catch (e) {
console.error('(FILE) - ' + owner + '/' + repo + '/' + path + ' does not exist')
return false
}
}
|
[getContent description]
@param {[type]} owner [description]
@param {[type]} repo [description]
@param {[type]} path [description]
@param {[type]} [token] [description]
@return {[type]} [description]
|
getContent
|
javascript
|
alxpez/vuegg
|
server/api/github/index.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/github/index.js
|
MIT
|
async function saveFile (content, owner, repo, path, token) {
let existentFile = await getContent(owner, repo, path, token)
let ghData = {
owner, repo, path,
content: Buffer.from(JSON.stringify(content)).toString('base64'),
committer: {name: 'vuegger', email: '[email protected]'}
}
octokit.authenticate({type: 'oauth', token})
try {
if (!existentFile) {
console.log('(FILE) - creating: ' + owner + '/' + repo + '/' + path)
return await octokit.repos.createFile({...ghData, message: 'vuegg save'})
} else {
console.log('(FILE) - updating: ' + owner + '/' + repo + '/' + path)
return await octokit.repos.updateFile({...ghData, message: 'vuegg update', sha: existentFile.data.sha})
}
} catch (e) {
console.error('(FILE) - Failed to save: ' + owner + '/' + repo + '/' + path)
return false
}
}
|
[saveFile description]
@param {[type]} content [description]
@param {[type]} owner [description]
@param {[type]} repo [description]
@param {[type]} token [description]
@return {[type]} [description]
|
saveFile
|
javascript
|
alxpez/vuegg
|
server/api/github/index.js
|
https://github.com/alxpez/vuegg/blob/master/server/api/github/index.js
|
MIT
|
async function getAccessToken ({code, state}) {
const options = {
method: 'POST',
uri: 'https://github.com/login/oauth/access_token',
form: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: code
}
}
try {
let resp = await rp(options)
return qs.parse(resp).access_token
} catch (e) {
console.error(e)
}
}
|
[getAccessToken description]
@param {[type]} code [description]
@return {[type]} [description]
|
getAccessToken
|
javascript
|
alxpez/vuegg
|
server/auth/index.js
|
https://github.com/alxpez/vuegg/blob/master/server/auth/index.js
|
MIT
|
addEntry(file: string): MochaWebpack {
this.entries = [
...this.entries,
file,
];
return this;
}
|
Add file run test against
@public
@param {string} file file or glob
@return {MochaWebpack}
|
addEntry
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
addInclude(file: string): MochaWebpack {
this.includes = [
...this.includes,
file,
];
return this;
}
|
Add file to include into the test bundle
@public
@param {string} file absolute path to module
@return {MochaWebpack}
|
addInclude
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
cwd(cwd: string): MochaWebpack {
this.options = {
...this.options,
cwd,
};
return this;
}
|
Sets the current working directory
@public
@param {string} cwd absolute working directory path
@return {MochaWebpack}
|
cwd
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
webpackConfig(config: {} = {}): MochaWebpack {
this.options = {
...this.options,
webpackConfig: config,
};
return this;
}
|
Sets the webpack config
@public
@param {Object} config webpack config
@return {MochaWebpack}
|
webpackConfig
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
bail(bail: boolean = false): MochaWebpack {
this.options = {
...this.options,
bail,
};
return this;
}
|
Enable or disable bailing on the first failure.
@public
@param {boolean} [bail]
@return {MochaWebpack}
|
bail
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
reporter(reporter: string | () => void, reporterOptions: {}): MochaWebpack {
this.options = {
...this.options,
reporter,
reporterOptions,
};
return this;
}
|
Set reporter to `reporter`, defaults to "spec".
@param {string|Function} reporter name or constructor
@param {Object} reporterOptions optional options
@return {MochaWebpack}
|
reporter
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
ui(ui: string): MochaWebpack {
this.options = {
...this.options,
ui,
};
return this;
}
|
Set test UI, defaults to "bdd".
@public
@param {string} ui bdd/tdd
@return {MochaWebpack}
|
ui
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
fgrep(str: string): MochaWebpack {
this.options = {
...this.options,
fgrep: str,
};
return this;
}
|
Only run tests containing <string>
@public
@param {string} str
@return {MochaWebpack}
|
fgrep
|
javascript
|
zinserjan/mocha-webpack
|
src/MochaWebpack.js
|
https://github.com/zinserjan/mocha-webpack/blob/master/src/MochaWebpack.js
|
MIT
|
constructor(options, answers) {
super();
this.options = utils.merge({}, options);
this.answers = { ...answers };
}
|
Create an instance of `Enquirer`.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
```
@name Enquirer
@param {Object} `options` (optional) Options to use with all prompts.
@param {Object} `answers` (optional) Answers object to initialize with.
@api public
|
constructor
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
register(type, fn) {
if (utils.isObject(type)) {
for (let key of Object.keys(type)) this.register(key, type[key]);
return this;
}
assert.equal(typeof fn, 'function', 'expected a function');
const name = type.toLowerCase();
if (fn.prototype instanceof this.Prompt) {
this.prompts[name] = fn;
} else {
this.prompts[name] = fn(this.Prompt, this);
}
return this;
}
|
Register a custom prompt type.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
enquirer.register('customType', require('./custom-prompt'));
```
@name register()
@param {String} `type`
@param {Function|Prompt} `fn` `Prompt` class, or a function that returns a `Prompt` class.
@return {Object} Returns the Enquirer instance
@api public
|
register
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
async prompt(questions = []) {
for (let question of [].concat(questions)) {
try {
if (typeof question === 'function') question = await question.call(this);
await this.ask(utils.merge({}, this.options, question));
} catch (err) {
return Promise.reject(err);
}
}
return this.answers;
}
|
Prompt function that takes a "question" object or array of question objects,
and returns an object with responses from the user.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const response = await enquirer.prompt({
type: 'input',
name: 'username',
message: 'What is your username?'
});
console.log(response);
```
@name prompt()
@param {Array|Object} `questions` Options objects for one or more prompts to run.
@return {Promise} Promise that returns an "answers" object with the user's responses.
@api public
|
prompt
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
async ask(question) {
if (typeof question === 'function') {
question = await question.call(this);
}
let opts = utils.merge({}, this.options, question);
let { type, name } = question;
let { set, get } = utils;
if (typeof type === 'function') {
type = await type.call(this, question, this.answers);
}
if (!type) return this.answers[name];
if (type === 'number') type = 'numeral';
assert(this.prompts[type], `Prompt "${type}" is not registered`);
let prompt = new this.prompts[type](opts);
let value = get(this.answers, name);
prompt.state.answers = this.answers;
prompt.enquirer = this;
if (name) {
prompt.on('submit', value => {
this.emit('answer', name, value, prompt);
set(this.answers, name, value);
});
}
// bubble events
let emit = prompt.emit.bind(prompt);
prompt.emit = (...args) => {
this.emit.call(this, ...args);
return emit(...args);
};
this.emit('prompt', prompt, this);
if (opts.autofill && value != null) {
prompt.value = prompt.input = value;
// if "autofill=show" render the prompt, otherwise stay "silent"
if (opts.autofill === 'show') {
await prompt.submit();
}
} else {
value = prompt.value = await prompt.run();
}
return value;
}
|
Prompt function that takes a "question" object or array of question objects,
and returns an object with responses from the user.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const response = await enquirer.prompt({
type: 'input',
name: 'username',
message: 'What is your username?'
});
console.log(response);
```
@name prompt()
@param {Array|Object} `questions` Options objects for one or more prompts to run.
@return {Promise} Promise that returns an "answers" object with the user's responses.
@api public
|
ask
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
use(plugin) {
plugin.call(this, this);
return this;
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
use
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
set Prompt(value) {
this._Prompt = value;
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
Prompt
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
get Prompt() {
return this._Prompt || this.constructor.Prompt;
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
Prompt
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
get prompts() {
return this.constructor.prompts;
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
prompts
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
static set Prompt(value) {
this._Prompt = value;
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
Prompt
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
static get Prompt() {
return this._Prompt || require('./lib/prompt');
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
Prompt
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
static get prompts() {
return require('./lib/prompts');
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
prompts
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
static get types() {
return require('./lib/types');
}
|
Use an enquirer plugin.
```js
const Enquirer = require('enquirer');
const enquirer = new Enquirer();
const plugin = enquirer => {
// do stuff to enquire instance
};
enquirer.use(plugin);
```
@name use()
@param {Function} `plugin` Plugin function that takes an instance of Enquirer.
@return {Object} Returns the Enquirer instance.
@api public
|
types
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
static get prompt() {
const fn = (questions, ...rest) => {
let enquirer = new this(...rest);
let emit = enquirer.emit.bind(enquirer);
enquirer.emit = (...args) => {
fn.emit(...args);
return emit(...args);
};
return enquirer.prompt(questions);
};
utils.mixinEmitter(fn, new Events());
return fn;
}
|
Prompt function that takes a "question" object or array of question objects,
and returns an object with responses from the user.
```js
const { prompt } = require('enquirer');
const response = await prompt({
type: 'input',
name: 'username',
message: 'What is your username?'
});
console.log(response);
```
@name Enquirer#prompt
@param {Array|Object} `questions` Options objects for one or more prompts to run.
@return {Promise} Promise that returns an "answers" object with the user's responses.
@api public
|
prompt
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
fn = (questions, ...rest) => {
let enquirer = new this(...rest);
let emit = enquirer.emit.bind(enquirer);
enquirer.emit = (...args) => {
fn.emit(...args);
return emit(...args);
};
return enquirer.prompt(questions);
}
|
Prompt function that takes a "question" object or array of question objects,
and returns an object with responses from the user.
```js
const { prompt } = require('enquirer');
const response = await prompt({
type: 'input',
name: 'username',
message: 'What is your username?'
});
console.log(response);
```
@name Enquirer#prompt
@param {Array|Object} `questions` Options objects for one or more prompts to run.
@return {Promise} Promise that returns an "answers" object with the user's responses.
@api public
|
fn
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
fn = (questions, ...rest) => {
let enquirer = new this(...rest);
let emit = enquirer.emit.bind(enquirer);
enquirer.emit = (...args) => {
fn.emit(...args);
return emit(...args);
};
return enquirer.prompt(questions);
}
|
Prompt function that takes a "question" object or array of question objects,
and returns an object with responses from the user.
```js
const { prompt } = require('enquirer');
const response = await prompt({
type: 'input',
name: 'username',
message: 'What is your username?'
});
console.log(response);
```
@name Enquirer#prompt
@param {Array|Object} `questions` Options objects for one or more prompts to run.
@return {Promise} Promise that returns an "answers" object with the user's responses.
@api public
|
fn
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
define = name => {
utils.defineExport(Enquirer, name, () => Enquirer.types[name]);
}
|
Prompt function that takes a "question" object or array of question objects,
and returns an object with responses from the user.
```js
const { prompt } = require('enquirer');
const response = await prompt({
type: 'input',
name: 'username',
message: 'What is your username?'
});
console.log(response);
```
@name Enquirer#prompt
@param {Array|Object} `questions` Options objects for one or more prompts to run.
@return {Promise} Promise that returns an "answers" object with the user's responses.
@api public
|
define
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
define = name => {
utils.defineExport(Enquirer, name, () => Enquirer.types[name]);
}
|
Prompt function that takes a "question" object or array of question objects,
and returns an object with responses from the user.
```js
const { prompt } = require('enquirer');
const response = await prompt({
type: 'input',
name: 'username',
message: 'What is your username?'
});
console.log(response);
```
@name Enquirer#prompt
@param {Array|Object} `questions` Options objects for one or more prompts to run.
@return {Promise} Promise that returns an "answers" object with the user's responses.
@api public
|
define
|
javascript
|
enquirer/enquirer
|
index.js
|
https://github.com/enquirer/enquirer/blob/master/index.js
|
MIT
|
autofill = (answers = {}) => {
return enquirer => {
let prompt = enquirer.prompt.bind(enquirer);
let context = { ...enquirer.answers, ...answers };
enquirer.prompt = async questions => {
let list = [].concat(questions || []);
let choices = [];
for (let item of list) {
let value = context[item.name];
if (value !== void 0) {
choices.push({ name: item.name, value, hint: `(${value})` });
}
}
if (choices.length) {
let values = await enquirer.prompt({
type: 'multiselect',
name: 'autofill',
message: 'Would you like to autofill prompts with the following values?',
choices
});
for (let item of list) {
if (values.autofill.includes(item.name)) {
item.initial = context[item.name];
}
}
if (enquirer.cancelled) {
return values;
}
}
return prompt(list);
};
};
}
|
Example "autofill" plugin - to achieve similar goal to autofill for web forms.
_This isn't really needed in Enquirer, since the `autofill` option does
effectively the same thing natively_. This is just an example.
|
autofill
|
javascript
|
enquirer/enquirer
|
examples/autofill-plugin.js
|
https://github.com/enquirer/enquirer/blob/master/examples/autofill-plugin.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.