Skip to content

Commit

Permalink
Merge 64fe965 into 166ad01
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Sep 20, 2019
2 parents 166ad01 + 64fe965 commit 327de7f
Show file tree
Hide file tree
Showing 5 changed files with 251 additions and 207 deletions.
7 changes: 7 additions & 0 deletions packages/examples/package.json
Expand Up @@ -26,6 +26,13 @@
"headless",
"puppeteer"
],
"dependencies": {
"beauty-error": "~1.2.2",
"meow": "~5.0.0",
"ora": "~3.4.0",
"process-stats": "~3.1.1",
"time-span": "~3.1.0"
},
"devDependencies": {
"browserless": "latest",
"lodash": "latest",
Expand Down
41 changes: 31 additions & 10 deletions packages/examples/src/main.js
@@ -1,14 +1,35 @@
'use strict'

const beautyError = require('beauty-error')
const procStats = require('process-stats')
const { URL } = require('url')
const meow = require('meow')
const ora = require('ora')

module.exports = fn =>
fn(new URL(process.argv[2]))
.then(output => {
if (output) console.log(output)
process.exit()
})
.catch(err => {
console.error('ERROR', err)
process.exit(1)
})
const cli = meow()

module.exports = async fn => {
const spinner = ora().start()
try {
const url = new URL(cli.input[0]).toString()
const output = await fn(url, cli.flags)

spinner.stop()

if (output) console.log(output)

if (!cli.flags.quiet) {
const { cpu, uptime, memUsed } = procStats()
console.log()
console.log(` time : ${uptime.pretty}`)
console.log(` memory : ${memUsed.pretty}`)
console.log(` cpu : ${cpu}`)
}

process.exit()
} catch (err) {
spinner.stop()
console.error(beautyError(err))
process.exit(1)
}
}
71 changes: 39 additions & 32 deletions packages/examples/src/screenshot.js
@@ -1,44 +1,51 @@
'use strict'

// const uniqueRandomArray = require('unique-random-array')
const uniqueRandomArray = require('unique-random-array')
const createBrowserless = require('browserless')
const termImg = require('term-img')

const browserless = createBrowserless()

// const BACKGROUNDS = [
// 'linear-gradient(225deg, #FF057C 0%, #8D0B93 50%, #321575 100%)',
// 'linear-gradient(225deg, #A445B2 0%, #D41872 52%, #FF0066 100%)',
// 'linear-gradient(225deg, #AC32E4 0%, #7918F2 48%, #4801FF 100%)',
// 'linear-gradient(225deg, #22E1FF 0%, #1D8FE1 48%, #625EB1 100%)',
// 'linear-gradient(225deg, #2CD8D5 0%, #6B8DD6 48%, #8E37D7 100%)',
// 'linear-gradient(90deg, #495AFF 0%, #0ACFFE 100%)',
// 'linear-gradient(0deg, #6713D2 0%, #CC208E 100%)',
// 'linear-gradient(270deg, #EC8C69 0%, #ED6EA0 100%)',
// 'linear-gradient(0deg, #FE5196 0%, #F77062 100%)',
// 'linear-gradient(270deg, #F9D423 0%, #F83600 100%)',
// 'linear-gradient(270deg, #FE9A8B 0%, #FD868C 41%, #F9748F 73%, #F78CA0 100%)',
// 'linear-gradient(0deg, #6F86D6 0%, #48C6EF 100%)',
// 'linear-gradient(0deg, #FA71CD 0%, #C471F5 100%)',
// 'linear-gradient(270deg, #6A11CB 0%, #2575FC 100%)',
// 'linear-gradient(270deg, #B465DA 0%, #CF6CC9 28%, #EE609C 68%, #EE609C 100%)',
// 'linear-gradient(0deg, #330867 0%, #30CFD0 100%)',
// 'linear-gradient(270deg, #FEE140 0%, #FA709A 100%)'
// ]
// const randBackground = uniqueRandomArray(BACKGROUNDS)

require('./main')(async url => {
const buffer = await browserless.screenshot(url.toString(), {
hide: ['.crisp-client', '#cookies-policy'],
disableAnimations: true,
overlay: {
browser: 'safari-dark',
// background: '#c1c'
const BACKGROUNDS = [
'linear-gradient(225deg, #FF057C 0%, #8D0B93 50%, #321575 100%)',
'linear-gradient(225deg, #A445B2 0%, #D41872 52%, #FF0066 100%)',
'linear-gradient(225deg, #AC32E4 0%, #7918F2 48%, #4801FF 100%)',
'linear-gradient(225deg, #22E1FF 0%, #1D8FE1 48%, #625EB1 100%)',
'linear-gradient(225deg, #2CD8D5 0%, #6B8DD6 48%, #8E37D7 100%)',
'linear-gradient(90deg, #495AFF 0%, #0ACFFE 100%)',
'linear-gradient(0deg, #6713D2 0%, #CC208E 100%)',
'linear-gradient(270deg, #EC8C69 0%, #ED6EA0 100%)',
'linear-gradient(0deg, #FE5196 0%, #F77062 100%)',
'linear-gradient(270deg, #F9D423 0%, #F83600 100%)',
'linear-gradient(270deg, #FE9A8B 0%, #FD868C 41%, #F9748F 73%, #F78CA0 100%)',
'linear-gradient(0deg, #6F86D6 0%, #48C6EF 100%)',
'linear-gradient(0deg, #FA71CD 0%, #C471F5 100%)',
'linear-gradient(270deg, #6A11CB 0%, #2575FC 100%)',
'linear-gradient(270deg, #B465DA 0%, #CF6CC9 28%, #EE609C 68%, #EE609C 100%)',
'linear-gradient(0deg, #330867 0%, #30CFD0 100%)',
'linear-gradient(270deg, #FEE140 0%, #FA709A 100%)'
]

const randBackground = uniqueRandomArray(BACKGROUNDS)

require('./main')(async (url, opts) => {
if (opts.background === 'unsplash') {
opts.overlay = {
background: 'https://source.unsplash.com/random/1920x1080'
// background: randBackground()
}
})
}

if (opts.background === 'gradient') {
opts.overlay = {
background: randBackground()
}
}

const buffer = await browserless.screenshot(url, opts)
termImg(buffer)
// require('fs').writeFileSync('screenshot.png', buffer)

if (opts.save) {
require('fs').writeFileSync('screenshot.png', buffer)
console.log('image saved!')
}
})
170 changes: 5 additions & 165 deletions packages/screenshot/src/index.js
@@ -1,15 +1,12 @@
'use strict'

const svgGradient = require('svg-gradient')
const goto = require('@browserless/goto')
const isHttpUrl = require('is-url-http')
const sharp = require('sharp')
const path = require('path')
const got = require('got')

const isUrl = string => /^(https?|file):\/\/|^data:/.test(string)

const toArray = value => [].concat(value)
const preparePage = require('./prepare')

const browserOverlay = ['safari-light', 'safari-dark'].reduce(
(acc, key) => ({
Expand All @@ -19,90 +16,6 @@ const browserOverlay = ['safari-light', 'safari-dark'].reduce(
{}
)

const scrollToElement = (element, options) => {
const isOverflown = element => {
return element.scrollHeight > element.clientHeight || element.scrollWidth > element.clientWidth
}

const findScrollParent = element => {
if (element === undefined) {
return
}

if (isOverflown(element)) {
return element
}

return findScrollParent(element.parentElement)
}

const calculateOffset = (rect, options) => {
if (options === undefined) {
return {
x: rect.left,
y: rect.top
}
}

const offset = options.offset || 0

switch (options.offsetFrom) {
case 'top':
return {
x: rect.left,
y: rect.top + offset
}
case 'right':
return {
x: rect.left - offset,
y: rect.top
}
case 'bottom':
return {
x: rect.left,
y: rect.top - offset
}
case 'left':
return {
x: rect.left + offset,
y: rect.top
}
default:
throw new Error('Invalid `scrollToElement.offsetFrom` value')
}
}

const rect = element.getBoundingClientRect()
const offset = calculateOffset(rect, options)
const parent = findScrollParent(element)

if (parent !== undefined) {
parent.scrollTo(offset.x, offset.y)
}
}

const doDisableAnimations = () => {
const rule = `
*,
::before,
::after {
animation: initial !important;
transition: initial !important;
}
`
const style = document.createElement('style')
if (document.body) document.body.append(style)
if (style.sheet) style.sheet.insertRule(rule)
}

const hideElements = elements => {
for (const element of elements) {
if (element) element.style.display = 'none'
}
}

const createSvgBackground = css => svgGradient(css, { width: '1388px', height: '955px' })

const getBackground = async (bg = 'transparent') => {
if (isHttpUrl(bg)) {
const { body } = await got(bg, { encoding: null })
Expand All @@ -116,84 +29,12 @@ const getBackground = async (bg = 'transparent') => {
return Buffer.from(createSvgBackground(bg))
}

const getInjectKey = (ext, value) =>
isUrl(value) ? 'url' : value.endsWith(`.${ext}`) ? 'path' : 'content'

module.exports = page => async (url, opts = {}) => {
const {
device = 'macbook pro 13',
type = 'png',
disableAnimations = true,
hide,
click,
modules,
scripts,
styles,
element,
scrollTo,
overlay,
...args
} = opts

await goto(page, { url, device, ...args })
await page.evaluateHandle('document.fonts.ready')

if (disableAnimations) {
await page.evaluate(doDisableAnimations)
}

if (hide) {
await Promise.all(toArray(hide).map(selector => page.$$eval(selector, hideElements)))
}

if (click) {
for (const selector of toArray(click)) {
try {
await page.click(selector)
} catch (err) {}
}
}

if (modules) {
await Promise.all(
toArray(modules).map(m => {
return page.addScriptTag({
[getInjectKey('js', m)]: m,
type: 'module'
})
})
)
}

if (scripts) {
await Promise.all(
toArray(scripts).map(script => {
return page.addScriptTag({
[getInjectKey('js', script)]: script
})
})
)
}
const createSvgBackground = css => svgGradient(css, { width: '1388px', height: '955px' })

if (styles) {
await Promise.all(
toArray(styles).map(style => {
return page.addStyleTag({
[getInjectKey('css', style)]: style
})
})
)
}
module.exports = page => async (url, { direction = 'vertical', overlay, ...opts } = {}) => {
await preparePage(page, url, opts)
const screenshot = await page.screenshot(opts)

if (scrollTo) {
if (typeof scrollTo === 'object') {
await page.$eval(scrollTo.element, scrollToElement, scrollTo)
} else {
await page.$eval(scrollTo, scrollToElement)
}
}

const screenshot = await page.screenshot({ type, ...args })
if (!overlay) return screenshot

const { browser: browserTheme, background } = overlay
Expand All @@ -207,7 +48,6 @@ module.exports = page => async (url, opts = {}) => {
}

image = await image.composite(inputs)

const buffer = await image.toBuffer()
return buffer
}

0 comments on commit 327de7f

Please sign in to comment.