|
1 | | -import { isStr } from './isStr' |
2 | 1 | import { preload } from './preload' |
3 | 2 | import { addEventListener } from './addEventListener' |
4 | 3 | import { createElement } from './createElement' |
5 | 4 | import { isNum } from './isNum' |
6 | | -import { findElement } from './findElement' |
| 5 | +import { mount } from './mount' |
7 | 6 |
|
8 | | -export function waterfall(imageList: string[], container: string | HTMLElement | number, width = 200, space = 20) { |
9 | | - let mounted = false |
10 | | - let hasMounted = false |
11 | | - if (isNum(container)) { |
12 | | - width = container as number |
13 | | - container = 'body' |
| 7 | +export function waterfall(imageList: string[], target: string | HTMLElement | number, width = 200, space = 20) { |
| 8 | + if (isNum(target)) { |
| 9 | + width = target as number |
| 10 | + target = 'body' |
14 | 11 | } |
15 | | - if (!container) |
16 | | - container = 'body' |
17 | | - if (isStr(container)) |
18 | | - container = findElement(container) || container |
19 | | - if (isStr(container)) |
20 | | - throw new Error(`${container} is not a HTMLElement`) |
| 12 | + if (!target) |
| 13 | + target = 'body' |
21 | 14 | const imagesElement = preload(imageList, `width:${width}px;position:absolute;`) |
22 | 15 | const wrapper = createElement('div', { |
23 | 16 | id: 'simon-waterfall', |
24 | 17 | style: 'position:relative;width:100%;height:100%;', |
25 | 18 | }) |
26 | 19 |
|
27 | | - update() |
28 | | - addEventListener(window, 'resize', () => { |
29 | | - hasMounted = false |
30 | | - update() |
31 | | - }) |
32 | | - async function update() { |
33 | | - if (hasMounted) |
34 | | - return |
| 20 | + addEventListener(window, 'resize', () => update(target as HTMLElement)) |
35 | 21 |
|
36 | | - if (isStr(container) && !mounted) |
37 | | - return mounted = true |
38 | | - if (isStr(container)) |
39 | | - throw new Error(`${container} is not a HTMLElement`) |
| 22 | + async function update(container: Element) { |
40 | 23 | const realWidth = width + space |
41 | 24 | const n = Math.floor((container as HTMLElement).offsetWidth / realWidth) |
42 | 25 | const H = new Array(n).fill(0) |
@@ -75,14 +58,13 @@ export function waterfall(imageList: string[], container: string | HTMLElement | |
75 | 58 | (await promiseElements()).forEach(image => wrapper.appendChild(image)) |
76 | 59 | removeWrapper(container as HTMLElement); |
77 | 60 | (container as HTMLElement).appendChild(wrapper) |
78 | | - hasMounted = true |
79 | 61 | } |
| 62 | + mount(target, container => update(target = container as HTMLElement)) |
80 | 63 |
|
81 | 64 | return (imageList: string[]) => { |
82 | 65 | const appendElement = preload(imageList, `width:${width}px;position:absolute;`) |
83 | 66 | imagesElement.push(...appendElement) |
84 | | - hasMounted = false |
85 | | - update() |
| 67 | + update(target as HTMLElement) |
86 | 68 | } |
87 | 69 |
|
88 | 70 | function removeWrapper(container: HTMLElement) { |
|
0 commit comments