@americana/diplomat 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,121 @@
1
+ Creative Commons Legal Code
2
+
3
+ CC0 1.0 Universal
4
+
5
+ CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
6
+ LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
7
+ ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
8
+ INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
9
+ REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
10
+ PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
11
+ THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
12
+ HEREUNDER.
13
+
14
+ Statement of Purpose
15
+
16
+ The laws of most jurisdictions throughout the world automatically confer
17
+ exclusive Copyright and Related Rights (defined below) upon the creator
18
+ and subsequent owner(s) (each and all, an "owner") of an original work of
19
+ authorship and/or a database (each, a "Work").
20
+
21
+ Certain owners wish to permanently relinquish those rights to a Work for
22
+ the purpose of contributing to a commons of creative, cultural and
23
+ scientific works ("Commons") that the public can reliably and without fear
24
+ of later claims of infringement build upon, modify, incorporate in other
25
+ works, reuse and redistribute as freely as possible in any form whatsoever
26
+ and for any purposes, including without limitation commercial purposes.
27
+ These owners may contribute to the Commons to promote the ideal of a free
28
+ culture and the further production of creative, cultural and scientific
29
+ works, or to gain reputation or greater distribution for their Work in
30
+ part through the use and efforts of others.
31
+
32
+ For these and/or other purposes and motivations, and without any
33
+ expectation of additional consideration or compensation, the person
34
+ associating CC0 with a Work (the "Affirmer"), to the extent that he or she
35
+ is an owner of Copyright and Related Rights in the Work, voluntarily
36
+ elects to apply CC0 to the Work and publicly distribute the Work under its
37
+ terms, with knowledge of his or her Copyright and Related Rights in the
38
+ Work and the meaning and intended legal effect of CC0 on those rights.
39
+
40
+ 1. Copyright and Related Rights. A Work made available under CC0 may be
41
+ protected by copyright and related or neighboring rights ("Copyright and
42
+ Related Rights"). Copyright and Related Rights include, but are not
43
+ limited to, the following:
44
+
45
+ i. the right to reproduce, adapt, distribute, perform, display,
46
+ communicate, and translate a Work;
47
+ ii. moral rights retained by the original author(s) and/or performer(s);
48
+ iii. publicity and privacy rights pertaining to a person's image or
49
+ likeness depicted in a Work;
50
+ iv. rights protecting against unfair competition in regards to a Work,
51
+ subject to the limitations in paragraph 4(a), below;
52
+ v. rights protecting the extraction, dissemination, use and reuse of data
53
+ in a Work;
54
+ vi. database rights (such as those arising under Directive 96/9/EC of the
55
+ European Parliament and of the Council of 11 March 1996 on the legal
56
+ protection of databases, and under any national implementation
57
+ thereof, including any amended or successor version of such
58
+ directive); and
59
+ vii. other similar, equivalent or corresponding rights throughout the
60
+ world based on applicable law or treaty, and any national
61
+ implementations thereof.
62
+
63
+ 2. Waiver. To the greatest extent permitted by, but not in contravention
64
+ of, applicable law, Affirmer hereby overtly, fully, permanently,
65
+ irrevocably and unconditionally waives, abandons, and surrenders all of
66
+ Affirmer's Copyright and Related Rights and associated claims and causes
67
+ of action, whether now known or unknown (including existing as well as
68
+ future claims and causes of action), in the Work (i) in all territories
69
+ worldwide, (ii) for the maximum duration provided by applicable law or
70
+ treaty (including future time extensions), (iii) in any current or future
71
+ medium and for any number of copies, and (iv) for any purpose whatsoever,
72
+ including without limitation commercial, advertising or promotional
73
+ purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
74
+ member of the public at large and to the detriment of Affirmer's heirs and
75
+ successors, fully intending that such Waiver shall not be subject to
76
+ revocation, rescission, cancellation, termination, or any other legal or
77
+ equitable action to disrupt the quiet enjoyment of the Work by the public
78
+ as contemplated by Affirmer's express Statement of Purpose.
79
+
80
+ 3. Public License Fallback. Should any part of the Waiver for any reason
81
+ be judged legally invalid or ineffective under applicable law, then the
82
+ Waiver shall be preserved to the maximum extent permitted taking into
83
+ account Affirmer's express Statement of Purpose. In addition, to the
84
+ extent the Waiver is so judged Affirmer hereby grants to each affected
85
+ person a royalty-free, non transferable, non sublicensable, non exclusive,
86
+ irrevocable and unconditional license to exercise Affirmer's Copyright and
87
+ Related Rights in the Work (i) in all territories worldwide, (ii) for the
88
+ maximum duration provided by applicable law or treaty (including future
89
+ time extensions), (iii) in any current or future medium and for any number
90
+ of copies, and (iv) for any purpose whatsoever, including without
91
+ limitation commercial, advertising or promotional purposes (the
92
+ "License"). The License shall be deemed effective as of the date CC0 was
93
+ applied by Affirmer to the Work. Should any part of the License for any
94
+ reason be judged legally invalid or ineffective under applicable law, such
95
+ partial invalidity or ineffectiveness shall not invalidate the remainder
96
+ of the License, and in such case Affirmer hereby affirms that he or she
97
+ will not (i) exercise any of his or her remaining Copyright and Related
98
+ Rights in the Work or (ii) assert any associated claims and causes of
99
+ action with respect to the Work, in either case contrary to Affirmer's
100
+ express Statement of Purpose.
101
+
102
+ 4. Limitations and Disclaimers.
103
+
104
+ a. No trademark or patent rights held by Affirmer are waived, abandoned,
105
+ surrendered, licensed or otherwise affected by this document.
106
+ b. Affirmer offers the Work as-is and makes no representations or
107
+ warranties of any kind concerning the Work, express, implied,
108
+ statutory or otherwise, including without limitation warranties of
109
+ title, merchantability, fitness for a particular purpose, non
110
+ infringement, or the absence of latent or other defects, accuracy, or
111
+ the present or absence of errors, whether or not discoverable, all to
112
+ the greatest extent permissible under applicable law.
113
+ c. Affirmer disclaims responsibility for clearing rights of other persons
114
+ that may apply to the Work or any use thereof, including without
115
+ limitation any person's Copyright and Related Rights in the Work.
116
+ Further, Affirmer disclaims responsibility for obtaining any necessary
117
+ consents, permissions or other rights required for any use of the
118
+ Work.
119
+ d. Affirmer understands and acknowledges that Creative Commons is not a
120
+ party to this document and has no duty or obligation with respect to
121
+ this CC0 or use of the Work.
package/README.md ADDED
@@ -0,0 +1,209 @@
1
+ # Diplomat
2
+
3
+ Diplomat prepares your interactive map for an international audience. With a few lines of code, your [MapLibre GL JS](https://github.com/maplibre/maplibre-gl-js/)–powered map will speak the user’s preferred language while informing them about local languages the world over.
4
+
5
+ | Before | After |
6
+ | ----------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
7
+ | <img src="docs/navajo-nation.png" width="400" alt="Navajo Nation;Naabeehó Bináhásdzo"> | [<img src="docs/navajo-nation-es.png" width="400" alt="Nación Navajo (Navajo Nation • Naabeehó Bináhásdzo)">](https://americanamap.org/#map=9/36.2134/-109.2837&language=es) |
8
+ | <img src="docs/north-sea.png" width="400" alt="North Sea / Nordsee / Noordzee / Nordsøen / Nordsjøen / Mer du Nord"> | [<img src="docs/north-sea-la.png" width="400" alt="Mare Germanicum">](https://americanamap.org/#map=4/56/3&language=la) |
9
+ | <img src="docs/section-ross.png" width="400" alt="Ross Avenue;Tennesssee Avenue at Rhode Island Avenue;Section Avenue"> | [<img src="docs/section-ross-en.png" width="400" alt="Ross Avenue • Tennesssee Avenue at Rhode Island Avenue • Section Avenue">](https://americanamap.org/#map=17/39.168568/-84.460075) |
10
+
11
+ ## Requirements
12
+
13
+ Diplomat is compatible with applications using MapLibre GL&nbsp;JS v5.13.0 and above.
14
+
15
+ The stylesheet must use the newer [expression](https://maplibre.org/maplibre-style-spec/expressions/) syntax; [legacy style functions](https://maplibre.org/maplibre-style-spec/deprecations/#function) are not supported. The stylesheet’s sources must conform to [Diplomat’s schema](#schema). Several popular vector tilesets already conform to this schema, including:
16
+
17
+ - [OpenMapTiles](https://openmaptiles.org/schema/) implementations, e.g., [MapTiler](https://cloud.maptiler.com/tiles/v3-openmaptiles/), [OpenFreeMap](https://openfreemap.org/), and [OpenStreetMap U.S.](https://tiles.openstreetmap.us/vector/openmaptiles/)
18
+ - [Tilezen](https://tilezen.readthedocs.io/en/latest/layers/) implementations, e.g., [Protomaps](https://protomaps.com/)
19
+
20
+ ## Installation
21
+
22
+ <!-- This plugin is available as [an NPM package](https://www.npmjs.com/package/@americana/diplomat). To install it, run the following command:
23
+
24
+ ```sh
25
+ npm install @americana/diplomat
26
+ ```
27
+
28
+ Alternatively, you can include the plugin as a standalone script from a CDN such as [unpkg](https://unpkg.com/@americana/diplomat/index.js). -->
29
+
30
+ ## Usage
31
+
32
+ After creating an instance of `maplibregl.Map`, register an event listener for the `styledata` event that localizes the map:
33
+
34
+ ```js
35
+ map.once("styledata", (event) => {
36
+ // Prepare layers to be localized.
37
+ map.setLayoutProperty(
38
+ "country-labels",
39
+ "text-field",
40
+ maplibregl.Diplomat.localizedName
41
+ );
42
+ map.setLayoutProperty(
43
+ "city-labels",
44
+ "text-field",
45
+ maplibregl.Diplomat.localizedNameWithGloss
46
+ );
47
+ map.setLayoutProperty(
48
+ "road-labels",
49
+ "text-field",
50
+ maplibregl.Diplomat.localizedNameInline
51
+ );
52
+
53
+ // Localize the layers.
54
+ const locales = maplibregl.Diplomat.getLocales();
55
+ const style = map.getStyle();
56
+ map.localizeLayers(style.layers, locales);
57
+ map.setStyle(style);
58
+ });
59
+ ```
60
+
61
+ If you set the `hash` option to a string when creating the `Map`, you can have this code respond to a `language` parameter in the URL hash. Add a window event listener for whenever the hash changes, in order to update the layers:
62
+
63
+ ```js
64
+ addEventListener("hashchange", (event) => {
65
+ let oldLanguage = maplibregl.Diplomat.getLanguageFromURL(
66
+ new URL(event.oldURL)
67
+ );
68
+ let newLanguage = maplibregl.Diplomat.getLanguageFromURL(
69
+ new URL(event.newURL)
70
+ );
71
+
72
+ if (oldLanguage !== newLanguage) {
73
+ let locales = maplibregl.Diplomat.getLocales();
74
+ let style = map.getStyle();
75
+ map.localizeLayers(style.layers, locales);
76
+ map.setStyle(style);
77
+ }
78
+ });
79
+ ```
80
+
81
+ > [!NOTE]
82
+ > By default, MapLibre GL&nbsp;JS does not support bidirectional text. Arabic, Hebrew, and other right-to-left languages will be unreadable unless you [install the mapbox-gl-rtl-text plugin](https://maplibre.org/maplibre-gl-js/docs/examples/add-support-for-right-to-left-scripts/).
83
+
84
+ ## Schema
85
+
86
+ Diplomat can manipulate any GeoJSON or vector tile source, as long as it includes the following properties on each feature:
87
+
88
+ - **`name`** (`string`): The name in the local or official language.
89
+ - **<code>name:<var>xyz</var></code>** (`string`): The name in another language, where <var>xyz</var> is a valid [IETF language tag](https://en.wikipedia.org/wiki/IETF_language_tag). For example, <code>name:zh</code> for Chinese, <code>name:zh-Hant</code> for Traditional Chinese, <code>name:zh-Hant-TW</code> for Traditional Chinese (Taiwan), and <code>name:zh-Latn-pinyin</code> for Chinese in pinyin.
90
+
91
+ For compatibility with the [OpenMapTiles](https://openmaptiles.org/schema/) schema, `name_en` and `name_de` are also recognized as alternatives to `name:en` and `name:de` for English and German, respectively, but only in the `transportation_name` layer. For performance reasons, this format is not supported for any other language or layer.
92
+
93
+ Each of the supported properties may be set to a list of values separated by [semicolons](https://wiki.openstreetmap.org/wiki/Semi-colon_value_separator). For example, if a place speaks both English and French, `name` should be `English Name;French Name`. Similarly, if a landmark has three equally common names in Spanish, regardless of dialect, `name:es` should be `Nombre Uno;Nombre Dos;Nombre Tres`. In the rare case that a single name contains a semicolon, it should be escaped as a double semicolon (`;;`).
94
+
95
+ ## API
96
+
97
+ This plugin adds several constants to a `maplibregl.Diplomat` namespace and adds a single method to each instance of `maplibregl.Map`.
98
+
99
+ ### `maplibregl.Diplomat.localizedName`
100
+
101
+ An expression that produces the names in the user's preferred language, each on a separate line.
102
+
103
+ This expression is appropriate for labeling a type of feature that almost always has a familiar translation in the user’s preferred language, such as the name of a country. It is also appropriate for minor features like points of interest, for which an extra local-language gloss would clutter the map.
104
+
105
+ Example:
106
+
107
+ ```js
108
+ map.setLayoutProperty(
109
+ "country-labels",
110
+ "text-field",
111
+ maplibregl.Diplomat.localizedName
112
+ );
113
+ ```
114
+
115
+ ### `maplibregl.Diplomat.localizedNameInline`
116
+
117
+ An expression that produces the names in the user's preferred language, all on the same line.
118
+
119
+ This expression is appropriate for labeling a linear feature, such as a road or waterway. The symbol layer’s [`symbol-placement`](https://maplibre.org/maplibre-style-spec/layers/#symbol-placement) layout property should be set to either `line` or `line-center`.
120
+
121
+ Example:
122
+
123
+ ```js
124
+ map.setLayoutProperty(
125
+ "road-labels",
126
+ "text-field",
127
+ maplibregl.Diplomat.localizedNameInline
128
+ );
129
+ ```
130
+
131
+ ### `maplibre.Diplomat.localizedNameWithLocalGloss`
132
+
133
+ An expression that produces the name in the user's preferred language, followed by the name in the local language in parentheses if it differs.
134
+
135
+ This expression is appropriate for labeling a type of feature that is only sometimes translated into user’s preferred language, such as the name of a city or town. The extra local-language gloss respects local customs and keeps the user informed, but it can also risk [information overload](https://en.wikipedia.org/wiki/Information_overload) and crowd out other useful labels.
136
+
137
+ Example:
138
+
139
+ ```js
140
+ map.setLayoutProperty(
141
+ "city-labels",
142
+ "text-field",
143
+ maplibregl.Diplomat.localizedNameWithGloss
144
+ );
145
+ ```
146
+
147
+ ### `maplibregl.Diplomat.getCountryName()`
148
+
149
+ Returns an expression that converts the given country code to a human-readable name in the user's preferred language.
150
+
151
+ This method is useful for stylesheets powered by OpenMapTiles, which only provides the ISO&nbsp;3166-1 alpha-3 code of the country on either side of a boundary, but not the full country name in any language.
152
+
153
+ Parameters:
154
+
155
+ - **`code`** (`string`): An expression that evaluates to an ISO&nbsp;3166-1 alpha-3 country code.
156
+
157
+ Example:
158
+
159
+ ```js
160
+ map.setLayoutProperty(
161
+ "boundary-edge-labels",
162
+ "text-field",
163
+ getCountryName(["get", "adm0_l"])
164
+ );
165
+ ```
166
+
167
+ ### `maplibregl.Diplomat.getLocales()`
168
+
169
+ Returns the languages that the user prefers.
170
+
171
+ Example:
172
+
173
+ ```js
174
+ maplibregl.Diplomat.getLocales().includes("en");
175
+ ```
176
+
177
+ ### `maplibregl.Map.prototype.localizeLayers()`
178
+
179
+ Updates localizable variables at the top level of each layer's `text-field` expression based on the given locales.
180
+
181
+ Parameters:
182
+
183
+ - **`layers`** (`[object]`): The style layers to localize.
184
+ - **`locales`** (`[string]`): The locales to insert into each layer, as a comma-separated list of [IETF language tags](https://en.wikipedia.org/wiki/IETF_language_tag). Uses the `language` URL hash parameter or browser preferences by default.
185
+
186
+ > [!NOTE]
187
+ > This method modifies the `layers` structure in place. If it comes from the return value of [`maplibregl.Map.prototype.getStyle()`](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#getstyle), you must manually synchronize the layers with the style afterwards by calling [`maplibregl.Map.prototype.setStyle()`](https://maplibre.org/maplibre-gl-js/docs/API/classes/Map/#setstyle).
188
+
189
+ Example:
190
+
191
+ ```js
192
+ const style = map.getStyle();
193
+ map.localizeLayers(style.layers, locales);
194
+ map.setStyle(style);
195
+ ```
196
+
197
+ ## Caveats
198
+
199
+ Diplomat only switches between languages that are present in the stylesheet’s data sources. It does not fetch translations from other sources or generate its own transliterations. By convention, [OpenStreetMap’s coverage in some regions](https://wiki.openstreetmap.org/wiki/Multilingual_names) is largely limited to locally spoken languages. If you need more comprehensive coverage in a given language, consider using a tileset that combines names from OpenStreetMap and Wikidata, such as the [OpenStreetMap U.S. Tileservice](https://tiles.openstreetmap.us/vector/openmaptiles/).
200
+
201
+ By default, MapLibre GL&nbsp;JS does not support bidirectional text. Arabic, Hebrew, and other right-to-left languages will be unreadable unless you [install the mapbox-gl-rtl-text plugin](https://maplibre.org/maplibre-gl-js/docs/examples/add-support-for-right-to-left-scripts/).
202
+
203
+ Diplomat only performs basic language fallbacks according to the [ICU locale fallback algorithm](https://unicode-org.github.io/icu/userguide/locale/#fallback). It makes no attempt to fallback to a related but distinct language code, for example from `sr-Cyrl` to `ru` or from `nb` to `no`. Instead, the user can [set their preferred languages](https://www.w3.org/International/questions/qa-lang-priorities) in their browser or operating system settings.
204
+
205
+ For historical reasons, [OpenStreetMap’s coverage in many reasons](https://wiki.openstreetmap.org/wiki/Multilingual_names) encodes multiple local names separated by human-readable punctuation. Diplomat makes no attempt to guess which punctuation is part of a name and which punctuation delimits two names.
206
+
207
+ ## Acknowledgments
208
+
209
+ This plugin was spun out of the [OpenStreetMap Americana](https://github.com/osm-americana/openstreetmap-americana/) project. It was originally inspired by [Mapbox GL Language](https://github.com/mapbox/mapbox-gl-language/).
@@ -0,0 +1,34 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width" />
6
+ <title>MapLibre GL Diplomat</title>
7
+ <script
8
+ src="https://unpkg.com/maplibre-gl@%5E5.13.0/dist/maplibre-gl.js"
9
+ type="text/javascript"
10
+ ></script>
11
+ <script src="../index.js" type="text/javascript"></script>
12
+ <script src="./index.js" type="text/javascript"></script>
13
+ <link
14
+ rel="stylesheet"
15
+ href="https://unpkg.com/maplibre-gl@%5E5.13.0/dist/maplibre-gl.css"
16
+ />
17
+ <style type="text/css">
18
+ body {
19
+ margin: 0;
20
+ padding: 0;
21
+ }
22
+
23
+ html,
24
+ body,
25
+ #map {
26
+ width: 100%;
27
+ height: 100%;
28
+ }
29
+ </style>
30
+ </head>
31
+ <body>
32
+ <div id="map"></div>
33
+ </body>
34
+ </html>
@@ -0,0 +1,75 @@
1
+ addEventListener("load", () => {
2
+ window.map = new maplibregl.Map({
3
+ container: "map",
4
+ hash: "map",
5
+ style: {
6
+ version: 8,
7
+ glyphs: "https://font.americanamap.org/{fontstack}/{range}.pbf",
8
+ sources: {
9
+ openmaptiles: {
10
+ type: "vector",
11
+ url: "https://tiles.openstreetmap.us/vector/openmaptiles.json",
12
+ },
13
+ },
14
+ layers: [
15
+ {
16
+ type: "symbol",
17
+ id: "road-labels",
18
+ source: "openmaptiles",
19
+ "source-layer": "transportation_name",
20
+ layout: {
21
+ "symbol-placement": "line",
22
+ "text-field": maplibregl.Diplomat.localizedNameInline,
23
+ "text-font": ["Americana"],
24
+ },
25
+ },
26
+ {
27
+ type: "symbol",
28
+ id: "place-labels",
29
+ source: "openmaptiles",
30
+ "source-layer": "place",
31
+ layout: {
32
+ "text-field": ["get", "name"],
33
+ "text-font": ["Americana-Bold"],
34
+ },
35
+ },
36
+ ],
37
+ },
38
+ });
39
+
40
+ map.addControl(new maplibregl.NavigationControl(), "top-left");
41
+ map.addControl(new maplibregl.FullscreenControl(), "top-left");
42
+
43
+ maplibregl.setRTLTextPlugin(
44
+ "https://unpkg.com/@mapbox/mapbox-gl-rtl-text@0.2.3/mapbox-gl-rtl-text.min.js",
45
+ true
46
+ );
47
+
48
+ map.once("styledata", (event) => {
49
+ map.setLayoutProperty(
50
+ "place-labels",
51
+ "text-field",
52
+ maplibregl.Diplomat.localizedName
53
+ );
54
+ let locales = maplibregl.Diplomat.getLocales();
55
+ let style = map.getStyle();
56
+ map.localizeLayers(style.layers, locales);
57
+ map.setStyle(style);
58
+ });
59
+
60
+ addEventListener("hashchange", (event) => {
61
+ let oldLanguage = maplibregl.Diplomat.getLanguageFromURL(
62
+ new URL(event.oldURL)
63
+ );
64
+ let newLanguage = maplibregl.Diplomat.getLanguageFromURL(
65
+ new URL(event.newURL)
66
+ );
67
+ if (oldLanguage !== newLanguage) {
68
+ let locales = maplibregl.Diplomat.getLocales();
69
+ console.log(`Changed to ${locales}`);
70
+ let style = map.getStyle();
71
+ map.localizeLayers(style.layers, locales);
72
+ map.setStyle(style);
73
+ }
74
+ });
75
+ });