@nocobase/plugin-map 0.13.0-alpha.4 → 0.13.0-alpha.6

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.
@@ -1,3145 +1,106 @@
1
- (function(global2, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("react"), require("@nocobase/client"), require("react-i18next"), require("@ant-design/icons"), require("@formily/react"), require("ahooks"), require("antd"), require("react-router-dom"), require("lodash"), require("@formily/shared"), require("@formily/antd-v5")) : typeof define === "function" && define.amd ? define(["exports", "react", "@nocobase/client", "react-i18next", "@ant-design/icons", "@formily/react", "ahooks", "antd", "react-router-dom", "lodash", "@formily/shared", "@formily/antd-v5"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2["@nocobase/plugin-map"] = {}, global2.react, global2["@nocobase/client"], global2["react-i18next"], global2["@ant-design/icons"], global2["@formily/react"], global2.ahooks, global2.antd, global2["react-router-dom"], global2.lodash, global2["@formily/shared"], global2["@formily/antd-v5"]));
3
- })(this, function(exports2, React, client, reactI18next, icons, react, ahooks, antd, reactRouterDom, lodash, shared, antdV5) {
4
- "use strict";
5
- var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
6
- function getDefaultExportFromCjs(x) {
7
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
8
- }
9
- var jsxRuntime = { exports: {} };
10
- var reactJsxRuntime_production_min = {};
11
- /**
12
- * @license React
13
- * react-jsx-runtime.production.min.js
14
- *
15
- * Copyright (c) Facebook, Inc. and its affiliates.
16
- *
17
- * This source code is licensed under the MIT license found in the
18
- * LICENSE file in the root directory of this source tree.
19
- */
20
- var f = React, k = Symbol.for("react.element"), l = Symbol.for("react.fragment"), m = Object.prototype.hasOwnProperty, n = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, p = { key: true, ref: true, __self: true, __source: true };
21
- function q(c, a, g) {
22
- var b, d = {}, e = null, h = null;
23
- void 0 !== g && (e = "" + g);
24
- void 0 !== a.key && (e = "" + a.key);
25
- void 0 !== a.ref && (h = a.ref);
26
- for (b in a)
27
- m.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]);
28
- if (c && c.defaultProps)
29
- for (b in a = c.defaultProps, a)
30
- void 0 === d[b] && (d[b] = a[b]);
31
- return { $$typeof: k, type: c, key: e, ref: h, props: d, _owner: n.current };
32
- }
33
- reactJsxRuntime_production_min.Fragment = l;
34
- reactJsxRuntime_production_min.jsx = q;
35
- reactJsxRuntime_production_min.jsxs = q;
36
- {
37
- jsxRuntime.exports = reactJsxRuntime_production_min;
38
- }
39
- var jsxRuntimeExports = jsxRuntime.exports;
40
- const NAMESPACE = "map";
41
- function generateNTemplate(key) {
42
- return `{{t('${key}', { ns: '${NAMESPACE}', nsMode: 'fallback' })}}`;
43
- }
44
- function useMapTranslation() {
45
- return reactI18next.useTranslation(NAMESPACE, {
46
- nsMode: "fallback"
47
- });
48
- }
49
- const MapActionInitializers = {
50
- title: "{{t('Configure actions')}}",
51
- icon: "SettingOutlined",
52
- style: {
53
- marginLeft: 8
54
- },
55
- items: [
56
- {
57
- type: "itemGroup",
58
- title: "{{t('Enable actions')}}",
59
- children: [
60
- {
61
- type: "item",
62
- title: "{{t('Filter')}}",
63
- component: "FilterActionInitializer",
64
- schema: {
65
- "x-align": "left"
66
- }
67
- },
68
- {
69
- type: "item",
70
- title: "{{t('Add new')}}",
71
- component: "CreateActionInitializer",
72
- schema: {
73
- "x-align": "right",
74
- "x-decorator": "ACLActionProvider",
75
- "x-acl-action-props": {
76
- skipScopeCheck: true
77
- }
78
- }
79
- },
80
- {
81
- type: "item",
82
- title: "{{t('Refresh')}}",
83
- component: "RefreshActionInitializer",
84
- schema: {
85
- "x-align": "right"
86
- }
87
- }
88
- ]
89
- },
90
- {
91
- type: "divider"
92
- },
93
- {
94
- type: "subMenu",
95
- title: '{{t("Customize")}}',
96
- children: [
97
- {
98
- type: "item",
99
- title: '{{t("Bulk update")}}',
100
- component: "CustomizeActionInitializer",
101
- schema: {
102
- type: "void",
103
- title: '{{ t("Bulk update") }}',
104
- "x-component": "Action",
105
- "x-align": "right",
106
- "x-acl-action": "update",
107
- "x-decorator": "ACLActionProvider",
108
- "x-acl-action-props": {
109
- skipScopeCheck: true
110
- },
111
- "x-action": "customize:bulkUpdate",
112
- "x-designer": "Action.Designer",
113
- "x-action-settings": {
114
- assignedValues: {},
115
- updateMode: "selected",
116
- onSuccess: {
117
- manualClose: true,
118
- redirecting: false,
119
- successMessage: '{{t("Updated successfully")}}'
120
- }
121
- },
122
- "x-component-props": {
123
- icon: "EditOutlined",
124
- useProps: "{{ useCustomizeBulkUpdateActionProps }}"
125
- }
126
- }
127
- },
128
- {
129
- type: "item",
130
- title: '{{t("Bulk edit")}}',
131
- component: "CustomizeBulkEditActionInitializer",
132
- schema: {
133
- "x-align": "right",
134
- "x-decorator": "ACLActionProvider",
135
- "x-acl-action": "update",
136
- "x-acl-action-props": {
137
- skipScopeCheck: true
138
- }
139
- }
140
- }
141
- ]
142
- }
143
- ]
144
- };
145
- const MapTypes = [
146
- { label: generateNTemplate("AMap"), value: "amap" },
147
- { label: generateNTemplate("Google Maps"), value: "google" }
148
- ];
149
- const selectedImage = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAA/CAMAAAC7OkrPAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAEJQTFRFAAAA8Yti8Yti8Itj8Iti74tj8Itj8YtiKwADKwADKhw5Kh07KwADKwADKwADKwAD4odn1YBlKwADKwADKwADKwAD/5y7LQAAABZ0Uk5TAP/8/f/B/PYOHjY3CCozLP3XCSkvMhA05K4AAAC4SURBVHic7dXLDoIwEIXhwSsoLSrw/q8qbSAiMy3/oivj2czmS5omnVORdapVJJFKBSEL2mrrUurbpdXa5dTH5dXi9tTsGNtX0TFG1OT+7PdY2YdEGd0FuFmUwXWm5UAZbCTKYA3SUrXZQTHLHbUy2OlsMO0ultLsajLlbEWZMEUZ+ig5E6YKM2GqMBOmGKubW1D3ps6g1nnvA5uGa5Os85E9nmF2ebYkzeKhc9wre4V+GMeh317hDfXgCWigIGJbAAAAAElFTkSuQmCC";
150
- const defaultImage = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAA/CAYAAACM5Lr9AAAFkklEQVR42s3VaWxUVRjG8ddiEKPRxAQTCVSWLnZaWmjpTgulpYUBExP9Agou4IKAogUKAgItlNJCgUIXINFPfsFoDCjibkQRI0QIICAQWUpZugKtpcv0+DxyYqaTe2/vTLf58Etu7znnPf+0k44opQw5i5qsjIFs2APHoBZatFq+02vZeq94yyKs0dOjsAzOTCtuVtNKWtX0UpeaXqHU07tgt4ZnvuMa93Avz/CsniE2WIQV3iEaCDnQ8F/MTgZ4h2d4ljNgmZ4pFszDpmIRIuFP57YWDMcFu7uHMziLMyEKxJBl2MbbM6DZub2NQ3sUZ3K2vkMMGIdNKbi1ADqcZe1q2i7VKzibd8BCEE8GUQ3PQ4ez3KWcGNCbeAfv0neKm85hWRvqo+Hu1LJ2HuwTvAt3tkAciKbDIDO/7iE4l7X9rpqCA30pa3uLwt3nYRAIuIfV5mcWN6msnapf8G405IGQMGry+prB0DiloqPfwng3G3SLDltXnTt5S6PK3NnRr9jAFhDJyLsZAJcz8SGcjOr+xAa0XGGTpOfeSMrYUKcyKlx+gS1oSkbY9VXpm2+rjHKXX2ALm2TS2qq96duaVHp5u19gC5skbc3V05N23FWT8NIfsIVNkra6siGttE2llbX7h9JWhaZ6mfj+lfaJZW3Kn6DJJRNWXWqbgN+Y39jRqtDUKKkrL15PxfdjammrfyhpVmiqlNQVfx9KwX/cFJT6A7awSVLeu1CeUlinxu9o8QsphbUKTWUyfvn5Wcm511QSXvoDtrBJkpedewzaE/E58wdsYZMopSQ55+z+pKK6fo9KKqpXaDkAIgxLWnomK3H1JZVQ0tyv2ICW6XAvLHHJ6QD4K6GgRsVjQ3/g3WzQLffCKGHJqfHgisOXaNy2f/oU7+TdukGIUW5xJ0vic6+oWGzsS7yTd4NoncPiF594GC7FFlSrcVub+gTv4p36btE6h1Fc9nFn7IpzKmZrY5/gXbwTxI0O8xD77rGPYtZeVtE42Jt4B+8C8WAcNu6dPwZDzVh8PYzdcqdXcDbvgMdBPDHEOG7R0Xkxqy6oKAzpDZzNO0AMmIfFvH1kABwZk1epIotv9yjOxOyj+g4xYB4W/dbvlAAdozGsJ3Gmni0mzMPGLvyN6IMo/NojNt/qEZyFmR+CWLAIW3CYaDDUR+D/TTgGdwdncJaeKRbMw8bM/9XdosjlZ5VjU0O3cAZngXTBPCzqzV/cPQAXHeuqVBgu8IVj/TXFGXqWdME8LHLez55mRSw9qUI31fuEZzFjNogNFmFvHPQUACfC8IUbUlTvlbDcSsWzeobYYB42+vWfjDwbnn3c6zCewdnnQGwyD4t47UcjAXA2JO+qCi6ss4V7eUafFZuswn4wM8ex+LgKwqV2cC/OzAXxgnlY+KvfmxkIVaPyr6tRhbWWuId79RnxgnmYY+53VlaHLj2lRm6stRSSc0ph7xoQL1mEzfnWyhPQNrKgGgE1hrjGPTAExEvmYWGvfNOVPUErz6vhiDDCNez5GMQHVmFfd2Vq6MLD6smCGkNc4x4QH5iHPfXyV125H64NX1eFkOpO+I5reo/4wDws9KUDdhSPxFdNIGLc8R3XQHxkFfalHYnB8w6qYRuqO+E7roH4yDws5MX9dtwHlYF5lQi6qYjPfKfXxEcWYbO/sKtsBP50QxFFI/D/De8qQLrBPCwYizY9M2r+of/D+Mx3ID6zDJv1uaVwGfAIBDqGJsbhZ9eQ/BuK+OwYlhzPNe7hXh9Yhe0zwqBB4IAYouCZn1wIXH5GEZ/d1sjBMzzrBfOwoBf2GWFYBMS4C03JWRA087OaoBmf3uCz5zrP8Kx9lmF7jXiE2RbBs95ghB0MIo8/pS0OeJAzvOBLmKY//BAGURBN+jmMa3qPkLdh/wKOL8SpLbnYFgAAAABJRU5ErkJggg==";
151
- var dist = { exports: {} };
152
- (function(module2, exports3) {
153
- (function(m2, p2) {
154
- module2.exports = p2();
155
- })(commonjsGlobal, function() {
156
- function m2(a) {
157
- var b2 = [];
158
- a.AMapUI && b2.push(p2(a.AMapUI));
159
- a.Loca && b2.push(r(a.Loca));
160
- return Promise.all(b2);
161
- }
162
- function p2(a) {
163
- return new Promise(function(h, c) {
164
- var f2 = [];
165
- if (a.plugins)
166
- for (var e = 0; e < a.plugins.length; e += 1)
167
- -1 == d.AMapUI.plugins.indexOf(a.plugins[e]) && f2.push(a.plugins[e]);
168
- if (g.AMapUI === b.failed)
169
- c("前次请求 AMapUI 失败");
170
- else if (g.AMapUI === b.notload) {
171
- g.AMapUI = b.loading;
172
- d.AMapUI.version = a.version || d.AMapUI.version;
173
- e = d.AMapUI.version;
174
- var l2 = document.body || document.head, k2 = document.createElement("script");
175
- k2.type = "text/javascript";
176
- k2.src = "https://webapi.amap.com/ui/" + e + "/main.js";
177
- k2.onerror = function(a2) {
178
- g.AMapUI = b.failed;
179
- c("请求 AMapUI 失败");
180
- };
181
- k2.onload = function() {
182
- g.AMapUI = b.loaded;
183
- if (f2.length)
184
- window.AMapUI.loadUI(f2, function() {
185
- for (var a2 = 0, b2 = f2.length; a2 < b2; a2++) {
186
- var c2 = f2[a2].split("/").slice(-1)[0];
187
- window.AMapUI[c2] = arguments[a2];
188
- }
189
- for (h(); n2.AMapUI.length; )
190
- n2.AMapUI.splice(0, 1)[0]();
191
- });
192
- else
193
- for (h(); n2.AMapUI.length; )
194
- n2.AMapUI.splice(0, 1)[0]();
195
- };
196
- l2.appendChild(k2);
197
- } else
198
- g.AMapUI === b.loaded ? a.version && a.version !== d.AMapUI.version ? c("不允许多个版本 AMapUI 混用") : f2.length ? window.AMapUI.loadUI(f2, function() {
199
- for (var a2 = 0, b2 = f2.length; a2 < b2; a2++) {
200
- var c2 = f2[a2].split("/").slice(-1)[0];
201
- window.AMapUI[c2] = arguments[a2];
202
- }
203
- h();
204
- }) : h() : a.version && a.version !== d.AMapUI.version ? c("不允许多个版本 AMapUI 混用") : n2.AMapUI.push(function(a2) {
205
- a2 ? c(a2) : f2.length ? window.AMapUI.loadUI(f2, function() {
206
- for (var a3 = 0, b2 = f2.length; a3 < b2; a3++) {
207
- var c2 = f2[a3].split("/").slice(-1)[0];
208
- window.AMapUI[c2] = arguments[a3];
209
- }
210
- h();
211
- }) : h();
212
- });
213
- });
214
- }
215
- function r(a) {
216
- return new Promise(function(h, c) {
217
- if (g.Loca === b.failed)
218
- c("前次请求 Loca 失败");
219
- else if (g.Loca === b.notload) {
220
- g.Loca = b.loading;
221
- d.Loca.version = a.version || d.Loca.version;
222
- var f2 = d.Loca.version, e = d.AMap.version.startsWith("2"), l2 = f2.startsWith("2");
223
- if (e && !l2 || !e && l2)
224
- c("JSAPI 与 Loca 版本不对应!!");
225
- else {
226
- e = d.key;
227
- l2 = document.body || document.head;
228
- var k2 = document.createElement("script");
229
- k2.type = "text/javascript";
230
- k2.src = "https://webapi.amap.com/loca?v=" + f2 + "&key=" + e;
231
- k2.onerror = function(a2) {
232
- g.Loca = b.failed;
233
- c("请求 AMapUI 失败");
234
- };
235
- k2.onload = function() {
236
- g.Loca = b.loaded;
237
- for (h(); n2.Loca.length; )
238
- n2.Loca.splice(0, 1)[0]();
239
- };
240
- l2.appendChild(k2);
241
- }
242
- } else
243
- g.Loca === b.loaded ? a.version && a.version !== d.Loca.version ? c("不允许多个版本 Loca 混用") : h() : a.version && a.version !== d.Loca.version ? c("不允许多个版本 Loca 混用") : n2.Loca.push(function(a2) {
244
- a2 ? c(a2) : c();
245
- });
246
- });
247
- }
248
- if (!window)
249
- throw Error("AMap JSAPI can only be used in Browser.");
250
- var b;
251
- (function(a) {
252
- a.notload = "notload";
253
- a.loading = "loading";
254
- a.loaded = "loaded";
255
- a.failed = "failed";
256
- })(b || (b = {}));
257
- var d = { key: "", AMap: { version: "1.4.15", plugins: [] }, AMapUI: { version: "1.1", plugins: [] }, Loca: { version: "1.3.2" } }, g = { AMap: b.notload, AMapUI: b.notload, Loca: b.notload }, n2 = { AMap: [], AMapUI: [], Loca: [] }, q2 = [], t = function(a) {
258
- "function" == typeof a && (g.AMap === b.loaded ? a(window.AMap) : q2.push(a));
259
- };
260
- return { load: function(a) {
261
- return new Promise(function(h, c) {
262
- if (g.AMap == b.failed)
263
- c("");
264
- else if (g.AMap == b.notload) {
265
- var f2 = a.key, e = a.version, l2 = a.plugins;
266
- f2 ? (window.AMap && "lbs.amap.com" !== location.host && c("禁止多种API加载方式混用"), d.key = f2, d.AMap.version = e || d.AMap.version, d.AMap.plugins = l2 || d.AMap.plugins, g.AMap = b.loading, e = document.body || document.head, window.___onAPILoaded = function(d2) {
267
- delete window.___onAPILoaded;
268
- if (d2)
269
- g.AMap = b.failed, c(d2);
270
- else
271
- for (g.AMap = b.loaded, m2(a).then(function() {
272
- h(window.AMap);
273
- })["catch"](c); q2.length; )
274
- q2.splice(0, 1)[0]();
275
- }, l2 = document.createElement("script"), l2.type = "text/javascript", l2.src = "https://webapi.amap.com/maps?callback=___onAPILoaded&v=" + d.AMap.version + "&key=" + f2 + "&plugin=" + d.AMap.plugins.join(","), l2.onerror = function(a2) {
276
- g.AMap = b.failed;
277
- c(a2);
278
- }, e.appendChild(l2)) : c("请填写key");
279
- } else if (g.AMap == b.loaded)
280
- if (a.key && a.key !== d.key)
281
- c("多个不一致的 key");
282
- else if (a.version && a.version !== d.AMap.version)
283
- c("不允许多个版本 JSAPI 混用");
284
- else {
285
- f2 = [];
286
- if (a.plugins)
287
- for (e = 0; e < a.plugins.length; e += 1)
288
- -1 == d.AMap.plugins.indexOf(a.plugins[e]) && f2.push(a.plugins[e]);
289
- if (f2.length)
290
- window.AMap.plugin(f2, function() {
291
- m2(a).then(function() {
292
- h(window.AMap);
293
- })["catch"](c);
294
- });
295
- else
296
- m2(a).then(function() {
297
- h(window.AMap);
298
- })["catch"](c);
299
- }
300
- else if (a.key && a.key !== d.key)
301
- c("多个不一致的 key");
302
- else if (a.version && a.version !== d.AMap.version)
303
- c("不允许多个版本 JSAPI 混用");
304
- else {
305
- var k2 = [];
306
- if (a.plugins)
307
- for (e = 0; e < a.plugins.length; e += 1)
308
- -1 == d.AMap.plugins.indexOf(a.plugins[e]) && k2.push(a.plugins[e]);
309
- t(function() {
310
- if (k2.length)
311
- window.AMap.plugin(k2, function() {
312
- m2(a).then(function() {
313
- h(window.AMap);
314
- })["catch"](c);
315
- });
316
- else
317
- m2(a).then(function() {
318
- h(window.AMap);
319
- })["catch"](c);
320
- });
321
- }
322
- });
323
- }, reset: function() {
324
- delete window.AMap;
325
- delete window.AMapUI;
326
- delete window.Loca;
327
- d = { key: "", AMap: { version: "1.4.15", plugins: [] }, AMapUI: { version: "1.1", plugins: [] }, Loca: { version: "1.3.2" } };
328
- g = {
329
- AMap: b.notload,
330
- AMapUI: b.notload,
331
- Loca: b.notload
332
- };
333
- n2 = { AMap: [], AMapUI: [], Loca: [] };
334
- } };
335
- });
336
- })(dist);
337
- var distExports = dist.exports;
338
- const AMapLoader = /* @__PURE__ */ getDefaultExportFromCjs(distExports);
339
- const MapConfigurationResourceKey = "map-configuration";
340
- const getSSKey = (type) => {
341
- return `NOCOBASE_PLUGIN_MAP_CONFIGURATION_${type}`;
342
- };
343
- const useMapConfiguration = (type) => {
344
- const config = React.useMemo(() => {
345
- const d = sessionStorage.getItem(getSSKey(type));
346
- if (d) {
347
- return JSON.parse(d);
348
- }
349
- return d;
350
- }, [type]);
351
- const { data } = client.useRequest(
352
- {
353
- resource: MapConfigurationResourceKey,
354
- action: "get",
355
- params: {
356
- type
357
- }
358
- },
359
- {
360
- onSuccess(data2) {
361
- sessionStorage.setItem(getSSKey(type), JSON.stringify(data2 == null ? void 0 : data2.data));
362
- },
363
- refreshOnWindowFocus: false,
364
- refreshDeps: [],
365
- manual: config ? true : false
366
- }
367
- );
368
- if (config)
369
- return config;
370
- return data == null ? void 0 : data.data;
371
- };
372
- const Search$1 = (props) => {
373
- const { aMap, toCenter } = props;
374
- const { t } = useMapTranslation();
375
- const placeSearch = React.useRef();
376
- const [options, setOptions] = React.useState([]);
377
- React.useEffect(() => {
378
- aMap == null ? void 0 : aMap.plugin("AMap.PlaceSearch", () => {
379
- placeSearch.current = new aMap.PlaceSearch({
380
- city: "全国",
381
- pageSize: 30
382
- });
383
- });
384
- }, [aMap]);
385
- const { run: onSearch } = ahooks.useDebounceFn(
386
- (keyword) => {
387
- if (!placeSearch.current) {
388
- return;
389
- }
390
- placeSearch.current.search(keyword || " ", (status, result) => {
391
- if (status === "complete") {
392
- setOptions(
393
- result.poiList.pois.map((item) => {
394
- return {
395
- ...item,
396
- label: `${item.name}-${item.address}`,
397
- value: item.id
398
- };
399
- })
400
- );
401
- } else {
402
- if (status === "no_data") {
403
- setOptions([]);
404
- return;
405
- }
406
- antd.message.error(t("Please configure the AMap securityCode or securityHost correctly"));
407
- }
408
- });
409
- },
410
- {
411
- wait: 300
412
- }
413
- );
414
- const onSelect = (value) => {
415
- const place = options.find((o) => {
416
- return o.value === value;
417
- });
418
- if (place == null ? void 0 : place.location) {
419
- toCenter(place.location);
420
- }
421
- };
422
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
423
- "div",
424
- {
425
- className: client.css`
1
+ (function(O,r){typeof exports=="object"&&typeof module!="undefined"?r(exports,require("react/jsx-runtime"),require("@nocobase/client"),require("react"),require("react-i18next"),require("@ant-design/icons"),require("@formily/react"),require("ahooks"),require("antd"),require("react-router-dom"),require("lodash"),require("@formily/shared"),require("@formily/antd-v5")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","@nocobase/client","react","react-i18next","@ant-design/icons","@formily/react","ahooks","antd","react-router-dom","lodash","@formily/shared","@formily/antd-v5"],r):(O=typeof globalThis!="undefined"?globalThis:O||self,r(O["@nocobase/plugin-map"]={},O.jsxRuntime,O["@nocobase/client"],O.react,O["react-i18next"],O["@ant-design/icons"],O["@formily/react"],O.ahooks,O.antd,O["react-router-dom"],O.lodash,O["@formily/shared"],O["@formily/antd-v5"]))})(this,function(O,r,s,d,le,ee,Z,G,x,re,Me,We,Ye){"use strict";var Tt=Object.defineProperty,Dt=Object.defineProperties;var Kt=Object.getOwnPropertyDescriptors;var de=Object.getOwnPropertySymbols;var je=Object.prototype.hasOwnProperty,qe=Object.prototype.propertyIsEnumerable;var Ne=(O,r,s)=>r in O?Tt(O,r,{enumerable:!0,configurable:!0,writable:!0,value:s}):O[r]=s,I=(O,r)=>{for(var s in r||(r={}))je.call(r,s)&&Ne(O,s,r[s]);if(de)for(var s of de(r))qe.call(r,s)&&Ne(O,s,r[s]);return O},_=(O,r)=>Dt(O,Kt(r));var Ve=(O,r)=>{var s={};for(var d in O)je.call(O,d)&&r.indexOf(d)<0&&(s[d]=O[d]);if(O!=null&&de)for(var d of de(O))r.indexOf(d)<0&&qe.call(O,d)&&(s[d]=O[d]);return s};var fe=(O,r,s)=>new Promise((d,le)=>{var ee=x=>{try{G(s.next(x))}catch(re){le(re)}},Z=x=>{try{G(s.throw(x))}catch(re){le(re)}},G=x=>x.done?d(x.value):Promise.resolve(x.value).then(ee,Z);G((s=s.apply(O,r)).next())});const be="map";function R(e){return`{{t('${e}', { ns: '${be}', nsMode: 'fallback' })}}`}function Q(){return le.useTranslation(be,{nsMode:"fallback"})}const _e={title:"{{t('Configure actions')}}",icon:"SettingOutlined",style:{marginLeft:8},items:[{type:"itemGroup",title:"{{t('Enable actions')}}",children:[{type:"item",title:"{{t('Filter')}}",component:"FilterActionInitializer",schema:{"x-align":"left"}},{type:"item",title:"{{t('Add new')}}",component:"CreateActionInitializer",schema:{"x-align":"right","x-decorator":"ACLActionProvider","x-acl-action-props":{skipScopeCheck:!0}}},{type:"item",title:"{{t('Refresh')}}",component:"RefreshActionInitializer",schema:{"x-align":"right"}}]},{type:"divider"},{type:"subMenu",title:'{{t("Customize")}}',children:[{type:"item",title:'{{t("Bulk update")}}',component:"CustomizeActionInitializer",schema:{type:"void",title:'{{ t("Bulk update") }}',"x-component":"Action","x-align":"right","x-acl-action":"update","x-decorator":"ACLActionProvider","x-acl-action-props":{skipScopeCheck:!0},"x-action":"customize:bulkUpdate","x-designer":"Action.Designer","x-action-settings":{assignedValues:{},updateMode:"selected",onSuccess:{manualClose:!0,redirecting:!1,successMessage:'{{t("Updated successfully")}}'}},"x-component-props":{icon:"EditOutlined",useProps:"{{ useCustomizeBulkUpdateActionProps }}"}}},{type:"item",title:'{{t("Bulk edit")}}',component:"CustomizeBulkEditActionInitializer",schema:{"x-align":"right","x-decorator":"ACLActionProvider","x-acl-action":"update","x-acl-action-props":{skipScopeCheck:!0}}}]}]},Ce=[{label:R("AMap"),value:"amap"},{label:R("Google Maps"),value:"google"}],ge="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAA/CAMAAAC7OkrPAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAEJQTFRFAAAA8Yti8Yti8Itj8Iti74tj8Itj8YtiKwADKwADKhw5Kh07KwADKwADKwADKwAD4odn1YBlKwADKwADKwADKwAD/5y7LQAAABZ0Uk5TAP/8/f/B/PYOHjY3CCozLP3XCSkvMhA05K4AAAC4SURBVHic7dXLDoIwEIXhwSsoLSrw/q8qbSAiMy3/oivj2czmS5omnVORdapVJJFKBSEL2mrrUurbpdXa5dTH5dXi9tTsGNtX0TFG1OT+7PdY2YdEGd0FuFmUwXWm5UAZbCTKYA3SUrXZQTHLHbUy2OlsMO0ultLsajLlbEWZMEUZ+ig5E6YKM2GqMBOmGKubW1D3ps6g1nnvA5uGa5Os85E9nmF2ebYkzeKhc9wre4V+GMeh317hDfXgCWigIGJbAAAAAElFTkSuQmCC",ae="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACYAAAA/CAYAAACM5Lr9AAAFkklEQVR42s3VaWxUVRjG8ddiEKPRxAQTCVSWLnZaWmjpTgulpYUBExP9Agou4IKAogUKAgItlNJCgUIXINFPfsFoDCjibkQRI0QIICAQWUpZugKtpcv0+DxyYqaTe2/vTLf58Etu7znnPf+0k44opQw5i5qsjIFs2APHoBZatFq+02vZeq94yyKs0dOjsAzOTCtuVtNKWtX0UpeaXqHU07tgt4ZnvuMa93Avz/CsniE2WIQV3iEaCDnQ8F/MTgZ4h2d4ljNgmZ4pFszDpmIRIuFP57YWDMcFu7uHMziLMyEKxJBl2MbbM6DZub2NQ3sUZ3K2vkMMGIdNKbi1ADqcZe1q2i7VKzibd8BCEE8GUQ3PQ4ez3KWcGNCbeAfv0neKm85hWRvqo+Hu1LJ2HuwTvAt3tkAciKbDIDO/7iE4l7X9rpqCA30pa3uLwt3nYRAIuIfV5mcWN6msnapf8G405IGQMGry+prB0DiloqPfwng3G3SLDltXnTt5S6PK3NnRr9jAFhDJyLsZAJcz8SGcjOr+xAa0XGGTpOfeSMrYUKcyKlx+gS1oSkbY9VXpm2+rjHKXX2ALm2TS2qq96duaVHp5u19gC5skbc3V05N23FWT8NIfsIVNkra6siGttE2llbX7h9JWhaZ6mfj+lfaJZW3Kn6DJJRNWXWqbgN+Y39jRqtDUKKkrL15PxfdjammrfyhpVmiqlNQVfx9KwX/cFJT6A7awSVLeu1CeUlinxu9o8QsphbUKTWUyfvn5Wcm511QSXvoDtrBJkpedewzaE/E58wdsYZMopSQ55+z+pKK6fo9KKqpXaDkAIgxLWnomK3H1JZVQ0tyv2ICW6XAvLHHJ6QD4K6GgRsVjQ3/g3WzQLffCKGHJqfHgisOXaNy2f/oU7+TdukGIUW5xJ0vic6+oWGzsS7yTd4NoncPiF594GC7FFlSrcVub+gTv4p36btE6h1Fc9nFn7IpzKmZrY5/gXbwTxI0O8xD77rGPYtZeVtE42Jt4B+8C8WAcNu6dPwZDzVh8PYzdcqdXcDbvgMdBPDHEOG7R0Xkxqy6oKAzpDZzNO0AMmIfFvH1kABwZk1epIotv9yjOxOyj+g4xYB4W/dbvlAAdozGsJ3Gmni0mzMPGLvyN6IMo/NojNt/qEZyFmR+CWLAIW3CYaDDUR+D/TTgGdwdncJaeKRbMw8bM/9XdosjlZ5VjU0O3cAZngXTBPCzqzV/cPQAXHeuqVBgu8IVj/TXFGXqWdME8LHLez55mRSw9qUI31fuEZzFjNogNFmFvHPQUACfC8IUbUlTvlbDcSsWzeobYYB42+vWfjDwbnn3c6zCewdnnQGwyD4t47UcjAXA2JO+qCi6ss4V7eUafFZuswn4wM8ex+LgKwqV2cC/OzAXxgnlY+KvfmxkIVaPyr6tRhbWWuId79RnxgnmYY+53VlaHLj2lRm6stRSSc0ph7xoQL1mEzfnWyhPQNrKgGgE1hrjGPTAExEvmYWGvfNOVPUErz6vhiDDCNez5GMQHVmFfd2Vq6MLD6smCGkNc4x4QH5iHPfXyV125H64NX1eFkOpO+I5reo/4wDws9KUDdhSPxFdNIGLc8R3XQHxkFfalHYnB8w6qYRuqO+E7roH4yDws5MX9dtwHlYF5lQi6qYjPfKfXxEcWYbO/sKtsBP50QxFFI/D/De8qQLrBPCwYizY9M2r+of/D+Mx3ID6zDJv1uaVwGfAIBDqGJsbhZ9eQ/BuK+OwYlhzPNe7hXh9Yhe0zwqBB4IAYouCZn1wIXH5GEZ/d1sjBMzzrBfOwoBf2GWFYBMS4C03JWRA087OaoBmf3uCz5zrP8Kx9lmF7jXiE2RbBs95ghB0MIo8/pS0OeJAzvOBLmKY//BAGURBN+jmMa3qPkLdh/wKOL8SpLbnYFgAAAABJRU5ErkJggg==";var Je=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Xe(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var xe={exports:{}};(function(e,n){(function(t,o){e.exports=o()})(Je,function(){function t(u){var g=[];return u.AMapUI&&g.push(o(u.AMapUI)),u.Loca&&g.push(a(u.Loca)),Promise.all(g)}function o(u){return new Promise(function(g,p){var m=[];if(u.plugins)for(var v=0;v<u.plugins.length;v+=1)l.AMapUI.plugins.indexOf(u.plugins[v])==-1&&m.push(u.plugins[v]);if(h.AMapUI===i.failed)p("前次请求 AMapUI 失败");else if(h.AMapUI===i.notload){h.AMapUI=i.loading,l.AMapUI.version=u.version||l.AMapUI.version,v=l.AMapUI.version;var K=document.body||document.head,F=document.createElement("script");F.type="text/javascript",F.src="https://webapi.amap.com/ui/"+v+"/main.js",F.onerror=function(k){h.AMapUI=i.failed,p("请求 AMapUI 失败")},F.onload=function(){if(h.AMapUI=i.loaded,m.length)window.AMapUI.loadUI(m,function(){for(var k=0,D=m.length;k<D;k++){var V=m[k].split("/").slice(-1)[0];window.AMapUI[V]=arguments[k]}for(g();A.AMapUI.length;)A.AMapUI.splice(0,1)[0]()});else for(g();A.AMapUI.length;)A.AMapUI.splice(0,1)[0]()},K.appendChild(F)}else h.AMapUI===i.loaded?u.version&&u.version!==l.AMapUI.version?p("不允许多个版本 AMapUI 混用"):m.length?window.AMapUI.loadUI(m,function(){for(var k=0,D=m.length;k<D;k++){var V=m[k].split("/").slice(-1)[0];window.AMapUI[V]=arguments[k]}g()}):g():u.version&&u.version!==l.AMapUI.version?p("不允许多个版本 AMapUI 混用"):A.AMapUI.push(function(k){k?p(k):m.length?window.AMapUI.loadUI(m,function(){for(var D=0,V=m.length;D<V;D++){var B=m[D].split("/").slice(-1)[0];window.AMapUI[B]=arguments[D]}g()}):g()})})}function a(u){return new Promise(function(g,p){if(h.Loca===i.failed)p("前次请求 Loca 失败");else if(h.Loca===i.notload){h.Loca=i.loading,l.Loca.version=u.version||l.Loca.version;var m=l.Loca.version,v=l.AMap.version.startsWith("2"),K=m.startsWith("2");if(v&&!K||!v&&K)p("JSAPI 与 Loca 版本不对应!!");else{v=l.key,K=document.body||document.head;var F=document.createElement("script");F.type="text/javascript",F.src="https://webapi.amap.com/loca?v="+m+"&key="+v,F.onerror=function(k){h.Loca=i.failed,p("请求 AMapUI 失败")},F.onload=function(){for(h.Loca=i.loaded,g();A.Loca.length;)A.Loca.splice(0,1)[0]()},K.appendChild(F)}}else h.Loca===i.loaded?u.version&&u.version!==l.Loca.version?p("不允许多个版本 Loca 混用"):g():u.version&&u.version!==l.Loca.version?p("不允许多个版本 Loca 混用"):A.Loca.push(function(k){k?p(k):p()})})}if(!window)throw Error("AMap JSAPI can only be used in Browser.");var i;(function(u){u.notload="notload",u.loading="loading",u.loaded="loaded",u.failed="failed"})(i||(i={}));var l={key:"",AMap:{version:"1.4.15",plugins:[]},AMapUI:{version:"1.1",plugins:[]},Loca:{version:"1.3.2"}},h={AMap:i.notload,AMapUI:i.notload,Loca:i.notload},A={AMap:[],AMapUI:[],Loca:[]},S=[],M=function(u){typeof u=="function"&&(h.AMap===i.loaded?u(window.AMap):S.push(u))};return{load:function(u){return new Promise(function(g,p){if(h.AMap==i.failed)p("");else if(h.AMap==i.notload){var m=u.key,v=u.version,K=u.plugins;m?(window.AMap&&location.host!=="lbs.amap.com"&&p("禁止多种API加载方式混用"),l.key=m,l.AMap.version=v||l.AMap.version,l.AMap.plugins=K||l.AMap.plugins,h.AMap=i.loading,v=document.body||document.head,window.___onAPILoaded=function(k){if(delete window.___onAPILoaded,k)h.AMap=i.failed,p(k);else for(h.AMap=i.loaded,t(u).then(function(){g(window.AMap)}).catch(p);S.length;)S.splice(0,1)[0]()},K=document.createElement("script"),K.type="text/javascript",K.src="https://webapi.amap.com/maps?callback=___onAPILoaded&v="+l.AMap.version+"&key="+m+"&plugin="+l.AMap.plugins.join(","),K.onerror=function(k){h.AMap=i.failed,p(k)},v.appendChild(K)):p("请填写key")}else if(h.AMap==i.loaded)if(u.key&&u.key!==l.key)p("多个不一致的 key");else if(u.version&&u.version!==l.AMap.version)p("不允许多个版本 JSAPI 混用");else{if(m=[],u.plugins)for(v=0;v<u.plugins.length;v+=1)l.AMap.plugins.indexOf(u.plugins[v])==-1&&m.push(u.plugins[v]);m.length?window.AMap.plugin(m,function(){t(u).then(function(){g(window.AMap)}).catch(p)}):t(u).then(function(){g(window.AMap)}).catch(p)}else if(u.key&&u.key!==l.key)p("多个不一致的 key");else if(u.version&&u.version!==l.AMap.version)p("不允许多个版本 JSAPI 混用");else{var F=[];if(u.plugins)for(v=0;v<u.plugins.length;v+=1)l.AMap.plugins.indexOf(u.plugins[v])==-1&&F.push(u.plugins[v]);M(function(){F.length?window.AMap.plugin(F,function(){t(u).then(function(){g(window.AMap)}).catch(p)}):t(u).then(function(){g(window.AMap)}).catch(p)})}})},reset:function(){delete window.AMap,delete window.AMapUI,delete window.Loca,l={key:"",AMap:{version:"1.4.15",plugins:[]},AMapUI:{version:"1.1",plugins:[]},Loca:{version:"1.3.2"}},h={AMap:i.notload,AMapUI:i.notload,Loca:i.notload},A={AMap:[],AMapUI:[],Loca:[]}}}})})(xe);var Ze=xe.exports;const He=Xe(Ze),we="map-configuration",me=e=>`NOCOBASE_PLUGIN_MAP_CONFIGURATION_${e}`,he=e=>{const n=d.useMemo(()=>{const o=sessionStorage.getItem(me(e));return o&&JSON.parse(o)},[e]),{data:t}=s.useRequest({resource:we,action:"get",params:{type:e}},{onSuccess(o){sessionStorage.setItem(me(e),JSON.stringify(o==null?void 0:o.data))},refreshOnWindowFocus:!1,refreshDeps:[],manual:!!n});return n||(t==null?void 0:t.data)},Qe=e=>{const{aMap:n,toCenter:t}=e,{t:o}=Q(),a=d.useRef(),[i,l]=d.useState([]);d.useEffect(()=>{n==null||n.plugin("AMap.PlaceSearch",()=>{a.current=new n.PlaceSearch({city:"全国",pageSize:30})})},[n]);const{run:h}=G.useDebounceFn(S=>{a.current&&a.current.search(S||" ",(M,u)=>{if(M==="complete")l(u.poiList.pois.map(g=>_(I({},g),{label:`${g.name}-${g.address}`,value:g.id})));else{if(M==="no_data"){l([]);return}x.message.error(o("Please configure the AMap securityCode or securityHost correctly"))}})},{wait:300}),A=S=>{const M=i.find(u=>u.value===S);M!=null&&M.location&&t(M.location)};return r.jsx("div",{className:s.css`
426
2
  position: absolute;
427
3
  top: 10px;
428
4
  left: 10px;
429
5
  z-index: 10;
430
6
  width: calc(100% - 20px);
431
- `,
432
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
433
- antd.Select,
434
- {
435
- showSearch: true,
436
- allowClear: true,
437
- style: {
438
- background: "rgba(255, 255, 255, 0.8)"
439
- },
440
- placeholder: t("Enter keywords to search"),
441
- filterOption: false,
442
- onSearch,
443
- onSelect,
444
- options,
445
- popupMatchSelectWidth: false
446
- }
447
- )
448
- }
449
- );
450
- };
451
- const methodMapping$1 = {
452
- point: {
453
- mouseTool: "marker",
454
- propertyKey: "position",
455
- overlay: "Marker"
456
- },
457
- polygon: {
458
- mouseTool: "polygon",
459
- editor: "PolygonEditor",
460
- propertyKey: "path",
461
- overlay: "Polygon"
462
- },
463
- lineString: {
464
- mouseTool: "polyline",
465
- editor: "PolylineEditor",
466
- propertyKey: "path",
467
- overlay: "Polyline"
468
- },
469
- circle: {
470
- mouseTool: "circle",
471
- editor: "CircleEditor",
472
- transformOptions(value) {
473
- return {
474
- center: value.slice(0, 2),
475
- radius: value[2]
476
- };
477
- },
478
- overlay: "Circle"
479
- }
480
- };
481
- const AMapComponent = React.forwardRef((props, ref) => {
482
- const { accessKey, securityJsCode } = useMapConfiguration(props.mapType) || {};
483
- const { value, onChange, block = false, readonly, disabled = block, zoom = 13, overlayCommonOptions } = props;
484
- const { t } = useMapTranslation();
485
- const fieldSchema = react.useFieldSchema();
486
- const aMap = React.useRef();
487
- const map = React.useRef();
488
- const mouseTool = React.useRef();
489
- const [needUpdateFlag, forceUpdate] = React.useState([]);
490
- const [errMessage, setErrMessage] = React.useState("");
491
- const { getField } = client.useCollection();
492
- const type = React.useMemo(() => {
493
- if (props.type)
494
- return props.type;
495
- const collectionField = getField(fieldSchema == null ? void 0 : fieldSchema.name);
496
- return collectionField == null ? void 0 : collectionField.interface;
497
- }, [props == null ? void 0 : props.type, fieldSchema == null ? void 0 : fieldSchema.name]);
498
- const overlay = React.useRef();
499
- const editor = React.useRef(null);
500
- const navigate = reactRouterDom.useNavigate();
501
- const id = React.useRef(`nocobase-map-${type || ""}-${Date.now().toString(32)}`);
502
- const { modal } = antd.App.useApp();
503
- const [commonOptions] = React.useState({
504
- strokeWeight: 5,
505
- strokeColor: "#4e9bff",
506
- fillColor: "#4e9bff",
507
- strokeOpacity: 1,
508
- ...overlayCommonOptions
509
- });
510
- const toRemoveOverlay = ahooks.useMemoizedFn(() => {
511
- if (overlay.current) {
512
- overlay.current.remove();
513
- }
514
- });
515
- const setTarget = ahooks.useMemoizedFn(() => {
516
- if ((!disabled || block) && type !== "point" && editor.current) {
517
- editor.current.setTarget(overlay.current);
518
- editor.current.open();
519
- }
520
- });
521
- const onMapChange = ahooks.useMemoizedFn((target, onlyChange = false) => {
522
- let nextValue = null;
523
- if (type === "point") {
524
- const { lat, lng } = target.getPosition();
525
- nextValue = [lng, lat];
526
- } else if (type === "polygon" || type === "lineString") {
527
- nextValue = target.getPath().map((item) => [item.lng, item.lat]);
528
- if (nextValue.length < 2) {
529
- return;
530
- }
531
- } else if (type === "circle") {
532
- const center = target.getCenter();
533
- const radius = target.getRadius();
534
- nextValue = [center.lng, center.lat, radius];
535
- }
536
- if (!onlyChange) {
537
- toRemoveOverlay();
538
- overlay.current = target;
539
- setTarget();
540
- }
541
- onChange == null ? void 0 : onChange(nextValue);
542
- });
543
- const createEditor = ahooks.useMemoizedFn((curType = type) => {
544
- const mapping = methodMapping$1[curType];
545
- if (mapping && "editor" in mapping && !editor.current) {
546
- editor.current = new aMap.current[mapping.editor](map.current, null, {
547
- createOptions: commonOptions,
548
- editOptions: commonOptions,
549
- controlPoint: {
550
- ...commonOptions,
551
- strokeWeight: 3
552
- },
553
- midControlPoint: {
554
- ...commonOptions,
555
- strokeWeight: 2,
556
- fillColor: "#fff"
557
- }
558
- });
559
- editor.current.on("adjust", function({ target }) {
560
- onMapChange(target, true);
561
- });
562
- editor.current.on("move", function({ target }) {
563
- onMapChange(target, true);
564
- });
565
- return editor.current;
566
- }
567
- });
568
- const executeMouseTool = ahooks.useMemoizedFn((curType = type) => {
569
- var _a;
570
- if (!mouseTool.current || ((_a = editor.current) == null ? void 0 : _a.getTarget()))
571
- return;
572
- const mapping = methodMapping$1[curType];
573
- if (!mapping) {
574
- return;
575
- }
576
- mouseTool.current[mapping.mouseTool]({
577
- ...commonOptions
578
- });
579
- });
580
- const createMouseTool = ahooks.useMemoizedFn((curType = type) => {
581
- if (mouseTool.current)
582
- return;
583
- mouseTool.current = new aMap.current.MouseTool(map.current);
584
- mouseTool.current.on("draw", function({ obj }) {
585
- onMapChange(obj);
586
- });
587
- executeMouseTool(curType);
588
- });
589
- const toCenter = (position, imm) => {
590
- if (map.current) {
591
- map.current.setZoomAndCenter(18, position, imm);
592
- }
593
- };
594
- const onReset = () => {
595
- const ok = () => {
596
- toRemoveOverlay();
597
- if (editor.current) {
598
- editor.current.setTarget();
599
- editor.current.close();
600
- }
601
- onChange == null ? void 0 : onChange(null);
602
- };
603
- modal.confirm({
604
- title: t("Clear the canvas"),
605
- content: t("Are you sure to clear the canvas?"),
606
- okText: t("Confirm"),
607
- cancelText: t("Cancel"),
608
- getContainer: () => document.getElementById(id.current),
609
- onOk() {
610
- ok();
611
- }
612
- });
613
- };
614
- const onFocusOverlay = () => {
615
- if (overlay.current) {
616
- map.current.setFitView([overlay.current]);
617
- }
618
- };
619
- const getOverlay = React.useCallback(
620
- (t2 = type, v = value, o) => {
621
- const mapping = methodMapping$1[t2];
622
- if (!mapping) {
623
- return;
624
- }
625
- const options = { ...commonOptions, ...o };
626
- if ("transformOptions" in mapping) {
627
- Object.assign(options, mapping.transformOptions(v));
628
- } else if ("propertyKey" in mapping) {
629
- options[mapping.propertyKey] = v;
630
- }
631
- return new aMap.current[mapping.overlay](options);
632
- },
633
- [commonOptions]
634
- );
635
- const setOverlay = (t2 = type, v = value, o) => {
636
- if (!aMap.current)
637
- return;
638
- const nextOverlay = getOverlay(t2, v, o);
639
- nextOverlay.setMap(map.current);
640
- return nextOverlay;
641
- };
642
- React.useEffect(() => {
643
- if (!aMap.current)
644
- return;
645
- if (!value || !readonly && overlay.current) {
646
- return;
647
- }
648
- const nextOverlay = setOverlay();
649
- map.current.setFitView([nextOverlay]);
650
- overlay.current = nextOverlay;
651
- if (!disabled) {
652
- createEditor();
653
- setTarget();
654
- }
655
- }, [value, needUpdateFlag, type, commonOptions, disabled, readonly]);
656
- React.useEffect(() => {
657
- var _a, _b, _c;
658
- if (!mouseTool.current)
659
- return;
660
- if (disabled) {
661
- (_a = mouseTool.current) == null ? void 0 : _a.close();
662
- (_b = editor.current) == null ? void 0 : _b.close();
663
- } else {
664
- executeMouseTool();
665
- (_c = editor.current) == null ? void 0 : _c.open();
666
- }
667
- }, [disabled]);
668
- React.useEffect(() => {
669
- if (!aMap.current || !type || disabled)
670
- return;
671
- createMouseTool();
672
- createEditor();
673
- }, [disabled, needUpdateFlag, type]);
674
- React.useEffect(() => {
675
- var _a, _b;
676
- if (!mouseTool.current || !editor.current)
677
- return;
678
- const target = editor.current.getTarget();
679
- if (target) {
680
- (_b = (_a = mouseTool.current).close) == null ? void 0 : _b.call(_a);
681
- } else {
682
- executeMouseTool();
683
- }
684
- }, [type, value]);
685
- React.useEffect(() => {
686
- if (!accessKey || map.current)
687
- return;
688
- if (securityJsCode) {
689
- window._AMapSecurityConfig = {
690
- [securityJsCode.endsWith("_AMapService") ? "serviceHOST" : "securityJsCode"]: securityJsCode
691
- };
692
- }
693
- const _define = window.define;
694
- window.define = void 0;
695
- AMapLoader.load({
696
- key: accessKey,
697
- version: "2.0",
698
- plugins: ["AMap.MouseTool", "AMap.PolygonEditor", "AMap.PolylineEditor", "AMap.CircleEditor"]
699
- }).then((amap) => {
700
- window.define = _define;
701
- return requestIdleCallback(() => {
702
- map.current = new amap.Map(id.current, {
703
- resizeEnable: true,
704
- zoom
705
- });
706
- aMap.current = amap;
707
- setErrMessage("");
708
- forceUpdate([]);
709
- });
710
- }).catch((err) => {
711
- if (typeof err === "string") {
712
- if (err.includes("多个不一致的 key")) {
713
- setErrMessage(t("The AccessKey is incorrect, please check it"));
714
- } else {
715
- setErrMessage(err);
716
- }
717
- } else if ((err == null ? void 0 : err.type) === "error") {
718
- setErrMessage("Something went wrong, please refresh the page and try again");
719
- }
720
- });
721
- return () => {
722
- var _a;
723
- (_a = map.current) == null ? void 0 : _a.destroy();
724
- aMap.current = null;
725
- map.current = null;
726
- mouseTool.current = null;
727
- editor.current = null;
728
- };
729
- }, [accessKey, type, securityJsCode]);
730
- React.useImperativeHandle(ref, () => ({
731
- setOverlay,
732
- getOverlay,
733
- createMouseTool,
734
- createEditor,
735
- executeMouseTool,
736
- aMap: aMap.current,
737
- map: map.current,
738
- overlay: overlay.current,
739
- mouseTool: () => mouseTool.current,
740
- editor: () => editor.current,
741
- errMessage
742
- }));
743
- if (!accessKey || errMessage) {
744
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
745
- antd.Alert,
746
- {
747
- action: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Button, { type: "primary", onClick: () => navigate("/admin/settings/map/configuration"), children: t("Go to the configuration page") }),
748
- message: errMessage || t("Please configure the AccessKey and SecurityJsCode first"),
749
- type: "error"
750
- }
751
- );
752
- }
753
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(
754
- "div",
755
- {
756
- className: client.css`
7
+ `,children:r.jsx(x.Select,{showSearch:!0,allowClear:!0,style:{background:"rgba(255, 255, 255, 0.8)"},placeholder:o("Enter keywords to search"),filterOption:!1,onSearch:h,onSelect:A,options:i,popupMatchSelectWidth:!1})})},ye={point:{mouseTool:"marker",propertyKey:"position",overlay:"Marker"},polygon:{mouseTool:"polygon",editor:"PolygonEditor",propertyKey:"path",overlay:"Polygon"},lineString:{mouseTool:"polyline",editor:"PolylineEditor",propertyKey:"path",overlay:"Polyline"},circle:{mouseTool:"circle",editor:"CircleEditor",transformOptions(e){return{center:e.slice(0,2),radius:e[2]}},overlay:"Circle"}},Se=d.forwardRef((e,n)=>{const{accessKey:t,securityJsCode:o}=he(e.mapType)||{},{value:a,onChange:i,block:l=!1,readonly:h,disabled:A=l,zoom:S=13,overlayCommonOptions:M}=e,{t:u}=Q(),g=Z.useFieldSchema(),p=d.useRef(),m=d.useRef(),v=d.useRef(),[K,F]=d.useState([]),[k,D]=d.useState(""),{getField:V}=s.useCollection(),B=d.useMemo(()=>{if(e.type)return e.type;const c=V(g==null?void 0:g.name);return c==null?void 0:c.interface},[e==null?void 0:e.type,g==null?void 0:g.name]),E=d.useRef(),T=d.useRef(null),W=re.useNavigate(),q=d.useRef(`nocobase-map-${B||""}-${Date.now().toString(32)}`),{modal:$}=x.App.useApp(),[J]=d.useState(I({strokeWeight:5,strokeColor:"#4e9bff",fillColor:"#4e9bff",strokeOpacity:1},M)),te=G.useMemoizedFn(()=>{E.current&&E.current.remove()}),P=G.useMemoizedFn(()=>{(!A||l)&&B!=="point"&&T.current&&(T.current.setTarget(E.current),T.current.open())}),X=G.useMemoizedFn((c,f=!1)=>{let y=null;if(B==="point"){const{lat:C,lng:U}=c.getPosition();y=[U,C]}else if(B==="polygon"||B==="lineString"){if(y=c.getPath().map(C=>[C.lng,C.lat]),y.length<2)return}else if(B==="circle"){const C=c.getCenter(),U=c.getRadius();y=[C.lng,C.lat,U]}f||(te(),E.current=c,P()),i==null||i(y)}),N=G.useMemoizedFn((c=B)=>{const f=ye[c];if(f&&"editor"in f&&!T.current)return T.current=new p.current[f.editor](m.current,null,{createOptions:J,editOptions:J,controlPoint:_(I({},J),{strokeWeight:3}),midControlPoint:_(I({},J),{strokeWeight:2,fillColor:"#fff"})}),T.current.on("adjust",function({target:y}){X(y,!0)}),T.current.on("move",function({target:y}){X(y,!0)}),T.current}),H=G.useMemoizedFn((c=B)=>{var y;if(!v.current||(y=T.current)!=null&&y.getTarget())return;const f=ye[c];f&&v.current[f.mouseTool](I({},J))}),w=G.useMemoizedFn((c=B)=>{v.current||(v.current=new p.current.MouseTool(m.current),v.current.on("draw",function({obj:f}){X(f)}),H(c))}),z=(c,f)=>{m.current&&m.current.setZoomAndCenter(18,c,f)},b=()=>{const c=()=>{te(),T.current&&(T.current.setTarget(),T.current.close()),i==null||i(null)};$.confirm({title:u("Clear the canvas"),content:u("Are you sure to clear the canvas?"),okText:u("Confirm"),cancelText:u("Cancel"),getContainer:()=>document.getElementById(q.current),onOk(){c()}})},L=()=>{E.current&&m.current.setFitView([E.current])},Y=d.useCallback((c=B,f=a,y)=>{const C=ye[c];if(!C)return;const U=I(I({},J),y);return"transformOptions"in C?Object.assign(U,C.transformOptions(f)):"propertyKey"in C&&(U[C.propertyKey]=f),new p.current[C.overlay](U)},[J]),j=(c=B,f=a,y)=>{if(!p.current)return;const C=Y(c,f,y);return C.setMap(m.current),C};return d.useEffect(()=>{if(!p.current||!a||!h&&E.current)return;const c=j();m.current.setFitView([c]),E.current=c,A||(N(),P())},[a,K,B,J,A,h]),d.useEffect(()=>{var c,f,y;v.current&&(A?((c=v.current)==null||c.close(),(f=T.current)==null||f.close()):(H(),(y=T.current)==null||y.open()))},[A]),d.useEffect(()=>{!p.current||!B||A||(w(),N())},[A,K,B]),d.useEffect(()=>{var f,y;if(!v.current||!T.current)return;T.current.getTarget()?(y=(f=v.current).close)==null||y.call(f):H()},[B,a]),d.useEffect(()=>{if(!t||m.current)return;o&&(window._AMapSecurityConfig={[o.endsWith("_AMapService")?"serviceHOST":"securityJsCode"]:o});const c=window.define;return window.define=void 0,He.load({key:t,version:"2.0",plugins:["AMap.MouseTool","AMap.PolygonEditor","AMap.PolylineEditor","AMap.CircleEditor"]}).then(f=>(window.define=c,requestIdleCallback(()=>{m.current=new f.Map(q.current,{resizeEnable:!0,zoom:S}),p.current=f,D(""),F([])}))).catch(f=>{typeof f=="string"?f.includes("多个不一致的 key")?D(u("The AccessKey is incorrect, please check it")):D(f):(f==null?void 0:f.type)==="error"&&D("Something went wrong, please refresh the page and try again")}),()=>{var f;(f=m.current)==null||f.destroy(),p.current=null,m.current=null,v.current=null,T.current=null}},[t,B,o]),d.useImperativeHandle(n,()=>({setOverlay:j,getOverlay:Y,createMouseTool:w,createEditor:N,executeMouseTool:H,aMap:p.current,map:m.current,overlay:E.current,mouseTool:()=>v.current,editor:()=>T.current,errMessage:k})),!t||k?r.jsx(x.Alert,{action:r.jsx(x.Button,{type:"primary",onClick:()=>W("/admin/settings/map/configuration"),children:u("Go to the configuration page")}),message:k||u("Please configure the AccessKey and SecurityJsCode first"),type:"error"}):r.jsxs("div",{className:s.css`
757
8
  position: relative;
758
9
  height: 500px;
759
- `,
760
- id: id.current,
761
- style: props == null ? void 0 : props.style,
762
- children: [
763
- !aMap.current && /* @__PURE__ */ jsxRuntimeExports.jsx(
764
- "div",
765
- {
766
- className: client.css`
10
+ `,id:q.current,style:e==null?void 0:e.style,children:[!p.current&&r.jsx("div",{className:s.css`
767
11
  position: absolute;
768
12
  inset: 0;
769
13
  display: flex;
770
14
  align-items: center;
771
15
  justify-content: center;
772
- `,
773
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Spin, {})
774
- }
775
- ),
776
- !disabled ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
777
- /* @__PURE__ */ jsxRuntimeExports.jsx(Search$1, { toCenter, aMap: aMap.current }),
778
- /* @__PURE__ */ jsxRuntimeExports.jsx(
779
- "div",
780
- {
781
- className: client.css`
16
+ `,children:r.jsx(x.Spin,{})}),A?null:r.jsxs(r.Fragment,{children:[r.jsx(Qe,{toCenter:z,aMap:p.current}),r.jsx("div",{className:s.css`
782
17
  position: absolute;
783
18
  bottom: 80px;
784
19
  right: 20px;
785
20
  z-index: 10;
786
- `,
787
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
788
- antd.Button,
789
- {
790
- onClick: onFocusOverlay,
791
- disabled: !overlay.current,
792
- type: "primary",
793
- shape: "round",
794
- size: "large",
795
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.SyncOutlined, {})
796
- }
797
- )
798
- }
799
- ),
800
- type !== "point" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
801
- "div",
802
- {
803
- className: client.css`
21
+ `,children:r.jsx(x.Button,{onClick:L,disabled:!E.current,type:"primary",shape:"round",size:"large",icon:r.jsx(ee.SyncOutlined,{})})}),B!=="point"?r.jsx("div",{className:s.css`
804
22
  position: absolute;
805
23
  bottom: 20px;
806
24
  left: 10px;
807
25
  z-index: 2;
808
26
  pointer-events: none;
809
- `,
810
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
811
- antd.Alert,
812
- {
813
- message: t("Click to select the starting point and double-click to end the drawing"),
814
- type: "info"
815
- }
816
- )
817
- }
818
- ) : null,
819
- /* @__PURE__ */ jsxRuntimeExports.jsx(
820
- "div",
821
- {
822
- className: client.css`
27
+ `,children:r.jsx(x.Alert,{message:u("Click to select the starting point and double-click to end the drawing"),type:"info"})}):null,r.jsx("div",{className:s.css`
823
28
  position: absolute;
824
29
  bottom: 20px;
825
30
  right: 20px;
826
31
  z-index: 2;
827
- `,
828
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
829
- antd.Button,
830
- {
831
- disabled: !value,
832
- style: {
833
- height: "40px"
834
- },
835
- onClick: onReset,
836
- type: "primary",
837
- danger: true,
838
- children: t("Clear")
839
- }
840
- )
841
- }
842
- )
843
- ] }) : null
844
- ]
845
- }
846
- );
847
- });
848
- const getSource = (data, fields2, type) => {
849
- const res = fields2 == null ? void 0 : fields2.reduce((obj, field, index) => {
850
- if (index === fields2.length - 1 && (type === "o2m" || type === "m2m")) {
851
- return obj == null ? void 0 : obj.map((item) => item[field]).filter((v) => v !== null && v !== void 0);
852
- }
853
- return obj == null ? void 0 : obj[field];
854
- }, data);
855
- return type === "o2m" || type === "m2m" ? res : [res];
856
- };
857
- const AMapBlock = (props) => {
858
- var _a, _b, _c, _d;
859
- const { collectionField, fieldNames, dataSource, fixedBlock, zoom, setSelectedRecordKeys } = client.useProps(props);
860
- const { name: name2, getPrimaryKey } = client.useCollection();
861
- const { getCollectionJoinField } = client.useCollectionManager();
862
- const primaryKey = getPrimaryKey();
863
- const [isMapInitialization, setIsMapInitialization] = React.useState(false);
864
- const mapRef = React.useRef();
865
- const geometryUtils = (_b = (_a = mapRef.current) == null ? void 0 : _a.aMap) == null ? void 0 : _b.GeometryUtil;
866
- const [record, setRecord] = React.useState();
867
- const [selectingMode, setSelecting] = React.useState("");
868
- const { t } = useMapTranslation();
869
- const compile = client.useCompile();
870
- const { isConnected, doFilter } = client.useFilterAPI();
871
- const [, setPrevSelected] = React.useState(null);
872
- const selectingModeRef = React.useRef(selectingMode);
873
- selectingModeRef.current = selectingMode;
874
- const setOverlayOptions = (overlay, state) => {
875
- const extData = overlay.getExtData();
876
- const selected = typeof state === "undefined" ? extData.selected : !state;
877
- extData.selected = !selected;
878
- if ("setIcon" in overlay) {
879
- overlay.setIcon(
880
- new mapRef.current.aMap.Icon({
881
- imageSize: [19, 32],
882
- image: selected ? defaultImage : selectedImage
883
- })
884
- );
885
- }
886
- overlay.setOptions({
887
- extData,
888
- ...selected ? { strokeColor: "#4e9bff", fillColor: "#4e9bff" } : { strokeColor: "#F18b62", fillColor: "#F18b62" }
889
- });
890
- };
891
- const removeSelection = () => {
892
- var _a2, _b2, _c2;
893
- if (!mapRef.current)
894
- return;
895
- (_a2 = mapRef.current) == null ? void 0 : _a2.mouseTool().close(true);
896
- (_b2 = mapRef.current) == null ? void 0 : _b2.editor().setTarget(null);
897
- (_c2 = mapRef.current) == null ? void 0 : _c2.editor().close();
898
- };
899
- React.useEffect(() => {
900
- var _a2, _b2, _c2, _d2;
901
- if (selectingMode !== "selection") {
902
- return;
903
- }
904
- if (!((_a2 = mapRef.current) == null ? void 0 : _a2.editor())) {
905
- (_b2 = mapRef.current) == null ? void 0 : _b2.createEditor("polygon");
906
- (_c2 = mapRef.current) == null ? void 0 : _c2.createMouseTool("polygon");
907
- } else {
908
- (_d2 = mapRef.current) == null ? void 0 : _d2.executeMouseTool("polygon");
909
- }
910
- return () => {
911
- removeSelection();
912
- };
913
- }, [selectingMode]);
914
- React.useEffect(() => {
915
- if (selectingMode) {
916
- return () => {
917
- var _a2;
918
- if (!selectingModeRef.current) {
919
- (_a2 = mapRef.current) == null ? void 0 : _a2.map.getAllOverlays().forEach((o) => {
920
- setOverlayOptions(o, false);
921
- });
922
- }
923
- };
924
- }
925
- }, [selectingMode]);
926
- const onSelectingComplete = ahooks.useMemoizedFn(() => {
927
- var _a2, _b2, _c2;
928
- const selectingOverlay = (_a2 = mapRef.current) == null ? void 0 : _a2.editor().getTarget();
929
- const overlays = (_b2 = mapRef.current) == null ? void 0 : _b2.map.getAllOverlays();
930
- const selectedOverlays = overlays == null ? void 0 : overlays.filter((o) => {
931
- if (o === selectingOverlay || o.getExtData().id === void 0)
932
- return;
933
- if ("getPosition" in o) {
934
- return geometryUtils.isPointInRing(o.getPosition(), selectingOverlay == null ? void 0 : selectingOverlay.getPath());
935
- }
936
- return geometryUtils.doesRingRingIntersect(o.getPath(), selectingOverlay == null ? void 0 : selectingOverlay.getPath());
937
- });
938
- const ids = selectedOverlays == null ? void 0 : selectedOverlays.map((o) => {
939
- setOverlayOptions(o, true);
940
- return o.getExtData().id;
941
- });
942
- setSelectedRecordKeys((lastIds) => ids == null ? void 0 : ids.concat(lastIds));
943
- selectingOverlay == null ? void 0 : selectingOverlay.remove();
944
- (_c2 = mapRef.current) == null ? void 0 : _c2.editor().close();
945
- });
946
- React.useEffect(() => {
947
- var _a2, _b2;
948
- if (!collectionField || !mapRef.current || !dataSource)
949
- return;
950
- const fieldPaths = Array.isArray(fieldNames == null ? void 0 : fieldNames.field) && (fieldNames == null ? void 0 : fieldNames.field.length) > 1 ? fieldNames == null ? void 0 : fieldNames.field.slice(0, -1) : fieldNames == null ? void 0 : fieldNames.field;
951
- const cf = getCollectionJoinField([name2, ...fieldPaths].flat().join("."));
952
- const overlays = dataSource.map((item) => {
953
- const data = getSource(item, fieldNames == null ? void 0 : fieldNames.field, cf == null ? void 0 : cf.interface);
954
- if (!(data == null ? void 0 : data.length))
955
- return [];
956
- return data == null ? void 0 : data.filter(Boolean).map((mapItem) => {
957
- var _a3;
958
- const overlay = (_a3 = mapRef.current) == null ? void 0 : _a3.setOverlay(collectionField.type, mapItem, {
959
- strokeColor: "#4e9bff",
960
- fillColor: "#4e9bff",
961
- cursor: "pointer",
962
- label: {
963
- direction: "bottom",
964
- offset: [0, 5],
965
- content: (fieldNames == null ? void 0 : fieldNames.marker) ? compile(item[fieldNames.marker]) : void 0
966
- },
967
- extData: {
968
- id: item[primaryKey]
969
- }
970
- });
971
- return overlay;
972
- });
973
- }).flat().filter(Boolean);
974
- (_b2 = (_a2 = mapRef.current) == null ? void 0 : _a2.map) == null ? void 0 : _b2.setFitView(overlays);
975
- const events = overlays.map((o) => {
976
- const onClick = (e) => {
977
- const overlay = e.target;
978
- const extData = overlay.getExtData();
979
- if (!extData)
980
- return;
981
- if (selectingModeRef.current) {
982
- if (selectingModeRef.current === "click") {
983
- setSelectedRecordKeys(
984
- (keys) => extData.selected ? keys.filter((key) => key !== extData.id) : [...keys, extData.id]
985
- );
986
- setOverlayOptions(overlay);
987
- }
988
- return;
989
- }
990
- const data = dataSource.find((item) => {
991
- return extData.id === item[primaryKey];
992
- });
993
- if (isConnected) {
994
- setPrevSelected((prev) => {
995
- prev && clearSelected$1(prev);
996
- if (prev === o) {
997
- clearSelected$1(o);
998
- doFilter(null);
999
- return null;
1000
- } else {
1001
- selectMarker$1(o);
1002
- doFilter(data[primaryKey], (target) => target.field || primaryKey, "$eq");
1003
- }
1004
- return o;
1005
- });
1006
- return;
1007
- }
1008
- if (data) {
1009
- setRecord(data);
1010
- }
1011
- };
1012
- o.on("click", onClick);
1013
- return () => o.off("click", onClick);
1014
- });
1015
- return () => {
1016
- overlays.forEach((ov) => {
1017
- ov.remove();
1018
- });
1019
- events.forEach((e) => e());
1020
- };
1021
- }, [dataSource, isMapInitialization, fieldNames, name2, primaryKey, collectionField.type, isConnected]);
1022
- React.useEffect(() => {
1023
- setTimeout(() => {
1024
- setSelectedRecordKeys([]);
1025
- });
1026
- }, [dataSource]);
1027
- const mapRefCallback = (instance) => {
1028
- mapRef.current = instance;
1029
- setIsMapInitialization(!!(instance == null ? void 0 : instance.map) && !instance.errMessage);
1030
- };
1031
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(
1032
- "div",
1033
- {
1034
- className: client.css`
32
+ `,children:r.jsx(x.Button,{disabled:!a,style:{height:"40px"},onClick:b,type:"primary",danger:!0,children:u("Clear")})})]})]})}),Ie=(e,n,t)=>{const o=n==null?void 0:n.reduce((a,i,l)=>l===n.length-1&&(t==="o2m"||t==="m2m")?a==null?void 0:a.map(h=>h[i]).filter(h=>h!=null):a==null?void 0:a[i],e);return t==="o2m"||t==="m2m"?o:[o]},$e=e=>{var P,X,N,H;const{collectionField:n,fieldNames:t,dataSource:o,fixedBlock:a,zoom:i,setSelectedRecordKeys:l}=s.useProps(e),{name:h,getPrimaryKey:A}=s.useCollection(),{getCollectionJoinField:S}=s.useCollectionManager(),M=A(),[u,g]=d.useState(!1),p=d.useRef(),m=(X=(P=p.current)==null?void 0:P.aMap)==null?void 0:X.GeometryUtil,[v,K]=d.useState(),[F,k]=d.useState(""),{t:D}=Q(),V=s.useCompile(),{isConnected:B,doFilter:E}=s.useFilterAPI(),[,T]=d.useState(null),W=d.useRef(F);W.current=F;const q=(w,z)=>{const b=w.getExtData(),L=typeof z=="undefined"?b.selected:!z;b.selected=!L,"setIcon"in w&&w.setIcon(new p.current.aMap.Icon({imageSize:[19,32],image:L?ae:ge})),w.setOptions(I({extData:b},L?{strokeColor:"#4e9bff",fillColor:"#4e9bff"}:{strokeColor:"#F18b62",fillColor:"#F18b62"}))},$=()=>{var w,z,b;p.current&&((w=p.current)==null||w.mouseTool().close(!0),(z=p.current)==null||z.editor().setTarget(null),(b=p.current)==null||b.editor().close())};d.useEffect(()=>{var w,z,b,L;if(F==="selection")return(w=p.current)!=null&&w.editor()?(L=p.current)==null||L.executeMouseTool("polygon"):((z=p.current)==null||z.createEditor("polygon"),(b=p.current)==null||b.createMouseTool("polygon")),()=>{$()}},[F]),d.useEffect(()=>{if(F)return()=>{var w;W.current||(w=p.current)==null||w.map.getAllOverlays().forEach(z=>{q(z,!1)})}},[F]);const J=G.useMemoizedFn(()=>{var Y,j,c;const w=(Y=p.current)==null?void 0:Y.editor().getTarget(),z=(j=p.current)==null?void 0:j.map.getAllOverlays(),b=z==null?void 0:z.filter(f=>{if(!(f===w||f.getExtData().id===void 0))return"getPosition"in f?m.isPointInRing(f.getPosition(),w==null?void 0:w.getPath()):m.doesRingRingIntersect(f.getPath(),w==null?void 0:w.getPath())}),L=b==null?void 0:b.map(f=>(q(f,!0),f.getExtData().id));l(f=>L==null?void 0:L.concat(f)),w==null||w.remove(),(c=p.current)==null||c.editor().close()});d.useEffect(()=>{var Y,j;if(!n||!p.current||!o)return;const w=Array.isArray(t==null?void 0:t.field)&&(t==null?void 0:t.field.length)>1?t==null?void 0:t.field.slice(0,-1):t==null?void 0:t.field,z=S([h,...w].flat().join(".")),b=o.map(c=>{const f=Ie(c,t==null?void 0:t.field,z==null?void 0:z.interface);return f!=null&&f.length?f==null?void 0:f.filter(Boolean).map(y=>{var U;return(U=p.current)==null?void 0:U.setOverlay(n.type,y,{strokeColor:"#4e9bff",fillColor:"#4e9bff",cursor:"pointer",label:{direction:"bottom",offset:[0,5],content:t!=null&&t.marker?V(c[t.marker]):void 0},extData:{id:c[M]}})}):[]}).flat().filter(Boolean);(j=(Y=p.current)==null?void 0:Y.map)==null||j.setFitView(b);const L=b.map(c=>{const f=y=>{const C=y.target,U=C.getExtData();if(!U)return;if(W.current){W.current==="click"&&(l(oe=>U.selected?oe.filter(Ae=>Ae!==U.id):[...oe,U.id]),q(C));return}const pe=o.find(oe=>U.id===oe[M]);if(B){T(oe=>(oe&&Pe(oe),oe===c?(Pe(c),E(null),null):(et(c),E(pe[M],Ae=>Ae.field||M,"$eq"),c)));return}pe&&K(pe)};return c.on("click",f),()=>c.off("click",f)});return()=>{b.forEach(c=>{c.remove()}),L.forEach(c=>c())}},[o,u,t,h,M,n.type,B]),d.useEffect(()=>{setTimeout(()=>{l([])})},[o]);const te=w=>{p.current=w,g(!!(w!=null&&w.map)&&!w.errMessage)};return r.jsxs("div",{className:s.css`
1035
33
  position: relative;
1036
34
  height: 100%;
1037
- `,
1038
- children: [
1039
- /* @__PURE__ */ jsxRuntimeExports.jsx(
1040
- "div",
1041
- {
1042
- className: client.css`
35
+ `,children:[r.jsx("div",{className:s.css`
1043
36
  position: absolute;
1044
37
  left: 10px;
1045
38
  top: 10px;
1046
39
  z-index: 999;
1047
- `,
1048
- children: isMapInitialization && !((_c = mapRef.current) == null ? void 0 : _c.errMessage) ? /* @__PURE__ */ jsxRuntimeExports.jsxs(antd.Space, { direction: "vertical", children: [
1049
- /* @__PURE__ */ jsxRuntimeExports.jsx(
1050
- antd.Button,
1051
- {
1052
- style: {
1053
- color: !selectingMode ? "#F18b62" : void 0,
1054
- borderColor: "currentcolor"
1055
- },
1056
- onClick: (e) => {
1057
- e.stopPropagation();
1058
- setSelecting("");
1059
- },
1060
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.EnvironmentOutlined, {})
1061
- }
1062
- ),
1063
- /* @__PURE__ */ jsxRuntimeExports.jsx(
1064
- antd.Button,
1065
- {
1066
- style: {
1067
- color: selectingMode === "selection" ? "#F18b62" : void 0,
1068
- borderColor: "currentcolor"
1069
- },
1070
- onClick: (e) => {
1071
- e.stopPropagation();
1072
- setSelecting("selection");
1073
- },
1074
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.ExpandOutlined, {})
1075
- }
1076
- ),
1077
- selectingMode === "selection" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
1078
- antd.Button,
1079
- {
1080
- type: "primary",
1081
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.CheckOutlined, {}),
1082
- title: t("Confirm selection"),
1083
- onClick: onSelectingComplete
1084
- }
1085
- ) : null
1086
- ] }) : null
1087
- }
1088
- ),
1089
- /* @__PURE__ */ jsxRuntimeExports.jsx(MapBlockDrawer$1, { record, setVisible: setRecord }),
1090
- /* @__PURE__ */ jsxRuntimeExports.jsx(
1091
- AMapComponent,
1092
- {
1093
- ...(_d = collectionField == null ? void 0 : collectionField.uiSchema) == null ? void 0 : _d["x-component-props"],
1094
- ref: mapRefCallback,
1095
- style: { height: fixedBlock ? "100%" : null },
1096
- zoom,
1097
- disabled: true,
1098
- block: true,
1099
- overlayCommonOptions: {
1100
- strokeColor: "#F18b62",
1101
- fillColor: "#F18b62"
1102
- }
1103
- }
1104
- )
1105
- ]
1106
- }
1107
- );
1108
- };
1109
- const MapBlockDrawer$1 = (props) => {
1110
- const { setVisible, record } = props;
1111
- const fieldSchema = react.useFieldSchema();
1112
- const schema = React.useMemo(
1113
- () => fieldSchema.reduceProperties((buf, current) => {
1114
- if (current.name === "drawer") {
1115
- return current;
1116
- }
1117
- return buf;
1118
- }, null),
1119
- [fieldSchema]
1120
- );
1121
- return schema && /* @__PURE__ */ jsxRuntimeExports.jsx(client.ActionContextProvider, { value: { visible: !!record, setVisible }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(client.RecordProvider, { record, children: /* @__PURE__ */ jsxRuntimeExports.jsx(react.RecursionField, { schema, name: schema.name }) }) });
1122
- };
1123
- function clearSelected$1(marker) {
1124
- if (marker.dom) {
1125
- marker.dom.style.filter = "none";
1126
- } else if (marker.setOptions) {
1127
- marker.setOptions({
1128
- strokeColor: "#4e9bff",
1129
- fillColor: "#4e9bff"
1130
- });
1131
- }
1132
- }
1133
- function selectMarker$1(marker) {
1134
- if (marker.dom) {
1135
- marker.dom.style.filter = "brightness(1.2) contrast(1.2) hue-rotate(180deg)";
1136
- } else if (marker.setOptions) {
1137
- marker.setOptions({
1138
- strokeColor: "#F18b62",
1139
- fillColor: "#F18b62"
1140
- });
1141
- }
1142
- }
1143
- const BaseConfiguration = ({ type, children }) => {
1144
- const { t } = useMapTranslation();
1145
- const [isDisabled, disableAction] = ahooks.useBoolean(false);
1146
- const apiClient = client.useAPIClient();
1147
- const [form] = antd.Form.useForm();
1148
- const data = useMapConfiguration(type);
1149
- React.useEffect(() => {
1150
- if (data) {
1151
- form.setFieldsValue(data);
1152
- disableAction.toggle();
1153
- }
1154
- }, [data]);
1155
- const resource = React.useMemo(() => {
1156
- return apiClient.resource(MapConfigurationResourceKey);
1157
- }, [apiClient]);
1158
- const onSubmit = (values) => {
1159
- resource.set({
1160
- ...values,
1161
- type
1162
- }).then((res) => {
1163
- sessionStorage.removeItem(getSSKey(type));
1164
- disableAction.toggle();
1165
- antd.message.success(t("Saved successfully"));
1166
- }).catch((err) => {
1167
- antd.message.success(t("Saved failed"));
1168
- });
1169
- };
1170
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(antd.Form, { disabled: isDisabled, form, layout: "vertical", onFinish: onSubmit, children: [
1171
- children,
1172
- isDisabled ? /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Button, { disabled: false, onClick: disableAction.toggle, children: t("Edit") }) : /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Form.Item, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Button, { disabled: false, type: "primary", htmlType: "submit", children: t("Save") }) })
1173
- ] });
1174
- };
1175
- const AMapConfiguration = () => {
1176
- const { t } = useMapTranslation();
1177
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(BaseConfiguration, { type: "amap", children: [
1178
- /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Form.Item, { required: true, name: "accessKey", label: t("Access key"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Input, {}) }),
1179
- /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Form.Item, { required: true, name: "securityJsCode", label: t("securityJsCode or serviceHost"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Input, {}) })
1180
- ] });
1181
- };
1182
- const GoogleMapConfiguration = () => {
1183
- const { t } = useMapTranslation();
1184
- return /* @__PURE__ */ jsxRuntimeExports.jsx(BaseConfiguration, { type: "google", children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Form.Item, { required: true, name: "accessKey", label: t("Api key"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Input, {}) }) });
1185
- };
1186
- const components = {
1187
- amap: AMapConfiguration,
1188
- google: GoogleMapConfiguration
1189
- };
1190
- const tabList = MapTypes.map((item) => {
1191
- return {
1192
- ...item,
1193
- component: components[item.value]
1194
- };
1195
- });
1196
- const Configuration = () => {
1197
- const compile = client.useCompile();
1198
- const location2 = reactRouterDom.useLocation();
1199
- const search = new URLSearchParams(location2.search);
1200
- return /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Card, { bordered: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Tabs, { type: "card", defaultActiveKey: search.get("tab"), children: tabList.map((tab) => {
1201
- return /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Tabs.TabPane, { tab: compile(tab.label), children: /* @__PURE__ */ jsxRuntimeExports.jsx(tab.component, { type: tab.value }) }, tab.value);
1202
- }) }) });
1203
- };
1204
- /*! *****************************************************************************
1205
- Copyright (c) Microsoft Corporation.
1206
-
1207
- Permission to use, copy, modify, and/or distribute this software for any
1208
- purpose with or without fee is hereby granted.
1209
-
1210
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1211
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1212
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1213
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1214
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1215
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1216
- PERFORMANCE OF THIS SOFTWARE.
1217
- ***************************************************************************** */
1218
- function __awaiter(thisArg, _arguments, P, generator) {
1219
- function adopt(value) {
1220
- return value instanceof P ? value : new P(function(resolve) {
1221
- resolve(value);
1222
- });
1223
- }
1224
- return new (P || (P = Promise))(function(resolve, reject) {
1225
- function fulfilled(value) {
1226
- try {
1227
- step(generator.next(value));
1228
- } catch (e) {
1229
- reject(e);
1230
- }
1231
- }
1232
- function rejected(value) {
1233
- try {
1234
- step(generator["throw"](value));
1235
- } catch (e) {
1236
- reject(e);
1237
- }
1238
- }
1239
- function step(result) {
1240
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
1241
- }
1242
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1243
- });
1244
- }
1245
- var fastDeepEqual = function equal(a, b) {
1246
- if (a === b)
1247
- return true;
1248
- if (a && b && typeof a == "object" && typeof b == "object") {
1249
- if (a.constructor !== b.constructor)
1250
- return false;
1251
- var length, i, keys;
1252
- if (Array.isArray(a)) {
1253
- length = a.length;
1254
- if (length != b.length)
1255
- return false;
1256
- for (i = length; i-- !== 0; )
1257
- if (!equal(a[i], b[i]))
1258
- return false;
1259
- return true;
1260
- }
1261
- if (a.constructor === RegExp)
1262
- return a.source === b.source && a.flags === b.flags;
1263
- if (a.valueOf !== Object.prototype.valueOf)
1264
- return a.valueOf() === b.valueOf();
1265
- if (a.toString !== Object.prototype.toString)
1266
- return a.toString() === b.toString();
1267
- keys = Object.keys(a);
1268
- length = keys.length;
1269
- if (length !== Object.keys(b).length)
1270
- return false;
1271
- for (i = length; i-- !== 0; )
1272
- if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
1273
- return false;
1274
- for (i = length; i-- !== 0; ) {
1275
- var key = keys[i];
1276
- if (!equal(a[key], b[key]))
1277
- return false;
1278
- }
1279
- return true;
1280
- }
1281
- return a !== a && b !== b;
1282
- };
1283
- const DEFAULT_ID = "__googleMapsScriptId";
1284
- var LoaderStatus;
1285
- (function(LoaderStatus2) {
1286
- LoaderStatus2[LoaderStatus2["INITIALIZED"] = 0] = "INITIALIZED";
1287
- LoaderStatus2[LoaderStatus2["LOADING"] = 1] = "LOADING";
1288
- LoaderStatus2[LoaderStatus2["SUCCESS"] = 2] = "SUCCESS";
1289
- LoaderStatus2[LoaderStatus2["FAILURE"] = 3] = "FAILURE";
1290
- })(LoaderStatus || (LoaderStatus = {}));
1291
- class Loader {
1292
- /**
1293
- * Creates an instance of Loader using [[LoaderOptions]]. No defaults are set
1294
- * using this library, instead the defaults are set by the Google Maps
1295
- * JavaScript API server.
1296
- *
1297
- * ```
1298
- * const loader = Loader({apiKey, version: 'weekly', libraries: ['places']});
1299
- * ```
1300
- */
1301
- constructor({ apiKey, authReferrerPolicy, channel, client: client2, id = DEFAULT_ID, language, libraries = [], mapIds, nonce, region, retries = 3, url = "https://maps.googleapis.com/maps/api/js", version }) {
1302
- this.callbacks = [];
1303
- this.done = false;
1304
- this.loading = false;
1305
- this.errors = [];
1306
- this.apiKey = apiKey;
1307
- this.authReferrerPolicy = authReferrerPolicy;
1308
- this.channel = channel;
1309
- this.client = client2;
1310
- this.id = id || DEFAULT_ID;
1311
- this.language = language;
1312
- this.libraries = libraries;
1313
- this.mapIds = mapIds;
1314
- this.nonce = nonce;
1315
- this.region = region;
1316
- this.retries = retries;
1317
- this.url = url;
1318
- this.version = version;
1319
- if (Loader.instance) {
1320
- if (!fastDeepEqual(this.options, Loader.instance.options)) {
1321
- throw new Error(`Loader must not be called again with different options. ${JSON.stringify(this.options)} !== ${JSON.stringify(Loader.instance.options)}`);
1322
- }
1323
- return Loader.instance;
1324
- }
1325
- Loader.instance = this;
1326
- }
1327
- get options() {
1328
- return {
1329
- version: this.version,
1330
- apiKey: this.apiKey,
1331
- channel: this.channel,
1332
- client: this.client,
1333
- id: this.id,
1334
- libraries: this.libraries,
1335
- language: this.language,
1336
- region: this.region,
1337
- mapIds: this.mapIds,
1338
- nonce: this.nonce,
1339
- url: this.url,
1340
- authReferrerPolicy: this.authReferrerPolicy
1341
- };
1342
- }
1343
- get status() {
1344
- if (this.errors.length) {
1345
- return LoaderStatus.FAILURE;
1346
- }
1347
- if (this.done) {
1348
- return LoaderStatus.SUCCESS;
1349
- }
1350
- if (this.loading) {
1351
- return LoaderStatus.LOADING;
1352
- }
1353
- return LoaderStatus.INITIALIZED;
1354
- }
1355
- get failed() {
1356
- return this.done && !this.loading && this.errors.length >= this.retries + 1;
1357
- }
1358
- /**
1359
- * CreateUrl returns the Google Maps JavaScript API script url given the [[LoaderOptions]].
1360
- *
1361
- * @ignore
1362
- * @deprecated
1363
- */
1364
- createUrl() {
1365
- let url = this.url;
1366
- url += `?callback=__googleMapsCallback`;
1367
- if (this.apiKey) {
1368
- url += `&key=${this.apiKey}`;
1369
- }
1370
- if (this.channel) {
1371
- url += `&channel=${this.channel}`;
1372
- }
1373
- if (this.client) {
1374
- url += `&client=${this.client}`;
1375
- }
1376
- if (this.libraries.length > 0) {
1377
- url += `&libraries=${this.libraries.join(",")}`;
1378
- }
1379
- if (this.language) {
1380
- url += `&language=${this.language}`;
1381
- }
1382
- if (this.region) {
1383
- url += `&region=${this.region}`;
1384
- }
1385
- if (this.version) {
1386
- url += `&v=${this.version}`;
1387
- }
1388
- if (this.mapIds) {
1389
- url += `&map_ids=${this.mapIds.join(",")}`;
1390
- }
1391
- if (this.authReferrerPolicy) {
1392
- url += `&auth_referrer_policy=${this.authReferrerPolicy}`;
1393
- }
1394
- return url;
1395
- }
1396
- deleteScript() {
1397
- const script = document.getElementById(this.id);
1398
- if (script) {
1399
- script.remove();
1400
- }
1401
- }
1402
- /**
1403
- * Load the Google Maps JavaScript API script and return a Promise.
1404
- * @deprecated, use importLibrary() instead.
1405
- */
1406
- load() {
1407
- return this.loadPromise();
1408
- }
1409
- /**
1410
- * Load the Google Maps JavaScript API script and return a Promise.
1411
- *
1412
- * @ignore
1413
- * @deprecated, use importLibrary() instead.
1414
- */
1415
- loadPromise() {
1416
- return new Promise((resolve, reject) => {
1417
- this.loadCallback((err) => {
1418
- if (!err) {
1419
- resolve(window.google);
1420
- } else {
1421
- reject(err.error);
1422
- }
1423
- });
1424
- });
1425
- }
1426
- importLibrary(name2) {
1427
- this.execute();
1428
- return google.maps.importLibrary(name2);
1429
- }
1430
- /**
1431
- * Load the Google Maps JavaScript API script with a callback.
1432
- * @deprecated, use importLibrary() instead.
1433
- */
1434
- loadCallback(fn) {
1435
- this.callbacks.push(fn);
1436
- this.execute();
1437
- }
1438
- /**
1439
- * Set the script on document.
1440
- */
1441
- setScript() {
1442
- var _a, _b;
1443
- if (document.getElementById(this.id)) {
1444
- this.callback();
1445
- return;
1446
- }
1447
- const params = {
1448
- key: this.apiKey,
1449
- channel: this.channel,
1450
- client: this.client,
1451
- libraries: this.libraries.length && this.libraries,
1452
- v: this.version,
1453
- mapIds: this.mapIds,
1454
- language: this.language,
1455
- region: this.region,
1456
- authReferrerPolicy: this.authReferrerPolicy
1457
- };
1458
- Object.keys(params).forEach(
1459
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1460
- (key) => !params[key] && delete params[key]
1461
- );
1462
- if (!((_b = (_a = window === null || window === void 0 ? void 0 : window.google) === null || _a === void 0 ? void 0 : _a.maps) === null || _b === void 0 ? void 0 : _b.importLibrary)) {
1463
- ((g) => {
1464
- let h, a, k2, p2 = "The Google Maps JavaScript API", c = "google", l2 = "importLibrary", q2 = "__ib__", m2 = document, b = window;
1465
- b = b[c] || (b[c] = {});
1466
- const d = b.maps || (b.maps = {}), r = /* @__PURE__ */ new Set(), e = new URLSearchParams(), u = () => (
1467
- // @ts-ignore
1468
- h || (h = new Promise((f2, n2) => __awaiter(this, void 0, void 0, function* () {
1469
- var _a2;
1470
- yield a = m2.createElement("script");
1471
- a.id = this.id;
1472
- e.set("libraries", [...r] + "");
1473
- for (k2 in g)
1474
- e.set(k2.replace(/[A-Z]/g, (t) => "_" + t[0].toLowerCase()), g[k2]);
1475
- e.set("callback", c + ".maps." + q2);
1476
- a.src = this.url + `?` + e;
1477
- d[q2] = f2;
1478
- a.onerror = () => h = n2(Error(p2 + " could not load."));
1479
- a.nonce = this.nonce || ((_a2 = m2.querySelector("script[nonce]")) === null || _a2 === void 0 ? void 0 : _a2.nonce) || "";
1480
- m2.head.append(a);
1481
- })))
1482
- );
1483
- d[l2] ? console.warn(p2 + " only loads once. Ignoring:", g) : d[l2] = (f2, ...n2) => r.add(f2) && u().then(() => d[l2](f2, ...n2));
1484
- })(params);
1485
- }
1486
- const libraryPromises = this.libraries.map((library) => this.importLibrary(library));
1487
- if (!libraryPromises.length) {
1488
- libraryPromises.push(this.importLibrary("core"));
1489
- }
1490
- Promise.all(libraryPromises).then(() => this.callback(), (error) => {
1491
- const event = new ErrorEvent("error", { error });
1492
- this.loadErrorCallback(event);
1493
- });
1494
- }
1495
- /**
1496
- * Reset the loader state.
1497
- */
1498
- reset() {
1499
- this.deleteScript();
1500
- this.done = false;
1501
- this.loading = false;
1502
- this.errors = [];
1503
- this.onerrorEvent = null;
1504
- }
1505
- resetIfRetryingFailed() {
1506
- if (this.failed) {
1507
- this.reset();
1508
- }
1509
- }
1510
- loadErrorCallback(e) {
1511
- this.errors.push(e);
1512
- if (this.errors.length <= this.retries) {
1513
- const delay = this.errors.length * Math.pow(2, this.errors.length);
1514
- console.error(`Failed to load Google Maps script, retrying in ${delay} ms.`);
1515
- setTimeout(() => {
1516
- this.deleteScript();
1517
- this.setScript();
1518
- }, delay);
1519
- } else {
1520
- this.onerrorEvent = e;
1521
- this.callback();
1522
- }
1523
- }
1524
- callback() {
1525
- this.done = true;
1526
- this.loading = false;
1527
- this.callbacks.forEach((cb) => {
1528
- cb(this.onerrorEvent);
1529
- });
1530
- this.callbacks = [];
1531
- }
1532
- execute() {
1533
- this.resetIfRetryingFailed();
1534
- if (this.done) {
1535
- this.callback();
1536
- } else {
1537
- if (window.google && window.google.maps && window.google.maps.version) {
1538
- console.warn("Google Maps already loaded outside @googlemaps/js-api-loader.This may result in undesirable behavior as options and script parameters may not match.");
1539
- this.callback();
1540
- return;
1541
- }
1542
- if (this.loading)
1543
- ;
1544
- else {
1545
- this.loading = true;
1546
- this.setScript();
1547
- }
1548
- }
1549
- }
1550
- }
1551
- const Search = (props) => {
1552
- const { toCenter, mapRef } = props;
1553
- const { t } = useMapTranslation();
1554
- const placeSearchRef = React.useRef();
1555
- const [options, setOptions] = React.useState([]);
1556
- React.useEffect(() => {
1557
- google.maps.importLibrary("places").then((places) => {
1558
- placeSearchRef.current = new places.AutocompleteService();
1559
- }).catch(() => {
1560
- antd.message.error("Please configure the Google API Key correctly");
1561
- });
1562
- }, [mapRef]);
1563
- const { run: onSearch } = ahooks.useDebounceFn(
1564
- (keyword) => {
1565
- if (!placeSearchRef.current) {
1566
- return;
1567
- }
1568
- placeSearchRef.current.getPlacePredictions(
1569
- {
1570
- input: keyword || " "
1571
- },
1572
- (result, status) => {
1573
- if (status === google.maps.places.PlacesServiceStatus.OK) {
1574
- setOptions(
1575
- result.map((item) => {
1576
- const structured = item.structured_formatting;
1577
- return {
1578
- ...item,
1579
- label: `${structured.main_text}${structured.secondary_text ? " " + structured.secondary_text : ""}`,
1580
- value: item.place_id
1581
- };
1582
- })
1583
- );
1584
- } else {
1585
- setOptions([]);
1586
- return;
1587
- }
1588
- }
1589
- );
1590
- },
1591
- {
1592
- wait: 300
1593
- }
1594
- );
1595
- const onSelect = (value) => {
1596
- const place = options.find((o) => {
1597
- return o.value === value;
1598
- });
1599
- const service = new google.maps.places.PlacesService(mapRef.current);
1600
- service.getDetails(
1601
- {
1602
- placeId: place.place_id,
1603
- fields: ["geometry"]
1604
- },
1605
- (result, status) => {
1606
- if (status === google.maps.places.PlacesServiceStatus.OK) {
1607
- toCenter(result.geometry.location);
1608
- }
1609
- }
1610
- );
1611
- };
1612
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
1613
- "div",
1614
- {
1615
- className: client.css`
40
+ `,children:u&&!((N=p.current)!=null&&N.errMessage)?r.jsxs(x.Space,{direction:"vertical",children:[r.jsx(x.Button,{style:{color:F?void 0:"#F18b62",borderColor:"currentcolor"},onClick:w=>{w.stopPropagation(),k("")},icon:r.jsx(ee.EnvironmentOutlined,{})}),r.jsx(x.Button,{style:{color:F==="selection"?"#F18b62":void 0,borderColor:"currentcolor"},onClick:w=>{w.stopPropagation(),k("selection")},icon:r.jsx(ee.ExpandOutlined,{})}),F==="selection"?r.jsx(x.Button,{type:"primary",icon:r.jsx(ee.CheckOutlined,{}),title:D("Confirm selection"),onClick:J}):null]}):null}),r.jsx(Re,{record:v,setVisible:K}),r.jsx(Se,_(I({},(H=n==null?void 0:n.uiSchema)==null?void 0:H["x-component-props"]),{ref:te,style:{height:a?"100%":null},zoom:i,disabled:!0,block:!0,overlayCommonOptions:{strokeColor:"#F18b62",fillColor:"#F18b62"}}))]})},Re=e=>{const{setVisible:n,record:t}=e,o=Z.useFieldSchema(),a=d.useMemo(()=>o.reduceProperties((i,l)=>l.name==="drawer"?l:i,null),[o]);return a&&r.jsx(s.ActionContextProvider,{value:{visible:!!t,setVisible:n},children:r.jsx(s.RecordProvider,{record:t,children:r.jsx(Z.RecursionField,{schema:a,name:a.name})})})};function Pe(e){e.dom?e.dom.style.filter="none":e.setOptions&&e.setOptions({strokeColor:"#4e9bff",fillColor:"#4e9bff"})}function et(e){e.dom?e.dom.style.filter="brightness(1.2) contrast(1.2) hue-rotate(180deg)":e.setOptions&&e.setOptions({strokeColor:"#F18b62",fillColor:"#F18b62"})}const ke=({type:e,children:n})=>{const{t}=Q(),[o,a]=G.useBoolean(!1),i=s.useAPIClient(),[l]=x.Form.useForm(),h=he(e);d.useEffect(()=>{h&&(l.setFieldsValue(h),a.toggle())},[h]);const A=d.useMemo(()=>i.resource(we),[i]),S=M=>{A.set(_(I({},M),{type:e})).then(u=>{sessionStorage.removeItem(me(e)),a.toggle(),x.message.success(t("Saved successfully"))}).catch(u=>{x.message.success(t("Saved failed"))})};return r.jsxs(x.Form,{disabled:o,form:l,layout:"vertical",onFinish:S,children:[n,o?r.jsx(x.Button,{disabled:!1,onClick:a.toggle,children:t("Edit")}):r.jsx(x.Form.Item,{children:r.jsx(x.Button,{disabled:!1,type:"primary",htmlType:"submit",children:t("Save")})})]})},tt={amap:()=>{const{t:e}=Q();return r.jsxs(ke,{type:"amap",children:[r.jsx(x.Form.Item,{required:!0,name:"accessKey",label:e("Access key"),children:r.jsx(x.Input,{})}),r.jsx(x.Form.Item,{required:!0,name:"securityJsCode",label:e("securityJsCode or serviceHost"),children:r.jsx(x.Input,{})})]})},google:()=>{const{t:e}=Q();return r.jsx(ke,{type:"google",children:r.jsx(x.Form.Item,{required:!0,name:"accessKey",label:e("Api key"),children:r.jsx(x.Input,{})})})}},ot=Ce.map(e=>_(I({},e),{component:tt[e.value]})),rt=()=>{const e=s.useCompile(),n=re.useLocation(),t=new URLSearchParams(n.search);return r.jsx(x.Card,{bordered:!0,children:r.jsx(x.Tabs,{type:"card",defaultActiveKey:t.get("tab"),children:ot.map(o=>r.jsx(x.Tabs.TabPane,{tab:e(o.label),children:r.jsx(o.component,{type:o.value})},o.value))})})};/*! *****************************************************************************
41
+ Copyright (c) Microsoft Corporation.
42
+
43
+ Permission to use, copy, modify, and/or distribute this software for any
44
+ purpose with or without fee is hereby granted.
45
+
46
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
47
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
48
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
49
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
50
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
51
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
52
+ PERFORMANCE OF THIS SOFTWARE.
53
+ ***************************************************************************** */function nt(e,n,t,o){function a(i){return i instanceof t?i:new t(function(l){l(i)})}return new(t||(t=Promise))(function(i,l){function h(M){try{S(o.next(M))}catch(u){l(u)}}function A(M){try{S(o.throw(M))}catch(u){l(u)}}function S(M){M.done?i(M.value):a(M.value).then(h,A)}S((o=o.apply(e,n||[])).next())})}var st=function e(n,t){if(n===t)return!0;if(n&&t&&typeof n=="object"&&typeof t=="object"){if(n.constructor!==t.constructor)return!1;var o,a,i;if(Array.isArray(n)){if(o=n.length,o!=t.length)return!1;for(a=o;a--!==0;)if(!e(n[a],t[a]))return!1;return!0}if(n.constructor===RegExp)return n.source===t.source&&n.flags===t.flags;if(n.valueOf!==Object.prototype.valueOf)return n.valueOf()===t.valueOf();if(n.toString!==Object.prototype.toString)return n.toString()===t.toString();if(i=Object.keys(n),o=i.length,o!==Object.keys(t).length)return!1;for(a=o;a--!==0;)if(!Object.prototype.hasOwnProperty.call(t,i[a]))return!1;for(a=o;a--!==0;){var l=i[a];if(!e(n[l],t[l]))return!1}return!0}return n!==n&&t!==t};const Oe="__googleMapsScriptId";var se;(function(e){e[e.INITIALIZED=0]="INITIALIZED",e[e.LOADING=1]="LOADING",e[e.SUCCESS=2]="SUCCESS",e[e.FAILURE=3]="FAILURE"})(se||(se={}));class ne{constructor({apiKey:n,authReferrerPolicy:t,channel:o,client:a,id:i=Oe,language:l,libraries:h=[],mapIds:A,nonce:S,region:M,retries:u=3,url:g="https://maps.googleapis.com/maps/api/js",version:p}){if(this.callbacks=[],this.done=!1,this.loading=!1,this.errors=[],this.apiKey=n,this.authReferrerPolicy=t,this.channel=o,this.client=a,this.id=i||Oe,this.language=l,this.libraries=h,this.mapIds=A,this.nonce=S,this.region=M,this.retries=u,this.url=g,this.version=p,ne.instance){if(!st(this.options,ne.instance.options))throw new Error(`Loader must not be called again with different options. ${JSON.stringify(this.options)} !== ${JSON.stringify(ne.instance.options)}`);return ne.instance}ne.instance=this}get options(){return{version:this.version,apiKey:this.apiKey,channel:this.channel,client:this.client,id:this.id,libraries:this.libraries,language:this.language,region:this.region,mapIds:this.mapIds,nonce:this.nonce,url:this.url,authReferrerPolicy:this.authReferrerPolicy}}get status(){return this.errors.length?se.FAILURE:this.done?se.SUCCESS:this.loading?se.LOADING:se.INITIALIZED}get failed(){return this.done&&!this.loading&&this.errors.length>=this.retries+1}createUrl(){let n=this.url;return n+="?callback=__googleMapsCallback",this.apiKey&&(n+=`&key=${this.apiKey}`),this.channel&&(n+=`&channel=${this.channel}`),this.client&&(n+=`&client=${this.client}`),this.libraries.length>0&&(n+=`&libraries=${this.libraries.join(",")}`),this.language&&(n+=`&language=${this.language}`),this.region&&(n+=`&region=${this.region}`),this.version&&(n+=`&v=${this.version}`),this.mapIds&&(n+=`&map_ids=${this.mapIds.join(",")}`),this.authReferrerPolicy&&(n+=`&auth_referrer_policy=${this.authReferrerPolicy}`),n}deleteScript(){const n=document.getElementById(this.id);n&&n.remove()}load(){return this.loadPromise()}loadPromise(){return new Promise((n,t)=>{this.loadCallback(o=>{o?t(o.error):n(window.google)})})}importLibrary(n){return this.execute(),google.maps.importLibrary(n)}loadCallback(n){this.callbacks.push(n),this.execute()}setScript(){var n,t;if(document.getElementById(this.id)){this.callback();return}const o={key:this.apiKey,channel:this.channel,client:this.client,libraries:this.libraries.length&&this.libraries,v:this.version,mapIds:this.mapIds,language:this.language,region:this.region,authReferrerPolicy:this.authReferrerPolicy};Object.keys(o).forEach(i=>!o[i]&&delete o[i]),!((t=(n=window==null?void 0:window.google)===null||n===void 0?void 0:n.maps)===null||t===void 0)&&t.importLibrary||(i=>{let l,h,A,S="The Google Maps JavaScript API",M="google",u="importLibrary",g="__ib__",p=document,m=window;m=m[M]||(m[M]={});const v=m.maps||(m.maps={}),K=new Set,F=new URLSearchParams,k=()=>l||(l=new Promise((D,V)=>nt(this,void 0,void 0,function*(){var B;yield h=p.createElement("script"),h.id=this.id,F.set("libraries",[...K]+"");for(A in i)F.set(A.replace(/[A-Z]/g,E=>"_"+E[0].toLowerCase()),i[A]);F.set("callback",M+".maps."+g),h.src=this.url+"?"+F,v[g]=D,h.onerror=()=>l=V(Error(S+" could not load.")),h.nonce=this.nonce||((B=p.querySelector("script[nonce]"))===null||B===void 0?void 0:B.nonce)||"",p.head.append(h)})));v[u]?console.warn(S+" only loads once. Ignoring:",i):v[u]=(D,...V)=>K.add(D)&&k().then(()=>v[u](D,...V))})(o);const a=this.libraries.map(i=>this.importLibrary(i));a.length||a.push(this.importLibrary("core")),Promise.all(a).then(()=>this.callback(),i=>{const l=new ErrorEvent("error",{error:i});this.loadErrorCallback(l)})}reset(){this.deleteScript(),this.done=!1,this.loading=!1,this.errors=[],this.onerrorEvent=null}resetIfRetryingFailed(){this.failed&&this.reset()}loadErrorCallback(n){if(this.errors.push(n),this.errors.length<=this.retries){const t=this.errors.length*Math.pow(2,this.errors.length);console.error(`Failed to load Google Maps script, retrying in ${t} ms.`),setTimeout(()=>{this.deleteScript(),this.setScript()},t)}else this.onerrorEvent=n,this.callback()}callback(){this.done=!0,this.loading=!1,this.callbacks.forEach(n=>{n(this.onerrorEvent)}),this.callbacks=[]}execute(){if(this.resetIfRetryingFailed(),this.done)this.callback();else{if(window.google&&window.google.maps&&window.google.maps.version){console.warn("Google Maps already loaded outside @googlemaps/js-api-loader.This may result in undesirable behavior as options and script parameters may not match."),this.callback();return}this.loading||(this.loading=!0,this.setScript())}}}const it=e=>{const{toCenter:n,mapRef:t}=e,{t:o}=Q(),a=d.useRef(),[i,l]=d.useState([]);d.useEffect(()=>{google.maps.importLibrary("places").then(S=>{a.current=new S.AutocompleteService}).catch(()=>{x.message.error("Please configure the Google API Key correctly")})},[t]);const{run:h}=G.useDebounceFn(S=>{a.current&&a.current.getPlacePredictions({input:S||" "},(M,u)=>{if(u===google.maps.places.PlacesServiceStatus.OK)l(M.map(g=>{const p=g.structured_formatting;return _(I({},g),{label:`${p.main_text}${p.secondary_text?" "+p.secondary_text:""}`,value:g.place_id})}));else{l([]);return}})},{wait:300}),A=S=>{const M=i.find(g=>g.value===S);new google.maps.places.PlacesService(t.current).getDetails({placeId:M.place_id,fields:["geometry"]},(g,p)=>{p===google.maps.places.PlacesServiceStatus.OK&&n(g.geometry.location)})};return r.jsx("div",{className:s.css`
1616
54
  position: absolute;
1617
55
  top: 10px;
1618
56
  left: 10px;
1619
57
  z-index: 10;
1620
58
  width: calc(100% - 20px);
1621
- `,
1622
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
1623
- antd.Select,
1624
- {
1625
- id: "google-map-search",
1626
- showSearch: true,
1627
- allowClear: true,
1628
- style: {
1629
- background: "rgba(255, 255, 255, 0.8)"
1630
- },
1631
- placeholder: t("Enter keywords to search"),
1632
- filterOption: false,
1633
- onSearch,
1634
- onSelect,
1635
- options
1636
- }
1637
- )
1638
- }
1639
- );
1640
- };
1641
- const getIcon = (url) => {
1642
- return {
1643
- url,
1644
- scaledSize: {
1645
- width: 19,
1646
- height: 32
1647
- },
1648
- labelOrigin: new google.maps.Point(19 / 2, 32 + 10)
1649
- };
1650
- };
1651
- const getCurrentPosition = () => {
1652
- return new Promise((resolve) => {
1653
- const defaultLatLng = () => {
1654
- resolve({ lat: 37.4224764, lng: -122.0842499 });
1655
- };
1656
- if (navigator.geolocation) {
1657
- navigator.geolocation.getCurrentPosition(
1658
- (position) => {
1659
- const { latitude, longitude } = position.coords;
1660
- resolve({ lat: latitude, lng: longitude });
1661
- },
1662
- () => {
1663
- defaultLatLng();
1664
- }
1665
- );
1666
- } else {
1667
- defaultLatLng();
1668
- }
1669
- });
1670
- };
1671
- const getDrawingMode = (type) => {
1672
- if (type === "point") {
1673
- return "marker";
1674
- } else if (type === "lineString") {
1675
- return "polyline";
1676
- }
1677
- return type;
1678
- };
1679
- const methodMapping = {
1680
- point: {
1681
- propertyKey: "position",
1682
- overlay: "Marker"
1683
- },
1684
- polygon: {
1685
- propertyKey: "paths",
1686
- overlay: "Polygon"
1687
- },
1688
- lineString: {
1689
- propertyKey: "path",
1690
- overlay: "Polyline"
1691
- },
1692
- circle: {
1693
- transformOptions(value) {
1694
- return {
1695
- center: new google.maps.LatLng(value[1], value[0]),
1696
- radius: value[2]
1697
- };
1698
- },
1699
- overlay: "Circle"
1700
- }
1701
- };
1702
- const GoogleMapsComponent = React.forwardRef(
1703
- (props, ref) => {
1704
- const { value, onChange, block = false, readonly, disabled = block, zoom = 13, overlayCommonOptions } = props;
1705
- const { accessKey } = useMapConfiguration(props.mapType) || {};
1706
- const { t } = useMapTranslation();
1707
- const { getField } = client.useCollection();
1708
- const fieldSchema = react.useFieldSchema();
1709
- const drawingManagerRef = React.useRef();
1710
- const map = React.useRef();
1711
- const overlayRef = React.useRef();
1712
- const [needUpdateFlag, forceUpdate] = React.useState([]);
1713
- const [errMessage, setErrMessage] = React.useState("");
1714
- const api = client.useAPIClient();
1715
- const { modal } = antd.App.useApp();
1716
- const type = React.useMemo(() => {
1717
- if (props.type)
1718
- return props.type;
1719
- const collectionField = getField(fieldSchema == null ? void 0 : fieldSchema.name);
1720
- return collectionField == null ? void 0 : collectionField.interface;
1721
- }, [props == null ? void 0 : props.type, fieldSchema == null ? void 0 : fieldSchema.name]);
1722
- const drawingMode = React.useRef(getDrawingMode(type));
1723
- const [commonOptions] = React.useState({
1724
- strokeWeight: 5,
1725
- strokeColor: "#4e9bff",
1726
- fillColor: "#4e9bff",
1727
- strokeOpacity: 1,
1728
- editable: !disabled,
1729
- draggable: !disabled,
1730
- ...overlayCommonOptions
1731
- });
1732
- const navigate = reactRouterDom.useNavigate();
1733
- const mapContainerRef = React.useRef();
1734
- const cleanupOverlayListenersRef = React.useRef(/* @__PURE__ */ new Set());
1735
- const onAndOffListenOverlay = ahooks.useMemoizedFn((target) => {
1736
- cleanupOverlayListenersRef.current.forEach((cb) => {
1737
- cleanupOverlayListenersRef.current.delete(cb);
1738
- });
1739
- if ("getPath" in target) {
1740
- const mvcArray = target.getPath();
1741
- ["insert_at", "remove_at", "set_at"].forEach((event) => {
1742
- cleanupOverlayListenersRef.current.add(
1743
- mvcArray.addListener(event, () => {
1744
- onMapChange(target, true);
1745
- }).remove
1746
- );
1747
- });
1748
- } else if (target instanceof google.maps.Circle) {
1749
- ["center_changed", "radius_changed"].forEach((event) => {
1750
- cleanupOverlayListenersRef.current.add(
1751
- target.addListener(event, () => {
1752
- onMapChange(target, true);
1753
- }).remove
1754
- );
1755
- });
1756
- }
1757
- });
1758
- const toRemoveOverlay = ahooks.useMemoizedFn(() => {
1759
- var _a;
1760
- if (overlayRef.current) {
1761
- overlayRef.current.unbindAll();
1762
- overlayRef.current.setMap(null);
1763
- }
1764
- if (type !== "point") {
1765
- (_a = drawingManagerRef.current) == null ? void 0 : _a.setDrawingMode(null);
1766
- }
1767
- });
1768
- const toCenter = ahooks.useMemoizedFn((position) => {
1769
- if (map.current) {
1770
- map.current.setCenter(position);
1771
- map.current.setZoom(zoom);
1772
- }
1773
- });
1774
- const setupOverlay = ahooks.useMemoizedFn((nextOverlay) => {
1775
- toRemoveOverlay();
1776
- onAndOffListenOverlay(nextOverlay);
1777
- overlayRef.current = nextOverlay;
1778
- });
1779
- const setFitView = ahooks.useMemoizedFn((overlays) => {
1780
- const bounds = new google.maps.LatLngBounds();
1781
- overlays.forEach((overlay) => {
1782
- if (overlay instanceof google.maps.Marker) {
1783
- bounds.extend(overlay.getPosition());
1784
- } else if (overlay instanceof google.maps.Polyline || overlay instanceof google.maps.Polygon) {
1785
- const path = overlay.getPath();
1786
- for (let i = 0; i < path.getLength(); i++) {
1787
- bounds.extend(path.getAt(i));
1788
- }
1789
- } else if (overlay instanceof google.maps.Circle) {
1790
- bounds.union(overlay.getBounds());
1791
- }
1792
- });
1793
- map.current.setCenter(bounds.getCenter());
1794
- });
1795
- const onFocusOverlay = () => {
1796
- if (overlayRef.current) {
1797
- setFitView([overlayRef.current]);
1798
- }
1799
- };
1800
- const onMapChange = ahooks.useMemoizedFn((target, onlyChange = false) => {
1801
- let nextValue = null;
1802
- if (type === "point") {
1803
- const { lat, lng } = target.getPosition();
1804
- nextValue = [lng(), lat()];
1805
- } else if (type === "polygon" || type === "lineString") {
1806
- nextValue = target.getPath().getArray().map((item) => [item.lng(), item.lat()]);
1807
- if (nextValue.length < 2) {
1808
- return;
1809
- }
1810
- } else if (type === "circle") {
1811
- const center = target.getCenter();
1812
- const radius = target.getRadius();
1813
- nextValue = [center.lng(), center.lat(), radius];
1814
- }
1815
- if (!onlyChange) {
1816
- setupOverlay(target);
1817
- }
1818
- onChange == null ? void 0 : onChange(nextValue);
1819
- });
1820
- const createDraw = ahooks.useMemoizedFn((onlyCreate = false, additionalOptions) => {
1821
- const currentOptions = {
1822
- ...commonOptions,
1823
- ...additionalOptions,
1824
- map: map.current
1825
- };
1826
- drawingManagerRef.current = new google.maps.drawing.DrawingManager({
1827
- drawingMode: drawingMode.current,
1828
- drawingControl: false,
1829
- markerOptions: { ...currentOptions, icon: getIcon(defaultImage) },
1830
- polygonOptions: currentOptions,
1831
- polylineOptions: currentOptions,
1832
- circleOptions: currentOptions,
1833
- map: map.current
1834
- });
1835
- if (!onlyCreate) {
1836
- drawingManagerRef.current.addListener("overlaycomplete", (event) => {
1837
- const overlay = event.overlay;
1838
- onMapChange(overlay);
1839
- });
1840
- }
1841
- return drawingManagerRef.current;
1842
- });
1843
- const getOverlay = ahooks.useMemoizedFn((t2 = type, v = value, o) => {
1844
- const mapping = methodMapping[t2];
1845
- if (!mapping) {
1846
- return;
1847
- }
1848
- const options = { ...commonOptions, icon: getIcon(defaultImage), ...o };
1849
- if ("transformOptions" in mapping) {
1850
- Object.assign(options, mapping.transformOptions(v));
1851
- } else if ("propertyKey" in mapping) {
1852
- options[mapping.propertyKey] = Array.isArray(v[0]) ? v.map((item) => {
1853
- return new google.maps.LatLng(item[1], item[0]);
1854
- }) : new google.maps.LatLng(v[1], v[0]);
1855
- }
1856
- const overlay = new google.maps[mapping.overlay](options);
1857
- return overlay;
1858
- });
1859
- const setOverlay = ahooks.useMemoizedFn((t2 = type, v = value, o) => {
1860
- if (!map.current)
1861
- return;
1862
- const nextOverlay = getOverlay(t2, v, {
1863
- ...o,
1864
- map: map.current
1865
- });
1866
- return nextOverlay;
1867
- });
1868
- React.useEffect(() => {
1869
- if (!map.current)
1870
- return;
1871
- if (!value || !readonly && overlayRef.current) {
1872
- return;
1873
- }
1874
- const nextOverlay = setOverlay();
1875
- setupOverlay(nextOverlay);
1876
- setFitView([nextOverlay]);
1877
- }, [value, needUpdateFlag, type, disabled, readonly, setOverlay, setFitView, setupOverlay]);
1878
- React.useEffect(() => {
1879
- if (!accessKey || map.current || !mapContainerRef.current)
1880
- return;
1881
- let loader;
1882
- try {
1883
- loader = new Loader({
1884
- apiKey: accessKey,
1885
- version: "weekly",
1886
- language: api.auth.getLocale()
1887
- });
1888
- } catch (err) {
1889
- setErrMessage(t("Load google maps failed, Please check the Api key and refresh the page"));
1890
- return;
1891
- }
1892
- const error = console.error;
1893
- console.error = (err, ...args) => {
1894
- if (err == null ? void 0 : err.includes("InvalidKeyMapError")) {
1895
- setErrMessage(t("Load google maps failed, Please check the Api key and refresh the page"));
1896
- }
1897
- error(err, ...args);
1898
- };
1899
- Promise.all([loader.importLibrary("drawing"), loader.importLibrary("core"), loader.importLibrary("geometry")]).then(async (res) => {
1900
- const center = await getCurrentPosition();
1901
- map.current = new google.maps.Map(mapContainerRef.current, {
1902
- zoom,
1903
- center,
1904
- mapTypeId: google.maps.MapTypeId.ROADMAP,
1905
- zoomControl: false,
1906
- streetViewControl: false,
1907
- panControl: false,
1908
- mapTypeControl: false,
1909
- fullscreenControl: false
1910
- });
1911
- setErrMessage("");
1912
- forceUpdate([]);
1913
- }).catch((err) => {
1914
- if (err instanceof Error) {
1915
- setErrMessage(err.message);
1916
- return;
1917
- }
1918
- });
1919
- return () => {
1920
- var _a, _b;
1921
- (_a = map.current) == null ? void 0 : _a.unbindAll();
1922
- map.current = null;
1923
- (_b = drawingManagerRef.current) == null ? void 0 : _b.unbindAll();
1924
- };
1925
- }, [accessKey, api.auth, type, zoom]);
1926
- React.useEffect(() => {
1927
- if (!map.current || !type || disabled || drawingManagerRef.current)
1928
- return;
1929
- createDraw();
1930
- }, [createDraw, disabled, needUpdateFlag, type]);
1931
- React.useImperativeHandle(ref, () => ({
1932
- setOverlay,
1933
- getOverlay,
1934
- setFitView,
1935
- createDraw,
1936
- map: map.current,
1937
- overlay: overlayRef.current,
1938
- drawingManager: drawingManagerRef.current,
1939
- errMessage
1940
- }));
1941
- const onReset = ahooks.useMemoizedFn(() => {
1942
- const ok = () => {
1943
- toRemoveOverlay();
1944
- drawingManagerRef.current.setDrawingMode(drawingMode.current);
1945
- onChange == null ? void 0 : onChange(null);
1946
- };
1947
- modal.confirm({
1948
- title: t("Clear the canvas"),
1949
- content: t("Are you sure to clear the canvas?"),
1950
- okText: t("Confirm"),
1951
- cancelText: t("Cancel"),
1952
- getContainer: () => mapContainerRef.current,
1953
- onOk() {
1954
- ok();
1955
- }
1956
- });
1957
- });
1958
- if (!accessKey || errMessage) {
1959
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
1960
- antd.Alert,
1961
- {
1962
- action: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Button, { type: "primary", onClick: () => navigate("/admin/settings/map/configuration?tab=google"), children: t("Go to the configuration page") }),
1963
- message: errMessage || t("Please configure the Api key first"),
1964
- type: "error"
1965
- }
1966
- );
1967
- }
1968
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(
1969
- "div",
1970
- {
1971
- className: client.css`
59
+ `,children:r.jsx(x.Select,{id:"google-map-search",showSearch:!0,allowClear:!0,style:{background:"rgba(255, 255, 255, 0.8)"},placeholder:o("Enter keywords to search"),filterOption:!1,onSearch:h,onSelect:A,options:i})})},ie=e=>({url:e,scaledSize:{width:19,height:32},labelOrigin:new google.maps.Point(19/2,32+10)}),at=()=>new Promise(e=>{const n=()=>{e({lat:37.4224764,lng:-122.0842499})};navigator.geolocation?navigator.geolocation.getCurrentPosition(t=>{const{latitude:o,longitude:a}=t.coords;e({lat:o,lng:a})},()=>{n()}):n()}),lt=e=>e==="point"?"marker":e==="lineString"?"polyline":e,ct={point:{propertyKey:"position",overlay:"Marker"},polygon:{propertyKey:"paths",overlay:"Polygon"},lineString:{propertyKey:"path",overlay:"Polyline"},circle:{transformOptions(e){return{center:new google.maps.LatLng(e[1],e[0]),radius:e[2]}},overlay:"Circle"}},Fe=d.forwardRef((e,n)=>{const{value:t,onChange:o,block:a=!1,readonly:i,disabled:l=a,zoom:h=13,overlayCommonOptions:A}=e,{accessKey:S}=he(e.mapType)||{},{t:M}=Q(),{getField:u}=s.useCollection(),g=Z.useFieldSchema(),p=d.useRef(),m=d.useRef(),v=d.useRef(),[K,F]=d.useState([]),[k,D]=d.useState(""),V=s.useAPIClient(),{modal:B}=x.App.useApp(),E=d.useMemo(()=>{if(e.type)return e.type;const c=u(g==null?void 0:g.name);return c==null?void 0:c.interface},[e==null?void 0:e.type,g==null?void 0:g.name]),T=d.useRef(lt(E)),[W]=d.useState(I({strokeWeight:5,strokeColor:"#4e9bff",fillColor:"#4e9bff",strokeOpacity:1,editable:!l,draggable:!l},A)),q=re.useNavigate(),$=d.useRef(),J=d.useRef(new Set),te=G.useMemoizedFn(c=>{if(J.current.forEach(f=>{J.current.delete(f)}),"getPath"in c){const f=c.getPath();["insert_at","remove_at","set_at"].forEach(y=>{J.current.add(f.addListener(y,()=>{z(c,!0)}).remove)})}else c instanceof google.maps.Circle&&["center_changed","radius_changed"].forEach(f=>{J.current.add(c.addListener(f,()=>{z(c,!0)}).remove)})}),P=G.useMemoizedFn(()=>{var c;v.current&&(v.current.unbindAll(),v.current.setMap(null)),E!=="point"&&((c=p.current)==null||c.setDrawingMode(null))}),X=G.useMemoizedFn(c=>{m.current&&(m.current.setCenter(c),m.current.setZoom(h))}),N=G.useMemoizedFn(c=>{P(),te(c),v.current=c}),H=G.useMemoizedFn(c=>{const f=new google.maps.LatLngBounds;c.forEach(y=>{if(y instanceof google.maps.Marker)f.extend(y.getPosition());else if(y instanceof google.maps.Polyline||y instanceof google.maps.Polygon){const C=y.getPath();for(let U=0;U<C.getLength();U++)f.extend(C.getAt(U))}else y instanceof google.maps.Circle&&f.union(y.getBounds())}),m.current.setCenter(f.getCenter())}),w=()=>{v.current&&H([v.current])},z=G.useMemoizedFn((c,f=!1)=>{let y=null;if(E==="point"){const{lat:C,lng:U}=c.getPosition();y=[U(),C()]}else if(E==="polygon"||E==="lineString"){if(y=c.getPath().getArray().map(C=>[C.lng(),C.lat()]),y.length<2)return}else if(E==="circle"){const C=c.getCenter(),U=c.getRadius();y=[C.lng(),C.lat(),U]}f||N(c),o==null||o(y)}),b=G.useMemoizedFn((c=!1,f)=>{const y=_(I(I({},W),f),{map:m.current});return p.current=new google.maps.drawing.DrawingManager({drawingMode:T.current,drawingControl:!1,markerOptions:_(I({},y),{icon:ie(ae)}),polygonOptions:y,polylineOptions:y,circleOptions:y,map:m.current}),c||p.current.addListener("overlaycomplete",C=>{const U=C.overlay;z(U)}),p.current}),L=G.useMemoizedFn((c=E,f=t,y)=>{const C=ct[c];if(!C)return;const U=I(_(I({},W),{icon:ie(ae)}),y);return"transformOptions"in C?Object.assign(U,C.transformOptions(f)):"propertyKey"in C&&(U[C.propertyKey]=Array.isArray(f[0])?f.map(oe=>new google.maps.LatLng(oe[1],oe[0])):new google.maps.LatLng(f[1],f[0])),new google.maps[C.overlay](U)}),Y=G.useMemoizedFn((c=E,f=t,y)=>m.current?L(c,f,_(I({},y),{map:m.current})):void 0);d.useEffect(()=>{if(!m.current||!t||!i&&v.current)return;const c=Y();N(c),H([c])},[t,K,E,l,i,Y,H,N]),d.useEffect(()=>{if(!S||m.current||!$.current)return;let c;try{c=new ne({apiKey:S,version:"weekly",language:V.auth.getLocale()})}catch(y){D(M("Load google maps failed, Please check the Api key and refresh the page"));return}const f=console.error;return console.error=(y,...C)=>{y!=null&&y.includes("InvalidKeyMapError")&&D(M("Load google maps failed, Please check the Api key and refresh the page")),f(y,...C)},Promise.all([c.importLibrary("drawing"),c.importLibrary("core"),c.importLibrary("geometry")]).then(y=>fe(this,null,function*(){const C=yield at();m.current=new google.maps.Map($.current,{zoom:h,center:C,mapTypeId:google.maps.MapTypeId.ROADMAP,zoomControl:!1,streetViewControl:!1,panControl:!1,mapTypeControl:!1,fullscreenControl:!1}),D(""),F([])})).catch(y=>{if(y instanceof Error){D(y.message);return}}),()=>{var y,C;(y=m.current)==null||y.unbindAll(),m.current=null,(C=p.current)==null||C.unbindAll()}},[S,V.auth,E,h]),d.useEffect(()=>{!m.current||!E||l||p.current||b()},[b,l,K,E]),d.useImperativeHandle(n,()=>({setOverlay:Y,getOverlay:L,setFitView:H,createDraw:b,map:m.current,overlay:v.current,drawingManager:p.current,errMessage:k}));const j=G.useMemoizedFn(()=>{const c=()=>{P(),p.current.setDrawingMode(T.current),o==null||o(null)};B.confirm({title:M("Clear the canvas"),content:M("Are you sure to clear the canvas?"),okText:M("Confirm"),cancelText:M("Cancel"),getContainer:()=>$.current,onOk(){c()}})});return!S||k?r.jsx(x.Alert,{action:r.jsx(x.Button,{type:"primary",onClick:()=>q("/admin/settings/map/configuration?tab=google"),children:M("Go to the configuration page")}),message:k||M("Please configure the Api key first"),type:"error"}):r.jsxs("div",{className:s.css`
1972
60
  position: relative;
1973
61
  height: 500px;
1974
- `,
1975
- children: [
1976
- !map.current && /* @__PURE__ */ jsxRuntimeExports.jsx(
1977
- "div",
1978
- {
1979
- className: client.css`
62
+ `,children:[!m.current&&r.jsx("div",{className:s.css`
1980
63
  position: absolute;
1981
64
  inset: 0;
1982
65
  display: flex;
1983
66
  align-items: center;
1984
67
  justify-content: center;
1985
- `,
1986
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(antd.Spin, {})
1987
- }
1988
- ),
1989
- !disabled ? /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
1990
- map.current && /* @__PURE__ */ jsxRuntimeExports.jsx(Search, { toCenter, mapRef: map }),
1991
- /* @__PURE__ */ jsxRuntimeExports.jsx(
1992
- "div",
1993
- {
1994
- className: client.css`
68
+ `,children:r.jsx(x.Spin,{})}),l?null:r.jsxs(r.Fragment,{children:[m.current&&r.jsx(it,{toCenter:X,mapRef:m}),r.jsx("div",{className:s.css`
1995
69
  position: absolute;
1996
70
  bottom: 80px;
1997
71
  right: 20px;
1998
72
  z-index: 10;
1999
- `,
2000
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
2001
- antd.Button,
2002
- {
2003
- onClick: onFocusOverlay,
2004
- disabled: !overlayRef.current,
2005
- type: "primary",
2006
- shape: "round",
2007
- size: "large",
2008
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.SyncOutlined, {})
2009
- }
2010
- )
2011
- }
2012
- ),
2013
- type === "lineString" || type === "polygon" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
2014
- "div",
2015
- {
2016
- className: client.css`
73
+ `,children:r.jsx(x.Button,{onClick:w,disabled:!v.current,type:"primary",shape:"round",size:"large",icon:r.jsx(ee.SyncOutlined,{})})}),E==="lineString"||E==="polygon"?r.jsx("div",{className:s.css`
2017
74
  position: absolute;
2018
75
  bottom: 20px;
2019
76
  left: 10px;
2020
77
  z-index: 2;
2021
78
  pointer-events: none;
2022
- `,
2023
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
2024
- antd.Alert,
2025
- {
2026
- message: t("Click to select the starting point and double-click to end the drawing"),
2027
- type: "info"
2028
- }
2029
- )
2030
- }
2031
- ) : null,
2032
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2033
- "div",
2034
- {
2035
- className: client.css`
79
+ `,children:r.jsx(x.Alert,{message:M("Click to select the starting point and double-click to end the drawing"),type:"info"})}):null,r.jsx("div",{className:s.css`
2036
80
  position: absolute;
2037
81
  bottom: 20px;
2038
82
  right: 20px;
2039
83
  z-index: 2;
2040
- `,
2041
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(
2042
- antd.Button,
2043
- {
2044
- disabled: !value,
2045
- style: {
2046
- height: "40px"
2047
- },
2048
- onClick: onReset,
2049
- type: "primary",
2050
- danger: true,
2051
- children: t("Clear")
2052
- }
2053
- )
2054
- }
2055
- )
2056
- ] }) : null,
2057
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2058
- "div",
2059
- {
2060
- ref: mapContainerRef,
2061
- className: client.css`
84
+ `,children:r.jsx(x.Button,{disabled:!t,style:{height:"40px"},onClick:j,type:"primary",danger:!0,children:M("Clear")})})]}),r.jsx("div",{ref:$,className:s.css`
2062
85
  width: 100%;
2063
86
  height: 100%;
2064
- `,
2065
- style: props == null ? void 0 : props.style
2066
- }
2067
- )
2068
- ]
2069
- }
2070
- );
2071
- }
2072
- );
2073
- const OVERLAY_KEY = "google-maps-overlay-id";
2074
- const OVERLAY_SELECtED = "google-maps-overlay-selected";
2075
- const labelClass = client.css`
87
+ `,style:e==null?void 0:e.style})]})}),ce="google-maps-overlay-id",Ee="google-maps-overlay-selected",ut=s.css`
2076
88
  margin-top: 6px;
2077
89
  padding: 2px 4px;
2078
90
  background: #fff;
2079
91
  border: 1px solid #0000f5;
2080
- `;
2081
- const GoogleMapsBlock = (props) => {
2082
- const { collectionField, fieldNames, dataSource, fixedBlock, zoom, setSelectedRecordKeys } = client.useProps(props);
2083
- const { getPrimaryKey } = client.useCollection();
2084
- const primaryKey = getPrimaryKey();
2085
- const { marker: markerName = "id" } = fieldNames;
2086
- const [isMapInitialization, setIsMapInitialization] = React.useState(false);
2087
- const mapRef = React.useRef();
2088
- const [record, setRecord] = React.useState();
2089
- const [selectingMode, setSelecting] = React.useState("");
2090
- const { t } = useMapTranslation();
2091
- const compile = client.useCompile();
2092
- const { isConnected, doFilter } = client.useFilterAPI();
2093
- const [, setPrevSelected] = React.useState(null);
2094
- const selectingModeRef = React.useRef(selectingMode);
2095
- const selectionOverlayRef = React.useRef(null);
2096
- const overlaysRef = React.useRef([]);
2097
- selectingModeRef.current = selectingMode;
2098
- const { getCollectionJoinField } = client.useCollectionManager();
2099
- const setOverlayOptions = (overlay, state) => {
2100
- const selected = typeof state !== "undefined" ? !state : overlay.get(OVERLAY_SELECtED);
2101
- overlay.set(OVERLAY_SELECtED, !selected);
2102
- overlay.setOptions({
2103
- ...selected ? {
2104
- icon: getIcon(defaultImage),
2105
- strokeColor: "#4e9bff",
2106
- fillColor: "#4e9bff"
2107
- } : {
2108
- icon: getIcon(selectedImage),
2109
- strokeColor: "#F18b62",
2110
- fillColor: "#F18b62"
2111
- }
2112
- });
2113
- };
2114
- React.useEffect(() => {
2115
- var _a, _b, _c, _d;
2116
- if (selectingMode !== "selection") {
2117
- return;
2118
- }
2119
- if (mapRef.current && !((_a = mapRef.current) == null ? void 0 : _a.drawingManager)) {
2120
- mapRef.current.drawingManager = (_b = mapRef.current) == null ? void 0 : _b.createDraw(true, {
2121
- editable: true,
2122
- draggable: true
2123
- });
2124
- }
2125
- const listenerSet = /* @__PURE__ */ new Set();
2126
- (_c = mapRef.current) == null ? void 0 : _c.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
2127
- (_d = mapRef.current) == null ? void 0 : _d.drawingManager.addListener("overlaycomplete", (event) => {
2128
- var _a2;
2129
- const polygon2 = event.overlay;
2130
- (_a2 = mapRef.current) == null ? void 0 : _a2.drawingManager.setDrawingMode(null);
2131
- selectionOverlayRef.current = polygon2;
2132
- const path = polygon2.getPath();
2133
- ["insert_at", "remove_at", "set_at"].forEach((key) => {
2134
- listenerSet.add(path.addListener(key, () => {
2135
- }).remove);
2136
- });
2137
- });
2138
- return () => {
2139
- var _a2, _b2, _c2, _d2;
2140
- listenerSet.forEach((i) => {
2141
- i();
2142
- });
2143
- if (!mapRef.current)
2144
- return;
2145
- (_a2 = selectionOverlayRef.current) == null ? void 0 : _a2.unbindAll();
2146
- (_b2 = selectionOverlayRef.current) == null ? void 0 : _b2.setMap(null);
2147
- selectionOverlayRef.current = null;
2148
- (_c2 = mapRef.current) == null ? void 0 : _c2.drawingManager.setDrawingMode(null);
2149
- (_d2 = mapRef.current) == null ? void 0 : _d2.drawingManager.unbindAll();
2150
- };
2151
- }, [selectingMode]);
2152
- React.useEffect(() => {
2153
- if (selectingMode) {
2154
- return () => {
2155
- if (!selectingModeRef.current) {
2156
- overlaysRef.current.forEach((o) => {
2157
- setOverlayOptions(o, false);
2158
- });
2159
- }
2160
- };
2161
- }
2162
- }, [selectingMode]);
2163
- const onSelectingComplete = ahooks.useMemoizedFn(() => {
2164
- var _a;
2165
- const overlay = selectionOverlayRef.current;
2166
- const overlays = overlaysRef.current;
2167
- const poly = google.maps.geometry.poly;
2168
- const selectedOverlays = overlays.filter((o) => {
2169
- if (o === overlay || o.get(OVERLAY_KEY) === void 0)
2170
- return;
2171
- if (o instanceof google.maps.Marker) {
2172
- return poly.containsLocation(o.getPosition(), overlay);
2173
- } else if (o instanceof google.maps.Circle) {
2174
- return poly.containsLocation(o.getCenter(), overlay);
2175
- } else {
2176
- return o.getPath().getArray().some((position) => {
2177
- return poly.containsLocation(position, overlay);
2178
- });
2179
- }
2180
- });
2181
- const ids = selectedOverlays.map((o) => {
2182
- setOverlayOptions(o, true);
2183
- return o.get(OVERLAY_KEY);
2184
- });
2185
- setSelectedRecordKeys((lastIds) => ids.concat(lastIds));
2186
- overlay == null ? void 0 : overlay.unbindAll();
2187
- overlay == null ? void 0 : overlay.setMap(null);
2188
- (_a = mapRef.current) == null ? void 0 : _a.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
2189
- });
2190
- React.useEffect(() => {
2191
- var _a, _b;
2192
- if (!collectionField || !(dataSource == null ? void 0 : dataSource.length) || !((_a = mapRef.current) == null ? void 0 : _a.map))
2193
- return;
2194
- const fieldPaths = Array.isArray(fieldNames == null ? void 0 : fieldNames.field) && (fieldNames == null ? void 0 : fieldNames.field.length) > 1 ? fieldNames == null ? void 0 : fieldNames.field.slice(0, -1) : fieldNames == null ? void 0 : fieldNames.field;
2195
- const cf = getCollectionJoinField([name, ...fieldPaths].flat().join("."));
2196
- const overlays = dataSource.map((item) => {
2197
- const data = getSource(item, fieldNames == null ? void 0 : fieldNames.field, cf == null ? void 0 : cf.interface);
2198
- if (!(data == null ? void 0 : data.length))
2199
- return [];
2200
- return data == null ? void 0 : data.filter(Boolean).map((mapItem) => {
2201
- var _a2;
2202
- if (!data)
2203
- return;
2204
- const overlay = (_a2 = mapRef.current) == null ? void 0 : _a2.setOverlay(collectionField.type, mapItem, {
2205
- strokeColor: "#4e9bff",
2206
- fillColor: "#4e9bff",
2207
- cursor: "pointer",
2208
- label: {
2209
- className: labelClass,
2210
- fontFamily: "inherit",
2211
- fontSize: "13px",
2212
- color: "#333",
2213
- text: (fieldNames == null ? void 0 : fieldNames.marker) ? compile(item[markerName]) : void 0
2214
- }
2215
- });
2216
- overlay == null ? void 0 : overlay.set(OVERLAY_KEY, item[primaryKey]);
2217
- return overlay;
2218
- });
2219
- }).flat().filter(Boolean);
2220
- overlaysRef.current = overlays;
2221
- (_b = mapRef.current) == null ? void 0 : _b.setFitView(overlays);
2222
- const events = overlays.map((o) => {
2223
- const onClick = (event) => {
2224
- const overlay = o;
2225
- const id = overlay.get(OVERLAY_KEY);
2226
- if (!id)
2227
- return;
2228
- const data = dataSource == null ? void 0 : dataSource.find((item) => {
2229
- return id === item[primaryKey];
2230
- });
2231
- if (isConnected) {
2232
- setPrevSelected((prev) => {
2233
- prev && clearSelected(overlay);
2234
- if (prev === o) {
2235
- clearSelected(overlay);
2236
- doFilter(null);
2237
- return null;
2238
- } else {
2239
- selectMarker(overlay);
2240
- doFilter(data[primaryKey], (target) => target.field || primaryKey, "$eq");
2241
- }
2242
- return overlay;
2243
- });
2244
- return;
2245
- }
2246
- if (data) {
2247
- setRecord(data);
2248
- }
2249
- };
2250
- o.addListener("click", onClick);
2251
- return () => o.unbindAll();
2252
- });
2253
- return () => {
2254
- overlays.forEach((ov) => {
2255
- ov.setMap(null);
2256
- ov.unbindAll();
2257
- });
2258
- events.forEach((e) => e());
2259
- };
2260
- }, [dataSource, isMapInitialization, markerName, collectionField.type, isConnected]);
2261
- React.useEffect(() => {
2262
- setTimeout(() => {
2263
- setSelectedRecordKeys([]);
2264
- });
2265
- }, [dataSource]);
2266
- const mapRefCallback = (instance) => {
2267
- mapRef.current = instance;
2268
- setIsMapInitialization(!!(instance == null ? void 0 : instance.map) && !instance.errMessage);
2269
- };
2270
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(
2271
- "div",
2272
- {
2273
- className: client.css`
92
+ `,pt=e=>{const{collectionField:n,fieldNames:t,dataSource:o,fixedBlock:a,zoom:i,setSelectedRecordKeys:l}=s.useProps(e),{getPrimaryKey:h}=s.useCollection(),A=h(),{marker:S="id"}=t,[M,u]=d.useState(!1),g=d.useRef(),[p,m]=d.useState(),[v,K]=d.useState(""),{t:F}=Q(),k=s.useCompile(),{isConnected:D,doFilter:V}=s.useFilterAPI(),[,B]=d.useState(null),E=d.useRef(v),T=d.useRef(null),W=d.useRef([]);E.current=v;const{getCollectionJoinField:q}=s.useCollectionManager(),$=(P,X)=>{const N=typeof X!="undefined"?!X:P.get(Ee);P.set(Ee,!N),P.setOptions(I({},N?{icon:ie(ae),strokeColor:"#4e9bff",fillColor:"#4e9bff"}:{icon:ie(ge),strokeColor:"#F18b62",fillColor:"#F18b62"}))};d.useEffect(()=>{var X,N,H,w;if(v!=="selection")return;g.current&&!((X=g.current)!=null&&X.drawingManager)&&(g.current.drawingManager=(N=g.current)==null?void 0:N.createDraw(!0,{editable:!0,draggable:!0}));const P=new Set;return(H=g.current)==null||H.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON),(w=g.current)==null||w.drawingManager.addListener("overlaycomplete",z=>{var Y;const b=z.overlay;(Y=g.current)==null||Y.drawingManager.setDrawingMode(null),T.current=b;const L=b.getPath();["insert_at","remove_at","set_at"].forEach(j=>{P.add(L.addListener(j,()=>{}).remove)})}),()=>{var z,b,L,Y;P.forEach(j=>{j()}),g.current&&((z=T.current)==null||z.unbindAll(),(b=T.current)==null||b.setMap(null),T.current=null,(L=g.current)==null||L.drawingManager.setDrawingMode(null),(Y=g.current)==null||Y.drawingManager.unbindAll())}},[v]),d.useEffect(()=>{if(v)return()=>{E.current||W.current.forEach(P=>{$(P,!1)})}},[v]);const J=G.useMemoizedFn(()=>{var z;const P=T.current,X=W.current,N=google.maps.geometry.poly,w=X.filter(b=>{if(!(b===P||b.get(ce)===void 0))return b instanceof google.maps.Marker?N.containsLocation(b.getPosition(),P):b instanceof google.maps.Circle?N.containsLocation(b.getCenter(),P):b.getPath().getArray().some(L=>N.containsLocation(L,P))}).map(b=>($(b,!0),b.get(ce)));l(b=>w.concat(b)),P==null||P.unbindAll(),P==null||P.setMap(null),(z=g.current)==null||z.drawingManager.setDrawingMode(google.maps.drawing.OverlayType.POLYGON)});d.useEffect(()=>{var w,z;if(!n||!(o!=null&&o.length)||!((w=g.current)!=null&&w.map))return;const P=Array.isArray(t==null?void 0:t.field)&&(t==null?void 0:t.field.length)>1?t==null?void 0:t.field.slice(0,-1):t==null?void 0:t.field,X=q([name,...P].flat().join(".")),N=o.map(b=>{const L=Ie(b,t==null?void 0:t.field,X==null?void 0:X.interface);return L!=null&&L.length?L==null?void 0:L.filter(Boolean).map(Y=>{var c;if(!L)return;const j=(c=g.current)==null?void 0:c.setOverlay(n.type,Y,{strokeColor:"#4e9bff",fillColor:"#4e9bff",cursor:"pointer",label:{className:ut,fontFamily:"inherit",fontSize:"13px",color:"#333",text:t!=null&&t.marker?k(b[S]):void 0}});return j==null||j.set(ce,b[A]),j}):[]}).flat().filter(Boolean);W.current=N,(z=g.current)==null||z.setFitView(N);const H=N.map(b=>{const L=Y=>{const j=b,c=j.get(ce);if(!c)return;const f=o==null?void 0:o.find(y=>c===y[A]);if(D){B(y=>(y&&ze(j),y===b?(ze(j),V(null),null):(ft(j),V(f[A],C=>C.field||A,"$eq"),j)));return}f&&m(f)};return b.addListener("click",L),()=>b.unbindAll()});return()=>{N.forEach(b=>{b.setMap(null),b.unbindAll()}),H.forEach(b=>b())}},[o,M,S,n.type,D]),d.useEffect(()=>{setTimeout(()=>{l([])})},[o]);const te=P=>{g.current=P,u(!!(P!=null&&P.map)&&!P.errMessage)};return r.jsxs("div",{className:s.css`
2274
93
  position: relative;
2275
94
  height: 100%;
2276
- `,
2277
- children: [
2278
- isMapInitialization && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
2279
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2280
- "div",
2281
- {
2282
- className: client.css`
95
+ `,children:[M&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:s.css`
2283
96
  position: absolute;
2284
97
  left: 10px;
2285
98
  top: 10px;
2286
99
  z-index: 999;
2287
- `,
2288
- children: /* @__PURE__ */ jsxRuntimeExports.jsxs(antd.Space, { direction: "vertical", children: [
2289
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2290
- antd.Button,
2291
- {
2292
- style: {
2293
- color: !selectingMode ? "#F18b62" : void 0,
2294
- borderColor: "currentcolor"
2295
- },
2296
- onClick: (e) => {
2297
- e.stopPropagation();
2298
- setSelecting("");
2299
- },
2300
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.EnvironmentOutlined, {})
2301
- }
2302
- ),
2303
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2304
- antd.Button,
2305
- {
2306
- style: {
2307
- color: selectingMode === "selection" ? "#F18b62" : void 0,
2308
- borderColor: "currentcolor"
2309
- },
2310
- onClick: (e) => {
2311
- e.stopPropagation();
2312
- setSelecting("selection");
2313
- },
2314
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.ExpandOutlined, {})
2315
- }
2316
- ),
2317
- selectingMode === "selection" ? /* @__PURE__ */ jsxRuntimeExports.jsx(
2318
- antd.Button,
2319
- {
2320
- type: "primary",
2321
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.CheckOutlined, {}),
2322
- title: t("Confirm selection"),
2323
- onClick: onSelectingComplete
2324
- }
2325
- ) : null
2326
- ] })
2327
- }
2328
- ),
2329
- /* @__PURE__ */ jsxRuntimeExports.jsx(MapBlockDrawer, { record, setVisible: setRecord })
2330
- ] }),
2331
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2332
- GoogleMapsComponent,
2333
- {
2334
- ...props,
2335
- ref: mapRefCallback,
2336
- style: { height: fixedBlock ? "100%" : null },
2337
- zoom,
2338
- disabled: true,
2339
- block: true,
2340
- overlayCommonOptions: {
2341
- strokeColor: "#F18b62",
2342
- fillColor: "#F18b62"
2343
- }
2344
- }
2345
- )
2346
- ]
2347
- }
2348
- );
2349
- };
2350
- const MapBlockDrawer = (props) => {
2351
- const { setVisible, record } = props;
2352
- const fieldSchema = react.useFieldSchema();
2353
- const schema = React.useMemo(
2354
- () => fieldSchema.reduceProperties((buf, current) => {
2355
- if (current.name === "drawer") {
2356
- return current;
2357
- }
2358
- return buf;
2359
- }, null),
2360
- [fieldSchema]
2361
- );
2362
- return schema && /* @__PURE__ */ jsxRuntimeExports.jsx(client.ActionContextProvider, { value: { visible: !!record, setVisible }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(client.RecordProvider, { record, children: /* @__PURE__ */ jsxRuntimeExports.jsx(react.RecursionField, { schema, name: schema.name }) }) });
2363
- };
2364
- function clearSelected(target) {
2365
- if (target instanceof google.maps.Marker) {
2366
- return target.setIcon(getIcon(defaultImage));
2367
- }
2368
- target.setOptions({
2369
- strokeColor: "#4e9bff",
2370
- fillColor: "#4e9bff"
2371
- });
2372
- }
2373
- function selectMarker(target) {
2374
- if (target instanceof google.maps.Marker) {
2375
- return target.setIcon(getIcon(selectedImage));
2376
- }
2377
- target.setOptions({
2378
- strokeColor: "#F18b62",
2379
- fillColor: "#F18b62"
2380
- });
2381
- }
2382
- const Designer = () => {
2383
- var _a;
2384
- const { getCollectionJoinField } = client.useCollectionManager();
2385
- const { getField } = client.useCollection();
2386
- const { form } = client.useFormBlockContext();
2387
- const field = react.useField();
2388
- const fieldSchema = react.useFieldSchema();
2389
- const { t } = useMapTranslation();
2390
- const { dn, refresh } = client.useDesignable();
2391
- const collectionField = getField(fieldSchema["name"]) || getCollectionJoinField(fieldSchema["x-collection-field"]);
2392
- const originalTitle = (_a = collectionField == null ? void 0 : collectionField.uiSchema) == null ? void 0 : _a.title;
2393
- ({
2394
- title: field.title === originalTitle ? void 0 : field.title
2395
- });
2396
- if (!field.readPretty) {
2397
- field.required;
2398
- }
2399
- let readOnlyMode = "editable";
2400
- if (fieldSchema["x-disabled"] === true) {
2401
- readOnlyMode = "readonly";
2402
- }
2403
- if (fieldSchema["x-read-pretty"] === true) {
2404
- readOnlyMode = "read-pretty";
2405
- }
2406
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(client.GeneralSchemaDesigner, { children: [
2407
- /* @__PURE__ */ jsxRuntimeExports.jsx(client.GeneralSchemaItems, {}),
2408
- form && !(form == null ? void 0 : form.readPretty) && !client.isPatternDisabled(fieldSchema) && /* @__PURE__ */ jsxRuntimeExports.jsx(
2409
- client.SchemaSettings.SelectItem,
2410
- {
2411
- title: t("Pattern"),
2412
- options: [
2413
- { label: t("Editable"), value: "editable" },
2414
- { label: t("Readonly"), value: "readonly" },
2415
- { label: t("Easy-reading"), value: "read-pretty" }
2416
- ],
2417
- value: readOnlyMode,
2418
- onChange: (v) => {
2419
- const schema = {
2420
- ["x-uid"]: fieldSchema["x-uid"]
2421
- };
2422
- switch (v) {
2423
- case "readonly": {
2424
- fieldSchema["x-read-pretty"] = false;
2425
- fieldSchema["x-disabled"] = true;
2426
- schema["x-read-pretty"] = false;
2427
- schema["x-disabled"] = true;
2428
- field.readPretty = false;
2429
- field.disabled = true;
2430
- break;
2431
- }
2432
- case "read-pretty": {
2433
- fieldSchema["x-read-pretty"] = true;
2434
- fieldSchema["x-disabled"] = false;
2435
- schema["x-read-pretty"] = true;
2436
- schema["x-disabled"] = false;
2437
- field.readPretty = true;
2438
- break;
2439
- }
2440
- default: {
2441
- fieldSchema["x-read-pretty"] = false;
2442
- fieldSchema["x-disabled"] = false;
2443
- schema["x-read-pretty"] = false;
2444
- schema["x-disabled"] = false;
2445
- field.readPretty = false;
2446
- field.disabled = false;
2447
- break;
2448
- }
2449
- }
2450
- dn.emit("patch", {
2451
- schema
2452
- });
2453
- dn.refresh();
2454
- }
2455
- },
2456
- "pattern"
2457
- ),
2458
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2459
- client.SchemaSettings.ModalItem,
2460
- {
2461
- title: t("Set default zoom level"),
2462
- schema: {
2463
- type: "object",
2464
- title: t("Set default zoom level"),
2465
- properties: {
2466
- zoom: {
2467
- title: t("Zoom"),
2468
- default: field.componentProps.zoom || 13,
2469
- description: t("The default zoom level of the map"),
2470
- "x-decorator": "FormItem",
2471
- "x-component": "InputNumber",
2472
- "x-component-props": {
2473
- precision: 0
2474
- }
2475
- }
2476
- }
2477
- },
2478
- onSubmit: ({ zoom }) => {
2479
- if (zoom) {
2480
- lodash.set(fieldSchema, "x-component-props.zoom", zoom);
2481
- Object.assign(field.componentProps, fieldSchema["x-component-props"]);
2482
- dn.emit("patch", {
2483
- schema: {
2484
- "x-uid": fieldSchema["x-uid"],
2485
- "x-component-props": field.componentProps
2486
- }
2487
- });
2488
- }
2489
- dn.refresh();
2490
- }
2491
- },
2492
- "map-zoom"
2493
- ),
2494
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2495
- client.SchemaSettings.Remove,
2496
- {
2497
- removeParentsIfNoChildren: true,
2498
- confirm: {
2499
- title: t("Delete field")
2500
- },
2501
- breakRemoveOn: {
2502
- "x-component": "Grid"
2503
- }
2504
- },
2505
- "remove"
2506
- )
2507
- ] });
2508
- };
2509
- const MapComponents = {
2510
- amap: AMapComponent,
2511
- google: GoogleMapsComponent
2512
- };
2513
- const MapComponent = React.forwardRef((props, ref) => {
2514
- const { t } = useMapTranslation();
2515
- const { mapType } = props;
2516
- const Component = React.useMemo(() => {
2517
- return MapComponents[mapType];
2518
- }, [mapType]);
2519
- if (!Component) {
2520
- return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: t(`The ${mapType} cannot found`) });
2521
- }
2522
- return /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ref, ...props });
2523
- });
2524
- const ReadPretty = (props) => {
2525
- var _a;
2526
- const { value } = props;
2527
- const fieldSchema = react.useFieldSchema();
2528
- const { getField } = client.useCollection();
2529
- const collectionField = getField(fieldSchema.name);
2530
- const mapType = props.mapType || ((_a = collectionField == null ? void 0 : collectionField.uiSchema["x-component-props"]) == null ? void 0 : _a.mapType);
2531
- const form = react.useForm();
2532
- client.useFieldTitle();
2533
- if (!form.readPretty) {
2534
- return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(client.EllipsisWithTooltip, { ellipsis: true, children: value == null ? void 0 : value.map((item) => Array.isArray(item) ? `(${item.join(",")})` : item).join(",") }) });
2535
- }
2536
- return /* @__PURE__ */ jsxRuntimeExports.jsx(MapComponent, { readonly: true, mapType, ...props });
2537
- };
2538
- const InternalMap = react.connect((props) => {
2539
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
2540
- "div",
2541
- {
2542
- className: client.css`
100
+ `,children:r.jsxs(x.Space,{direction:"vertical",children:[r.jsx(x.Button,{style:{color:v?void 0:"#F18b62",borderColor:"currentcolor"},onClick:P=>{P.stopPropagation(),K("")},icon:r.jsx(ee.EnvironmentOutlined,{})}),r.jsx(x.Button,{style:{color:v==="selection"?"#F18b62":void 0,borderColor:"currentcolor"},onClick:P=>{P.stopPropagation(),K("selection")},icon:r.jsx(ee.ExpandOutlined,{})}),v==="selection"?r.jsx(x.Button,{type:"primary",icon:r.jsx(ee.CheckOutlined,{}),title:F("Confirm selection"),onClick:J}):null]})}),r.jsx(dt,{record:p,setVisible:m})]}),r.jsx(Fe,_(I({},e),{ref:te,style:{height:a?"100%":null},zoom:i,disabled:!0,block:!0,overlayCommonOptions:{strokeColor:"#F18b62",fillColor:"#F18b62"}}))]})},dt=e=>{const{setVisible:n,record:t}=e,o=Z.useFieldSchema(),a=d.useMemo(()=>o.reduceProperties((i,l)=>l.name==="drawer"?l:i,null),[o]);return a&&r.jsx(s.ActionContextProvider,{value:{visible:!!t,setVisible:n},children:r.jsx(s.RecordProvider,{record:t,children:r.jsx(Z.RecursionField,{schema:a,name:a.name})})})};function ze(e){if(e instanceof google.maps.Marker)return e.setIcon(ie(ae));e.setOptions({strokeColor:"#4e9bff",fillColor:"#4e9bff"})}function ft(e){if(e instanceof google.maps.Marker)return e.setIcon(ie(ge));e.setOptions({strokeColor:"#F18b62",fillColor:"#F18b62"})}const gt=()=>{var u;const{getCollectionJoinField:e}=s.useCollectionManager(),{getField:n}=s.useCollection(),{form:t}=s.useFormBlockContext(),o=Z.useField(),a=Z.useFieldSchema(),{t:i}=Q(),{dn:l,refresh:h}=s.useDesignable(),A=n(a.name)||e(a["x-collection-field"]),S=(u=A==null?void 0:A.uiSchema)==null?void 0:u.title;o.title===S||o.title,o.readPretty||o.required;let M="editable";return a["x-disabled"]===!0&&(M="readonly"),a["x-read-pretty"]===!0&&(M="read-pretty"),r.jsxs(s.GeneralSchemaDesigner,{children:[r.jsx(s.GeneralSchemaItems,{}),t&&!(t!=null&&t.readPretty)&&!s.isPatternDisabled(a)&&r.jsx(s.SchemaSettings.SelectItem,{title:i("Pattern"),options:[{label:i("Editable"),value:"editable"},{label:i("Readonly"),value:"readonly"},{label:i("Easy-reading"),value:"read-pretty"}],value:M,onChange:g=>{const p={"x-uid":a["x-uid"]};switch(g){case"readonly":{a["x-read-pretty"]=!1,a["x-disabled"]=!0,p["x-read-pretty"]=!1,p["x-disabled"]=!0,o.readPretty=!1,o.disabled=!0;break}case"read-pretty":{a["x-read-pretty"]=!0,a["x-disabled"]=!1,p["x-read-pretty"]=!0,p["x-disabled"]=!1,o.readPretty=!0;break}default:{a["x-read-pretty"]=!1,a["x-disabled"]=!1,p["x-read-pretty"]=!1,p["x-disabled"]=!1,o.readPretty=!1,o.disabled=!1;break}}l.emit("patch",{schema:p}),l.refresh()}},"pattern"),r.jsx(s.SchemaSettings.ModalItem,{title:i("Set default zoom level"),schema:{type:"object",title:i("Set default zoom level"),properties:{zoom:{title:i("Zoom"),default:o.componentProps.zoom||13,description:i("The default zoom level of the map"),"x-decorator":"FormItem","x-component":"InputNumber","x-component-props":{precision:0}}}},onSubmit:({zoom:g})=>{g&&(Me.set(a,"x-component-props.zoom",g),Object.assign(o.componentProps,a["x-component-props"]),l.emit("patch",{schema:{"x-uid":a["x-uid"],"x-component-props":o.componentProps}})),l.refresh()}},"map-zoom"),r.jsx(s.SchemaSettings.Remove,{removeParentsIfNoChildren:!0,confirm:{title:i("Delete field")},breakRemoveOn:{"x-component":"Grid"}},"remove")]})},mt={amap:Se,google:Fe},Le=d.forwardRef((e,n)=>{const{t}=Q(),{mapType:o}=e,a=d.useMemo(()=>mt[o],[o]);return a?r.jsx(a,I({ref:n},e)):r.jsx("div",{children:t(`The ${o} cannot found`)})}),ht=e=>{var h;const{value:n}=e,t=Z.useFieldSchema(),{getField:o}=s.useCollection(),a=o(t.name),i=e.mapType||((h=a==null?void 0:a.uiSchema["x-component-props"])==null?void 0:h.mapType),l=Z.useForm();return s.useFieldTitle(),l.readPretty?r.jsx(Le,I({readonly:!0,mapType:i},e)):r.jsx("div",{children:r.jsx(s.EllipsisWithTooltip,{ellipsis:!0,children:n==null?void 0:n.map(A=>Array.isArray(A)?`(${A.join(",")})`:A).join(",")})})},Be=Z.connect(e=>r.jsx("div",{className:s.css`
2543
101
  height: 100%;
2544
102
  border: 1px solid transparent;
2545
103
  .ant-formily-item-error & {
2546
104
  border: 1px solid #ff4d4f;
2547
105
  }
2548
- `,
2549
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(MapComponent, { ...props })
2550
- }
2551
- );
2552
- }, react.mapReadPretty(ReadPretty));
2553
- const Map = InternalMap;
2554
- Map.Designer = Designer;
2555
- const MapBlocks = {
2556
- amap: AMapBlock,
2557
- google: GoogleMapsBlock
2558
- };
2559
- const MapBlockComponent = (props) => {
2560
- const { t } = useMapTranslation();
2561
- const { mapType } = props;
2562
- const Component = React.useMemo(() => {
2563
- return MapBlocks[mapType];
2564
- }, [mapType]);
2565
- if (!Component) {
2566
- return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: t(`The ${mapType} cannot found`) });
2567
- }
2568
- return /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props });
2569
- };
2570
- const MapBlock = (props) => {
2571
- var _a;
2572
- const { fieldNames } = client.useProps(props);
2573
- const { getCollectionJoinField } = client.useCollectionManager();
2574
- const { name: name2 } = client.useCollection();
2575
- const collectionField = React.useMemo(() => {
2576
- return getCollectionJoinField([name2, fieldNames == null ? void 0 : fieldNames.field].flat().join("."));
2577
- }, [name2, fieldNames == null ? void 0 : fieldNames.field]);
2578
- const fieldComponentProps = (_a = collectionField == null ? void 0 : collectionField.uiSchema) == null ? void 0 : _a["x-component-props"];
2579
- return /* @__PURE__ */ jsxRuntimeExports.jsx(MapBlockComponent, { ...fieldComponentProps, ...props, collectionField });
2580
- };
2581
- const MapBlockContext = React.createContext({});
2582
- const InternalMapBlockProvider = (props) => {
2583
- var _a;
2584
- const { fieldNames } = props;
2585
- const fieldSchema = react.useFieldSchema();
2586
- const field = react.useField();
2587
- const { resource, service } = client.useBlockRequestContext();
2588
- const [selectedRecordKeys, setSelectedRecordKeys] = React.useState([]);
2589
- return /* @__PURE__ */ jsxRuntimeExports.jsx(client.FixedBlockWrapper, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaComponentOptions, { scope: { selectedRecordKeys }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
2590
- MapBlockContext.Provider,
2591
- {
2592
- value: {
2593
- field,
2594
- service,
2595
- resource,
2596
- fieldNames,
2597
- fixedBlock: (_a = fieldSchema == null ? void 0 : fieldSchema["x-decorator-props"]) == null ? void 0 : _a.fixedBlock,
2598
- selectedRecordKeys,
2599
- setSelectedRecordKeys
2600
- },
2601
- children: props.children
2602
- }
2603
- ) }) });
2604
- };
2605
- const MapBlockProvider = (props) => {
2606
- const { params, fieldNames } = props;
2607
- const appends = params.appends || [];
2608
- const { field } = fieldNames || {};
2609
- if (Array.isArray(field) && field.length > 1) {
2610
- appends.push(field[0]);
2611
- }
2612
- return /* @__PURE__ */ jsxRuntimeExports.jsx(client.BlockProvider, { ...props, params: { ...params, appends, paginate: false }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(InternalMapBlockProvider, { ...props }) });
2613
- };
2614
- const useMapBlockContext = () => {
2615
- return React.useContext(MapBlockContext);
2616
- };
2617
- const useMapBlockProps = () => {
2618
- var _a, _b, _c, _d;
2619
- const ctx = useMapBlockContext();
2620
- return {
2621
- ...ctx,
2622
- dataSource: (_b = (_a = ctx == null ? void 0 : ctx.service) == null ? void 0 : _a.data) == null ? void 0 : _b.data,
2623
- zoom: ((_d = (_c = ctx == null ? void 0 : ctx.field) == null ? void 0 : _c.componentProps) == null ? void 0 : _d.zoom) || 13
2624
- };
2625
- };
2626
- const createMapBlockSchema = (options) => {
2627
- const { collection, resource, fieldNames, ...others } = options;
2628
- const schema = {
2629
- type: "void",
2630
- "x-acl-action": `${resource || collection}:list`,
2631
- "x-decorator": "MapBlockProvider",
2632
- "x-decorator-props": {
2633
- collection,
2634
- resource: resource || collection,
2635
- action: "list",
2636
- fieldNames,
2637
- params: {
2638
- paginate: false
2639
- },
2640
- ...others
2641
- },
2642
- "x-designer": "MapBlockDesigner",
2643
- "x-component": "CardItem",
2644
- // 保存当前筛选区块所能过滤的数据区块
2645
- "x-filter-targets": [],
2646
- properties: {
2647
- actions: {
2648
- type: "void",
2649
- "x-initializer": "MapActionInitializers",
2650
- "x-component": "ActionBar",
2651
- "x-component-props": {
2652
- style: {
2653
- marginBottom: 16
2654
- }
2655
- },
2656
- properties: {}
2657
- },
2658
- [shared.uid()]: {
2659
- type: "void",
2660
- "x-component": "MapBlock",
2661
- "x-component-props": {
2662
- useProps: "{{ useMapBlockProps }}"
2663
- },
2664
- properties: {
2665
- drawer: {
2666
- type: "void",
2667
- "x-component": "Action.Drawer",
2668
- "x-component-props": {
2669
- className: "nb-action-popup"
2670
- },
2671
- title: '{{ t("View record") }}',
2672
- properties: {
2673
- tabs: {
2674
- type: "void",
2675
- "x-component": "Tabs",
2676
- "x-component-props": {},
2677
- "x-initializer": "TabPaneInitializers",
2678
- properties: {
2679
- tab1: {
2680
- type: "void",
2681
- title: '{{t("Details")}}',
2682
- "x-component": "Tabs.TabPane",
2683
- "x-designer": "Tabs.Designer",
2684
- "x-component-props": {},
2685
- properties: {
2686
- grid: {
2687
- type: "void",
2688
- "x-component": "Grid",
2689
- "x-initializer": "RecordBlockInitializers",
2690
- properties: {}
2691
- }
2692
- }
2693
- }
2694
- }
2695
- }
2696
- }
2697
- }
2698
- }
2699
- }
2700
- }
2701
- };
2702
- return schema;
2703
- };
2704
- const findNestedOption = (value, options = []) => {
2705
- if (typeof value === "string") {
2706
- value = [value];
2707
- }
2708
- return value == null ? void 0 : value.reduce((cur, v, index) => {
2709
- const matched = cur == null ? void 0 : cur.find((item) => item.value === v);
2710
- return index === value.length - 1 ? matched : matched == null ? void 0 : matched.children;
2711
- }, options);
2712
- };
2713
- const MapBlockDesigner = () => {
2714
- var _a, _b, _c, _d, _e, _f;
2715
- const { name: name2, title } = client.useCollection();
2716
- const field = react.useField();
2717
- const fieldSchema = react.useFieldSchema();
2718
- const dataSource = client.useCollectionFilterOptions(name2);
2719
- const { service } = useMapBlockContext();
2720
- const { t } = useMapTranslation();
2721
- const { dn } = client.useDesignable();
2722
- const { getCollectionFieldsOptions } = client.useCollectionManager();
2723
- const collection = client.useCollection();
2724
- const defaultFilter = ((_b = (_a = fieldSchema == null ? void 0 : fieldSchema["x-decorator-props"]) == null ? void 0 : _a.params) == null ? void 0 : _b.filter) || {};
2725
- const defaultResource = (_c = fieldSchema == null ? void 0 : fieldSchema["x-decorator-props"]) == null ? void 0 : _c.resource;
2726
- const fieldNames = ((_d = fieldSchema == null ? void 0 : fieldSchema["x-decorator-props"]) == null ? void 0 : _d["fieldNames"]) || {};
2727
- const defaultZoom = ((_e = fieldSchema == null ? void 0 : fieldSchema["x-component-props"]) == null ? void 0 : _e["zoom"]) || 13;
2728
- const template = client.useSchemaTemplate();
2729
- const mapFieldOptions = getCollectionFieldsOptions(collection == null ? void 0 : collection.name, ["point", "lineString", "polygon"], {
2730
- association: ["o2o", "obo", "oho", "o2m", "m2o", "m2m"]
2731
- });
2732
- const markerFieldOptions = getCollectionFieldsOptions(collection == null ? void 0 : collection.name, "string");
2733
- const isPointField = ((_f = findNestedOption(fieldNames.field, mapFieldOptions)) == null ? void 0 : _f.type) === "point";
2734
- return /* @__PURE__ */ jsxRuntimeExports.jsxs(client.GeneralSchemaDesigner, { template, title: title || name2, children: [
2735
- /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaSettings.BlockTitleItem, {}),
2736
- /* @__PURE__ */ jsxRuntimeExports.jsx(client.FixedBlockDesignerItem, {}),
2737
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2738
- client.SchemaSettings.CascaderItem,
2739
- {
2740
- title: t("Map field"),
2741
- value: fieldNames.field,
2742
- options: mapFieldOptions,
2743
- allowClear: false,
2744
- onChange: (v) => {
2745
- const fieldNames2 = field.decoratorProps.fieldNames || {};
2746
- fieldNames2["field"] = v;
2747
- field.decoratorProps.fieldNames = fieldNames2;
2748
- fieldSchema["x-decorator-props"]["fieldNames"] = fieldNames2;
2749
- service.refresh();
2750
- dn.emit("patch", {
2751
- schema: {
2752
- ["x-uid"]: fieldSchema["x-uid"],
2753
- "x-decorator-props": field.decoratorProps
2754
- }
2755
- });
2756
- dn.refresh();
2757
- }
2758
- }
2759
- ),
2760
- isPointField ? /* @__PURE__ */ jsxRuntimeExports.jsx(
2761
- client.SchemaSettings.SelectItem,
2762
- {
2763
- title: t("Marker field"),
2764
- value: fieldNames.marker,
2765
- options: markerFieldOptions,
2766
- onChange: (v) => {
2767
- const fieldNames2 = field.decoratorProps.fieldNames || {};
2768
- fieldNames2["marker"] = v;
2769
- field.decoratorProps.fieldNames = fieldNames2;
2770
- fieldSchema["x-decorator-props"]["fieldNames"] = fieldNames2;
2771
- service.refresh();
2772
- dn.emit("patch", {
2773
- schema: {
2774
- ["x-uid"]: fieldSchema["x-uid"],
2775
- "x-decorator-props": field.decoratorProps
2776
- }
2777
- });
2778
- dn.refresh();
2779
- }
2780
- }
2781
- ) : null,
2782
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2783
- client.SchemaSettings.ModalItem,
2784
- {
2785
- title: t("The default zoom level of the map"),
2786
- schema: {
2787
- type: "object",
2788
- title: t("Set default zoom level"),
2789
- properties: {
2790
- zoom: {
2791
- title: t("Zoom"),
2792
- default: defaultZoom,
2793
- "x-component": "InputNumber",
2794
- "x-decorator": "FormItem",
2795
- "x-component-props": {
2796
- precision: 0
2797
- }
2798
- }
2799
- }
2800
- },
2801
- onSubmit: ({ zoom }) => {
2802
- lodash.set(fieldSchema, "x-component-props.zoom", zoom);
2803
- Object.assign(field.componentProps, fieldSchema["x-component-props"]);
2804
- dn.emit("patch", {
2805
- schema: {
2806
- "x-uid": fieldSchema["x-uid"],
2807
- "x-component-props": field.componentProps
2808
- }
2809
- });
2810
- dn.refresh();
2811
- }
2812
- }
2813
- ),
2814
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2815
- client.SchemaSettings.ModalItem,
2816
- {
2817
- title: t("Set the data scope"),
2818
- schema: {
2819
- type: "object",
2820
- title: t("Set the data scope"),
2821
- properties: {
2822
- filter: {
2823
- default: defaultFilter,
2824
- // title: '数据范围',
2825
- enum: dataSource,
2826
- "x-component": "Filter",
2827
- "x-component-props": {}
2828
- }
2829
- }
2830
- },
2831
- onSubmit: ({ filter }) => {
2832
- var _a2, _b2, _c2;
2833
- const params = field.decoratorProps.params || {};
2834
- params.filter = filter;
2835
- field.decoratorProps.params = params;
2836
- fieldSchema["x-decorator-props"]["params"] = params;
2837
- const filters = ((_b2 = (_a2 = service.params) == null ? void 0 : _a2[1]) == null ? void 0 : _b2.filters) || {};
2838
- service.run(
2839
- { ...(_c2 = service.params) == null ? void 0 : _c2[0], filter: client.mergeFilter([...Object.values(filters), filter]), page: 1 },
2840
- { filters }
2841
- );
2842
- dn.emit("patch", {
2843
- schema: {
2844
- ["x-uid"]: fieldSchema["x-uid"],
2845
- "x-decorator-props": fieldSchema["x-decorator-props"]
2846
- }
2847
- });
2848
- }
2849
- }
2850
- ),
2851
- /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaSettings.ConnectDataBlocks, { type: client.FilterBlockType.TABLE, emptyDescription: t("No blocks to connect") }),
2852
- /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaSettings.Divider, {}),
2853
- /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaSettings.Template, { componentName: "Map", collectionName: name2, resourceName: defaultResource }),
2854
- /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaSettings.Divider, {}),
2855
- /* @__PURE__ */ jsxRuntimeExports.jsx(
2856
- client.SchemaSettings.Remove,
2857
- {
2858
- removeParentsIfNoChildren: true,
2859
- breakRemoveOn: {
2860
- "x-component": "Grid"
2861
- }
2862
- }
2863
- )
2864
- ] });
2865
- };
2866
- const MapBlockInitializer = (props) => {
2867
- const { insert } = props;
2868
- const options = React.useContext(react.SchemaOptionsContext);
2869
- const { getCollectionFieldsOptions } = client.useCollectionManager();
2870
- const { t } = useMapTranslation();
2871
- const { theme } = client.useGlobalTheme();
2872
- return /* @__PURE__ */ jsxRuntimeExports.jsx(
2873
- client.DataBlockInitializer,
2874
- {
2875
- ...props,
2876
- componentType: "Map",
2877
- icon: /* @__PURE__ */ jsxRuntimeExports.jsx(icons.TableOutlined, {}),
2878
- onCreateBlockSchema: async ({ item }) => {
2879
- const mapFieldOptions = getCollectionFieldsOptions(item.name, ["point", "lineString", "polygon"], {
2880
- association: ["o2o", "obo", "oho", "o2m", "m2o", "m2m"]
2881
- });
2882
- const markerFieldOptions = getCollectionFieldsOptions(item.name, "string");
2883
- const values = await client.FormDialog(
2884
- t("Create map block"),
2885
- () => {
2886
- var _a;
2887
- return /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaComponentOptions, { scope: options.scope, components: { ...options.components }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(antdV5.FormLayout, { layout: "vertical", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
2888
- client.SchemaComponent,
2889
- {
2890
- schema: {
2891
- properties: {
2892
- field: {
2893
- title: t("Map field"),
2894
- enum: mapFieldOptions,
2895
- required: true,
2896
- "x-component": "Cascader",
2897
- "x-decorator": "FormItem",
2898
- default: mapFieldOptions.length ? [mapFieldOptions[0].value, (_a = mapFieldOptions[0].children) == null ? void 0 : _a[0].value].filter(
2899
- (v) => v !== void 0 && v !== null
2900
- ) : []
2901
- },
2902
- marker: {
2903
- title: t("Marker field"),
2904
- enum: markerFieldOptions,
2905
- "x-component": "Select",
2906
- "x-decorator": "FormItem",
2907
- "x-reactions": (field) => {
2908
- const value = field.form.values.field;
2909
- if (!(value == null ? void 0 : value.length)) {
2910
- return;
2911
- }
2912
- const item2 = findNestedOption(value, mapFieldOptions);
2913
- if (item2) {
2914
- field.hidden = item2.type !== "point";
2915
- }
2916
- }
2917
- }
2918
- }
2919
- }
2920
- }
2921
- ) }) });
2922
- },
2923
- theme
2924
- ).open({
2925
- initialValues: {}
2926
- });
2927
- insert(
2928
- createMapBlockSchema({
2929
- collection: item.name,
2930
- fieldNames: {
2931
- ...values
2932
- }
2933
- })
2934
- );
2935
- },
2936
- title: t("Map block")
2937
- }
2938
- );
2939
- };
2940
- const MapBlockOptions = (props) => {
2941
- const items = React.useContext(client.SchemaInitializerContext);
2942
- const children = items.BlockInitializers.items[0].children;
2943
- React.useEffect(() => {
2944
- if (!children.find((item) => item.component === "MapBlockInitializer")) {
2945
- children.push({
2946
- key: "mapBlock",
2947
- type: "item",
2948
- title: generateNTemplate("Map"),
2949
- component: "MapBlockInitializer"
2950
- });
2951
- }
2952
- }, []);
2953
- return /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaInitializerProvider, { initializers: { MapActionInitializers }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
2954
- client.SchemaComponentOptions,
2955
- {
2956
- scope: { useMapBlockProps },
2957
- components: { MapBlockInitializer, MapBlockDesigner, MapBlockProvider, MapBlock },
2958
- children: props.children
2959
- }
2960
- ) });
2961
- };
2962
- const { defaultProps } = client.interfacesProperties;
2963
- if (Array.isArray(client.interfacesProperties.type.enum)) {
2964
- client.interfacesProperties.type.enum.push(
2965
- {
2966
- label: "Point",
2967
- value: "point"
2968
- },
2969
- {
2970
- label: "LineString",
2971
- value: "lineString"
2972
- },
2973
- {
2974
- label: "Polygon",
2975
- value: "polygon"
2976
- },
2977
- {
2978
- label: "Circle",
2979
- value: "circle"
2980
- }
2981
- );
2982
- }
2983
- const commonSchema = {
2984
- properties: {
2985
- ...defaultProps,
2986
- "uiSchema.x-component-props.mapType": {
2987
- title: generateNTemplate("Map type"),
2988
- type: "string",
2989
- required: true,
2990
- "x-decorator": "FormItem",
2991
- "x-component": "Select",
2992
- "x-component-props": {
2993
- showSearch: false,
2994
- allowClear: false
2995
- },
2996
- "x-disabled": "{{ isOverride || !createOnly }}",
2997
- default: "amap",
2998
- enum: MapTypes
2999
- }
3000
- },
3001
- schemaInitialize(schema, { block }) {
3002
- if (block === "Form") {
3003
- Object.assign(schema, {
3004
- "x-designer": "Map.Designer"
3005
- });
3006
- }
3007
- }
3008
- };
3009
- const circle = {
3010
- name: "circle",
3011
- type: "object",
3012
- group: "map",
3013
- order: 3,
3014
- title: generateNTemplate("Circle"),
3015
- description: generateNTemplate("Circle"),
3016
- sortable: true,
3017
- default: {
3018
- type: "circle",
3019
- uiSchema: {
3020
- type: "void",
3021
- "x-component": "Map",
3022
- "x-component-designer": "Map.Designer",
3023
- "x-component-props": {}
3024
- }
3025
- },
3026
- ...commonSchema
3027
- };
3028
- const lineString = {
3029
- name: "lineString",
3030
- type: "object",
3031
- group: "map",
3032
- order: 2,
3033
- title: generateNTemplate("Line"),
3034
- description: generateNTemplate("Line"),
3035
- sortable: true,
3036
- default: {
3037
- type: "lineString",
3038
- uiSchema: {
3039
- type: "void",
3040
- "x-component": "Map",
3041
- "x-component-designer": "Map.Designer",
3042
- "x-component-props": {}
3043
- }
3044
- },
3045
- ...commonSchema
3046
- };
3047
- const point = {
3048
- name: "point",
3049
- type: "object",
3050
- group: "map",
3051
- order: 1,
3052
- title: generateNTemplate("Point"),
3053
- description: generateNTemplate("Point"),
3054
- sortable: true,
3055
- default: {
3056
- type: "point",
3057
- uiSchema: {
3058
- type: "void",
3059
- "x-component": "Map",
3060
- "x-component-designer": "Map.Designer",
3061
- "x-component-props": {}
3062
- }
3063
- },
3064
- ...commonSchema
3065
- };
3066
- const polygon = {
3067
- name: "polygon",
3068
- type: "object",
3069
- group: "map",
3070
- order: 4,
3071
- title: generateNTemplate("Polygon"),
3072
- description: generateNTemplate("Polygon"),
3073
- sortable: true,
3074
- default: {
3075
- type: "polygon",
3076
- uiSchema: {
3077
- type: "void",
3078
- "x-component": "Map",
3079
- "x-component-designer": "Map.Designer",
3080
- "x-component-props": {}
3081
- }
3082
- },
3083
- ...commonSchema
3084
- };
3085
- const fields = [point, polygon, lineString, circle];
3086
- const interfaces = fields.reduce((ins, field) => {
3087
- ins[field.name] = field;
3088
- return ins;
3089
- }, {});
3090
- const useRegisterInterface = () => {
3091
- const { data } = client.useCurrentAppInfo() || {};
3092
- React.useEffect(() => {
3093
- const dialect = data == null ? void 0 : data.database.dialect;
3094
- if (!dialect)
3095
- return;
3096
- client.registerGroup(fields[0].group, {
3097
- label: generateNTemplate("Map-based geometry"),
3098
- order: 51
3099
- });
3100
- fields.forEach((field) => {
3101
- if (Array.isArray(field.dialects)) {
3102
- if (!field.dialects.includes(dialect)) {
3103
- return;
3104
- }
3105
- }
3106
- client.registerField(field.group, field.title, field);
3107
- });
3108
- }, [data]);
3109
- };
3110
- const MapInitializer = (props) => {
3111
- useRegisterInterface();
3112
- return /* @__PURE__ */ jsxRuntimeExports.jsx(React.Fragment, { children: props.children });
3113
- };
3114
- const MapProvider = React.memo((props) => {
3115
- const ctx = React.useContext(client.CollectionManagerContext);
3116
- const { t } = useMapTranslation();
3117
- return /* @__PURE__ */ jsxRuntimeExports.jsx(client.CurrentAppInfoProvider, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(MapInitializer, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
3118
- client.SettingsCenterProvider,
3119
- {
3120
- settings: {
3121
- map: {
3122
- title: t("Map Manager"),
3123
- icon: "EnvironmentOutlined",
3124
- tabs: {
3125
- configuration: {
3126
- title: t("Configuration"),
3127
- component: Configuration
3128
- }
3129
- }
3130
- }
3131
- },
3132
- children: /* @__PURE__ */ jsxRuntimeExports.jsx(client.SchemaComponentOptions, { components: { Map }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(MapBlockOptions, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(client.CollectionManagerContext.Provider, { value: { ...ctx, interfaces: { ...ctx.interfaces, ...interfaces } }, children: props.children }) }) })
3133
- }
3134
- ) }) });
3135
- });
3136
- MapProvider.displayName = "MapProvider";
3137
- class MapPlugin extends client.Plugin {
3138
- async load() {
3139
- this.app.use(MapProvider);
3140
- }
3141
- }
3142
- exports2.MapPlugin = MapPlugin;
3143
- exports2.default = MapPlugin;
3144
- Object.defineProperties(exports2, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } });
3145
- });
106
+ `,children:r.jsx(Le,I({},e))}),Z.mapReadPretty(ht));Be.Designer=gt;const yt={amap:$e,google:pt},vt=e=>{const{t:n}=Q(),{mapType:t}=e,o=d.useMemo(()=>yt[t],[t]);return o?r.jsx(o,I({},e)):r.jsx("div",{children:n(`The ${t} cannot found`)})},At=e=>{var l;const{fieldNames:n}=s.useProps(e),{getCollectionJoinField:t}=s.useCollectionManager(),{name:o}=s.useCollection(),a=d.useMemo(()=>t([o,n==null?void 0:n.field].flat().join(".")),[o,n==null?void 0:n.field]),i=(l=a==null?void 0:a.uiSchema)==null?void 0:l["x-component-props"];return r.jsx(vt,_(I(I({},i),e),{collectionField:a}))},Te=d.createContext({}),Mt=e=>{var A;const{fieldNames:n}=e,t=Z.useFieldSchema(),o=Z.useField(),{resource:a,service:i}=s.useBlockRequestContext(),[l,h]=d.useState([]);return r.jsx(s.FixedBlockWrapper,{children:r.jsx(s.SchemaComponentOptions,{scope:{selectedRecordKeys:l},children:r.jsx(Te.Provider,{value:{field:o,service:i,resource:a,fieldNames:n,fixedBlock:(A=t==null?void 0:t["x-decorator-props"])==null?void 0:A.fixedBlock,selectedRecordKeys:l,setSelectedRecordKeys:h},children:e.children})})})},bt=e=>{const{params:n,fieldNames:t}=e,o=n.appends||[],{field:a}=t||{};return Array.isArray(a)&&a.length>1&&o.push(a[0]),r.jsx(s.BlockProvider,_(I({},e),{params:_(I({},n),{appends:o,paginate:!1}),children:r.jsx(Mt,I({},e))}))},De=()=>d.useContext(Te),Ct=()=>{var n,t,o,a;const e=De();return _(I({},e),{dataSource:(t=(n=e==null?void 0:e.service)==null?void 0:n.data)==null?void 0:t.data,zoom:((a=(o=e==null?void 0:e.field)==null?void 0:o.componentProps)==null?void 0:a.zoom)||13})},xt=e=>{const l=e,{collection:n,resource:t,fieldNames:o}=l,a=Ve(l,["collection","resource","fieldNames"]);return{type:"void","x-acl-action":`${t||n}:list`,"x-decorator":"MapBlockProvider","x-decorator-props":I({collection:n,resource:t||n,action:"list",fieldNames:o,params:{paginate:!1}},a),"x-designer":"MapBlockDesigner","x-component":"CardItem","x-filter-targets":[],properties:{actions:{type:"void","x-initializer":"MapActionInitializers","x-component":"ActionBar","x-component-props":{style:{marginBottom:16}},properties:{}},[We.uid()]:{type:"void","x-component":"MapBlock","x-component-props":{useProps:"{{ useMapBlockProps }}"},properties:{drawer:{type:"void","x-component":"Action.Drawer","x-component-props":{className:"nb-action-popup"},title:'{{ t("View record") }}',properties:{tabs:{type:"void","x-component":"Tabs","x-component-props":{},"x-initializer":"TabPaneInitializers",properties:{tab1:{type:"void",title:'{{t("Details")}}',"x-component":"Tabs.TabPane","x-designer":"Tabs.Designer","x-component-props":{},properties:{grid:{type:"void","x-component":"Grid","x-initializer":"RecordBlockInitializers",properties:{}}}}}}}}}}}}},Ke=(e,n=[])=>(typeof e=="string"&&(e=[e]),e==null?void 0:e.reduce((t,o,a)=>{const i=t==null?void 0:t.find(l=>l.value===o);return a===e.length-1?i:i==null?void 0:i.children},n)),wt=()=>{var k,D,V,B,E,T;const{name:e,title:n}=s.useCollection(),t=Z.useField(),o=Z.useFieldSchema(),a=s.useCollectionFilterOptions(e),{service:i}=De(),{t:l}=Q(),{dn:h}=s.useDesignable(),{getCollectionFieldsOptions:A}=s.useCollectionManager(),S=s.useCollection(),M=((D=(k=o==null?void 0:o["x-decorator-props"])==null?void 0:k.params)==null?void 0:D.filter)||{},u=(V=o==null?void 0:o["x-decorator-props"])==null?void 0:V.resource,g=((B=o==null?void 0:o["x-decorator-props"])==null?void 0:B.fieldNames)||{},p=((E=o==null?void 0:o["x-component-props"])==null?void 0:E.zoom)||13,m=s.useSchemaTemplate(),v=A(S==null?void 0:S.name,["point","lineString","polygon"],{association:["o2o","obo","oho","o2m","m2o","m2m"]}),K=A(S==null?void 0:S.name,"string"),F=((T=Ke(g.field,v))==null?void 0:T.type)==="point";return r.jsxs(s.GeneralSchemaDesigner,{template:m,title:n||e,children:[r.jsx(s.SchemaSettings.BlockTitleItem,{}),r.jsx(s.FixedBlockDesignerItem,{}),r.jsx(s.SchemaSettings.CascaderItem,{title:l("Map field"),value:g.field,options:v,allowClear:!1,onChange:W=>{const q=t.decoratorProps.fieldNames||{};q.field=W,t.decoratorProps.fieldNames=q,o["x-decorator-props"].fieldNames=q,i.refresh(),h.emit("patch",{schema:{"x-uid":o["x-uid"],"x-decorator-props":t.decoratorProps}}),h.refresh()}}),F?r.jsx(s.SchemaSettings.SelectItem,{title:l("Marker field"),value:g.marker,options:K,onChange:W=>{const q=t.decoratorProps.fieldNames||{};q.marker=W,t.decoratorProps.fieldNames=q,o["x-decorator-props"].fieldNames=q,i.refresh(),h.emit("patch",{schema:{"x-uid":o["x-uid"],"x-decorator-props":t.decoratorProps}}),h.refresh()}}):null,r.jsx(s.SchemaSettings.ModalItem,{title:l("The default zoom level of the map"),schema:{type:"object",title:l("Set default zoom level"),properties:{zoom:{title:l("Zoom"),default:p,"x-component":"InputNumber","x-decorator":"FormItem","x-component-props":{precision:0}}}},onSubmit:({zoom:W})=>{Me.set(o,"x-component-props.zoom",W),Object.assign(t.componentProps,o["x-component-props"]),h.emit("patch",{schema:{"x-uid":o["x-uid"],"x-component-props":t.componentProps}}),h.refresh()}}),r.jsx(s.SchemaSettings.ModalItem,{title:l("Set the data scope"),schema:{type:"object",title:l("Set the data scope"),properties:{filter:{default:M,enum:a,"x-component":"Filter","x-component-props":{}}}},onSubmit:({filter:W})=>{var J,te,P;const q=t.decoratorProps.params||{};q.filter=W,t.decoratorProps.params=q,o["x-decorator-props"].params=q;const $=((te=(J=i.params)==null?void 0:J[1])==null?void 0:te.filters)||{};i.run(_(I({},(P=i.params)==null?void 0:P[0]),{filter:s.mergeFilter([...Object.values($),W]),page:1}),{filters:$}),h.emit("patch",{schema:{"x-uid":o["x-uid"],"x-decorator-props":o["x-decorator-props"]}})}}),r.jsx(s.SchemaSettings.ConnectDataBlocks,{type:s.FilterBlockType.TABLE,emptyDescription:l("No blocks to connect")}),r.jsx(s.SchemaSettings.Divider,{}),r.jsx(s.SchemaSettings.Template,{componentName:"Map",collectionName:e,resourceName:u}),r.jsx(s.SchemaSettings.Divider,{}),r.jsx(s.SchemaSettings.Remove,{removeParentsIfNoChildren:!0,breakRemoveOn:{"x-component":"Grid"}})]})},St=e=>{const{insert:n}=e,t=d.useContext(Z.SchemaOptionsContext),{getCollectionFieldsOptions:o}=s.useCollectionManager(),{t:a}=Q(),{theme:i}=s.useGlobalTheme();return r.jsx(s.DataBlockInitializer,_(I({},e),{componentType:"Map",icon:r.jsx(ee.TableOutlined,{}),onCreateBlockSchema:h=>fe(this,[h],function*({item:l}){const A=o(l.name,["point","lineString","polygon"],{association:["o2o","obo","oho","o2m","m2o","m2m"]}),S=o(l.name,"string"),M=yield s.FormDialog(a("Create map block"),()=>{var u;return r.jsx(s.SchemaComponentOptions,{scope:t.scope,components:I({},t.components),children:r.jsx(Ye.FormLayout,{layout:"vertical",children:r.jsx(s.SchemaComponent,{schema:{properties:{field:{title:a("Map field"),enum:A,required:!0,"x-component":"Cascader","x-decorator":"FormItem",default:A.length?[A[0].value,(u=A[0].children)==null?void 0:u[0].value].filter(g=>g!=null):[]},marker:{title:a("Marker field"),enum:S,"x-component":"Select","x-decorator":"FormItem","x-reactions":g=>{const p=g.form.values.field;if(!(p!=null&&p.length))return;const m=Ke(p,A);m&&(g.hidden=m.type!=="point")}}}}})})})},i).open({initialValues:{}});n(xt({collection:l.name,fieldNames:I({},M)}))}),title:a("Map block")}))},It=e=>{const t=d.useContext(s.SchemaInitializerContext).BlockInitializers.items[0].children;return d.useEffect(()=>{t.find(o=>o.component==="MapBlockInitializer")||t.push({key:"mapBlock",type:"item",title:R("Map"),component:"MapBlockInitializer"})},[]),r.jsx(s.SchemaInitializerProvider,{initializers:{MapActionInitializers:_e},children:r.jsx(s.SchemaComponentOptions,{scope:{useMapBlockProps:Ct},components:{MapBlockInitializer:St,MapBlockDesigner:wt,MapBlockProvider:bt,MapBlock:At},children:e.children})})},{defaultProps:Pt}=s.interfacesProperties;Array.isArray(s.interfacesProperties.type.enum)&&s.interfacesProperties.type.enum.push({label:"Point",value:"point"},{label:"LineString",value:"lineString"},{label:"Polygon",value:"polygon"},{label:"Circle",value:"circle"});const ue={properties:_(I({},Pt),{"uiSchema.x-component-props.mapType":{title:R("Map type"),type:"string",required:!0,"x-decorator":"FormItem","x-component":"Select","x-component-props":{showSearch:!1,allowClear:!1},"x-disabled":"{{ isOverride || !createOnly }}",default:"amap",enum:Ce}}),schemaInitialize(e,{block:n}){n==="Form"&&Object.assign(e,{"x-designer":"Map.Designer"})}},kt=I({name:"circle",type:"object",group:"map",order:3,title:R("Circle"),description:R("Circle"),sortable:!0,default:{type:"circle",uiSchema:{type:"void","x-component":"Map","x-component-designer":"Map.Designer","x-component-props":{}}}},ue),Ot=I({name:"lineString",type:"object",group:"map",order:2,title:R("Line"),description:R("Line"),sortable:!0,default:{type:"lineString",uiSchema:{type:"void","x-component":"Map","x-component-designer":"Map.Designer","x-component-props":{}}}},ue),Ft=I({name:"point",type:"object",group:"map",order:1,title:R("Point"),description:R("Point"),sortable:!0,default:{type:"point",uiSchema:{type:"void","x-component":"Map","x-component-designer":"Map.Designer","x-component-props":{}}}},ue),Et=I({name:"polygon",type:"object",group:"map",order:4,title:R("Polygon"),description:R("Polygon"),sortable:!0,default:{type:"polygon",uiSchema:{type:"void","x-component":"Map","x-component-designer":"Map.Designer","x-component-props":{}}}},ue),ve=[Ft,Et,Ot,kt],zt=ve.reduce((e,n)=>(e[n.name]=n,e),{}),Lt=()=>{const{data:e}=s.useCurrentAppInfo()||{};d.useEffect(()=>{const n=e==null?void 0:e.database.dialect;n&&(s.registerGroup(ve[0].group,{label:R("Map-based geometry"),order:51}),ve.forEach(t=>{Array.isArray(t.dialects)&&!t.dialects.includes(n)||s.registerField(t.group,t.title,t)}))},[e])},Bt=e=>(Lt(),r.jsx(d.Fragment,{children:e.children})),Ue=d.memo(e=>{const n=d.useContext(s.CollectionManagerContext),{t}=Q();return r.jsx(s.CurrentAppInfoProvider,{children:r.jsx(Bt,{children:r.jsx(s.SettingsCenterProvider,{settings:{map:{title:t("Map Manager"),icon:"EnvironmentOutlined",tabs:{configuration:{title:t("Configuration"),component:rt}}}},children:r.jsx(s.SchemaComponentOptions,{components:{Map:Be},children:r.jsx(It,{children:r.jsx(s.CollectionManagerContext.Provider,{value:_(I({},n),{interfaces:I(I({},n.interfaces),zt)}),children:e.children})})})})})})});Ue.displayName="MapProvider";class Ge extends s.Plugin{load(){return fe(this,null,function*(){this.app.use(Ue)})}}O.MapPlugin=Ge,O.default=Ge,Object.defineProperties(O,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});