-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcode-block.ts
More file actions
593 lines (508 loc) · 19.8 KB
/
Copy pathcode-block.ts
File metadata and controls
593 lines (508 loc) · 19.8 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
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
import { A11yModule, FocusMonitor } from '@angular/cdk/a11y';
import { Clipboard } from '@angular/cdk/clipboard';
import { SharedResizeObserver } from '@angular/cdk/observers/private';
import { Platform } from '@angular/cdk/platform';
import { CdkScrollable, CdkScrollableModule, ExtendedScrollToOptions } from '@angular/cdk/scrolling';
import { DOCUMENT, NgTemplateOutlet } from '@angular/common';
import {
AfterViewInit,
booleanAttribute,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
computed,
ContentChild,
DestroyRef,
Directive,
effect,
ElementRef,
inject,
InjectionToken,
Injector,
Input,
input,
numberAttribute,
output,
Provider,
SecurityContext,
signal,
TemplateRef,
viewChild,
ViewEncapsulation
} from '@angular/core';
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
import { DomSanitizer } from '@angular/platform-browser';
import { KbqButtonModule, KbqButtonStyles } from '@koobiq/components/button';
import {
KBQ_LOCALE_SERVICE,
KBQ_WINDOW,
KbqCodeBlockLocaleConfiguration,
KbqComponentColors,
KbqOverflowShadowContainer,
KbqOverflowShadowTop,
ruRULocaleData
} from '@koobiq/components/core';
import { KbqIconModule } from '@koobiq/components/icon';
import { KbqNativeScrollbar } from '@koobiq/components/scrollbar';
import { KbqTabsModule } from '@koobiq/components/tabs';
import { KbqToolTipModule, KbqTooltipTrigger } from '@koobiq/components/tooltip';
import { debounceTime, filter, fromEvent, map, merge, take } from 'rxjs';
import { KbqCodeBlockHighlight } from './code-block-highlight';
import { KbqCodeBlockFile, KbqTabLinkTemplateContext } from './types';
/** Localization configuration provider. */
export const KBQ_CODE_BLOCK_LOCALE_CONFIGURATION = new InjectionToken<KbqCodeBlockLocaleConfiguration>(
'KBQ_CODE_BLOCK_LOCALE_CONFIGURATION',
{ factory: () => ruRULocaleData.codeBlock }
);
/** Utility provider for `KBQ_CODE_BLOCK_LOCALE_CONFIGURATION`. */
export const kbqCodeBlockLocaleConfigurationProvider = (configuration: KbqCodeBlockLocaleConfiguration): Provider => ({
provide: KBQ_CODE_BLOCK_LOCALE_CONFIGURATION,
useValue: configuration
});
/** Fallback file name for code block if file name is not specified. */
export const KBQ_CODE_BLOCK_FALLBACK_FILE_NAME = new InjectionToken<string>('KBQ_CODE_BLOCK_FALLBACK_FILE_NAME', {
factory: () => 'code'
});
/** Utility provider for `KBQ_CODE_BLOCK_FALLBACK_FILE_NAME`. */
export const kbqCodeBlockFallbackFileNameProvider = (fileName: string): Provider => ({
provide: KBQ_CODE_BLOCK_FALLBACK_FILE_NAME,
useValue: fileName
});
/** Default options for `kbq-code-block`. */
export type KbqCodeBlockDefaultOptions = Partial<{
/** Whether the actionbar should remain visible when tabs are hidden. */
alwaysShowActionbar: boolean;
}>;
/** Injection token used to configure the default options for all `kbq-code-block` components. */
export const KBQ_CODE_BLOCK_DEFAULT_OPTIONS = new InjectionToken<KbqCodeBlockDefaultOptions>(
'KBQ_CODE_BLOCK_DEFAULT_OPTIONS'
);
/** Utility provider for `KBQ_CODE_BLOCK_DEFAULT_OPTIONS`. */
export const kbqCodeBlockDefaultOptionsProvider = (options: KbqCodeBlockDefaultOptions): Provider => ({
provide: KBQ_CODE_BLOCK_DEFAULT_OPTIONS,
useValue: options
});
/** Marks a template as a custom tab link. */
@Directive({
selector: 'ng-template[kbqCodeBlockTabLinkContent]',
exportAs: 'kbqCodeBlockTabLinkContent'
})
export class KbqCodeBlockTabLinkContent {}
/**
* Component which highlights blocks of code.
*/
@Component({
selector: 'kbq-code-block',
imports: [
KbqTabsModule,
KbqButtonModule,
KbqCodeBlockHighlight,
A11yModule,
CdkScrollableModule,
KbqToolTipModule,
KbqIconModule,
KbqNativeScrollbar,
NgTemplateOutlet,
KbqOverflowShadowContainer,
KbqOverflowShadowTop
],
templateUrl: './code-block.html',
styleUrls: ['./code-block.scss', './code-block-tokens.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: {
class: 'kbq-code-block',
// highlight.js rewrites the <code> subtree on the client (and builds a <table> for line numbers),
// which never matches the server-rendered DOM — skip hydration for this component to avoid NG0500.
ngSkipHydration: 'true',
'[class.kbq-code-block_filled]': 'filled()',
'[class.kbq-code-block_outline]': '!filled()',
'[class.kbq-code-block_hide-line-numbers]': '!lineNumbers()',
'[class.kbq-code-block_hide-tabs]': 'hideTabs',
'[class.kbq-code-block_no-border]': 'noBorder() || filled()',
'[class.kbq-code-block_show-actionbar]': 'actionbarVisible()',
'[class.kbq-code-block_soft-wrap]': 'softWrap',
'[class.kbq-code-block_view-all]': 'viewAll'
},
exportAs: 'kbqCodeBlock'
})
export class KbqCodeBlock implements AfterViewInit {
private readonly copyButtonTooltip = viewChild<KbqTooltipTrigger>('copyButtonTooltip');
private readonly defaultOptions = inject(KBQ_CODE_BLOCK_DEFAULT_OPTIONS, { optional: true });
/**
* Reference to the scrollable code content.
*
* @deprecated Use `scrollTo` method instead, will be removed from public API (mark as private) in the next major release.
*
* @docs-private
*/
readonly scrollableCodeContent = viewChild.required(CdkScrollable);
/** @docs-private */
private readonly highlight = viewChild.required(KbqCodeBlockHighlight);
/** @docs-private */
private readonly preElementRef = viewChild.required<ElementRef<HTMLElement>>('codeBlockPre');
/** @docs-private */
protected readonly contentExceedsMaxHeight = signal(false);
/** @docs-private */
@ContentChild(KbqCodeBlockTabLinkContent, { read: TemplateRef })
protected readonly tabLinkTemplate: TemplateRef<KbqTabLinkTemplateContext>;
/** Whether to display line numbers. */
readonly lineNumbers = input(false, { transform: booleanAttribute });
/** Whether the code block should be filled. */
readonly filled = input<boolean, unknown>(false, { transform: booleanAttribute });
/** Added soft wrap toggle button. */
readonly canToggleSoftWrap = input<boolean, unknown>(false, { transform: booleanAttribute });
/** Whether sequences of whitespace should be preserved. */
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input({ transform: booleanAttribute }) softWrap: boolean = false;
/**
* Output to support two-way binding on `[(softWrap)]` property.
*/
readonly softWrapChange = output<boolean>();
/**
* Allows to view all the code, otherwise it will be hidden.
* Works only with `maxHeight` property.
*/
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input({ transform: booleanAttribute }) viewAll: boolean = false;
/**
* Output to support two-way binding on `[(viewAll)]` property.
*/
readonly viewAllChange = output<boolean>();
/**
* Maximum height of the code block content, other parts will be hidden.
* Can be toggled by `viewAll` property.
*/
readonly maxHeight = input<number, unknown>(undefined!, { transform: numberAttribute });
/**
* @docs-private
*/
protected get calculatedMaxHeight(): number | null {
return this.maxHeight() > 0 && !this.viewAll ? this.maxHeight() : null;
}
/**
* @deprecated Will be removed in next major release, use `canDownload` instead.
*
* @docs-private
*/
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input({ transform: booleanAttribute })
set canLoad(value: boolean) {
this.canDownload = value;
}
/** Added download code button. */
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input({ transform: booleanAttribute }) canDownload: boolean = false;
/** Added copy code button. */
readonly canCopy = input<boolean, unknown>(true, { transform: booleanAttribute });
/** Whether the actionbar should remain visible when tabs are hidden. */
readonly alwaysShowActionbar = input<boolean, unknown>(this.defaultOptions?.alwaysShowActionbar ?? false, {
transform: booleanAttribute
});
/**
* @deprecated Will be removed in next major release, use `files` instead.
*/
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
set codeFiles(files: KbqCodeBlockFile[]) {
this.files = files;
}
/**
* @TODO Mark as `required`, after removing `codeFiles`
*
* Files to display.
*/
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input()
get files(): KbqCodeBlockFile[] {
return this._files;
}
set files(files: KbqCodeBlockFile[]) {
this._files = files;
if (this._files.length < this.activeFileIndex) {
this.onSelectedTabChange(0);
}
if (this._files.length === 1 && !this._files[0].filename) {
this.hideTabs = true;
}
}
private _files: KbqCodeBlockFile[] = [];
/** Defines which file (index) is active. */
// TODO: Skipped for migration because:
// Your application code writes to the input. This prevents migration.
@Input({ transform: numberAttribute }) activeFileIndex = 0;
/**
* Output to support two-way binding on `[(activeFileIndex)]` property.
*/
readonly activeFileIndexChange = output<number>();
/** Whether to hide border. */
readonly noBorder = input<boolean, unknown>(false, { transform: booleanAttribute });
/**
* Whether to hide header tabs.
* Always `true` if there is only one file without filename.
* Makes actionbar floating if tabs are hidden.
*/
// TODO: Skipped for migration because:
// Accessor inputs cannot be migrated as they are too complex.
@Input({ transform: booleanAttribute })
get hideTabs(): boolean {
return this._hideTabs();
}
set hideTabs(value: boolean) {
this._hideTabs.set(value);
this.hideTabsChange.emit(value);
}
private readonly _hideTabs = signal(false);
private readonly actionbarHovered = signal(false);
/**
* Output to support two-way binding on `[(hideTabs)]` property.
*/
readonly hideTabsChange = output<boolean>();
/**
* Component locale configuration.
*
* @docs-private
*/
protected get localeConfiguration(): KbqCodeBlockLocaleConfiguration {
return this._localeConfiguration;
}
private _localeConfiguration: KbqCodeBlockLocaleConfiguration = inject(KBQ_CODE_BLOCK_LOCALE_CONFIGURATION);
/**
* Code content tab index.
*
* @docs-private
*/
protected get codeContentTabIndex(): number {
return this.canCodeContentBeFocused ? 0 : -1;
}
/**
* Determines whether the code content can be focused.
*
* This checks if the scrollable code content element is present,
* has a scroll, and the calculated maximum height is not set.
*/
private get canCodeContentBeFocused(): boolean {
if (!this.platform.isBrowser) return false;
const element = this.scrollableCodeContent()?.getElementRef().nativeElement;
return element && this.hasScroll(element) && !this.calculatedMaxHeight;
}
/**
* @docs-private
*/
protected readonly componentColor = KbqComponentColors;
/**
* @docs-private
*/
protected readonly buttonStyle = KbqButtonStyles;
private readonly elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private readonly injector = inject(Injector);
private readonly changeDetectorRef = inject(ChangeDetectorRef);
private readonly localeService = inject(KBQ_LOCALE_SERVICE, { optional: true });
private readonly destroyRef = inject(DestroyRef);
private readonly platform = inject(Platform);
private readonly focusMonitor = inject(FocusMonitor);
private readonly clipboard = inject(Clipboard);
private readonly domSanitizer = inject(DomSanitizer);
private readonly document = inject<Document>(DOCUMENT);
private readonly sharedResizeObserver = inject(SharedResizeObserver);
/**
* @docs-private
*/
protected readonly fallbackFileName = inject(KBQ_CODE_BLOCK_FALLBACK_FILE_NAME);
private readonly window = inject(KBQ_WINDOW);
/** @docs-private */
protected readonly actionbarVisible = computed(
() =>
this.alwaysShowActionbar() ||
this.platform.IOS ||
this.platform.ANDROID ||
!this._hideTabs() ||
this.actionbarHovered()
);
constructor() {
this.trackHoverState();
this.localeService?.changes.pipe(takeUntilDestroyed()).subscribe(this.updateLocaleParams);
}
ngAfterViewInit(): void {
this.setupContentOverflowDetection();
this.copyButtonTooltip()
?.visibleChange.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((isVisible) => {
if (isVisible) {
this.copyButtonTooltip()!.content = this.localeConfiguration.copyTooltip;
}
});
// Should call `markForCheck` to ensure the `codeContentTabIndex` is updated after the view is initialized,
// for correct focus behavior.
this.changeDetectorRef.markForCheck();
}
/**
* Toggles the `viewAll` property.
*
* When `viewAll` is set to `true`, the content of the code block will be
* displayed in its entirety. When set to `false`, the content will be
* limited to the `maxHeight` property. If the content exceeds the
* `maxHeight`, it will be scrolled to the top and the `viewAll` button
* will be displayed.
*/
toggleViewAll(): void {
this.viewAll = !this.viewAll;
if (!this.viewAll) {
this.scrollTo({ top: 0, behavior: 'instant' });
}
this.viewAllChange.emit(this.viewAll);
}
/** Scrolls the code content to the specified position. */
scrollTo(options: ExtendedScrollToOptions): void {
const scroll = () => this.scrollableCodeContent().scrollTo(options);
const highlight = this.highlight();
if (highlight?.pending()) {
toObservable(highlight.pending, { injector: this.injector })
.pipe(
filter((pending) => !pending),
take(1)
)
.subscribe(scroll);
} else {
scroll();
}
}
/**
* Toggles `softWrap` property.
*
* When `softWrap` is set to `true`, the content of the code block will be
* wrapped if it exceeds the height of the component. When set to `false`
* the content will not be wrapped.
*/
toggleSoftWrap(): void {
this.softWrap = !this.softWrap;
this.softWrapChange.emit(this.softWrap);
}
/**
* Handles the change of the selected tab by updating the active file index
* and scrolling to the top of the scrollable content.
*
* @param index - The index of the newly selected tab.
*
* @docs-private
*/
protected onSelectedTabChange(index: number): void {
if (this.activeFileIndex !== index) {
this.activeFileIndex = index;
this.activeFileIndexChange.emit(this.activeFileIndex);
this.scrollTo({ top: 0, behavior: 'instant' });
}
}
/** Tracks hover when tabs are hidden and `alwaysShowActionbar` is disabled. */
private trackHoverState(): void {
effect(
(onCleanup) => {
const hideTabs = this._hideTabs();
const alwaysShowActionbar = this.alwaysShowActionbar();
this.actionbarHovered.set(false);
if (!hideTabs || alwaysShowActionbar || this.platform.IOS || this.platform.ANDROID) return;
const subscription = merge(
fromEvent<MouseEvent>(this.elementRef.nativeElement, 'mouseenter').pipe(map(() => true)),
fromEvent<MouseEvent>(this.elementRef.nativeElement, 'mouseleave').pipe(map(() => false))
)
.pipe(debounceTime(100))
.subscribe((isHovered) => {
this.actionbarHovered.set(isHovered);
});
onCleanup(() => subscription.unsubscribe());
},
{ injector: this.injector }
);
}
private setupContentOverflowDetection(): void {
if (!this.platform.isBrowser) return;
if (!this.maxHeight()) return;
const checkOverflow = () => {
this.contentExceedsMaxHeight.set(this.preElementRef().nativeElement.offsetHeight > this.maxHeight());
};
checkOverflow();
const highlight = this.highlight();
if (highlight?.pending()) {
toObservable(highlight.pending, { injector: this.injector })
.pipe(
filter((pending) => !pending),
take(1)
)
.subscribe(checkOverflow);
}
this.sharedResizeObserver
.observe(this.preElementRef().nativeElement)
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe(checkOverflow);
}
/** Whether the element has scroll. */
private hasScroll({ scrollHeight, scrollWidth, clientHeight, clientWidth }: HTMLElement): boolean {
return scrollHeight > clientHeight || scrollWidth > clientWidth;
}
/**
* Handles the enter keydown event on `viewAll` button.
*
* @docs-private
*/
protected onViewAllEnterKeydown(event: Event): void {
event.preventDefault();
this.toggleViewAll();
if (this.canCodeContentBeFocused) {
this.focusMonitor.focusVia(this.scrollableCodeContent().getElementRef().nativeElement, 'keyboard');
}
}
private updateLocaleParams = (): void => {
this._localeConfiguration = this.localeService?.getParams('codeBlock');
this.changeDetectorRef.markForCheck();
};
/**
* Copies the file code to the clipboard.
*
* If the copy was successful, the copy button tooltip content is updated
* to show the "copied" message.
*
* @docs-private
*/
protected copyCode(): void {
const file = this.files[this.activeFileIndex];
const copyButtonTooltip = this.copyButtonTooltip();
if (this.clipboard.copy(file.content) && copyButtonTooltip) {
copyButtonTooltip.content = this.localeConfiguration.copiedTooltip;
}
}
/**
* Opens the file link in a new window.
*
* @docs-private
*/
protected openLink(): void {
const file = this.files[this.activeFileIndex];
const safeURL = this.domSanitizer.sanitize(SecurityContext.URL, file.link!);
if (safeURL) {
this.window.open(safeURL.toString(), '_blank');
}
}
/**
* Downloads the file as a blob.
*
* Creates a link with a blob as href and the file name as download attribute.
* Then simulates a click event on the link to initiate the download.
*
* @docs-private
*/
protected downloadCode(): void {
const file = this.files[this.activeFileIndex];
const blob = new Blob([file.content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const link = this.document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', file.filename || this.fallbackFileName);
link.click();
}
}