@geolonia/embed 6.0.0-pre.6 → 6.0.1

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.
Files changed (41) hide show
  1. package/.github/workflows/build.yml +4 -4
  2. package/.tool-versions +1 -1
  3. package/CHANGELOG.md +47 -0
  4. package/README.md +1 -1
  5. package/dist/embed +1 -1
  6. package/dist/embed-chunks/{d1fe32cb4bfb0e9c6575.js → 124e026690b0fa17700b.js} +1 -1
  7. package/dist/embed-chunks/{5fc1f8cd252efa958f7d.js → 9734b8bdf9fe84261b54.js} +2 -2
  8. package/dist/embed-chunks/{64c22ed093c8de0fcbf8.js → ae36f6b8e34f85ae3045.js} +2 -2
  9. package/dist/embed-chunks/{4b5b1b54a5dac816ef15.js → db5eea9dfc49d1cf19e7.js} +1 -1
  10. package/dist/embed-core.d.ts +1 -1
  11. package/dist/embed-core.js +1 -1
  12. package/dist/embed-core.js.LICENSE.txt +1 -1
  13. package/dist/embed.d.ts +3 -3
  14. package/dist/embed.js +1 -1
  15. package/dist/embed.js.LICENSE.txt +1 -1
  16. package/dist/lib/parse-atts.d.ts +1 -1
  17. package/dist/lib/render.d.ts +2 -2
  18. package/dist/lib/util.d.ts +0 -5
  19. package/dist/types-internal.d.ts +4 -0
  20. package/dist/types.d.ts +13 -6
  21. package/dist/version.d.ts +1 -1
  22. package/e2e/iframe.spec.ts +37 -22
  23. package/eslint.config.js +15 -48
  24. package/package.json +14 -19
  25. package/src/embed-core.ts +5 -1
  26. package/src/embed.ts +7 -3
  27. package/src/lib/parse-atts.test.ts +6 -6
  28. package/src/lib/parse-atts.ts +8 -7
  29. package/src/lib/render.ts +111 -97
  30. package/src/lib/util.ts +0 -76
  31. package/src/testability.test.ts +20 -17
  32. package/src/types-internal.ts +18 -0
  33. package/src/types.ts +12 -4
  34. package/src/version.ts +1 -1
  35. package/tsconfig.build.json +5 -0
  36. package/tsconfig.json +5 -3
  37. package/webpack.config.js +2 -2
  38. /package/dist/embed-chunks/{4574b15eb540c5efc533.js → 5f80e0235f4b38778d0d.js} +0 -0
  39. /package/dist/embed-chunks/{5fc1f8cd252efa958f7d.js.LICENSE.txt → 9734b8bdf9fe84261b54.js.LICENSE.txt} +0 -0
  40. /package/dist/embed-chunks/{64c22ed093c8de0fcbf8.js.LICENSE.txt → ae36f6b8e34f85ae3045.js.LICENSE.txt} +0 -0
  41. /package/dist/embed-chunks/{ffdb8e820d823ee3571c.js → c83bb7c9a4a7ed9d5b23.js} +0 -0
package/src/lib/render.ts CHANGED
@@ -1,10 +1,17 @@
1
1
  import 'maplibre-gl/dist/maplibre-gl.css';
2
2
  import '../style.css';
3
3
  import { GeoloniaMap, keyring } from '@geolonia/maps-core';
4
- import { checkPermission, parseScriptTagApiKey } from './util';
4
+ import { parseScriptTagApiKey } from './util';
5
5
  import parseAtts, { attsToOptions } from './parse-atts';
6
+ import type {
7
+ EmbedAttributes,
8
+ EmbedPlugin,
9
+ EmbedPluginAttributes,
10
+ } from '../types';
6
11
 
7
- const plugins = [];
12
+ // 登録済みプラグインは個別の PluginAttributes を持ちうるので、配列としては
13
+ // それらをまとめて保持できる形にしておく (呼び出しは常に EmbedAttributes で行う)。
14
+ const plugins: EmbedPlugin<any>[] = [];
8
15
 
9
16
  /**
10
17
  * Move any inline HTML the author placed inside the map container into
@@ -32,8 +39,8 @@ export const renderGeoloniaMap = () => {
32
39
 
33
40
  // Backward compat: maps-core's keyring no longer scans the DOM, but legacy
34
41
  // embeds set the key only on the container via `data-key`. Seed the keyring
35
- // from the first container-side key so the iframe permission check below
36
- // (and Geolonia-style validation) sees the same effective key as before.
42
+ // from the first container-side key so Geolonia-style validation sees the
43
+ // same effective key as before.
37
44
  // Per-container `data-key` still flows through parseAtts → attsToOptions.
38
45
  if (!keyring.apiKey) {
39
46
  const keyed = document.querySelector<HTMLElement>('.geolonia[data-key]');
@@ -43,116 +50,123 @@ export const renderGeoloniaMap = () => {
43
50
  }
44
51
  }
45
52
 
46
- if (checkPermission()) {
47
- let isDOMContentLoaded = false;
48
- const alreadyRenderedMaps = [];
49
- const isRemoved = Symbol('map-is-removed');
50
-
51
- /**
52
- *
53
- * @param {HTMLElement} target
54
- */
55
- const renderSingleMap = (target) => {
56
- const atts = parseAtts(target);
57
-
58
- // Dedup: if this container was already initialised (e.g. constructed
59
- // programmatically before the lazy observer fired), reuse the instance.
60
- // Must happen before extractPopupContent(), otherwise we'd wipe the
61
- // already-rendered map DOM out of the container.
62
- let map = target.geoloniaMap;
63
- if (!map) {
64
- // Grab inline popup content before maps-core clears/renders the container.
65
- extractPopupContent(target);
66
- map = new GeoloniaMap(attsToOptions(target, atts));
67
- }
68
-
69
- // detect if the map removed manually
70
- map.on('remove', () => {
71
- map[isRemoved] = true;
72
- });
73
-
74
- // remove map instance automatically if the container removed.
75
- // prevent memory leak
76
- const observer = new MutationObserver((mutationRecords) => {
77
- const removed = mutationRecords.some((record) =>
78
- [...record.removedNodes].some((node) => node === target),
79
- );
80
- if (removed && !map[isRemoved]) {
81
- map.remove();
82
- }
83
- });
84
- observer.observe(target.parentNode, { childList: true });
53
+ let isDOMContentLoaded = false;
54
+ const isRemoved = Symbol('map-is-removed');
55
+
56
+ // 手動で remove された地図に印を付けるための symbol プロパティ。
57
+ type RemovableMap = GeoloniaMap & { [isRemoved]?: boolean };
58
+
59
+ const alreadyRenderedMaps: {
60
+ map: RemovableMap;
61
+ target: HTMLElement;
62
+ atts: EmbedAttributes;
63
+ }[] = [];
64
+
65
+ /**
66
+ *
67
+ * @param {HTMLElement} target
68
+ */
69
+ const renderSingleMap = (target: HTMLElement) => {
70
+ const atts = parseAtts(target);
71
+
72
+ // Dedup: if this container was already initialised (e.g. constructed
73
+ // programmatically before the lazy observer fired), reuse the instance.
74
+ // Must happen before extractPopupContent(), otherwise we'd wipe the
75
+ // already-rendered map DOM out of the container.
76
+ let map: RemovableMap | undefined = target.geoloniaMap;
77
+ if (!map) {
78
+ // Grab inline popup content before maps-core clears/renders the container.
79
+ extractPopupContent(target);
80
+ map = new GeoloniaMap(attsToOptions(target, atts));
81
+ }
85
82
 
86
- // plugin
87
- if (isDOMContentLoaded && !map[isRemoved]) {
88
- plugins.forEach((plugin) => plugin(map, target, atts));
89
- } else {
90
- alreadyRenderedMaps.push({ map, target: target, atts });
91
- }
92
- };
93
-
94
- document.addEventListener('DOMContentLoaded', () => {
95
- isDOMContentLoaded = true;
96
- alreadyRenderedMaps.forEach(({ map, target, atts }) => {
97
- if (!map[isRemoved]) {
98
- plugins.forEach((plugin) => plugin(map, target, atts));
99
- }
100
- });
101
- // clear
102
- alreadyRenderedMaps.splice(0, alreadyRenderedMaps.length);
83
+ // detect if the map removed manually
84
+ map.on('remove', () => {
85
+ map[isRemoved] = true;
103
86
  });
104
87
 
105
- const observer = new IntersectionObserver((entries) => {
106
- entries.forEach((item) => {
107
- if (!item.isIntersecting) {
108
- return;
109
- }
110
- try {
111
- renderSingleMap(item.target);
112
- } catch (e) {
113
- // Not throw error because, following maps will not be rendered.
114
- console.error('[Geolonia] Failed to initialize map', e); // eslint-disable-line
115
- }
116
- observer.unobserve(item.target);
117
- });
88
+ // remove map instance automatically if the container removed.
89
+ // prevent memory leak
90
+ const observer = new MutationObserver((mutationRecords) => {
91
+ const removed = mutationRecords.some((record) =>
92
+ [...record.removedNodes].some((node) => node === target),
93
+ );
94
+ if (removed && !map[isRemoved]) {
95
+ map.remove();
96
+ }
118
97
  });
98
+ // 親が無いコンテナは DOM から外されることがないので監視しない。
99
+ if (target.parentNode) {
100
+ observer.observe(target.parentNode, { childList: true });
101
+ }
119
102
 
120
- const containers = document.querySelectorAll(
121
- '.geolonia[data-lazy-loading="off"]',
122
- );
123
- const lazyContainers = document.querySelectorAll(
124
- '.geolonia:not([data-lazy-loading="off"])',
125
- );
126
-
127
- // This is required for correct initialization! Don't delete!
128
- if (keyring.isGeoloniaStyle && !keyring.apiKey) {
129
- console.error('[Geolonia] Missing API key.'); // eslint-disable-line
103
+ // plugin
104
+ if (isDOMContentLoaded && !map[isRemoved]) {
105
+ plugins.forEach((plugin) => plugin(map, target, atts));
106
+ } else {
107
+ alreadyRenderedMaps.push({ map, target: target, atts });
130
108
  }
109
+ };
131
110
 
132
- // render Map immediately
133
- for (let i = 0; i < containers.length; i++) {
111
+ document.addEventListener('DOMContentLoaded', () => {
112
+ isDOMContentLoaded = true;
113
+ alreadyRenderedMaps.forEach(({ map, target, atts }) => {
114
+ if (!map[isRemoved]) {
115
+ plugins.forEach((plugin) => plugin(map, target, atts));
116
+ }
117
+ });
118
+ // clear
119
+ alreadyRenderedMaps.splice(0, alreadyRenderedMaps.length);
120
+ });
121
+
122
+ const observer = new IntersectionObserver((entries) => {
123
+ entries.forEach((item) => {
124
+ if (!item.isIntersecting) {
125
+ return;
126
+ }
134
127
  try {
135
- renderSingleMap(containers[i]);
128
+ // 監視対象は下の querySelectorAll<HTMLElement> で集めた要素に限られる。
129
+ renderSingleMap(item.target as HTMLElement);
136
130
  } catch (e) {
137
131
  // Not throw error because, following maps will not be rendered.
138
132
  console.error('[Geolonia] Failed to initialize map', e); // eslint-disable-line
139
133
  }
140
- }
134
+ observer.unobserve(item.target);
135
+ });
136
+ });
137
+
138
+ const containers = document.querySelectorAll<HTMLElement>(
139
+ '.geolonia[data-lazy-loading="off"]',
140
+ );
141
+ const lazyContainers = document.querySelectorAll<HTMLElement>(
142
+ '.geolonia:not([data-lazy-loading="off"])',
143
+ );
144
+
145
+ // This is required for correct initialization! Don't delete!
146
+ if (keyring.isGeoloniaStyle && !keyring.apiKey) {
147
+ console.error('[Geolonia] Missing API key.'); // eslint-disable-line
148
+ }
141
149
 
142
- // set intersection observer
143
- for (let i = 0; i < lazyContainers.length; i++) {
144
- observer.observe(lazyContainers[i]);
150
+ // render Map immediately
151
+ for (let i = 0; i < containers.length; i++) {
152
+ try {
153
+ renderSingleMap(containers[i]);
154
+ } catch (e) {
155
+ // Not throw error because, following maps will not be rendered.
156
+ console.error('[Geolonia] Failed to initialize map', e); // eslint-disable-line
145
157
  }
146
- } else {
147
- /* eslint-disable-next-line no-console */
148
- console.error(
149
- "[Geolonia] We are very sorry, but we can't display our map in iframe.",
150
- );
158
+ }
159
+
160
+ // set intersection observer
161
+ for (let i = 0; i < lazyContainers.length; i++) {
162
+ observer.observe(lazyContainers[i]);
151
163
  }
152
164
  };
153
165
 
154
- export const registerPlugin = (
155
- plugin: (map: GeoloniaMap, target: HTMLElement, atts) => void,
166
+ // PluginAttributes を推論させる。EmbedPlugin<{ foo: string }> のように固有の
167
+ // data-* を要求するプラグインも、そのまま登録できるようにするため。
168
+ export const registerPlugin = <PluginAttributes extends EmbedPluginAttributes>(
169
+ plugin: EmbedPlugin<PluginAttributes>,
156
170
  ): void => {
157
171
  plugins.push(plugin);
158
172
  return void 0;
package/src/lib/util.ts CHANGED
@@ -1,7 +1,5 @@
1
1
  'use strict';
2
2
 
3
- import { keyring } from '@geolonia/maps-core';
4
-
5
3
  /**
6
4
  * Parse the Geolonia API key from the `?geolonia-api-key=` query of the
7
5
  * embed `<script>` tag (backward compatibility).
@@ -41,77 +39,3 @@ export function parseScriptTagApiKey(
41
39
 
42
40
  return null;
43
41
  }
44
-
45
- /**
46
- * Detect whether the embed is allowed to render in the current (possibly
47
- * iframed) context. Embed-specific: not provided by maps-core.
48
- */
49
- export function checkPermission() {
50
- // It looks that isn't iFrame, so returns true.
51
- if (window.self === window.parent) {
52
- return true;
53
- }
54
-
55
- // Always returns true if API key is loaded.
56
- if (keyring.apiKey) {
57
- return true;
58
- }
59
-
60
- /**
61
- * For the https://codepen.io/
62
- * iFrame による Codepen の地図の認可外のサイトへの埋め込みを許可しない
63
- */
64
- if (
65
- window.self.location.origin === 'https://cdpn.io' ||
66
- window.self.location.origin === 'https://codepen.io'
67
- ) {
68
- if (
69
- window.self !== window.parent &&
70
- window.document.referrer.indexOf('https://codepen.io') === 0
71
- ) {
72
- return true;
73
- }
74
- }
75
-
76
- /**
77
- * For the https://jsfiddle.net/
78
- */
79
- if (window.self.location.origin === 'https://fiddle.jshell.net') {
80
- if (
81
- window.self !== window.parent &&
82
- window.document.referrer.indexOf('https://jsfiddle.net') === 0
83
- ) {
84
- return true;
85
- }
86
- }
87
-
88
- /**
89
- * For the https://codesandbox.io/
90
- *
91
- * Note:
92
- * codesandbox.io has two preview window, one is in right sidebar with iframe and
93
- * another one is in new window.
94
- */
95
- if (window.self.location.origin.match(/csb\.app$/)) {
96
- if (
97
- window.self !== window.parent &&
98
- window.document.referrer.indexOf('https://codesandbox.io') === 0
99
- ) {
100
- return true;
101
- }
102
- }
103
-
104
- /**
105
- * `window.parent` will be blocked if same origin policy is activated.
106
- * So, it should be caught.
107
- */
108
- try {
109
- if (window.self.location.origin === window.top.location.origin) {
110
- return true;
111
- }
112
- } catch {
113
- return false;
114
- }
115
-
116
- return false;
117
- }
@@ -1,5 +1,4 @@
1
- import { describe, it, expect, vi } from 'vitest';
2
- import { JSDOM } from 'jsdom';
1
+ import { describe, it, expect } from 'vitest';
3
2
 
4
3
  // maplibre-gl v6 にデフォルトエクスポートは無いので名前空間でインポートする。
5
4
  import * as maplibregl from 'maplibre-gl';
@@ -12,20 +11,14 @@ import * as maplibregl from 'maplibre-gl';
12
11
 
13
12
  describe('maplibre-gl jsdom limitation', () => {
14
13
  it('jsdom上ではMaplibre Mapインスタンス生成時にエラー(WebGL未対応のため)', () => {
15
- // jsdom の "Not implemented" メッセージを抑制
16
- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
14
+ // vitest.config.ts の environment: 'jsdom' が用意する document を使う。
15
+ // 以前はここで JSDOM を自前に生成して global.window / global.document を
16
+ // 差し替えていたが、vitest 5 では jsdom 環境の document が getter のみになり
17
+ // 代入できない (Cannot set property document of [object Window])。
18
+ // 環境として jsdom が既にあるので、器だけ用意すれば足りる。
19
+ document.body.innerHTML = '<div id="map"></div>';
17
20
 
18
- const dom = new JSDOM(
19
- '<!DOCTYPE html><html><body><div id="map"></div></body></html>',
20
- {
21
- url: 'http://localhost',
22
- pretendToBeVisual: true,
23
- },
24
- );
25
- // @ts-ignore
26
- global.window = dom.window;
27
- global.document = dom.window.document;
28
- let errorCaught = null;
21
+ let errorCaught: unknown = null;
29
22
  try {
30
23
  new maplibregl.Map({
31
24
  container: 'map',
@@ -38,10 +31,20 @@ describe('maplibre-gl jsdom limitation', () => {
38
31
  }
39
32
  expect(errorCaught).toBeInstanceOf(Error);
40
33
  expect(
41
- /webgl|WebGL|context|device|Not implemented/i.test(errorCaught.message),
34
+ /webgl|WebGL|context|device|Not implemented/i.test(
35
+ (errorCaught as Error).message,
36
+ ),
42
37
  ).toBe(true);
43
38
 
44
- consoleSpy.mockRestore();
39
+ // 実行すると jsdom が
40
+ // Not implemented: HTMLCanvasElement's getContext() method
41
+ // をテスト出力に書く。これは失敗ではなく、このテストが記録している
42
+ // 「jsdom には WebGL が無い」ことの証跡そのもの。
43
+ //
44
+ // 以前は console.error を spy で潰していたが、vitest 5 では jsdom 環境が
45
+ // 環境セットアップ時に VirtualConsole を作るため、テスト内で貼る spy では
46
+ // もう捕まえられない (environmentOptions.jsdom.console: true でも同じ)。
47
+ // 何も抑制しない spy を残すと誤解を生むので外してある。
45
48
  });
46
49
 
47
50
  it('【NOTE】描画テストが必要な場合はE2E(ブラウザ実行)で行うこと', () => {
@@ -1,4 +1,22 @@
1
+ // 型を持たないモジュールと、maps-core が実行時に生やすプロパティのための
2
+ // アンビエント宣言をここにまとめている。
3
+
1
4
  declare module '*.svg' {
2
5
  const content: string;
3
6
  export default content;
4
7
  }
8
+
9
+ // TypeScript 6 は型を持たないモジュールの副作用 import を TS2882 として
10
+ // 報告するようになった。webpack 側は css-loader / style-loader が処理する。
11
+ declare module '*.css';
12
+
13
+ // maps-core は初期化した地図インスタンスをコンテナ要素に生やす。
14
+ // render.ts の二重初期化チェックと e2e がこれを読んでいる。
15
+ //
16
+ // このファイルはアンビエント宣言のためのスクリプト (module ではない) なので、
17
+ // グローバルの HTMLElement をそのまま宣言マージする。declare global は module で
18
+ // しか使えず、module にすると上の declare module '*.svg' が書けなくなる。
19
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
20
+ interface HTMLElement {
21
+ geoloniaMap?: import('@geolonia/maps-core').GeoloniaMap;
22
+ }
package/src/types.ts CHANGED
@@ -209,9 +209,19 @@ export type EmbedAttributes = {
209
209
  * 追加の `data-*` 属性はそのまま透過される({@link EmbedPlugin} が利用する
210
210
  * プラグイン固有の属性など)。
211
211
  */
212
- [otherKey: string]: string | number;
212
+ [otherKey: string]: string | number | undefined;
213
213
  };
214
214
 
215
+ /**
216
+ * プラグインが独自に読む `data-*` 属性の型。
217
+ *
218
+ * {@link EmbedAttributes} のインデックスシグネチャが `number` も許すのは、
219
+ * `maxZoom: 20` のように既定値が数値の組み込み属性があるため。一方こちらは
220
+ * プラグイン固有の `data-*` だけを指し、`parseAtts` が `container.dataset`
221
+ * (`DOMStringMap`) をそのまま広げて渡すので、実行時には必ず文字列か未定義になる。
222
+ */
223
+ export type EmbedPluginAttributes = { [otherKey: string]: string | undefined };
224
+
215
225
  /**
216
226
  * 埋め込みプラグインの型。地図インスタンス、対象のコンテナ要素、正規化済みの
217
227
  * {@link EmbedAttributes} を受け取って呼び出される。
@@ -222,9 +232,7 @@ export type EmbedAttributes = {
222
232
  * 対しては呼び出されない。
223
233
  */
224
234
  export type EmbedPlugin<
225
- PluginAttributes extends { [otherKey: string]: string } = {
226
- [otherKey: string]: string;
227
- },
235
+ PluginAttributes extends EmbedPluginAttributes = EmbedPluginAttributes,
228
236
  > = (
229
237
  map: GeoloniaMap,
230
238
  target: HTMLElement,
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const VERSION = '6.0.0-pre.6';
1
+ export const VERSION = '6.0.1';
@@ -1,5 +1,10 @@
1
1
  {
2
2
  "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ // TypeScript 6 は rootDir の明示を要求する (TS5011)。これまでの推論結果と
5
+ // 同じ ./src を指定しており、dist の .d.ts の配置は変わらない。
6
+ "rootDir": "./src"
7
+ },
3
8
  "exclude": [
4
9
  "src/**/*.test.ts",
5
10
  "e2e",
package/tsconfig.json CHANGED
@@ -12,13 +12,15 @@
12
12
  "sourceMap": true,
13
13
  "esModuleInterop": true,
14
14
  "allowSyntheticDefaultImports": true,
15
- // "strict": true,
15
+ "strict": true,
16
16
  "forceConsistentCasingInFileNames": true,
17
17
  "module": "esnext",
18
- "moduleResolution": "node",
18
+ "moduleResolution": "bundler",
19
+ // TypeScript 6 は node_modules/@types を自動で全部取り込まなくなったので、
20
+ // グローバル型が要るものを明示する (process など)。
21
+ "types": ["node"],
19
22
  "resolveJsonModule": true,
20
23
  "isolatedModules": true,
21
- "jsx": "react-jsx",
22
24
  "noFallthroughCasesInSwitch": true,
23
25
  "newLine": "lf"
24
26
  },
package/webpack.config.js CHANGED
@@ -83,7 +83,7 @@ const sharedConfig = {
83
83
  },
84
84
  },
85
85
  {
86
- test: /\.tsx?$/,
86
+ test: /\.ts$/,
87
87
  use: {
88
88
  loader: 'ts-loader',
89
89
  options: {
@@ -99,7 +99,7 @@ const sharedConfig = {
99
99
  ],
100
100
  },
101
101
  resolve: {
102
- extensions: ['.tsx', '.ts', '.js'],
102
+ extensions: ['.ts', '.js'],
103
103
  },
104
104
  };
105
105