Repository navigation
Expand file tree
/
Copy pathcode.component.ts
More file actions
185 lines (162 loc) · 5.17 KB
/
Copy pathcode.component.ts
File metadata and controls
185 lines (162 loc) · 5.17 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
import { Component, ElementRef, ViewChild, OnChanges, OnDestroy, Input } from '@angular/core';
import { Logger } from 'app/shared/logger.service';
import { PrettyPrinter } from './pretty-printer.service';
import { CopierService } from 'app/shared/copier.service';
import { MdSnackBar } from '@angular/material';
const originalLabel = 'Copy Code';
const copiedLabel = 'Copied!';
const defaultLineNumsCount = 10; // by default, show linenums over this number
/**
* Formatted Code Block
*
* Pretty renders a code block, used in the docs and API reference by the code-example and
* code-tabs embedded components.
* It includes a "copy" button that will send the content to the clipboard when clicked
*
* Example usage:
*
* ```
* <aio-code
* [code]="variableContainingCode"
* [language]="ts"
* [linenums]="true"
* [path]="ts-to-js/ts/src/app/app.module.ts"
* [region]="ng2import">
* </aio-code>
* ```
*/
@Component({
selector: 'aio-code',
template: `
<pre class="prettyprint lang-{{language}}">
<button *ngIf="!hideCopy" class="material-icons copy-button"
title="Copy code snippet"
[attr.aria-label]="ariaLabel"
(click)="doCopy()">
<span aria-hidden="true">content_copy</span>
</button>
<code class="animated fadeIn" #codeContainer></code>
</pre>
`
})
export class CodeComponent implements OnChanges {
ariaLabel = '';
/**
* The code to be formatted, this should already be HTML encoded
*/
@Input()
code: string;
/**
* The code to be copied when clicking the copy button, this should not be HTML encoded
*/
private codeText: string;
/**
* set to true if the copy button is not to be shown
*/
@Input()
hideCopy: boolean;
/**
* The language of the code to render
* (could be javascript, dart, typescript, etc)
*/
@Input()
language: string;
/**
* Whether to display line numbers:
* - false: don't display
* - true: do display
* - number: do display but start at the given number
*/
@Input()
linenums: boolean | number | string;
/**
* path to the source of the code being displayed
*/
@Input()
path: string;
/**
* region of the source of the code being displayed
*/
@Input()
region: string;
/**
* title for this snippet (optional)
*/
@Input()
title: string;
/**
* The element in the template that will display the formatted code
*/
@ViewChild('codeContainer') codeContainer: ElementRef;
constructor(
private snackbar: MdSnackBar,
private pretty: PrettyPrinter,
private copier: CopierService,
private logger: Logger) {}
ngOnChanges() {
this.code = this.code && leftAlign(this.code);
this.ariaLabel = this.title ? `Copy code snippet from ${this.title}` : '';
if (!this.code) {
const src = this.path ? this.path + (this.region ? '#' + this.region : '') : '';
const srcMsg = src ? ` for\n${src}` : '.';
this.setCodeHtml(`<p class="code-missing">The code sample is missing${srcMsg}</p>`);
return;
}
const linenums = this.getLinenums();
this.setCodeHtml(this.code); // start with unformatted code
this.codeText = this.getCodeText(); // store the unformatted code as text (for copying)
this.pretty.formatCode(this.code, this.language, linenums).subscribe(
formattedCode => this.setCodeHtml(formattedCode),
err => { /* ignore failure to format */ }
);
}
private setCodeHtml(formattedCode: string) {
// **Security:** `codeExampleContent` is provided by docs authors and as such its considered to
// be safe for innerHTML purposes.
this.codeContainer.nativeElement.innerHTML = formattedCode;
}
private getCodeText() {
// `prettify` may remove newlines, e.g. when `linenums` are on. Retrieve the content of the
// container as text, before prettifying it.
// We take the textContent because we don't want it to be HTML encoded.
return this.codeContainer.nativeElement.textContent;
}
doCopy() {
const code = this.codeText;
if (this.copier.copyText(code)) {
this.logger.log('Copied code to clipboard:', code);
// success snackbar alert
this.snackbar.open('Code Copied', '', {
duration: 800,
});
} else {
this.logger.error('ERROR copying code to clipboard:', code);
// failure snackbar alert
this.snackbar.open('Copy failed. Please try again!', '', {
duration: 800,
});
}
}
getLinenums() {
const linenums =
typeof this.linenums === 'boolean' ? this.linenums :
this.linenums === 'true' ? true :
this.linenums === 'false' ? false :
typeof this.linenums === 'string' ? parseInt(this.linenums, 10) :
this.linenums;
// if no linenums, enable line numbers if more than one line
return linenums == null || linenums === NaN ?
(this.code.match(/\n/g) || []).length > defaultLineNumsCount : linenums;
}
}
function leftAlign(text) {
let indent = Number.MAX_VALUE;
const lines = text.split('\n');
lines.forEach(line => {
const lineIndent = line.search(/\S/);
if (lineIndent !== -1) {
indent = Math.min(lineIndent, indent);
}
});
return lines.map(line => line.substr(indent)).join('\n').trim();
}