=============== LIBRARY RULES =============== From library maintainers: - 优先查询文档SKLL.md中说明 ### Install Project Dependencies Source: https://github.com/an501920078/micro-gis-base/blob/main/README.md Run this command to install all necessary dependencies for the project. ```sh npm install ``` -------------------------------- ### Compile and Hot-Reload for Development Source: https://github.com/an501920078/micro-gis-base/blob/main/README.md Use this command to start the development server with hot-reloading enabled. This is useful for rapid development cycles. ```sh npm run dev ``` -------------------------------- ### Component Initialization and Event Handling Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Initializes component variables and sets up event handling. This snippet appears to be part of a larger component lifecycle or setup process. ```javascript var t,r,u,i,o=0,f=[],c=l$1,e=c.__b,a=c.__r,v=c.diffed,l=c.__c,m=c.unmount,s=c.__;function p(n,t){c.__h&&c.__h(r,n,o||t),o=0; ``` -------------------------------- ### Initialize and Use Measure Tool in Cesium Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md Demonstrates how to initialize the Measure tool with a Cesium viewer and start distance or area measurements. Includes a callback for when a measurement ends and a method to clear measurements. ```typescript import { Measure } from 'micro-gis'; import { getCesiumViewer } from "@/tools/utils/getCesium"; const viewer = getCesiumViewer(); const measure = new Measure(viewer); // 距离测量 measure.start({ type: 'Distance', onEnd: (result) => { console.log('距离测量完成:', result); }, }); // 面积测量 measure.start({ type: 'Area', onEnd: (result) => { console.log('面积测量完成:', result); }, }); // 清除测量 measure.clear(); ``` -------------------------------- ### Create and Add Line Entity Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md This example demonstrates how to create a line entity with a series of coordinates, custom color, and width, then add it to the map. ```typescript import { Line } from 'micro-gis/openlayers'; const line = new Line({ position: [[116.4, 39.9], [116.5, 40.0], [116.6, 39.95]], color: '#FF4D4F', width: 8, }); olMap.addEntity(line); ``` -------------------------------- ### Handle Slashes in Glob Parsing Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Manages slash characters, treating them as path separators. If the glob starts with './', it adjusts the starting position. ```javascript if (value === '/') { // if the beginning of the glob is "./", advance the start // to the current index, and don't add the "./" characters // to the state. This greatly simplifies lookbehinds when // checking for BOS characters like "!" and "." (not "./") if (prev.type === 'dot' && state.index === state.start + 1) { state.start = state.index + 1; state.consumed = ''; state.output = ''; tokens.pop(); prev = bos; // reset "prev" to the first token continue; } push({ type: 'slash', value, output: SLASH_LITERAL }); continue; } ``` -------------------------------- ### Compute Height Function Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Calculates and sets the height property for each node in the hierarchy, starting from the leaves and moving up to the root. ```javascript function computeHeight(node) { var height = 0; do node.height = height; while ((node = node.parent) && (node.height < ++height)); } ``` -------------------------------- ### Node Ancestors Function Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Returns an array of ancestor nodes for the current node, starting from the parent and going up to the root. ```javascript function node_ancestors() { var node = this, nodes = [node]; while (node = node.parent) { nodes.push(node); } return nodes; } ``` -------------------------------- ### Picomatch Initialization Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Initializes the picomatch library, handling platform-specific options and exposing the main matching function. ```javascript function requirePicomatch () { if (hasRequiredPicomatch) return picomatch_1; hasRequiredPicomatch = 1; const pico = /*@__PURE__*/ requirePicomatch$1(); const utils = /*@__PURE__*/ requireUtils(); function picomatch(glob, options, returnState = false) { // default to os.platform() if if (options && (options.windows === null || options.windows === undefined)) { // don't mutate the original options object options = { ...options, windows: utils.isWindows() }; } return pico(glob, options, returnState); } Object.assign(picomatch, pico); picomatch_1 = picomatch; return picomatch_1; } ``` -------------------------------- ### Basic Glob Matching with Picomatch Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Demonstrates how to use picomatch to create a matcher function for a glob pattern and test strings against it. This is useful for simple file path filtering. ```javascript const picomatch = require('picomatch'); // picomatch(glob[, options]); const isMatch = picomatch('*.!(a)'); console.log(isMatch('a.a')); //=> false console.log(isMatch('a.b')); //=> true ``` -------------------------------- ### Package Project for Distribution Source: https://github.com/an501920078/micro-gis-base/blob/main/README.md Run this command to package the project, typically for distribution or archival purposes. ```sh npm pack ``` -------------------------------- ### Node Path Function Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Returns an array of nodes representing the path from the current node to a specified target node. Includes both start and end nodes. ```javascript function node_path(end) { var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start]; while (start !== ancestor) { start = start.parent; nodes.push(start); } var k = nodes.length; while (end !== ancestor) { nodes.splice(k, 0, end); end = end.parent; } return nodes; } ``` -------------------------------- ### Type-Check, Compile, and Minify for Production Source: https://github.com/an501920078/micro-gis-base/blob/main/README.md Execute this command to perform type checking, compile the project, and minify the output for production deployment. ```sh npm run build ``` -------------------------------- ### Node Sum Function Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Computes the sum of values for each node, starting from the leaves and moving upwards. Requires a function to extract the value from node data. ```javascript function node_sum(value) { return this.eachAfter(function(node) { var sum = +value(node.data) || 0, children = node.children, i = children && children.length; while (--i >= 0) sum += children[i].value; node.value = sum; }); } ``` -------------------------------- ### Define Constructor, Factory, and Prototype Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Helper function to set up constructor, factory, and prototype relationships for classes. ```javascript function define(constructor, factory, prototype) { constructor.prototype = factory.prototype = prototype; prototype.constructor = constructor; } ``` -------------------------------- ### Integrate Measure Tool with Vue Component Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md Shows how to integrate the Measure tool within a Vue.js component, handling user interactions to start different measurement types or clear existing ones. ```vue ``` -------------------------------- ### Initialize and Use Drawer Tool in Cesium for Excavation Analysis Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md Demonstrates initializing the Drawer tool for drawing a rectangle in Cesium. The `onEnd` callback processes the drawn geometry, sends it for excavation analysis, loads models, and then removes the drawing entity. ```typescript import { Drawer } from "micro-gis"; import useCesium from "@/tools/hooks/useCesium"; const { viewer } = useCesium(); const drawer = new Drawer(viewer); // 开始绘制矩形区域 drawer.start({ type: "RECTANGLE", async onEnd(entity, cartesians) { // 将笛卡尔坐标转换为经纬度 const positionArr = cartesians.map(item => CartesiantoLonlat(item, viewer)); const positions = [...positionArr.flat(), ...positionArr[0]]; // 发送开挖分析请求 const { data } = await GisServer.apiStatisticalQueryDiggingPost({ layerNames: getLayerNames(), positions, versionCode: selectedVersion.value?.versionCode, }); // 加载开挖模型 loadWall(cartesians, maxDep); loadPipesModel(data); // 移除绘制的实体 viewer.entities.remove(entity); }, }); ``` -------------------------------- ### Match Base Filename with Picomatch Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Illustrates how to use `picomatch.matchBase` to test only the basename of a filepath against a glob pattern. This is helpful when you only care about the filename part of a path. ```javascript const picomatch = require('picomatch'); // picomatch.matchBase(input, glob[, options]); console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true ``` -------------------------------- ### Generate Tick Formatter for Scales Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Creates a formatter function suitable for tick labels on a scale, based on the scale's domain (start and stop values) and the desired tick count. It intelligently chooses the best format specifier (e.g., 's' for SI-prefix, 'f' for fixed-point). ```javascript var format = d3.tickFormat(0, 1000, 5); format(500) ``` -------------------------------- ### picomatch(glob, options) Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Creates a matcher function based on the provided glob pattern(s) and options. It can handle single patterns, arrays of patterns, and returns a function that tests input strings. ```APIDOC ## picomatch(glob, options) ### Description Creates a matcher function based on the provided glob pattern(s) and options. It can handle single patterns, arrays of patterns, and returns a function that tests input strings. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **glob** (String|Array) - One or more glob patterns. - **options** (Object) - Optional configuration object. ### Returns - **Function** - Returns a matcher function. ### Example ```js const picomatch = require('picomatch'); const isMatch = picomatch('*.!'); console.log(isMatch('a.b')); //=> true console.log(isMatch('a.a')); //=> false ``` ``` -------------------------------- ### Parent Application: Initializing GIS Service Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md Initialize the GIS service in the parent application's App.vue component. This involves creating the MicroGis instance with necessary configurations like GIS server API, WebComponent mode, and user permissions, then exposing it globally. ```typescript // App.vue - GIS服务初始化 import { createMicroGis } from "micro-gis-base"; import { GisServer } from "@/api"; import { ref, watch } from "vue"; const microGisInitFlag = ref(false); const initGlobData = async () => { if (userStore.userInfo && userStore.userInfo.currentTenantId) { if (microGisInitFlag.value) return; microGisInitFlag.value = true; // 获取用户图层权限 const { data } = await AdminServer.apiRoleGetCustomLayerAuthorityByUserIdPost(userStore.userInfo.id!); try { const microGis = await createMicroGis({ GisServer: GisServer, // GIS服务API WebComponent: true, // 启用WebComponent模式 showPipeLayerNames: data!, }); // 将microGis暴露给子应用 window.MicroGis = microGis; } catch (error) { console.error('GIS配置请求错误,请检查相关配置'); } } }; watch(() => userStore.userInfo, initGlobData, { immediate: true }); ``` -------------------------------- ### picomatch.matchBase(input, glob, options) Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Matches the basename of a filepath against a glob pattern. This is useful for ignoring directory paths and only matching filenames. ```APIDOC ## picomatch.matchBase(input, glob, options) ### Description Matches the basename of a filepath against a glob pattern. This is useful for ignoring directory paths and only matching filenames. ### Parameters - **input** (String) - The string to test. - **glob** (RegExp|String) - Glob pattern or regex created by `picomatch.makeRe`. - **options** (Object) - Optional configuration object. ### Returns - **Boolean** - Returns true if the basename matches the glob pattern. ### Example ```js const picomatch = require('picomatch'); console.log(picomatch.matchBase('foo/bar.js', '*.js')); //=> true ``` ``` -------------------------------- ### Available Size Options Retrieval Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Determines which size options (rendered, gzip, brotli) are available based on provided configuration. Defaults to 'renderedLength' and includes others if specified. ```javascript const getAvailableSizeOptions = (options) => { const availableSizeProperties = ["renderedLength"]; if (options.gzip) { availableSizeProperties.push("gzipLength"); } if (options.brotli) { availableSizeProperties.push("brotliLength"); } return availableSizeProperties; }; ``` -------------------------------- ### Initialize Cesium Viewer with useCesium Hook in Vue Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md Shows how to use the `useCesium` hook to initialize and manage a Cesium Viewer instance within a Vue.js application. It covers setting viewer options, handling viewer mount events, and initializing the map. ```vue ``` -------------------------------- ### HSL Color Constructor and Utilities Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Defines the Hsl color class and its constructor. Includes methods for converting to HSL, manipulating HSL properties, and formatting to HSL strings. Handles opacity and ensures values are within valid ranges. ```javascript function hsla(h, s, l, a) { if (a <= 0) h = s = l = NaN; else if (l <= 0 || l >= 1) h = s = NaN; else if (s <= 0) h = NaN; return new Hsl(h, s, l, a); } ``` ```javascript function hslConvert(o) { if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); if (!(o instanceof Color)) o = color(o); if (!o) return new Hsl; if (o instanceof Hsl) return o; o = o.rgb(); var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2; if (s) { if (r === max) h = (g - b) / s + (g < b) * 6; else if (g === max) h = (b - r) / s + 2; else h = (r - g) / s + 4; s /= l < 0.5 ? max + min : 2 - max - min; h *= 60; } else { s = l > 0 && l < 1 ? 0 : h; } return new Hsl(h, s, l, o.opacity); } ``` ```javascript function hsl(h, s, l, opacity) { return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); } ``` ```javascript function Hsl(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } ``` ```javascript define(Hsl, hsl, extend(Color, { brighter(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, ``` -------------------------------- ### Importing Modules in Child Application Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md Demonstrates how to import core APIs, OpenLayers modules, bridge modules, Vue tools, and state management from the 'micro-gis' package in a child application. ```typescript // 主入口导入 import { createMicroGis, onMountGis } from 'micro-gis'; // OpenLayers模块导入 import { OlMap, Line, IconMarker, DrawFeatures, Math as OlMath } from 'micro-gis/openlayers'; // 桥接模块导入 import { addBridgeModule } from 'micro-gis/bridge'; // Vue工具导入 import { useOlPopups } from 'micro-gis/vueTools'; // 状态管理导入 import microGis from 'micro-gis/microGis'; ``` -------------------------------- ### Create a Linear Scale Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Initializes a linear scale, which maps a continuous domain to a continuous range. Use this for standard linear interpolations between values. ```javascript d3.scaleLinear().domain([0, 1]).range([0, 100]) ``` -------------------------------- ### Initialize Range for Scale Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Sets the domain and range for a scale. Handles different argument counts for flexibility. ```javascript function initRange(domain, range) { switch (arguments.length) { case 0: break; case 1: this.range(domain); break; default: this.range(range).domain(domain); break; } return this; } ``` -------------------------------- ### Picomatch Test Function Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Shows how to use the `picomatch.test` function to directly test an input string against a pre-compiled regular expression. This is useful for more advanced or custom matching scenarios. ```javascript const picomatch = require('picomatch'); // picomatch.test(input, regex[, options]); console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } ``` -------------------------------- ### Parent Application: Exposing Global GIS Dependencies Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md In the parent application's main entry point, expose Cesium and OpenLayers to the child applications by assigning them to the window object. Also, import the necessary GIS styles. ```typescript // main.ts - 全局依赖暴露 import * as Cesium from "cesium"; import * as ol from "ol"; // 暴露Cesium给子应用 window.Cesium = Cesium; window.CESIUM_BASE_URL = `${window.location.origin}/cesium/`; // 暴露OpenLayers给子应用 window.ol = ol; // 引入GIS样式 import "micro-gis-base/dist/style.css"; ``` -------------------------------- ### Size Options Labels Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Defines labels for different size metrics used in the project, such as rendered length, gzip, and brotli. ```javascript const LABELS = { renderedLength: "Rendered", gzipLength: "Gzip", brotliLength: "Brotli", }; ``` -------------------------------- ### picomatch.test(input, regex, options) Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Tests an input string against a regular expression generated from a glob pattern. It returns an object containing matching information. ```APIDOC ## picomatch.test(input, regex, options) ### Description Tests an input string against a regular expression generated from a glob pattern. It returns an object containing matching information. ### Parameters - **input** (String) - The string to test. - **regex** (RegExp) - The regular expression to test against. - **options** (Object) - Optional configuration object. ### Returns - **Object** - Returns an object with matching info: `{ isMatch: Boolean, match: any, output: String }`. ### Example ```js const picomatch = require('picomatch'); const regex = /^(?:([^/]*?)\/([^/]*?))$/; console.log(picomatch.test('foo/bar', regex)); //=> { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } ``` ``` -------------------------------- ### Matcher Creation Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Generates bundle and file matchers based on filter criteria. Uses `globToTest` for pattern matching. ```javascript const getMatcher = (filter) => { const bundleTest = "bundle" in filter && filter.bundle != null ? globToTest(filter.bundle) : testTrue; const fileTest = "file" in filter && filter.file != null ? globToTest(filter.file) : testTrue; return { bundleTest, fileTest }; }; ``` -------------------------------- ### Scanning a Glob Pattern Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Demonstrates how to use the `pm.scan` function to parse a glob pattern and inspect its properties. This is useful for understanding the structure of a glob string. ```javascript const pm = require('picomatch'); console.log(pm.scan('foo/bar/*.js')); // { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } ``` -------------------------------- ### Require Constants and Utils Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Loads necessary constants and utility functions for parsing and glob operations. ```javascript const constants = /*@__PURE__*/ requireConstants(); const utils = /*@__PURE__*/ requireUtils(); ``` -------------------------------- ### Create GLOB_CHARS Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Returns a character set object for glob matching, adapting to Windows or POSIX path conventions. ```javascript globChars(win32) { return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; } ``` -------------------------------- ### picomatch.makeRe Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Creates a regular expression from a glob pattern, internally using `parse` and `compileRe`. ```APIDOC ## picomatch.makeRe(input, options, returnOutput, returnState) ### Description Creates a regular expression from the given glob pattern. This function combines parsing and compilation steps. ### Method `picomatch.makeRe` ### Parameters #### Path Parameters - `input` (String) - The glob pattern to convert into a regular expression. - `options` (Object) - Optional configuration options. Defaults to `{}`. - `returnOutput` (Boolean) - If true, returns the raw output string instead of a RegExp object. Defaults to `false`. - `returnState` (Boolean) - If true, adds the state to a `state` property on the returned regex. Defaults to `false`. ### Throws - `TypeError` - If the input is not a non-empty string. ### Return Value - `RegExp` - A regular expression created from the given glob pattern. ``` -------------------------------- ### Initialize DrawFeatures for Circle Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md Set up a DrawFeatures tool for drawing circles. The callback function receives an object containing the circle's center coordinates and radius, as Circle geometries do not have a standard `getCoordinates()` method. ```typescript // 4. 绘制圆形(回调接收 { center, radius }) import type { CircleCallbackParam } from 'micro-gis/openlayers'; const circleDraw = new DrawFeatures((param: CircleCallbackParam) => { console.log('圆心:', param.center, '半径:', param.radius); }, { type: 'Circle', once: true }); olMap.addDraw(circleDraw); ``` -------------------------------- ### Project Constants and Regular Expressions Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Centralized constants and regular expressions for the micro-GIS-base project, including maximum length, glob replacements, and character codes. ```javascript constants$1 = { MAX_LENGTH: 1024 * 64, POSIX_REGEX_SOURCE, // regular expressions REGEX_BACKSLASH: /\\(?![*+?^${}()|[\]])/g, REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\]+/, REGEX_SPECIAL_CHARS: /[-\*+?.^${}()|[\\\]]/g, REGEX_SPECIAL_CHARS_BACKREF: /(?)((\W)(\3*))/g, REGEX_SPECIAL_CHARS_GLOBAL: /([-\* +?.^${}()|[\]])/g, REGEX_REMOVE_BACKSLASH: /(?:\\[.*?[^\\].*?]|\\(?=.))/g, // Replace globs with equivalent patterns to reduce parsing time. REPLACEMENTS: { __proto__: null, '***': '*', '**/\**': '**', '**/\**/\**': '**' }, // Digits CHAR_0: 48, /* 0 */ CHAR_9: 57, /* 9 */ // Alphabet chars. CHAR_UPPERCASE_A: 65, /* A */ CHAR_LOWERCASE_A: 97, /* a */ CHAR_UPPERCASE_Z: 90, /* Z */ CHAR_LOWERCASE_Z: 122, /* z */ // Parentheses chars. CHAR_LEFT_PARENTHESES: 40, /* ( */ CHAR_RIGHT_PARENTHESES: 41, /* ) */ // Special chars. CHAR_ASTERISK: 42, /* * */ CHAR_AMPERSAND: 38, /* & */ CHAR_AT: 64, /* @ */ CHAR_BACKWARD_SLASH: 92, /* \ */ CHAR_CARRIAGE_RETURN: 13, /* \r */ CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */ CHAR_COLON: 58, /* : */ CHAR_COMMA: 44, /* , */ CHAR_DOT: 46 /* . */ }; ``` -------------------------------- ### Create and Add Icon Marker Entity Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md This snippet shows how to create an icon marker with a specific position, icon source path, and scale, then add it to the map. ```typescript import { IconMarker } from 'micro-gis/openlayers'; const marker = new IconMarker({ position: [116.4, 39.9], src: '/marker.png', scale: 0.8, }); olMap.addEntity(marker); ``` -------------------------------- ### RGB Color Constructor and Utilities Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Defines the Rgb color class and its associated constructor. Includes methods for color manipulation like `brighter`, `darker`, `clamp`, and formatting to hex and rgb strings. Ensures color values are within valid ranges. ```javascript function rgbn(n) { return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1); } ``` ```javascript function rgba(r, g, b, a) { if (a <= 0) r = g = b = NaN; return new Rgb(r, g, b, a); } ``` ```javascript function rgbConvert(o) { if (!(o instanceof Color)) o = color(o); if (!o) return new Rgb; o = o.rgb(); return new Rgb(o.r, o.g, o.b, o.opacity); } ``` ```javascript function rgb$1(r, g, b, opacity) { return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); } ``` ```javascript function Rgb(r, g, b, opacity) { this.r = +r; this.g = +g; this.b = +b; this.opacity = +opacity; } ``` ```javascript define(Rgb, rgb$1, extend(Color, { brighter(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, darker(k) { k = k == null ? darker : Math.pow(darker, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, rgb() { return this; }, clamp() { return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity)); }, displayable() { return (-0.5 <= this.r && this.r < 255.5) && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1); }, hex: rgb_formatHex, // Deprecated! Use color.formatHex. formatHex: rgb_formatHex, formatHex8: rgb_formatHex8, formatRgb: rgb_formatRgb, toString: rgb_formatRgb })); ``` ```javascript function rgb_formatHex() { return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`; } ``` ```javascript function rgb_formatHex8() { return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`; } ``` ```javascript function rgb_formatRgb() { const a = clampa(this.opacity); return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : ", ${a}) `} `; } ``` ```javascript function clampa(opacity) { return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity)); } ``` ```javascript function clampi(value) { return Math.max(0, Math.min(255, Math.round(value) || 0)); } ``` ```javascript function hex(value) { value = clampi(value); return (value < 16 ? "0" : "") + value.toString(16); } ``` -------------------------------- ### Extended Glob Opening Logic Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Handles the opening of extended glob patterns, setting up token properties and managing state for nested structures. It increments parenthesis count and pushes initial tokens. ```javascript const extglobOpen = (type, value) => { const token = { ...EXTGLOB_CHARS[value], conditions: 1, inner: '' }; token.prev = prev; token.parens = state.parens; token.output = state.output; const output = (opts.capture ? '(' : '') + token.open; increment('parens'); push({ type, value, output: state.output ? '' : ONE_CHAR }); push({ type: 'paren', extglob: true, value: advance(), output }); extglobs.push(token); }; ``` -------------------------------- ### Child Application: Connecting to Parent GIS Service Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md In the child application's main entry point, use the 'addBridgeModule' function from 'micro-gis/bridge' to connect to the parent's GIS service. This allows the child to consume GIS functionalities provided by the parent. ```typescript // main.ts import { addBridgeModule } from "micro-gis/bridge"; let app = null; window.mount = async () => { app = createApp(App); // 微前端环境下连接GIS服务 if (window.__MICRO_APP_ENVIRONMENT__) { // 通过桥接模块连接父应用的GIS服务 addBridgeModule(window.rawWindow); // 或使用 window.MicroGis // addBridgeModule({ MicroGis: window.MicroGis }); } app.mount('#app'); }; // 非微前端环境直接挂载 if (!window.__MICRO_APP_ENVIRONMENT__) { window.mount(); } ``` -------------------------------- ### InternMap Class for Key Management Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html An extension of the Map class that uses an internal map to manage keys, allowing for custom key generation and retrieval. Useful for scenarios where keys need to be normalized or transformed. ```javascript class InternMap extends Map { constructor(entries, key = keyof) { super(); Object.defineProperties(this, {"_intern": {value: new Map()}, "_key": {value: key}}); if (entries != null) for (const [key, value] of entries) this.set(key, value); } get(key) { return super.get(intern_get(this, key)); } has(key) { return super.has(intern_get(this, key)); } set(key, value) { return super.set(intern_set(this, key), value); } delete(key) { return super.delete(intern_delete(this, key)); } } function intern_get({"_intern", "_key"}, value) { const key = _key(value); return _intern.has(key) ? _intern.get(key) : value; } function intern_set({"_intern", "_key"}, value) { const key = _key(value); if (_intern.has(key)) return _intern.get(key); _intern.set(key, value); return value; } function intern_delete({"_intern", "_key"}, value) { const key = _key(value); if (_intern.has(key)) { value = _intern.get(key); _intern.delete(key); } return value; } function keyof(value) { return value !== null && typeof value === "object" ? value.valueOf() : value; } ``` -------------------------------- ### Glob Pattern Matching Helper Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Creates a test function for a given glob pattern, enabling dotfiles to be included in the match. ```javascript const globToTest = (glob) => { const pattern = glob; const fn = pm(pattern, { dot: true }); return { test: (what) => { const result = fn(what); return result; } }; }; ``` -------------------------------- ### Node Traversal: Each Before Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Applies a callback function to each node in a tree structure before visiting its children. This is useful for pre-order traversal. ```javascript function node_eachBefore(callback, that) { var node = this, nodes = [node], children, i, index = -1; while (node = nodes.pop()) { callback.call(that, node, ++index, this); if (children = node.children) { for (i = children.length - 1; i >= 0; --i) { nodes.push(children[i]); } } } return this; } ``` -------------------------------- ### Check if Any Pattern Matches with Picomatch Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Demonstrates the `picomatch.isMatch` function, which checks if a string matches any of the provided glob patterns. This is convenient for scenarios where multiple patterns need to be checked against a single string. ```javascript const picomatch = require('picomatch'); // picomatch.isMatch(string, patterns[, options]); console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true console.log(picomatch.isMatch('a.a', 'b.*')); //=> false ``` -------------------------------- ### Memoized Value Hook with Initial Value Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html This hook is similar to `T` but allows specifying an initial value. It memoizes the value and recomputes it only when dependencies change. Useful for derived state that needs an initial value. ```javascript function q(n,t){return o=8,T(function(){return n},t);} ``` -------------------------------- ### Bytes Formatting and Parsing Utility Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Provides functions to format byte values into human-readable strings and parse strings back into byte values. Supports various units (B, KB, MB, GB, TB, PB) and customizable formatting options. ```javascript var bytes = {exports: {}}; /*! * bytes * Copyright(c) 2012-2014 TJ Holowaychuk * Copyright(c) 2015 Jed Watson * MIT Licensed */ var hasRequiredBytes; function requireBytes () { if (hasRequiredBytes) return bytes.exports; hasRequiredBytes = 1; /** * Module exports. * @public */ bytes.exports = bytes$1; bytes.exports.format = format; bytes.exports.parse = parse; /** * Module variables. * @private */ var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; var formatDecimalsRegExp = /(?:\.0*|(\.([^0]+))0+$)/; var map = { b: 1, kb: 1 << 10, mb: 1 << 20, gb: 1 << 30, tb: Math.pow(1024, 4), pb: Math.pow(1024, 5), }; var parseRegExp = /^((-|\+)?(\d+(\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; /** * Convert the given value in bytes into a string or parse to string to an integer in bytes. * * @param {string|number} value * @param {{ * case: [string], * decimalPlaces: [number] * fixedDecimals: [boolean] * thousandsSeparator: [string] * unitSeparator: [string] * }} [options] bytes options. * * @returns {string|number|null} */ function bytes$1(value, options) { if (typeof value === 'string') { return parse(value); } if (typeof value === 'number') { return format(value, options); } return null; } /** * Format the given value in bytes into a string. * * If the value is negative, it is kept as such. If it is a float, * it is rounded. * * @param {number} value * @param {object} [options] * @param {number} [options.decimalPlaces=2] * @param {number} [options.fixedDecimals=false] * @param {string} [options.thousandsSeparator=] * @param {string} [options.unit=] * @param {string} [options.unitSeparator=] * * @returns {string|null} * @public */ function format(value, options) { if (!Number.isFinite(value)) { return null; } var mag = Math.abs(value); var thousandsSeparator = (options && options.thousandsSeparator) || ''; var unitSeparator = (options && options.unitSeparator) || ''; var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; var fixedDecimals = Boolean(options && options.fixedDecimals); var unit = (options && options.unit) || ''; if (!unit || !map[unit.toLowerCase()]) { if (mag >= map.pb) { unit = 'PB'; } else if (mag >= map.tb) { unit = 'TB'; } else if (mag >= map.gb) { unit = 'GB'; } else if (mag >= map.mb) { unit = 'MB'; } else if (mag >= map.kb) { unit = 'KB'; } else { unit = 'B'; } } var val = value / map[unit.toLowerCase()]; var str = val.toFixed(decimalPlaces); if (!fixedDecimals) { str = str.replace(formatDecimalsRegExp, '$1'); } if (thousandsSeparator) { str = str.split('.').map(function (s, i) { return i === 0 ? s.replace(formatThousandsRegExp, thousandsSeparator) : s }).join('.'); } return str + unitSeparator + unit; } /** * Parse the string value into an integer in bytes. */ ``` -------------------------------- ### Define Module Imports Source: https://github.com/an501920078/micro-gis-base/blob/main/test/index.html Specifies module imports for Vue, Axios, and Cesium. ```json { "imports": { "vue":"./vue.js", "axios":"./axios.js", "cesium":"../Cesium/index.js" } } ``` -------------------------------- ### Create EXTGLOB_CHARS Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Generates an object mapping extended glob characters to their corresponding regex components for negation, optional matching, and repetition. ```javascript extglobChars(chars) { return { '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR}) ` }, '?': { type: 'qmark', open: '(?:', close: ')?' }, '+': { type: 'plus', open: '(?:', close: ')+' }, '*': { type: 'star', open: '(?:', close: ')*' }, '@': { type: 'at', open: '(?:', close: ')' } }; } ``` -------------------------------- ### Math Utility Functions Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md A collection of mathematical utility functions for conversions between camera height and zoom levels, and for converting map extents to coordinate arrays. ```APIDOC ## Module: Math Utilities ### Description Provides utility functions for common geospatial calculations. ### Functions #### `heightToZoom(height: number): number` - **Description**: Converts camera height in meters to an OpenLayers zoom level using a logarithmic scale based on EPSG:4326. Calibrated such that 25000m height corresponds to zoom level 12. - **Parameters**: - `height` (number): Camera height in meters. Handles `height <= 0` by returning 28. - **Returns**: (number) The corresponding zoom level. #### `zoomToHeight(zoom: number): number` - **Description**: Converts an OpenLayers zoom level back to camera height in meters. This is the precise inverse of `heightToZoom`. - **Parameters**: - `zoom` (number): The zoom level. Handles `zoom < 0` by returning the K value used in the logarithmic scale. - **Returns**: (number) The corresponding camera height in meters. #### `zoomToradius(zoom: number): number` - **Description**: Converts a zoom level to a search radius. - **Parameters**: - `zoom` (number): The zoom level. - **Returns**: (number) The calculated search radius. #### `ExtentToCoordinateArr(extent: Extent): Coordinate[]` - **Description**: Converts a map extent object to an array of coordinates. - **Parameters**: - `extent` (Extent): The extent object (e.g., `[minX, minY, maxX, maxY]`). - **Returns**: (Coordinate[]) An array of coordinates representing the extent boundaries. ``` -------------------------------- ### Filter Preparation Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Parses a comma-separated string of filters into an array of objects, normalizing bundle and file paths and handling quotes. ```javascript const prepareFilter = (filt) => { if (filt === "") return []; return ( filt .split(",") // remove spaces before and after .map((entry) => entry.trim()) // unquote " .map((entry) => entry.startsWith('"') && entry.endsWith('"') ? entry.substring(1, entry.length - 1) : entry) // unquote ' .map((entry) => entry.startsWith("'"') && entry.endsWith("'"') ? entry.substring(1, entry.length - 1) : entry) // remove empty strings .filter((entry) => entry) // parse bundle:file .map((entry) => entry.split(":")) // normalize entry just in case .flatMap((entry) => { if (entry.length === 0) return []; let bundle = null; let file = null; if (entry.length === 1 && entry[0]) { file = entry[0]; return [{ file, bundle }]; } bundle = entry[0] || null; file = entry.slice(1).join(":") || null; return [{ bundle, file }]; }) ); }; ``` -------------------------------- ### Set Node Environment Variable Source: https://github.com/an501920078/micro-gis-base/blob/main/test/index.html Sets the NODE_ENV to 'production' for the application. ```javascript const obj = { env: { NODE_ENV: "production" } } window.process = obj; ``` -------------------------------- ### useCesium Hook (Base) Source: https://github.com/an501920078/micro-gis-base/blob/main/SKILL.md A fundamental hook for integrating with Cesium. It provides access to the Cesium Viewer instance, map layer handlers, and initialization functions. ```APIDOC ## useCesium Hook (Base) ### Description Provides core functionalities for integrating with Cesium. ### Parameters - `options` (object): Configuration options for the Cesium map. - `settings` (object, optional): Map settings. - `lon` (number): Initial longitude. - `lat` (number): Initial latitude. - `height` (number): Initial height. - `name` (string, optional): Name for the map instance. ### Return Value - `viewerDivRef`: Ref for the map container DOM element. - `viewer`: ShallowRef of the Cesium Viewer instance. - `onViewerMounted(func) => void`: Callback function executed when the Viewer is mounted. - `init(fn?) => void`: Initializes the map. - `mapLayerHandle`: Handler for base map layers. - `pipeWmsLayerHandle`: Handler for pipe WMS layers. ### Example Usage ```vue ``` ``` -------------------------------- ### FormatSpecifier Constructor Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Constructor for FormatSpecifier objects, initializing properties from a specifier object. Sets default values if not provided. ```javascript function FormatSpecifier(specifier) { this.fill = specifier.fill === undefined ? " " : specifier.fill + ""; this.align = specifier.align === undefined ? ">" : specifier.align + ""; this.sign = specifier.sign === undefined ? "-" : specifier.sign + ""; this.symbol = specifier.symbol === undefined ? "" : specifier.symbol + ""; this.zero = !!specifier.zero; this.width = specifier.width === undefined ? undefined : +specifier.width; this.comma = !!specifier.comma; this.precision = specifier.precision === undefined ? undefined : +specifier.precision; this.trim = !!specifier.trim; this.type = specifier.type === undefined ? "" : specifier.type + ""; } ``` -------------------------------- ### Color Object Utility Methods Source: https://github.com/an501920078/micro-gis-base/blob/main/stats.html Provides utility methods for a Color object, including copying color channels, checking displayability, and formatting to hex. The `color_formatHex` method is deprecated. ```javascript define(Color, color, { copy(channels) { return Object.assign(new this.constructor, this, channels); }, displayable() { return this.rgb().displayable(); }, hex: color_formatHex, // Deprecated! Use color.formatHex. }); ```