OLD | NEW |
| (Empty) |
1 // | |
2 // Copyright 2014 Google Inc. All rights reserved. | |
3 // | |
4 // Use of this source code is governed by a BSD-style | |
5 // license that can be found in the LICENSE file or at | |
6 // https://developers.google.com/open-source/licenses/bsd | |
7 // | |
8 | |
9 part of charted.core.utils; | |
10 | |
11 /// Basic namespace handing for Charted - includes utilities to | |
12 /// parse the namespace prefixes and to create DOM elements using a | |
13 /// namespace. | |
14 class Namespace { | |
15 /// Supported namespace prefixes mapped to their URIs. | |
16 static const Map<String,String> NS_PREFIXES = const { | |
17 "svg": "http://www.w3.org/2000/svg", | |
18 "xhtml": "http://www.w3.org/1999/xhtml", | |
19 "xlink": "http://www.w3.org/1999/xlink", | |
20 "xml": "http://www.w3.org/XML/1998/namespace", | |
21 "xmlns": "http://www.w3.org/2000/xmlns/" | |
22 }; | |
23 | |
24 /// Create an element from [tag]. If tag is prefixed with a | |
25 /// supported namespace prefix, the created element will | |
26 /// have the namespaceUri set to the correct URI. | |
27 static Element createChildElement(String tag, Element parent) { | |
28 var separatorIndex = tag.indexOf(':'); | |
29 if (separatorIndex == -1 && parent != null) { | |
30 return parent.ownerDocument.createElementNS(parent.namespaceUri, tag); | |
31 } | |
32 Namespace parsed = new Namespace._internal(tag, separatorIndex); | |
33 return parsed.namespaceUri == null ? | |
34 parent.ownerDocument.createElementNS(parent.namespaceUri, tag) : | |
35 parent.ownerDocument.createElementNS(parsed.namespaceUri, | |
36 parsed.localName); | |
37 } | |
38 | |
39 /// Local part of the Element's tag name. | |
40 String localName; | |
41 | |
42 /// Name space URI for the selected namespace. | |
43 String namespaceUri; | |
44 | |
45 /// Parses a tag for namespace prefix and local name. | |
46 /// If a known namespace prefix is found, sets the namespaceUri property | |
47 /// to the URI of the namespace. | |
48 factory Namespace(String tagName) => | |
49 new Namespace._internal(tagName, tagName.indexOf(':')); | |
50 | |
51 /// Utility for use by createChildElement and factory constructor. | |
52 Namespace._internal(String tagName, int separatorIdx) { | |
53 String prefix = tagName; | |
54 if (separatorIdx >= 0) { | |
55 prefix = tagName.substring(0, separatorIdx); | |
56 localName = tagName.substring(separatorIdx + 1); | |
57 } | |
58 | |
59 if (NS_PREFIXES.containsKey(prefix)) { | |
60 namespaceUri = NS_PREFIXES[prefix]; | |
61 } else { | |
62 localName = tagName; | |
63 } | |
64 } | |
65 } | |
OLD | NEW |