@alikhalilll/a-smart-skeleton 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +356 -2
- package/dist/_chunks/core.js +2314 -0
- package/dist/_chunks/core.js.map +1 -0
- package/dist/_chunks/index.d.ts +431 -0
- package/dist/core/index.cjs +67 -0
- package/dist/core/index.d.cts +2 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/element/index.cjs +47 -0
- package/dist/element/index.cjs.map +1 -0
- package/dist/element/index.d.cts +24 -0
- package/dist/element/index.d.ts +24 -0
- package/dist/element/index.js +46 -0
- package/dist/element/index.js.map +1 -0
- package/dist/index.cjs +512 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +204 -0
- package/dist/index.d.ts +204 -0
- package/dist/index.js +441 -0
- package/dist/index.js.map +1 -0
- package/dist/nuxt/index.cjs +36 -0
- package/dist/nuxt/index.cjs.map +1 -0
- package/dist/nuxt/index.d.cts +30 -0
- package/dist/nuxt/index.d.ts +30 -0
- package/dist/nuxt/index.js +36 -0
- package/dist/nuxt/index.js.map +1 -0
- package/dist/resolver/index.cjs +26 -0
- package/dist/resolver/index.cjs.map +1 -0
- package/dist/resolver/index.d.cts +19 -0
- package/dist/resolver/index.d.ts +19 -0
- package/dist/resolver/index.js +26 -0
- package/dist/resolver/index.js.map +1 -0
- package/dist/styles.css +136 -0
- package/package.json +144 -3
- package/src/components/ASmartSkeleton.vue +228 -0
- package/src/components/ASmartSkeletonBox.vue +23 -0
- package/src/components/ASmartSkeletonProvider.vue +34 -0
- package/src/components/ASmartSkeletonSuspense.vue +142 -0
- package/src/composables/useSmartSkeleton.ts +20 -0
- package/src/composables/useStyles.ts +8 -0
- package/src/core/boot.ts +63 -0
- package/src/core/canvas.ts +7 -0
- package/src/core/constants.ts +76 -0
- package/src/core/debug.ts +154 -0
- package/src/core/dev.ts +53 -0
- package/src/core/fade.ts +490 -0
- package/src/core/ghost.ts +236 -0
- package/src/core/images.ts +28 -0
- package/src/core/index.ts +71 -0
- package/src/core/inline.generated.ts +9 -0
- package/src/core/measure.ts +571 -0
- package/src/core/memory.ts +146 -0
- package/src/core/motion.ts +12 -0
- package/src/core/plan.ts +368 -0
- package/src/core/reveal.ts +89 -0
- package/src/core/reveals.ts +39 -0
- package/src/core/shapes.ts +84 -0
- package/src/core/shimmer.ts +229 -0
- package/src/core/skeleton.ts +43 -0
- package/src/core/snapshot.ts +159 -0
- package/src/core/styles.ts +187 -0
- package/src/core/sweep.ts +203 -0
- package/src/core/theme.ts +162 -0
- package/src/element/index.ts +59 -0
- package/src/index.ts +27 -0
- package/src/nuxt/index.ts +59 -0
- package/src/resolver/index.ts +35 -0
- package/src/types.ts +100 -0
- package/src/vue/Skeleton.ts +275 -0
- package/src/vue/Suspense.ts +157 -0
- package/src/vue/config.ts +78 -0
- package/src/vue/index.ts +7 -0
- package/web-types.json +256 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { serialize } from './snapshot';
|
|
2
|
+
|
|
3
|
+
const STORAGE_KEY = 'a-smart-skeleton:shapes';
|
|
4
|
+
const VERSION = 2; // Bumped whenever the stored markup changes meaning
|
|
5
|
+
const MAX_SHAPES = 50;
|
|
6
|
+
const MAX_LENGTH = 20_000;
|
|
7
|
+
|
|
8
|
+
type Stored = Record<string, string>; // Oldest first
|
|
9
|
+
|
|
10
|
+
// Real text, kept in memory only — exact for a reload within the same visit
|
|
11
|
+
const session = new Map<string, string>();
|
|
12
|
+
const shown = new Map<string, Set<() => void>>();
|
|
13
|
+
|
|
14
|
+
/** Registers a save for content on screen under `key`; returns its unregister. */
|
|
15
|
+
export function trackShape(key: string, save: () => void) {
|
|
16
|
+
if (!shown.has(key)) shown.set(key, new Set());
|
|
17
|
+
shown.get(key)!.add(save);
|
|
18
|
+
return () => shown.get(key)?.delete(save);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Saves every shown copy of `key` now, so a skeleton about to recall it gets the latest. */
|
|
22
|
+
export function flushShapes(key: string) {
|
|
23
|
+
for (const save of shown.get(key) ?? []) save();
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Treats anything parsed from localStorage as hostile: must be the expected envelope,
|
|
27
|
+
// `shapes` must be a plain string-to-string dictionary, and the output is a null-prototype
|
|
28
|
+
// object so no later lookup can be confused by an inherited key.
|
|
29
|
+
function read(): Stored {
|
|
30
|
+
try {
|
|
31
|
+
const raw = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? 'null');
|
|
32
|
+
if (!raw || typeof raw !== 'object' || raw.v !== VERSION) return Object.create(null);
|
|
33
|
+
const incoming = raw.shapes;
|
|
34
|
+
if (!incoming || typeof incoming !== 'object') return Object.create(null);
|
|
35
|
+
const out: Stored = Object.create(null);
|
|
36
|
+
for (const key of Object.keys(incoming)) {
|
|
37
|
+
const value = (incoming as Record<string, unknown>)[key];
|
|
38
|
+
if (typeof value === 'string') out[key] = value;
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
} catch {
|
|
42
|
+
return Object.create(null);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function write(shapes: Stored) {
|
|
47
|
+
try {
|
|
48
|
+
localStorage.setItem(STORAGE_KEY, JSON.stringify({ v: VERSION, shapes }));
|
|
49
|
+
} catch {
|
|
50
|
+
// Storage full or blocked; the session copy still covers this visit
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function rememberShape(key: string, element: HTMLElement) {
|
|
55
|
+
session.set(key, serialize(element, false));
|
|
56
|
+
|
|
57
|
+
const html = serialize(element, true);
|
|
58
|
+
if (html.length > MAX_LENGTH) return;
|
|
59
|
+
|
|
60
|
+
const shapes = read();
|
|
61
|
+
// Re-inserted so it moves to the end: key order is recency
|
|
62
|
+
delete shapes[key];
|
|
63
|
+
shapes[key] = html;
|
|
64
|
+
const keys = Object.keys(shapes);
|
|
65
|
+
for (const stale of keys.slice(0, keys.length - MAX_SHAPES)) {
|
|
66
|
+
delete shapes[stale];
|
|
67
|
+
}
|
|
68
|
+
write(shapes);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function recallShape(key: string): string | null {
|
|
72
|
+
return session.get(key) ?? read()[key] ?? null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Forgets remembered shapes — call it on sign-out. */
|
|
76
|
+
export function forgetShapes({ persisted = true } = {}) {
|
|
77
|
+
session.clear();
|
|
78
|
+
if (!persisted) return;
|
|
79
|
+
try {
|
|
80
|
+
localStorage.removeItem(STORAGE_KEY);
|
|
81
|
+
} catch {
|
|
82
|
+
// Nothing stored to forget
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { ATTR_RECT, DURATIONS, HIGHLIGHT } from './constants';
|
|
2
|
+
import type { SkeletonAnimation, SkeletonSpeed } from './theme';
|
|
3
|
+
import { animationsOf, prefersReducedMotion } from './motion';
|
|
4
|
+
import type { SkeletonRect } from './measure';
|
|
5
|
+
|
|
6
|
+
const SWEEP = 0.7; // of a duration a sweep takes at the reference width — sweeps run back to back, so this sets the pace
|
|
7
|
+
const REFERENCE_WIDTH = 1280; // A shimmer's duration is one loop across this; any other width keeps its pace
|
|
8
|
+
const MAX_BAND = 320; // The highlight's width, so it doesn't grow heavier on a wide screen
|
|
9
|
+
const SPACING = 2.5; // bands follow each other this many band-widths apart, start to start — the gap between sweeps
|
|
10
|
+
const PULSE_LOW = 0.45; // opacity at the bottom of a pulse
|
|
11
|
+
|
|
12
|
+
const ANIMATIONS: readonly SkeletonAnimation[] = ['shimmer', 'group-shimmer', 'pulse', 'none'];
|
|
13
|
+
|
|
14
|
+
export type Motion = { animation: SkeletonAnimation; duration: number };
|
|
15
|
+
|
|
16
|
+
/** The animation an element inherits from the theme: `--ask-animation` and `--ask-speed`. */
|
|
17
|
+
export function motionOf(element: Element): Motion {
|
|
18
|
+
const style = getComputedStyle(element);
|
|
19
|
+
const read = <T extends string>(name: string, allowed: readonly T[], fallback: T): T => {
|
|
20
|
+
const value = style.getPropertyValue(name).trim() as T;
|
|
21
|
+
return allowed.includes(value) ? value : fallback;
|
|
22
|
+
};
|
|
23
|
+
const animation = read('--ask-animation', ANIMATIONS, 'shimmer');
|
|
24
|
+
const speed = read<SkeletonSpeed>('--ask-speed', ['slow', 'fast'], 'slow');
|
|
25
|
+
return {
|
|
26
|
+
animation,
|
|
27
|
+
duration: DURATIONS[animation === 'pulse' ? 'pulse' : 'shimmer'][speed],
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type Span = { left: number; top: number; width: number; height: number };
|
|
32
|
+
|
|
33
|
+
const SLANT = 20; // degrees from vertical: the highlight is a diagonal, top right to bottom left
|
|
34
|
+
const SIN = Math.sin((SLANT * Math.PI) / 180);
|
|
35
|
+
const COS = Math.cos((SLANT * Math.PI) / 180);
|
|
36
|
+
export const SLANT_TAN = SIN / COS;
|
|
37
|
+
export const SLANT_COS = COS;
|
|
38
|
+
export const SLANT_ANGLE = `${90 + SLANT}deg`;
|
|
39
|
+
export const PEAK = 0.85; // Where across the band the highlight is brightest: 0 → PEAK eases up, PEAK → 1 eases down — later is a harder leading edge
|
|
40
|
+
export const STEPS = 12; // stops per ramp — enough for an eased curve to read as one, with no banding
|
|
41
|
+
|
|
42
|
+
// Every gradient ramps on this (a scrim), so no stop shows as a hard line
|
|
43
|
+
export const ease = (t: number) => (1 - Math.cos(Math.PI * t)) / 2;
|
|
44
|
+
|
|
45
|
+
/** Highlights `SPACING` band-widths apart, in px from the box's corner, so every rect draws the same stream. */
|
|
46
|
+
function highlights(band: number) {
|
|
47
|
+
const period = band * SPACING;
|
|
48
|
+
const stop = (at: number, alpha: number) =>
|
|
49
|
+
`color-mix(in srgb, ${HIGHLIGHT} ${(alpha * 100).toFixed(1)}%, transparent) ${(at * band).toFixed(2)}px`;
|
|
50
|
+
const stops: string[] = [];
|
|
51
|
+
for (let i = 0; i <= STEPS; i++) stops.push(stop((i / STEPS) * PEAK, ease(i / STEPS)));
|
|
52
|
+
for (let i = 1; i <= STEPS; i++) {
|
|
53
|
+
stops.push(stop(PEAK + (i / STEPS) * (1 - PEAK), ease(1 - i / STEPS)));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return {
|
|
57
|
+
// Across, the stream repeats every `period` along the slant
|
|
58
|
+
width: period / COS,
|
|
59
|
+
image: `repeating-linear-gradient(${SLANT_ANGLE}, ${stops.join(', ')}, transparent ${period.toFixed(2)}px)`,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Animates `element` as its slice of one sweep, on the document clock, so however late it mounts it joins the sweep under way. */
|
|
64
|
+
export function shimmer(element: HTMLElement, group?: Span, motion: Motion = motionOf(element)) {
|
|
65
|
+
for (const animation of animationsOf(element)) animation.cancel();
|
|
66
|
+
element.style.backgroundImage = '';
|
|
67
|
+
element.style.backgroundRepeat = '';
|
|
68
|
+
if (prefersReducedMotion() || typeof element.animate !== 'function') return;
|
|
69
|
+
if (motion.animation === 'none') return;
|
|
70
|
+
|
|
71
|
+
const timing = { duration: motion.duration, iterations: Infinity };
|
|
72
|
+
|
|
73
|
+
if (motion.animation === 'pulse') {
|
|
74
|
+
element.animate(
|
|
75
|
+
[
|
|
76
|
+
{ opacity: 1, easing: 'ease-in-out' },
|
|
77
|
+
{ opacity: PULSE_LOW, easing: 'ease-in-out' },
|
|
78
|
+
{ opacity: 1 },
|
|
79
|
+
],
|
|
80
|
+
timing
|
|
81
|
+
).startTime = 0;
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const rect = element.getBoundingClientRect();
|
|
86
|
+
const x = rect.left + scrollX;
|
|
87
|
+
const area: Span =
|
|
88
|
+
motion.animation === 'group-shimmer'
|
|
89
|
+
? (group ?? {
|
|
90
|
+
left: x,
|
|
91
|
+
top: rect.top,
|
|
92
|
+
width: rect.width,
|
|
93
|
+
height: rect.height,
|
|
94
|
+
})
|
|
95
|
+
: {
|
|
96
|
+
left: 0,
|
|
97
|
+
top: 0,
|
|
98
|
+
width: document.documentElement.clientWidth || innerWidth,
|
|
99
|
+
height: innerHeight,
|
|
100
|
+
};
|
|
101
|
+
const band = Math.min(Math.max(area.width * 0.4, 80), MAX_BAND);
|
|
102
|
+
const { width: tile, image } = highlights(band);
|
|
103
|
+
|
|
104
|
+
// Where this bone sits in the area's one stream: further right, and lower down the slant, is further along it
|
|
105
|
+
const along = x - area.left + (rect.top - area.top) * SLANT_TAN;
|
|
106
|
+
// One pace on any screen, as a sweep across the reference width took
|
|
107
|
+
const pace = (motion.duration * SWEEP) / (REFERENCE_WIDTH + MAX_BAND);
|
|
108
|
+
|
|
109
|
+
element.style.backgroundImage = image;
|
|
110
|
+
element.style.backgroundSize = `${tile}px 100%`;
|
|
111
|
+
element.style.backgroundRepeat = 'repeat-x';
|
|
112
|
+
element.animate(
|
|
113
|
+
[{ backgroundPosition: `${-along}px 0` }, { backgroundPosition: `${tile - along}px 0` }],
|
|
114
|
+
{ duration: tile * pace, iterations: Infinity }
|
|
115
|
+
).startTime = 0;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** ms per px of the band in `element`'s shimmer; null when it has no band. */
|
|
119
|
+
export function paceOf(element: Element): number | null {
|
|
120
|
+
if (prefersReducedMotion()) return null;
|
|
121
|
+
const motion = motionOf(element);
|
|
122
|
+
if (motion.animation !== 'shimmer' && motion.animation !== 'group-shimmer') return null;
|
|
123
|
+
return (motion.duration * SWEEP) / (REFERENCE_WIDTH + MAX_BAND);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The rect elements drawn into `layer`. */
|
|
127
|
+
export const rectsOf = (layer: Element): HTMLElement[] => [
|
|
128
|
+
...layer.querySelectorAll<HTMLElement>(`:scope > [${ATTR_RECT}]`),
|
|
129
|
+
];
|
|
130
|
+
|
|
131
|
+
/** Soft floor on skeleton bone corners — anything sharper than this reads as a glyph,
|
|
132
|
+
* not a placeholder, which fights the whole point of a skeleton. 4 px is the smallest
|
|
133
|
+
* radius that still reads as "rounded" at typical display DPI. Applied only to
|
|
134
|
+
* text / media / box bones; chrome bones carry the consumer's own radius verbatim. */
|
|
135
|
+
const MIN_BONE_RADIUS = 4;
|
|
136
|
+
const clampRadius = (radius: string): string =>
|
|
137
|
+
radius.replace(/(\d+(?:\.\d+)?)px/g, (_, raw) => {
|
|
138
|
+
const n = parseFloat(raw);
|
|
139
|
+
return Number.isFinite(n) && n < MIN_BONE_RADIUS ? `${MIN_BONE_RADIUS}px` : `${n}px`;
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
/** Draws `rects` into `layer`, reusing the elements already there.
|
|
143
|
+
*
|
|
144
|
+
* Bones live in the light DOM (not a shadow root) so a consumer's stylesheet
|
|
145
|
+
* can reach them — selectors like `[ask-rect="text"]`, `[ask-rect="media"]`,
|
|
146
|
+
* `[ask-rect="box"]`, or the `--ask-base` / `--ask-highlight` custom
|
|
147
|
+
* properties — and theme the skeleton with the consumer's own tokens rather
|
|
148
|
+
* than plugin defaults. Positioning (x/y/width/height/radius) stays inline
|
|
149
|
+
* because it is per-bone; fill colour comes from the stylesheet.
|
|
150
|
+
*
|
|
151
|
+
* Added after mount, so Vue/React hydration never sees them.
|
|
152
|
+
*/
|
|
153
|
+
export function drawSkeleton(layer: HTMLElement, rects: SkeletonRect[]) {
|
|
154
|
+
const existing = rectsOf(layer);
|
|
155
|
+
const rect = layer.getBoundingClientRect();
|
|
156
|
+
const group = {
|
|
157
|
+
left: rect.left + scrollX,
|
|
158
|
+
top: rect.top,
|
|
159
|
+
width: rect.width,
|
|
160
|
+
height: rect.height,
|
|
161
|
+
};
|
|
162
|
+
// Read once for the layer: every rect in it inherits the same theme
|
|
163
|
+
const motion = motionOf(layer);
|
|
164
|
+
|
|
165
|
+
rects.forEach((part, index) => {
|
|
166
|
+
let element = existing[index];
|
|
167
|
+
if (!element) {
|
|
168
|
+
element = document.createElement('div');
|
|
169
|
+
// Positioning-only: the stylesheet owns colour so the consumer can retheme
|
|
170
|
+
element.style.cssText = `position:absolute;display:block;pointer-events:none;background-repeat:no-repeat`;
|
|
171
|
+
layer.append(element);
|
|
172
|
+
}
|
|
173
|
+
// Type attribute set every pass — bone reuse across renders may change type
|
|
174
|
+
element.setAttribute(ATTR_RECT, part.type);
|
|
175
|
+
|
|
176
|
+
Object.assign(element.style, {
|
|
177
|
+
left: `${part.x}px`,
|
|
178
|
+
top: `${part.y}px`,
|
|
179
|
+
width: `${part.width}px`,
|
|
180
|
+
height: `${part.height}px`,
|
|
181
|
+
// Chrome reproduces the real element's border-radius exactly (0 stays 0);
|
|
182
|
+
// placeholder bones get a 4-px floor so sharp-cornered text / media / box
|
|
183
|
+
// bones still read as rounded skeletons, not glyphs of the real content.
|
|
184
|
+
borderRadius: part.type === 'chrome' ? part.radius : clampRadius(part.radius),
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
if (part.type === 'chrome') {
|
|
188
|
+
// Chrome bones reproduce the container's painted surface (bg / borders / shadow),
|
|
189
|
+
// captured from the consumer's own CSS. Reset shimmer side-effects so an element
|
|
190
|
+
// reused across draws isn't left with a shimmer background from a previous pass,
|
|
191
|
+
// then apply the captured paint inline — the stylesheet default fill would obscure
|
|
192
|
+
// the real colour.
|
|
193
|
+
for (const anim of animationsOf(element)) anim.cancel();
|
|
194
|
+
element.style.backgroundImage = '';
|
|
195
|
+
element.style.backgroundSize = '';
|
|
196
|
+
element.style.backgroundRepeat = '';
|
|
197
|
+
const chrome = part.chrome;
|
|
198
|
+
element.style.background = chrome?.background ?? '';
|
|
199
|
+
element.style.borderTop = chrome?.borderTop ?? '';
|
|
200
|
+
element.style.borderRight = chrome?.borderRight ?? '';
|
|
201
|
+
element.style.borderBottom = chrome?.borderBottom ?? '';
|
|
202
|
+
element.style.borderLeft = chrome?.borderLeft ?? '';
|
|
203
|
+
element.style.boxShadow = chrome?.boxShadow ?? '';
|
|
204
|
+
// Chrome never shimmers — it's the outline, not a loading placeholder
|
|
205
|
+
element.dataset.motion = 'chrome';
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Non-chrome bones: drop any chrome state left on a reused element, then shimmer.
|
|
210
|
+
if (element.dataset.motion === 'chrome') {
|
|
211
|
+
element.style.background = '';
|
|
212
|
+
element.style.borderTop = '';
|
|
213
|
+
element.style.borderRight = '';
|
|
214
|
+
element.style.borderBottom = '';
|
|
215
|
+
element.style.borderLeft = '';
|
|
216
|
+
element.style.boxShadow = '';
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Restarted only when its place, group, the page's width or the motion changes
|
|
220
|
+
const key = `${Math.round(group.left + part.x)}|${Math.round(part.y)}|${Math.round(part.height)}|${Math.round(group.left)}|${Math.round(group.width)}|${Math.round(group.height)}|${document.documentElement.clientWidth}|${motion.animation}|${motion.duration}`;
|
|
221
|
+
if (element.dataset.motion !== key) {
|
|
222
|
+
element.dataset.motion = key;
|
|
223
|
+
shimmer(element, group, motion);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
// Trim excess bones left over from a previous, longer draw
|
|
228
|
+
for (let i = existing.length - 1; i >= rects.length; i--) existing[i]!.remove();
|
|
229
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { ATTR_BAR } from './constants';
|
|
2
|
+
import { shimmer } from './shimmer';
|
|
3
|
+
import { addStyles } from './styles';
|
|
4
|
+
|
|
5
|
+
type Length = string | number;
|
|
6
|
+
|
|
7
|
+
export type SkeletonBoxOptions = {
|
|
8
|
+
height?: Length;
|
|
9
|
+
width?: Length;
|
|
10
|
+
radius?: Length;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export const DEFAULT_SKELETON_BOX_OPTIONS = {
|
|
14
|
+
height: '1em',
|
|
15
|
+
width: '60%',
|
|
16
|
+
radius: 'var(--ask-radius, 0.25em)',
|
|
17
|
+
} satisfies Required<SkeletonBoxOptions>;
|
|
18
|
+
|
|
19
|
+
const toCSS = (value: Length) => (typeof value === 'number' ? `${value}px` : value);
|
|
20
|
+
|
|
21
|
+
export function skeletonBoxStyle({
|
|
22
|
+
height = DEFAULT_SKELETON_BOX_OPTIONS.height,
|
|
23
|
+
width = DEFAULT_SKELETON_BOX_OPTIONS.width,
|
|
24
|
+
radius = DEFAULT_SKELETON_BOX_OPTIONS.radius,
|
|
25
|
+
}: SkeletonBoxOptions = {}) {
|
|
26
|
+
return {
|
|
27
|
+
height: toCSS(height),
|
|
28
|
+
width: toCSS(width),
|
|
29
|
+
borderRadius: toCSS(radius),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** A single bar, shimmering in step with every skeleton on the page once it is in the document. */
|
|
34
|
+
export function createSkeletonBox(options?: SkeletonBoxOptions): HTMLSpanElement {
|
|
35
|
+
addStyles();
|
|
36
|
+
const element = document.createElement('span');
|
|
37
|
+
element.setAttribute(ATTR_BAR, '');
|
|
38
|
+
Object.assign(element.style, skeletonBoxStyle(options));
|
|
39
|
+
requestAnimationFrame(() => {
|
|
40
|
+
if (element.isConnected) shimmer(element);
|
|
41
|
+
});
|
|
42
|
+
return element;
|
|
43
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { textContext } from './canvas';
|
|
2
|
+
import { ATTR_COVERED, MEDIA_TAGS } from './constants';
|
|
3
|
+
|
|
4
|
+
const MEDIA = new Set(MEDIA_TAGS);
|
|
5
|
+
const REMOVED = 'script, noscript, template, base, meta, link';
|
|
6
|
+
const REPLACED = new Set(['iframe', 'object', 'embed']);
|
|
7
|
+
const STRIPPED = new Set([
|
|
8
|
+
'src',
|
|
9
|
+
'srcset',
|
|
10
|
+
'sizes',
|
|
11
|
+
'poster',
|
|
12
|
+
'data',
|
|
13
|
+
'srcdoc',
|
|
14
|
+
'action',
|
|
15
|
+
'formaction',
|
|
16
|
+
'formtarget',
|
|
17
|
+
'background',
|
|
18
|
+
'ping',
|
|
19
|
+
'dynsrc',
|
|
20
|
+
'lowsrc',
|
|
21
|
+
'value',
|
|
22
|
+
'alt',
|
|
23
|
+
ATTR_COVERED,
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
// A style attribute saved from an unknown origin can carry `url(javascript:…)`,
|
|
27
|
+
// `expression(…)` (legacy IE), or close the attribute to inject rules; drop the whole
|
|
28
|
+
// attribute if any show up — `data:` URLs in CSS are left alone because they render
|
|
29
|
+
// as images, not documents, and are a routine way to inline background art.
|
|
30
|
+
const STYLE_UNSAFE = /url\s*\(\s*['"]?\s*(javascript|vbscript):|expression\s*\(|<|>/i;
|
|
31
|
+
|
|
32
|
+
export const fill = (value: string) =>
|
|
33
|
+
value.replace(/[A-Z]/g, 'X').replace(/[a-z]/g, 'x').replace(/\d/g, '0');
|
|
34
|
+
|
|
35
|
+
// Filler has different glyphs to the text it replaces; letter-spacing makes up the difference, so it wraps the same
|
|
36
|
+
function fillText(original: Text, copy: Text) {
|
|
37
|
+
const filled = fill(copy.data);
|
|
38
|
+
copy.data = filled;
|
|
39
|
+
|
|
40
|
+
const parent = original.parentElement;
|
|
41
|
+
const context = textContext();
|
|
42
|
+
if (!parent || !context || !filled.trim()) return;
|
|
43
|
+
|
|
44
|
+
const style = getComputedStyle(parent);
|
|
45
|
+
context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
|
|
46
|
+
const shape = (value: string) => {
|
|
47
|
+
const collapsed = value.replace(/\s+/g, ' ');
|
|
48
|
+
if (style.textTransform === 'uppercase') return collapsed.toUpperCase();
|
|
49
|
+
if (style.textTransform === 'lowercase') return collapsed.toLowerCase();
|
|
50
|
+
return collapsed;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const target = context.measureText(shape(original.data)).width;
|
|
54
|
+
const current = context.measureText(shape(filled)).width;
|
|
55
|
+
const delta = (target - current) / shape(filled).length;
|
|
56
|
+
if (Math.abs(delta) < 0.01) return;
|
|
57
|
+
|
|
58
|
+
const span = document.createElement('span');
|
|
59
|
+
span.style.letterSpacing = `${(parseFloat(style.letterSpacing) || 0) + delta}px`;
|
|
60
|
+
copy.replaceWith(span);
|
|
61
|
+
span.append(copy);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function sanitize(root: ParentNode) {
|
|
65
|
+
for (const element of root.querySelectorAll(REMOVED)) element.remove();
|
|
66
|
+
|
|
67
|
+
for (const element of root.querySelectorAll('*')) {
|
|
68
|
+
if (REPLACED.has(element.localName)) {
|
|
69
|
+
const stand = document.createElement('span');
|
|
70
|
+
stand.style.cssText = element.getAttribute('style') ?? '';
|
|
71
|
+
stand.style.display ||= 'inline-block';
|
|
72
|
+
element.replaceWith(stand);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
for (const { name, value } of [...element.attributes]) {
|
|
77
|
+
const lower = name.toLowerCase();
|
|
78
|
+
const unsafe =
|
|
79
|
+
lower.startsWith('on') ||
|
|
80
|
+
STRIPPED.has(lower) ||
|
|
81
|
+
(lower.endsWith('href') && /^\s*(javascript|vbscript|data):/i.test(value)) ||
|
|
82
|
+
(lower === 'style' && STYLE_UNSAFE.test(value));
|
|
83
|
+
if (unsafe) element.removeAttribute(name);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (element.localName === 'img') element.setAttribute('alt', '');
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
for (const source of root.querySelectorAll('video source, picture source')) {
|
|
90
|
+
source.remove();
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The markup in `root`, safe to keep: no scripts, handlers or media sources; `filler` replaces its text too. */
|
|
95
|
+
export function serialize(root: HTMLElement, filler: boolean): string {
|
|
96
|
+
const clone = root.cloneNode(true) as HTMLElement;
|
|
97
|
+
const show = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT;
|
|
98
|
+
const original = document.createTreeWalker(root, show);
|
|
99
|
+
const copy = document.createTreeWalker(clone, show);
|
|
100
|
+
|
|
101
|
+
const texts: [Text, Text][] = [];
|
|
102
|
+
const media: [Element, HTMLElement][] = [];
|
|
103
|
+
while (original.nextNode() && copy.nextNode()) {
|
|
104
|
+
const a = original.currentNode;
|
|
105
|
+
const b = copy.currentNode;
|
|
106
|
+
if (a.nodeType === Node.TEXT_NODE) {
|
|
107
|
+
if (filler) texts.push([a as Text, b as Text]);
|
|
108
|
+
} else if (MEDIA.has((a as Element).localName) || REPLACED.has((a as Element).localName)) {
|
|
109
|
+
media.push([a as Element, b as HTMLElement]);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Applied after the walk, which would lose its place in a tree changing under it
|
|
114
|
+
for (const [a, b] of media) {
|
|
115
|
+
const rect = a.getBoundingClientRect();
|
|
116
|
+
b.style.boxSizing = 'border-box';
|
|
117
|
+
b.style.width = `${rect.width}px`;
|
|
118
|
+
if (rect.width && rect.height) {
|
|
119
|
+
// Its proportions, not its pixels: restored somewhere narrower, it scales down as the real one would
|
|
120
|
+
b.style.maxWidth = '100%';
|
|
121
|
+
b.style.height = 'auto';
|
|
122
|
+
b.style.aspectRatio = `${rect.width} / ${rect.height}`;
|
|
123
|
+
} else {
|
|
124
|
+
b.style.height = `${rect.height}px`;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
for (const [a, b] of texts) fillText(a, b);
|
|
128
|
+
|
|
129
|
+
sanitize(clone);
|
|
130
|
+
return clone.innerHTML;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function restore(html: string): DocumentFragment {
|
|
134
|
+
const template = document.createElement('template');
|
|
135
|
+
template.innerHTML = html;
|
|
136
|
+
sanitize(template.content);
|
|
137
|
+
return template.content;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const signature = (element: Element, depth: number): string =>
|
|
141
|
+
[...element.children]
|
|
142
|
+
.map((child) => {
|
|
143
|
+
const classes = [...child.classList].sort().join('.');
|
|
144
|
+
const inner = depth > 1 && child.firstElementChild ? `(${signature(child, depth - 1)})` : '';
|
|
145
|
+
return `${child.localName}${classes ? `.${classes}` : ''}${inner}`;
|
|
146
|
+
})
|
|
147
|
+
.join(',');
|
|
148
|
+
|
|
149
|
+
const hash = (value: string) => {
|
|
150
|
+
let h = 5381;
|
|
151
|
+
for (let i = 0; i < value.length; i++) h = (h * 33) ^ value.charCodeAt(i);
|
|
152
|
+
return (h >>> 0).toString(36);
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/** Identifies content by its page and the shape of its top two levels — the parts that rarely hang on data. */
|
|
156
|
+
export function autoKey(element: Element): string | null {
|
|
157
|
+
const shape = signature(element, 2);
|
|
158
|
+
return shape ? `${location.pathname}|${hash(shape)}` : null;
|
|
159
|
+
}
|