Skip to content

Commit

Permalink
feat: warnings are printed only when debug is enabled (close #106)
Browse files Browse the repository at this point in the history
  • Loading branch information
qq15725 committed Nov 6, 2024
1 parent f702db8 commit b50711a
Show file tree
Hide file tree
Showing 16 changed files with 76 additions and 74 deletions.
8 changes: 5 additions & 3 deletions src/clone-canvas.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { consoleWarn, createImage } from './utils'
import type { Context } from './context'
import { createImage } from './utils'

export function cloneCanvas<T extends HTMLCanvasElement>(
canvas: T,
context: Context,
): HTMLCanvasElement | HTMLImageElement {
if (canvas.ownerDocument) {
try {
Expand All @@ -11,7 +13,7 @@ export function cloneCanvas<T extends HTMLCanvasElement>(
}
}
catch (error) {
consoleWarn('Failed to clone canvas', error)
context.log.warn('Failed to clone canvas', error)
}
}

Expand All @@ -30,7 +32,7 @@ export function cloneCanvas<T extends HTMLCanvasElement>(
return cloned
}
catch (error) {
consoleWarn('Failed to clone canvas', error)
context.log.warn('Failed to clone canvas', error)
}

return cloned
Expand Down
4 changes: 2 additions & 2 deletions src/clone-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function cloneElement<T extends HTMLElement | SVGElement>(
context: Context,
): (HTMLElement | SVGElement) | Promise<HTMLElement | SVGElement> {
if (isCanvasElement(node)) {
return cloneCanvas(node)
return cloneCanvas(node, context)
}

if (isIFrameElement(node)) {
Expand All @@ -27,7 +27,7 @@ export function cloneElement<T extends HTMLElement | SVGElement>(
}

if (isVideoElement(node)) {
return cloneVideo(node)
return cloneVideo(node, context)
}

return node.cloneNode(false) as T
Expand Down
3 changes: 1 addition & 2 deletions src/clone-iframe.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import type { Context } from './context'
import { cloneNode } from './clone-node'
import { consoleWarn } from './utils'

export function cloneIframe<T extends HTMLIFrameElement>(
iframe: T,
Expand All @@ -12,7 +11,7 @@ export function cloneIframe<T extends HTMLIFrameElement>(
}
}
catch (error) {
consoleWarn('Failed to clone iframe', error)
context.log.warn('Failed to clone iframe', error)
}

return iframe.cloneNode(false) as HTMLIFrameElement
Expand Down
12 changes: 6 additions & 6 deletions src/clone-video.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { Context } from './context'
import { cloneCanvas } from './clone-canvas'
import { consoleWarn, createImage, loadMedia } from './utils'
import { createImage, loadMedia } from './utils'

export async function cloneVideo<T extends HTMLVideoElement>(
video: T,
context: Context,
): Promise<HTMLCanvasElement | HTMLImageElement | HTMLVideoElement> {
if (
video.ownerDocument
Expand All @@ -22,9 +24,7 @@ export async function cloneVideo<T extends HTMLVideoElement>(
const ownerDocument = cloned.ownerDocument
if (ownerDocument) {
let canPlay = true
await loadMedia(cloned, {
onError: () => canPlay = false,
})
await loadMedia(cloned, { onError: () => canPlay = false, onWarn: context.log.warn })
if (!canPlay) {
if (video.poster) {
return createImage(video.poster, video.ownerDocument)
Expand All @@ -44,13 +44,13 @@ export async function cloneVideo<T extends HTMLVideoElement>(
ctx.drawImage(cloned, 0, 0, canvas.width, canvas.height)
}
catch (error) {
consoleWarn('Failed to clone video', error)
context.log.warn('Failed to clone video', error)
if (video.poster) {
return createImage(video.poster, video.ownerDocument)
}
return cloned
}
return cloneCanvas(canvas)
return cloneCanvas(canvas, context)
}

return cloned
Expand Down
3 changes: 1 addition & 2 deletions src/converts/dom-to-foreign-object-svg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { destroyContext } from '../destroy-context'
import { embedNode } from '../embed-node'
import { embedWebFont } from '../embed-web-font'
import {
consoleWarn,
createSvg,
isElementNode,
isSVGElementNode,
Expand Down Expand Up @@ -67,7 +66,7 @@ export async function domToForeignObjectSvg(node: any, options?: any): Promise<S
await task
}
catch (error) {
consoleWarn('Failed to run task', error)
context.log.warn('Failed to run task', error)
}
progress?.(++current, count)
}
Expand Down
4 changes: 2 additions & 2 deletions src/copy-pseudo-class.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Context } from './context'
import { getDefaultStyle } from './get-default-style'
import { getDiffStyle } from './get-diff-style'
import { consoleWarn, uuid } from './utils'
import { uuid } from './utils'

const pseudoClasses = [
':before',
Expand Down Expand Up @@ -76,7 +76,7 @@ export function copyPseudoClass<T extends HTMLElement | SVGElement>(
(cloned as any).className = [(cloned as any).className, ...klasses].join(' ')
}
catch (err) {
consoleWarn('Failed to copyPseudoClass', err)
context.log.warn('Failed to copyPseudoClass', err)
return
}

Expand Down
5 changes: 2 additions & 3 deletions src/create-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type { Options } from './options'
import { createLogger } from './create-logger'
import { getDefaultRequestInit } from './get-default-request-init'
import {
consoleWarn,
IN_BROWSER,
isContext,
isElementNode,
Expand Down Expand Up @@ -97,7 +96,7 @@ export async function createContext<T extends Node>(node: T, options?: Options &
return worker
}
catch (error) {
consoleWarn('Failed to new Worker', error)
context.log.warn('Failed to new Worker', error)
return null
}
}).filter(Boolean) as any,
Expand Down Expand Up @@ -126,7 +125,7 @@ export async function createContext<T extends Node>(node: T, options?: Options &
}

context.log.time('wait until load')
await waitUntilLoad(node, context.timeout)
await waitUntilLoad(node, { timeout: context.timeout, onWarn: context.log.warn })
context.log.timeEnd('wait until load')

const { width, height } = resolveBoundingBox(node, context)
Expand Down
8 changes: 5 additions & 3 deletions src/create-logger.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { consoleTime, consoleTimeEnd, consoleWarn } from './utils'
import { consoleWarn, PREFIX } from './utils'

export interface Logger {
time: (label: string) => void
Expand All @@ -8,8 +8,10 @@ export interface Logger {

export function createLogger(debug: boolean): Logger {
return {
time: (label: string) => debug && consoleTime(label),
timeEnd: (label: string) => debug && consoleTimeEnd(label),
// eslint-disable-next-line no-console
time: (label: string) => debug && console.time(`${PREFIX} ${label}`),
// eslint-disable-next-line no-console
timeEnd: (label: string) => debug && console.timeEnd(`${PREFIX} ${label}`),
warn: (...args: any[]) => debug && consoleWarn(...args),
}
}
4 changes: 2 additions & 2 deletions src/css-url.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Context } from './context'
import { contextFetch } from './fetch'
import { consoleWarn, isDataUrl, resolveUrl } from './utils'
import { isDataUrl, resolveUrl } from './utils'

export async function replaceCssUrlToDataUrl(
cssText: string,
Expand All @@ -24,7 +24,7 @@ export async function replaceCssUrlToDataUrl(
cssText = cssText.replace(toRE(rawUrl), `$1${dataUrl}$3`)
}
catch (error) {
consoleWarn('Failed to fetch css data url', rawUrl, error)
context.log.warn('Failed to fetch css data url', rawUrl, error)
}
}

Expand Down
3 changes: 1 addition & 2 deletions src/destroy-context.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import type { Context } from './context'
import { consoleWarn } from './utils'

export function destroyContext(context: Context): void {
context.ownerDocument = undefined
Expand All @@ -13,7 +12,7 @@ export function destroyContext(context: Context): void {
context.sandbox.remove()
}
catch (err) {
consoleWarn('Failed to destroyContext', err)
context.log.warn('Failed to destroyContext', err)
}
context.sandbox = undefined
}
Expand Down
8 changes: 4 additions & 4 deletions src/embed-web-font.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { Context } from './context'
import { hasCssUrl, replaceCssUrlToDataUrl, URL_RE } from './css-url'
import { contextFetch } from './fetch'
import { consoleWarn, isCssFontFaceRule, isCSSImportRule, resolveUrl, splitFontFamily } from './utils'
import { isCssFontFaceRule, isCSSImportRule, resolveUrl, splitFontFamily } from './utils'

export async function embedWebFont<T extends Element>(
clone: T,
Expand Down Expand Up @@ -34,7 +34,7 @@ export async function embedWebFont<T extends Element>(
return 'cssRules' in styleSheet && Boolean(styleSheet.cssRules.length)
}
catch (error) {
consoleWarn(`Error while reading CSS rules from ${styleSheet.href}`, error)
context.log.warn(`Error while reading CSS rules from ${styleSheet.href}`, error)
return false
}
})
Expand All @@ -54,7 +54,7 @@ export async function embedWebFont<T extends Element>(
})
}
catch (error) {
consoleWarn(`Error fetch remote css import from ${baseUrl}`, error)
context.log.warn(`Error fetch remote css import from ${baseUrl}`, error)
}
const replacedCssText = cssText.replace(
URL_RE,
Expand All @@ -70,7 +70,7 @@ export async function embedWebFont<T extends Element>(
)
}
catch (error) {
consoleWarn('Error inserting rule from remote css import', { rule, error })
context.log.warn('Error inserting rule from remote css import', { rule, error })
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Context } from './context'
import { blobToDataUrl, consoleWarn, IN_FIREFOX, IN_SAFARI } from './utils'
import { blobToDataUrl, IN_FIREFOX, IN_SAFARI } from './utils'

export type BaseFetchOptions = RequestInit & {
url: string
Expand Down Expand Up @@ -122,7 +122,7 @@ export function contextFetch(context: Context, options: ContextFetchOptions): Pr
requests.delete(rawUrl)

if (requestType === 'image' && placeholderImage) {
consoleWarn('Failed to fetch image base64, trying to use placeholder image', url)
context.log.warn('Failed to fetch image base64, trying to use placeholder image', url)
return typeof placeholderImage === 'string'
? placeholderImage
: placeholderImage(imageDom!)
Expand Down
32 changes: 6 additions & 26 deletions src/get-default-style.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Context } from './context'
import { consoleWarn, isSVGElementNode, uuid, XMLNS } from './utils'
import { getSandBox } from './sandbox'
import { isSVGElementNode, XMLNS } from './utils'

const ignoredStyles = [
'width',
Expand All @@ -17,7 +18,7 @@ export function getDefaultStyle(
pseudoElement: string | null,
context: Context,
): Map<string, any> {
const { defaultComputedStyles, ownerDocument } = context
const { defaultComputedStyles } = context

const nodeName = node.nodeName.toLowerCase()
const isSvgNode = isSVGElementNode(node) && nodeName !== 'svg'
Expand All @@ -39,32 +40,11 @@ export function getDefaultStyle(
if (defaultComputedStyles.has(key))
return defaultComputedStyles.get(key)!

let sandbox = context.sandbox
if (!sandbox) {
try {
if (ownerDocument) {
sandbox = ownerDocument.createElement('iframe')
sandbox.id = `__SANDBOX__-${uuid()}`
sandbox.width = '0'
sandbox.height = '0'
sandbox.style.visibility = 'hidden'
sandbox.style.position = 'fixed'
ownerDocument.body.appendChild(sandbox)
sandbox.contentWindow?.document.write('<!DOCTYPE html><meta charset="UTF-8"><title></title><body>')
context.sandbox = sandbox
}
}
catch (error) {
consoleWarn('Failed to create iframe sandbox', error)
}
}
if (!sandbox)
return new Map()

const sandboxWindow = sandbox.contentWindow
const sandbox = getSandBox(context)
const sandboxWindow = sandbox?.contentWindow
if (!sandboxWindow)
return new Map()
const sandboxDocument = sandboxWindow.document
const sandboxDocument = sandboxWindow?.document

let root: HTMLElement | SVGSVGElement
let el: Element
Expand Down
6 changes: 3 additions & 3 deletions src/image-to-canvas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { Context } from './context'
import { consoleWarn, loadMedia } from './utils'
import { loadMedia } from './utils'

export async function imageToCanvas<T extends HTMLImageElement>(
image: T,
Expand All @@ -13,14 +13,14 @@ export async function imageToCanvas<T extends HTMLImageElement>(
} = context

log.time('image to canvas')
const loaded = await loadMedia(image, { timeout })
const loaded = await loadMedia(image, { timeout, onWarn: context.log.warn })
const { canvas, context2d } = createCanvas(image.ownerDocument, context)
const drawImage = (): void => {
try {
context2d?.drawImage(loaded, 0, 0, canvas.width, canvas.height)
}
catch (error) {
consoleWarn('Failed to drawImage', error)
context.log.warn('Failed to drawImage', error)
}
}

Expand Down
26 changes: 26 additions & 0 deletions src/sandbox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type { Context } from './context'
import { uuid } from './utils'

export function getSandBox(context: Context): HTMLIFrameElement | undefined {
let sandbox = context.sandbox
if (!sandbox) {
const { ownerDocument } = context
try {
if (ownerDocument) {
sandbox = ownerDocument.createElement('iframe')
sandbox.id = `__SANDBOX__-${uuid()}`
sandbox.width = '0'
sandbox.height = '0'
sandbox.style.visibility = 'hidden'
sandbox.style.position = 'fixed'
ownerDocument.body.appendChild(sandbox)
sandbox.contentWindow?.document.write('<!DOCTYPE html><meta charset="UTF-8"><title></title><body>')
context.sandbox = sandbox
}
}
catch (error) {
context.log.warn('Failed to getSandBox', error)
}
}
return sandbox
}
Loading

0 comments on commit b50711a

Please sign in to comment.