|
import { default as defaultOptions, flatten as flattenOptions, } from './options.js'; |
|
import * as staticMethods from './static.js'; |
|
import { Cheerio } from './cheerio.js'; |
|
import { isHtml, isCheerio } from './utils.js'; |
|
export function getLoad(parse, render) { |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return function load(content, options, isDocument = true) { |
|
if (content == null) { |
|
throw new Error('cheerio.load() expects a string'); |
|
} |
|
const internalOpts = { ...defaultOptions, ...flattenOptions(options) }; |
|
const initialRoot = parse(content, internalOpts, isDocument, null); |
|
|
|
class LoadedCheerio extends Cheerio { |
|
_make(selector, context) { |
|
const cheerio = initialize(selector, context); |
|
cheerio.prevObject = this; |
|
return cheerio; |
|
} |
|
_parse(content, options, isDocument, context) { |
|
return parse(content, options, isDocument, context); |
|
} |
|
_render(dom) { |
|
return render(dom, this.options); |
|
} |
|
} |
|
function initialize(selector, context, root = initialRoot, opts) { |
|
|
|
if (selector && isCheerio(selector)) |
|
return selector; |
|
const options = { |
|
...internalOpts, |
|
...flattenOptions(opts), |
|
}; |
|
const r = typeof root === 'string' |
|
? [parse(root, options, false, null)] |
|
: 'length' in root |
|
? root |
|
: [root]; |
|
const rootInstance = isCheerio(r) |
|
? r |
|
: new LoadedCheerio(r, null, options); |
|
|
|
rootInstance._root = rootInstance; |
|
|
|
if (!selector) { |
|
return new LoadedCheerio(undefined, rootInstance, options); |
|
} |
|
const elements = typeof selector === 'string' && isHtml(selector) |
|
? |
|
parse(selector, options, false, null).children |
|
: isNode(selector) |
|
? |
|
[selector] |
|
: Array.isArray(selector) |
|
? |
|
selector |
|
: undefined; |
|
const instance = new LoadedCheerio(elements, rootInstance, options); |
|
if (elements) { |
|
return instance; |
|
} |
|
if (typeof selector !== 'string') { |
|
throw new Error('Unexpected type of selector'); |
|
} |
|
|
|
let search = selector; |
|
const searchContext = !context |
|
? |
|
rootInstance |
|
: typeof context === 'string' |
|
? isHtml(context) |
|
? |
|
new LoadedCheerio([parse(context, options, false, null)], rootInstance, options) |
|
: |
|
((search = `${context} ${search}`), rootInstance) |
|
: isCheerio(context) |
|
? |
|
context |
|
: |
|
new LoadedCheerio(Array.isArray(context) ? context : [context], rootInstance, options); |
|
|
|
if (!searchContext) |
|
return instance; |
|
|
|
|
|
|
|
return searchContext.find(search); |
|
} |
|
|
|
Object.assign(initialize, staticMethods, { |
|
load, |
|
|
|
_root: initialRoot, |
|
_options: internalOpts, |
|
|
|
fn: LoadedCheerio.prototype, |
|
|
|
prototype: LoadedCheerio.prototype, |
|
}); |
|
return initialize; |
|
}; |
|
} |
|
function isNode(obj) { |
|
return (!!obj.name || |
|
obj.type === 'root' || |
|
obj.type === 'text' || |
|
obj.type === 'comment'); |
|
} |
|
|