-
Notifications
You must be signed in to change notification settings - Fork 14
/
index.ts
820 lines (755 loc) · 22.7 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
// types
export type ICursorType = "normal" | "text" | "block";
/**
* if without unit, `px` is used by default
*/
type MaybeSize = string | number;
/** if without unit `ms` is used by default */
type MaybeDuration = string | number;
/** do not use 0x000000, use #000000 instead */
type MaybeColor = string;
/**
* Configurations for the cursor
*/
export interface IpadCursorConfig {
/**
* Strength of adsorption, the larger the value,
* The higher the value, the greater the range of the block that can be moved when it is hovered
* @type {number} between 0 and 30
* @default 10
*/
adsorptionStrength?: number;
/**
* The class name of the cursor element
* @type {string}
* @default 'cursor'
*/
className?: string;
/**
* The style of the cursor, when it does not hover on any element
*/
normalStyle?: IpadCursorStyle;
/**
* The style of the cursor, when it hovers on text
*/
textStyle?: IpadCursorStyle;
/**
* The style of the cursor, when it hovers on a block
*/
blockStyle?: IpadCursorStyle;
/**
* The style of the cursor, when mousedown
*/
mouseDownStyle?: IpadCursorStyle;
/**
* Cursor padding when hover on block
*/
blockPadding?: number | "auto";
/**
* detect text node and apply text cursor automatically
**/
enableAutoTextCursor?: boolean;
/**
* enable detect dom change and auto call updateCursor
**/
enableAutoUpdateCursor?: boolean;
/**
* whether to enable lighting effect
*/
enableLighting?: boolean;
/**
* whether to apply effect for mousedown action
*/
enableMouseDownEffect?: boolean;
}
/**
* Configurable style of the cursor (Experimental)
* This feature is Experimental, so it's set to false by default.
* And it not support `block` yet
*/
export interface IpadCursorStyle {
/**
* The width of the cursor
*/
width?: MaybeSize;
/**
* The width of the cursor
*/
height?: MaybeSize;
/**
* Border radius of cursor
*/
radius?: MaybeSize | "auto";
/**
* Transition duration of basic properties like width, height, radius, border, background-color
*/
durationBase?: MaybeDuration;
/**
* Transition duration of position: left, top
*/
durationPosition?: MaybeDuration;
/**
* Transition duration of backdrop-filter
*/
durationBackdropFilter?: MaybeDuration;
/**
* The background color of the cursor
*/
background?: MaybeColor;
/**
* Border of the cursor
* @example '1px solid rgba(100, 100, 100, 0.1)'
*/
border?: string;
/** z-index of cursor */
zIndex?: number;
/**
* Scale of cursor
*/
scale?: number;
/**
* backdrop-filter blur
*/
backdropBlur?: MaybeSize;
/**
* backdrop-filter saturate
*/
backdropSaturate?: string;
}
let ready = false;
let observer: MutationObserver | null = null;
let cursorEle: HTMLDivElement | null = null;
let activeDom: Element | null = null;
let isBlockActive = false;
let isTextActive = false;
let isMouseDown = false;
let styleTag: HTMLStyleElement | null = null;
let latestCursorStyle: Record<string, any> = {};
let mousedownStyleRecover: Record<string, any> = {};
const position = { x: -100, y: -100};
const isServer = typeof document === "undefined";
const registeredNodeSet = new Set<Element>();
const eventMap = new Map<
Element,
Array<{ event: string; handler: (e: Event) => void }>
>();
const config = getDefaultConfig();
/**
* Util collection
*/
class Utils {
static clamp(num: number, min: number, max: number) {
return Math.min(Math.max(num, min), max);
}
static isNum(v: string | number) {
return typeof v === "number" || /^\d+$/.test(v);
}
static getSize(size: MaybeSize) {
if (this.isNum(size)) return `${size}px`;
return size;
}
static getDuration(duration: MaybeDuration): string {
if (this.isNum(duration)) return `${duration}ms`;
return `${duration}`;
}
static getColor(color: MaybeColor) {
return color;
}
static objectKeys<T extends string>(obj: Partial<Record<T, any>>): T[] {
return Object.keys(obj) as T[];
}
static style2Vars(style: IpadCursorStyle) {
const map: Record<keyof IpadCursorStyle, string> = {
backdropBlur: "--cursor-bg-blur",
backdropSaturate: "--cursor-bg-saturate",
background: "--cursor-bg",
border: "--cursor-border",
durationBackdropFilter: "--cursor-blur-duration",
durationBase: "--cursor-duration",
durationPosition: "--cursor-position-duration",
height: "--cursor-height",
radius: "--cursor-radius",
scale: "--cursor-scale",
width: "--cursor-width",
zIndex: "--cursor-z-index",
};
return this.objectKeys(style).reduce((prev, key) => {
let value = style[key];
if (value === undefined) return prev;
const maybeColor = ["background", "border"].includes(key);
const maybeSize = ["width", "height", "radius", "backdropBlur"].includes(
key
);
const maybeDuration = key.startsWith("duration");
if (maybeColor) value = this.getColor(value as MaybeColor);
if (maybeSize) value = this.getSize(value as MaybeSize);
if (maybeDuration) value = this.getDuration(value as MaybeDuration);
const recordKey = map[key] || key;
return { ...prev, [recordKey]: value };
}, {});
}
static isMergebleObject(obj: any) {
const isObject = (o: any) =>
o && typeof o === "object" && !Array.isArray(o);
return isObject(obj);
}
static mergeDeep<T extends any = any>(obj: T, ...sources: any[]): T {
if (!sources.length) return obj;
const source = sources.shift();
if (!source) return obj;
if (this.isMergebleObject(obj) && this.isMergebleObject(source)) {
Utils.objectKeys(source).forEach((key) => {
if (this.isMergebleObject(source[key])) {
if (!(obj as any)[key]) Object.assign(obj as any, { [key]: {} });
this.mergeDeep((obj as any)[key], source[key]);
} else {
Object.assign(obj as any, { [key]: source[key] });
}
});
}
return this.mergeDeep(obj, ...sources);
}
}
/**
* Get default config
* @returns
*/
function getDefaultConfig(): IpadCursorConfig {
const normalStyle: IpadCursorStyle = {
width: "20px",
height: "20px",
radius: "10px",
durationBase: "0.23s",
durationPosition: "0s",
durationBackdropFilter: "0s",
background: "rgba(150, 150, 150, 0.2)",
scale: 1,
border: "1px solid rgba(100, 100, 100, 0.1)",
zIndex: 9999,
backdropBlur: "0px",
backdropSaturate: "180%",
};
const textStyle: IpadCursorStyle = {
background: "rgba(100, 100, 100, 0.3)",
scale: 1,
width: "4px",
height: "1.2em",
border: "0px solid rgba(100, 100, 100, 0)",
durationBackdropFilter: "1s",
radius: "10px",
};
const blockStyle: IpadCursorStyle = {
background: "rgba(100, 100, 100, 0.3)",
border: "1px solid rgba(100, 100, 100, 0.05)",
backdropBlur: "0px",
durationBase: "0.23s",
durationBackdropFilter: "0.1s",
backdropSaturate: "120%",
radius: "10px",
};
const mouseDownStyle: IpadCursorStyle = {
background: "rgba(150, 150, 150, 0.3)",
scale: 0.8,
};
const defaultConfig: IpadCursorConfig = {
blockPadding: "auto",
adsorptionStrength: 10,
className: "ipad-cursor",
normalStyle,
textStyle,
blockStyle,
mouseDownStyle,
};
return defaultConfig;
}
/** update cursor style (single or multiple) */
function updateCursorStyle(
keyOrObj: string | Record<string, any>,
value?: string
) {
if (!cursorEle) return;
if (typeof keyOrObj === "string") {
latestCursorStyle[keyOrObj] = value;
value && cursorEle.style.setProperty(keyOrObj, value);
} else {
Object.entries(keyOrObj).forEach(([key, value]) => {
cursorEle && cursorEle.style.setProperty(key, value);
latestCursorStyle[key] = value;
});
}
}
/** record mouse position */
function onMousemove(e: MouseEvent) {
position.x = e.clientX;
position.y = e.clientY;
autoApplyTextCursor(e.target as HTMLElement);
}
function onMousedown() {
if (isMouseDown || !config.enableMouseDownEffect || isBlockActive) return;
isMouseDown = true;
mousedownStyleRecover = { ...latestCursorStyle };
updateCursorStyle(Utils.style2Vars(config.mouseDownStyle || {}));
}
function onMouseup() {
if (!isMouseDown || !config.enableMouseDownEffect || isBlockActive) return;
isMouseDown = false;
const target = mousedownStyleRecover;
const styleToRecover = Utils.objectKeys(
Utils.style2Vars(config.mouseDownStyle || {})
).reduce((prev, curr) => ({ ...prev, [curr]: target[curr] }), {});
updateCursorStyle(styleToRecover);
}
/**
* Automatically apply cursor style when hover on target
* @param target
* @returns
*/
function autoApplyTextCursor(target: HTMLElement) {
if (isBlockActive || isTextActive || !config.enableAutoTextCursor) return;
if (target && target.childNodes.length === 1) {
const child = target.childNodes[0] as HTMLElement;
if (child.nodeType === 3 && child.textContent?.trim() !== "") {
target.setAttribute("data-cursor", "text");
applyTextCursor(target);
return;
}
}
resetCursorStyle();
}
let lastNode: Element | null = null;
const scrollHandler = () => {
const currentNode = document.elementFromPoint(position.x, position.y);
const mouseLeaveEvent = new MouseEvent("mouseleave", {
bubbles: true,
cancelable: true,
view: window,
});
if (currentNode !== lastNode && lastNode && mouseLeaveEvent) {
lastNode.dispatchEvent(mouseLeaveEvent);
}
lastNode = currentNode;
};
/**
* Init cursor, hide default cursor, and listen mousemove event
* will only run once in client even if called multiple times
* @returns
*/
function initCursor(_config?: IpadCursorConfig) {
if (isServer || ready) return;
if (_config) updateConfig(_config);
ready = true;
window.addEventListener("mousemove", onMousemove);
window.addEventListener("mousedown", onMousedown);
window.addEventListener("mouseup", onMouseup);
window.addEventListener("scroll", scrollHandler);
createCursor();
createStyle();
updateCursorPosition();
updateCursor();
createObserver();
}
function createObserver() {
if (config.enableAutoUpdateCursor) {
observer = new MutationObserver(function () {
updateCursor();
});
observer.observe(document.body, { childList: true, subtree: true });
}
}
/**
* destroy cursor, remove event listener and remove cursor element
* @returns
*/
function disposeCursor() {
if (!ready) return;
ready = false;
window.removeEventListener("mousemove", onMousemove);
window.removeEventListener("scroll", scrollHandler);
cursorEle && cursorEle.remove();
styleTag && styleTag.remove();
styleTag = null;
cursorEle = null;
// iterate nodesMap
registeredNodeSet.forEach((node) => unregisterNode(node));
observer?.disconnect()
}
/**
* Update current Configuration
* @param _config
*/
function updateConfig(_config: IpadCursorConfig) {
if ("adsorptionStrength" in _config) {
config.adsorptionStrength = Utils.clamp(
_config.adsorptionStrength ?? 10,
0,
30
);
}
return Utils.mergeDeep(config, _config);
}
/**
* Create style tag
* @returns
*/
function createStyle() {
if (styleTag) return;
const selector = `.${config.className!.split(/\s+/).join(".")}`;
styleTag = document.createElement("style");
styleTag.innerHTML = `
body, * {
cursor: none;
}
${selector} {
--cursor-transform-duration: 0.23s;
overflow: hidden;
pointer-events: none;
position: fixed;
left: var(--cursor-x);
top: var(--cursor-y);
width: var(--cursor-width);
height: var(--cursor-height);
border-radius: var(--cursor-radius);
background-color: var(--cursor-bg);
border: var(--cursor-border);
z-index: var(--cursor-z-index);
font-size: var(--cursor-font-size);
backdrop-filter:
blur(var(--cursor-bg-blur))
saturate(var(--cursor-bg-saturate));
transition:
width var(--cursor-duration) ease,
height var(--cursor-duration) ease,
border-radius var(--cursor-duration) ease,
border var(--cursor-duration) ease,
background-color var(--cursor-duration) ease,
left var(--cursor-position-duration) ease,
top var(--cursor-position-duration) ease,
backdrop-filter var(--cursor-blur-duration) ease,
transform var(--cursor-transform-duration) ease;
transform:
translateX(calc(var(--cursor-translateX, 0px) - 50%))
translateY(calc(var(--cursor-translateY, 0px) - 50%))
scale(var(--cursor-scale, 1));
}
${selector}.block-active {
--cursor-transform-duration: 0s;
}
${selector} .lighting {
display: none;
}
${selector}.lighting--on .lighting {
display: block;
width: 0;
height: 0;
position: absolute;
left: calc(var(--lighting-size) / -2);
top: calc(var(--lighting-size) / -2);
transform: translateX(var(--lighting-offset-x, 0)) translateY(var(--lighting-offset-y, 0));
background-image: radial-gradient(
circle at center,
rgba(255, 255, 255, 0.1) 0%,
rgba(255, 255, 255, 0) 30%
);
border-radius: 50%;
}
${selector}.block-active .lighting {
width: var(--lighting-size, 20px);
height: var(--lighting-size, 20px);
}
`;
document.head.appendChild(styleTag);
}
/**
* create cursor element, append to body
* @returns
*/
function createCursor() {
if (isServer) return;
cursorEle = document.createElement("div");
const lightingEle = document.createElement("div");
cursorEle.classList.add(config.className!);
lightingEle.classList.add("lighting");
cursorEle.appendChild(lightingEle);
document.body.appendChild(cursorEle);
resetCursorStyle();
}
/**
* update cursor position, request animation frame
* @returns
*/
function updateCursorPosition() {
if (isServer || !cursorEle) return;
if (!isBlockActive) {
updateCursorStyle("--cursor-x", `${position.x}px`);
updateCursorStyle("--cursor-y", `${position.y}px`);
}
window.requestAnimationFrame(updateCursorPosition);
}
/**
* get all hover targets
* @returns
*/
function queryAllTargets() {
if (isServer || !ready) return [];
return document.querySelectorAll("[data-cursor]");
}
/**
* Detect all interactive elements in the page
* Update the binding of events, remove listeners for elements that are removed
* @returns
*/
function updateCursor() {
initCursor()
if (isServer || !ready) return;
const nodesMap = new Map();
// addDataCursorText(document.body.childNodes)
const nodes = queryAllTargets();
nodes.forEach((node) => {
nodesMap.set(node, true);
if (registeredNodeSet.has(node)) return;
registerNode(node);
});
registeredNodeSet.forEach((node) => {
if (nodesMap.has(node)) return;
unregisterNode(node);
});
}
function registerNode(node: Element) {
let type = node.getAttribute("data-cursor") as ICursorType;
registeredNodeSet.add(node);
if (type === "text") registerTextNode(node);
if (type === "block") registerBlockNode(node);
else registeredNodeSet.delete(node);
}
function unregisterNode(node: Element) {
registeredNodeSet.delete(node);
eventMap.get(node)?.forEach(({ event, handler }: any) => {
if (event === 'mouseleave')
handler();
node.removeEventListener(event, handler);
});
eventMap.delete(node);
(node as HTMLElement).style.setProperty("transform", "none");
}
function extractCustomStyle(node: Element) {
const customStyleRaw = node.getAttribute("data-cursor-style");
const styleObj: Record<string, any> = {};
if (customStyleRaw) {
customStyleRaw.split(/(;)/).forEach((style) => {
const [key, value] = style.split(":").map((s) => s.trim());
styleObj[key] = value;
});
}
return styleObj;
}
/**
* + ---------------------- +
* | TextNode |
* + ---------------------- +
*/
function registerTextNode(node: Element) {
let timer: any;
function toggleTextActive(active?: boolean) {
isTextActive = !!active;
cursorEle &&
(active
? cursorEle.classList.add("text-active")
: cursorEle.classList.remove("text-active"));
}
function onTextOver(e: Event) {
timer && clearTimeout(timer);
toggleTextActive(true);
// for some edge case, two ele very close
timer = setTimeout(() => toggleTextActive(true));
applyTextCursor(e.target as HTMLElement);
}
function onTextLeave() {
timer && clearTimeout(timer);
timer = setTimeout(() => toggleTextActive(false));
resetCursorStyle();
}
node.addEventListener("mouseover", onTextOver, { passive: true });
node.addEventListener("mouseleave", onTextLeave, { passive: true });
eventMap.set(node, [
{ event: "mouseover", handler: onTextOver },
{ event: "mouseleave", handler: onTextLeave },
]);
}
/**
* + ---------------------- +
* | BlockNode |
* + ---------------------- +
*/
function registerBlockNode(_node: Element) {
const node = _node as HTMLElement;
node.addEventListener("mouseenter", onBlockEnter, { passive: true });
node.addEventListener("mousemove", onBlockMove, { passive: true });
node.addEventListener("mouseleave", onBlockLeave, { passive: true });
let timer: any;
function toggleBlockActive(active?: boolean) {
isBlockActive = !!active;
cursorEle &&
(active
? cursorEle.classList.add("block-active")
: cursorEle.classList.remove("block-active"));
activeDom = active ? node : null;
}
function onBlockEnter() {
// TODO: maybe control this in other way
cursorEle &&
cursorEle.classList.toggle("lighting--on", !!config.enableLighting);
// Prevents the cursor from shifting from the node during rapid enter/leave.
toggleNodeTransition(false);
const rect = node.getBoundingClientRect();
timer && clearTimeout(timer);
toggleBlockActive(true);
// for some edge case, two ele very close
timer = setTimeout(() => toggleBlockActive(true));
cursorEle && cursorEle.classList.add("block-active");
const updateStyleObj: IpadCursorStyle = { ...(config.blockStyle || {}) };
const blockPadding = config.blockPadding ?? 0;
let padding = blockPadding;
let radius = updateStyleObj?.radius;
if (padding === "auto") {
const size = Math.min(rect.width, rect.height);
padding = Math.max(2, Math.floor(size / 25));
}
if (radius === "auto") {
const paddingCss = Utils.getSize(padding);
const nodeRadius = window.getComputedStyle(node).borderRadius;
if (nodeRadius.startsWith("0") || nodeRadius === "none") radius = "0";
else radius = `calc(${paddingCss} + ${nodeRadius})`;
updateStyleObj.radius = radius;
}
updateCursorStyle("--cursor-x", `${rect.left + rect.width / 2}px`);
updateCursorStyle("--cursor-y", `${rect.top + rect.height / 2}px`);
updateCursorStyle("--cursor-width", `${rect.width + padding * 2}px`);
updateCursorStyle("--cursor-height", `${rect.height + padding * 2}px`);
const styleToUpdate: IpadCursorStyle = {
...updateStyleObj,
...extractCustomStyle(node),
};
if (styleToUpdate.durationPosition === undefined) {
styleToUpdate.durationPosition =
styleToUpdate.durationBase ?? config.normalStyle?.durationBase;
}
updateCursorStyle(Utils.style2Vars(styleToUpdate));
toggleNodeTransition(true);
node.style.setProperty(
"transform",
"translate(var(--translateX), var(--translateY))"
);
}
function onBlockMove() {
if (!isBlockActive) {
onBlockEnter();
}
const rect = node.getBoundingClientRect();
const halfHeight = rect.height / 2;
const topOffset = (position.y - rect.top - halfHeight) / halfHeight;
const halfWidth = rect.width / 2;
const leftOffset = (position.x - rect.left - halfWidth) / halfWidth;
const strength = config.adsorptionStrength ?? 10;
updateCursorStyle(
"--cursor-translateX",
`${leftOffset * ((rect.width / 100) * strength)}px`
);
updateCursorStyle(
"--cursor-translateY",
`${topOffset * ((rect.height / 100) * strength)}px`
);
toggleNodeTransition(false);
const nodeTranslateX = leftOffset * ((rect.width / 100) * strength);
const nodeTranslateY = topOffset * ((rect.height / 100) * strength);
node.style.setProperty("--translateX", `${nodeTranslateX}px`);
node.style.setProperty("--translateY", `${nodeTranslateY}px`);
// lighting
if (config.enableLighting) {
const lightingSize = Math.max(rect.width, rect.height) * 3 * 1.2;
const lightingOffsetX = position.x - rect.left;
const lightingOffsetY = position.y - rect.top;
updateCursorStyle("--lighting-size", `${lightingSize}px`);
updateCursorStyle("--lighting-offset-x", `${lightingOffsetX}px`);
updateCursorStyle("--lighting-offset-y", `${lightingOffsetY}px`);
}
}
function onBlockLeave() {
timer && clearTimeout(timer);
timer = setTimeout(() => toggleBlockActive(false));
resetCursorStyle();
toggleNodeTransition(true);
node.style.setProperty("transform", "translate(0px, 0px)");
}
function toggleNodeTransition(enable?: boolean) {
const duration = enable
? Utils.getDuration(
config?.blockStyle?.durationPosition ??
config?.blockStyle?.durationBase ??
config?.normalStyle?.durationBase ??
"0.23s"
)
: "";
node.style.setProperty(
"transition",
duration ? `all ${duration} cubic-bezier(.58,.09,.46,1.46)` : "none"
);
}
eventMap.set(node, [
{ event: "mouseenter", handler: onBlockEnter },
{ event: "mousemove", handler: onBlockMove },
{ event: "mouseleave", handler: onBlockLeave },
]);
}
function resetCursorStyle() {
if (config.normalStyle?.radius === "auto")
config.normalStyle.radius = config.normalStyle.width;
updateCursorStyle(Utils.style2Vars(config.normalStyle || {}));
}
function applyTextCursor(sourceNode: HTMLElement) {
updateCursorStyle(Utils.style2Vars(config.textStyle || {}));
const fontSize = window.getComputedStyle(sourceNode).fontSize;
updateCursorStyle("--cursor-font-size", fontSize);
updateCursorStyle(
Utils.style2Vars({
...config.textStyle,
...extractCustomStyle(sourceNode),
})
);
}
/**
* Create custom style that can be bound to `data-cursor-style`
* @param style
*/
function customCursorStyle(style: IpadCursorStyle & Record<string, any>) {
return Object.entries(style)
.map(([key, value]) => `${key}: ${value}`)
.join("; ");
}
function resetCursor() {
isBlockActive = false;
isTextActive = false;
resetCursorStyle();
}
const CursorType = {
TEXT: "text" as ICursorType,
BLOCK: "block" as ICursorType,
};
const exported = {
CursorType,
resetCursor,
initCursor,
updateCursor,
disposeCursor,
updateConfig,
customCursorStyle,
};
export {
CursorType,
resetCursor,
initCursor,
updateCursor,
disposeCursor,
updateConfig,
customCursorStyle,
};
export default exported;