/
icon.tsx
executable file
路280 lines (233 loc) 路 6.76 KB
/
icon.tsx
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
import { Component, Element, Prop, State, Watch } from '@stencil/core';
import { getIconMap, getName, getSrc, isValid } from './utils';
@Component({
tag: 'ion-icon',
assetsDir: 'svg',
styleUrl: 'icon.css',
shadow: true
})
export class Icon {
private io?: IntersectionObserver;
@Element() el!: HTMLElement;
@State() private svgContent?: string;
@State() private isVisible = false;
@Prop({ context: 'isServer' }) isServer!: boolean;
@Prop({ context: 'resourcesUrl' }) resourcesUrl!: string;
@Prop({ context: 'document' }) doc!: Document;
@Prop({ context: 'window' }) win: any;
/**
* The color to use for the background of the item.
*/
@Prop() color?: string;
/**
* The mode determines which platform styles to use.
* Possible values are: `"ios"` or `"md"`.
*/
@Prop() mode?: 'ios' | 'md';
/**
* Specifies the label to use for accessibility. Defaults to the icon name.
*/
@Prop({ mutable: true, reflectToAttr: true }) ariaLabel?: string;
/**
* Specifies which icon to use on `ios` mode.
*/
@Prop() ios?: string;
/**
* Specifies which icon to use on `md` mode.
*/
@Prop() md?: string;
/**
* Specifies whether the icon should horizontally flip when `dir` is `"rtl"`.
*/
@Prop() flipRtl?: boolean;
/**
* Specifies which icon to use from the built-in set of icons.
*/
@Prop() name?: string;
/**
* Specifies the exact `src` of an SVG file to use.
*/
@Prop() src?: string;
/**
* A combination of both `name` and `src`. If a `src` url is detected
* it will set the `src` property. Otherwise it assumes it's a built-in named
* SVG and set the `name` property.
*/
@Prop() icon?: string;
/**
* The size of the icon.
* Available options are: `"small"` and `"large"`.
*/
@Prop() size?: string;
/**
* If enabled, ion-icon will be loaded lazily when it's visible in the viewport.
* Default, `false`.
*/
@Prop() lazy = false;
componentWillLoad() {
// purposely do not return the promise here because loading
// the svg file should not hold up loading the app
// only load the svg if it's visible
this.waitUntilVisible(this.el, '50px', () => {
this.isVisible = true;
this.loadIcon();
});
}
componentDidUnload() {
if (this.io) {
this.io.disconnect();
this.io = undefined;
}
}
private waitUntilVisible(el: HTMLElement, rootMargin: string, cb: () => void) {
if (this.lazy && this.win && this.win.IntersectionObserver) {
const io = this.io = new this.win.IntersectionObserver((data: IntersectionObserverEntry[]) => {
if (data[0].isIntersecting) {
io.disconnect();
this.io = undefined;
cb();
}
}, { rootMargin });
io.observe(el);
} else {
// browser doesn't support IntersectionObserver
// so just fallback to always show it
cb();
}
}
@Watch('name')
@Watch('src')
@Watch('icon')
loadIcon() {
if (!this.isServer && this.isVisible) {
const url = this.getUrl();
if (url) {
getSvgContent(this.doc, url, 's-ion-icon')
.then(svgContent => this.svgContent = svgContent);
} else {
console.error('icon was not resolved');
}
}
if (!this.ariaLabel) {
const name = getName(this.name, this.mode, this.ios, this.md);
// user did not provide a label
// come up with the label based on the icon name
if (name) {
this.ariaLabel = name
.replace('ios-', '')
.replace('md-', '')
.replace(/\-/g, ' ');
}
}
}
getUrl() {
let url = getSrc(this.src);
if (url) {
return url;
}
url = getName(this.name, this.mode, this.ios, this.md);
if (url) {
return this.getNamedUrl(url);
}
url = getSrc(this.icon);
if (url) {
return url;
}
url = getName(this.icon, this.mode, this.ios, this.md);
if (url) {
return this.getNamedUrl(url);
}
return null;
}
private getNamedUrl(name: string) {
const url = getIconMap().get(name);
if (url) {
return url;
}
return `${this.resourcesUrl}svg/${name}.svg`;
}
hostData() {
const flipRtl = this.flipRtl || (this.ariaLabel && this.ariaLabel.indexOf('arrow') > -1 && this.flipRtl !== false);
return {
'role': 'img',
class: {
...createColorClasses(this.color),
[`icon-${this.size}`]: !!this.size,
'flip-rtl': flipRtl && hostContext('[dir=rtl]', this.el)
}
};
}
render() {
if (!this.isServer && this.svgContent) {
// we've already loaded up this svg at one point
// and the svg content we've loaded and assigned checks out
// render this svg!!
return <div class="icon-inner" innerHTML={this.svgContent}></div>;
}
// actively requesting the svg
// or it's an SSR render
// so let's just render an empty div for now
return <div class="icon-inner"></div>;
}
}
const requests = new Map<string, Promise<string>>();
function getSvgContent(doc: Document, url: string, scopedId: string | undefined) {
// see if we already have a request for this url
let req = requests.get(url);
if (!req) {
// we don't already have a request
req = fetch(url, { cache: 'force-cache' }).then(rsp => {
if (isStatusValid(rsp.status)) {
return rsp.text();
}
return Promise.resolve(null);
}).then(svgContent => validateContent(doc, svgContent, scopedId));
// cache for the same requests
requests.set(url, req);
}
return req;
}
function isStatusValid(status: number) {
return status <= 299;
}
function validateContent(
document: Document,
svgContent: string | null,
scopeId: string | undefined
) {
if (svgContent) {
const frag = document.createDocumentFragment();
const div = document.createElement('div');
div.innerHTML = svgContent;
frag.appendChild(div);
// setup this way to ensure it works on our buddy IE
for (let i = div.childNodes.length - 1; i >= 0; i--) {
if (div.childNodes[i].nodeName.toLowerCase() !== 'svg') {
div.removeChild(div.childNodes[i]);
}
}
// must only have 1 root element
const svgElm = div.firstElementChild;
if (svgElm && svgElm.nodeName.toLowerCase() === 'svg') {
if (scopeId) {
svgElm.setAttribute('class', scopeId);
}
// root element must be an svg
// lets double check we've got valid elements
// do not allow scripts
if (isValid(svgElm as any)) {
return div.innerHTML;
}
}
}
return '';
}
function createColorClasses(color: string | undefined) {
return (color) ? {
'ion-color': true,
[`ion-color-${color}`]: true
} : null;
}
function hostContext(selector: string, el: HTMLElement): boolean {
return el.closest(selector) !== null;
}