-
Notifications
You must be signed in to change notification settings - Fork 210
Expand file tree
/
Copy pathnav-sprite.component.ts
More file actions
314 lines (262 loc) · 8.82 KB
/
nav-sprite.component.ts
File metadata and controls
314 lines (262 loc) · 8.82 KB
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
import { DOCUMENT } from '@angular/common';
import {
AfterViewInit,
ChangeDetectorRef,
Component,
ElementRef,
EventEmitter,
Inject,
Input,
OnDestroy,
OnInit,
Output,
QueryList,
Renderer2,
TemplateRef,
ViewChild,
ViewChildren
} from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { scrollAnimate } from 'ng-devui/utils';
import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { NavMenu, SpriteMode, SpriteOption } from './nav-sprite.type';
const DEFAULT_OPTIONS = {
top: '30%',
left: '80%',
zIndex: 1,
};
@Component({
selector: 'd-nav-sprite',
templateUrl: './nav-sprite.component.html',
styleUrls: ['./nav-sprite.component.scss'],
})
export class NavSpriteComponent implements OnInit, AfterViewInit, OnDestroy {
@Input() target: HTMLElement; // 爬取目录的容器
@Input() scrollTarget: HTMLElement; // 指定滚动的DOM
@Input() view: {
top?: number;
bottom?: number;
} = { top: 0, bottom: 0 }; // 矫正参数
@Input() hashSupport = false; // 支持锚点
@Input() mode: SpriteMode = 'default'; // 模式
@Input() maxLevel = 3; // 最大层级
@Input() title = 'menu'; // 名称
@Input() indent = 2; // 缩进
@Input() width = 300; // 高度
@Input() height = 400; // 高度
@Input() isOpen = true; // sprite模式下的初始状态
@Input() spriteOption: SpriteOption; // sprite模式下的初始位置
@Input() navItemTemplate: TemplateRef<any>; // 导航目录模板
@ViewChild('spriteTemp', { static: true }) spriteTemp: TemplateRef<any>;
@ViewChild('defaultTemp', { static: true }) defaultTemp: TemplateRef<any>;
@ViewChild('defaultNavItemTemplate', { static: true }) defaultNavItemTemplate: TemplateRef<any>; // 单条导航目录的默认模板
@ViewChildren('items', { read: ElementRef })
items!: QueryList<ElementRef>;
@Output() afterNavInit = new EventEmitter<NavSpriteComponent>(); // 组件初始化后返回组件实例
currentTemp: TemplateRef<any>;
menus: NavMenu[] = [];
activeIndex = -1;
isToViewByNav = false; // 区分是页面滚动还是点击目录事件
itemsInit = false;
contents: HTMLElement[];
targetContainer: HTMLElement;
scrollSub: Subscription;
isDragging = false;
mouseenterSub: Subscription;
itemsSub: Subscription;
timeGap = 60;
get baseUrl() {
if (typeof window === 'undefined') {
return '';
}
return window.location.href.replace(window.location.hash, '');
}
constructor(
private render: Renderer2,
private element: ElementRef,
private router: Router,
private activeRout: ActivatedRoute,
private cdr: ChangeDetectorRef,
@Inject(DOCUMENT) private document: Document
) {
}
ngOnInit() {
this.currentTemp = this.mode === 'default' ? this.defaultTemp : this.spriteTemp; // 设置当前的模式
this.navItemTemplate = this.navItemTemplate || this.defaultNavItemTemplate; // 设置当前的目录模板
this.targetContainer = this.scrollTarget || this.target;
}
ngAfterViewInit() {
setTimeout(() => {
const container = this.targetContainer === this.document.documentElement ? window : this.targetContainer;
this.scrollSub = fromEvent(container, 'scroll')
.pipe(debounceTime(300))
.subscribe(() => {
this.scrollEventHandler();
});
this.itemsSub = this.items.changes.subscribe((items) => {
if (!this.itemsInit) {
this.itemsInit = true;
this.setActiveMenu();
}
});
this.initStyles();
}, 0);
}
setActiveIndex() {
if (this.hashSupport && this.activeRout.snapshot.fragment) {
this.activeIndex = this.menus.findIndex((menu) => {
return menu.label === this.activeRout.snapshot.fragment;
});
this.isToViewByNav = true;
scrollAnimate(
this.targetContainer,
this.targetContainer.scrollTop,
this.menus[this.activeIndex].scrollPosition?.startLine,
undefined,
undefined,
() => {
setTimeout(() => {
this.isToViewByNav = false;
}, 160);
}
);
} else {
this.activeIndex = this.menus.findIndex((i) => {
const scrollTop = this.targetContainer.scrollTop;
return scrollTop < i.scrollPosition.top;
});
}
this.cdr.detectChanges();
}
getNavData(setActive = true) {
const search = [];
for (let i = 0; i < this.maxLevel; i++) {
search.push(`h${i + 1}`);
}
this.contents = Array.from(this.target.querySelectorAll(search.join(',')));
this.menus = this.contents.map((i) => {
return {
originEle: i,
level: +i.tagName.match(/\d+/)[0],
label: i.innerText,
href: this.baseUrl + '#' + i.innerText,
scrollPosition: this.getScrollPosition(i),
};
});
if (setActive) {
this.setActiveIndex();
}
}
// 设定目录范围
getScrollPosition(ele) {
const containerTop = Math.max(this.targetContainer.getBoundingClientRect().top, 0);
const containerScrollTop = this.targetContainer.scrollTop;
const top = ele.getBoundingClientRect().bottom - containerTop + containerScrollTop - this.view.top + this.view.bottom;
const startLine = ele.getBoundingClientRect().top - containerTop + containerScrollTop - this.view.top + this.view.bottom;
return { top, startLine };
}
// 监听页面滚动
scrollEventHandler() {
if (!this.isToViewByNav) {
const scrollTop = this.targetContainer.scrollTop;
const index = this.menus.findIndex((i) => {
return scrollTop < i.scrollPosition.top;
});
if (index !== -1 && this.activeIndex !== index) {
this.activeIndex = index;
this.menuScrollToTarget();
}
}
}
menuScrollToTarget() {
const item = this.items.toArray()[this.activeIndex];
const menuContainer = this.element.nativeElement.querySelector('.devui-nav-sprite-menus');
const start = menuContainer?.scrollTop;
const end = item?.nativeElement.getBoundingClientRect().top + start - menuContainer.getBoundingClientRect().top;
scrollAnimate(menuContainer, start, end, undefined, undefined, () => {
if (this.hashSupport) {
this.setUrlHash();
}
});
}
setActiveMenu() {
const item = this.items.toArray()[this.activeIndex];
const menuContainer = this.element.nativeElement.querySelector('.devui-nav-sprite-menus');
const top = item?.nativeElement.getBoundingClientRect().top - menuContainer.getBoundingClientRect().top;
scrollAnimate(menuContainer, menuContainer.scrollTop, top, undefined, undefined);
}
initStyles() {
if (this.mode === 'sprite') {
const content = this.element.nativeElement.querySelector('.devui-nav-sprite-content');
const spriteOptions = Object.assign({}, DEFAULT_OPTIONS, this.spriteOption);
this.render.addClass(content, 'devui-is-sprite');
this.render.setStyle(content, 'position', 'fixed');
this.render.setStyle(content, 'top', spriteOptions.top);
this.render.setStyle(content, 'left', spriteOptions.left);
this.render.setStyle(content, 'z-index', spriteOptions.zIndex);
this.render.setStyle(content, 'height', this.height + 'px');
this.render.setStyle(content, 'width', this.width + 'px');
}
this.render.setStyle(this.element.nativeElement, 'height', this.height + 'px');
this.render.setStyle(this.element.nativeElement, 'width', this.width + 'px');
this.afterNavInit.emit(this);
}
// 设置hash
setUrlHash() {
const activeMenu = this.menus[this.activeIndex];
this.router.navigate([], { fragment: activeMenu.label, replaceUrl: true });
}
// addClass
setTargetActive() {
const target = this.menus[this.activeIndex];
this.menus.forEach((i) => {
if (i.originEle) {
this.render.removeClass(i.originEle, 'nav-active');
}
});
this.render.addClass(target?.originEle, 'nav-active');
}
navTo(index) {
if (this.activeIndex !== index) {
this.activeIndex = index;
const target = this.menus[index];
scrollAnimate(this.targetContainer, this.targetContainer.scrollTop, target.scrollPosition.startLine, undefined, undefined, () => {
this.setUrlHash();
this.setTargetActive();
setTimeout(() => {
this.isToViewByNav = false;
}, this.timeGap);
});
this.isToViewByNav = true;
}
}
cdkDragStarted() {
this.isDragging = true;
}
cdkDragEnded() {
setTimeout(() => {
this.isDragging = false;
}, 100);
}
hide() {
this.isOpen = false;
}
open() {
if (this.isDragging) {
return;
}
this.isOpen = true;
}
ngOnDestroy() {
if (this.scrollSub) {
this.scrollSub.unsubscribe();
}
if (this.mouseenterSub) {
this.mouseenterSub.unsubscribe();
}
if (this.itemsSub) {
this.itemsSub.unsubscribe();
}
}
}