repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
vue-vapor
github_2023
vuejs
typescript
mockElementWithStyle
function mockElementWithStyle() { const store: any = {} return { style: { display: '', WebkitTransition: '', setProperty(key: string, val: string) { store[key] = val }, getPropertyValue(key: string) { return store[key] }, }, } }
// JSDOM doesn't support custom properties on style object so we have to
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/__tests__/patchStyle.spec.ts#L123-L137
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
VueElement._resolveDef
private _resolveDef() { if (this._pendingResolve) { return } // set initial attrs for (let i = 0; i < this.attributes.length; i++) { this._setAttr(this.attributes[i].name) } // watch future attr changes this._ob = new MutationObserver(mutations => { for (const m of mutations) { this._setAttr(m.attributeName!) } }) this._ob.observe(this, { attributes: true }) const resolve = (def: InnerComponentDef, isAsync = false) => { this._resolved = true this._pendingResolve = undefined const { props, styles } = def // cast Number-type props set before resolve let numberProps if (props && !isArray(props)) { for (const key in props) { const opt = props[key] if (opt === Number || (opt && opt.type === Number)) { if (key in this._props) { this._props[key] = toNumber(this._props[key]) } ;(numberProps || (numberProps = Object.create(null)))[ camelize(key) ] = true } } } this._numberProps = numberProps if (isAsync) { // defining getter/setters on prototype // for sync defs, this already happened in the constructor this._resolveProps(def) } // apply CSS if (this.shadowRoot) { this._applyStyles(styles) } else if (__DEV__ && styles) { warn( 'Custom element style injection is not supported when using ' + 'shadowRoot: false', ) } // initial mount this._mount(def) } const asyncDef = (this._def as ComponentOptions).__asyncLoader if (asyncDef) { this._pendingResolve = asyncDef().then(def => resolve((this._def = def), true), ) } else { resolve(this._def) } }
/** * resolve inner component definition (handle possible async component) */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/apiCustomElement.ts#L342-L412
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
VueElement._getProp
protected _getProp(key: string): any { return this._props[key] }
/** * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/apiCustomElement.ts#L480-L482
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
VueElement._setProp
_setProp( key: string, val: any, shouldReflect = true, shouldUpdate = false, ): void { if (val !== this._props[key]) { if (val === REMOVAL) { delete this._props[key] } else { this._props[key] = val // support set key on ceVNode if (key === 'key' && this._app) { this._app._ceVNode!.key = val } } if (shouldUpdate && this._instance) { this._update() } // reflect if (shouldReflect) { const ob = this._ob ob && ob.disconnect() if (val === true) { this.setAttribute(hyphenate(key), '') } else if (typeof val === 'string' || typeof val === 'number') { this.setAttribute(hyphenate(key), val + '') } else if (!val) { this.removeAttribute(hyphenate(key)) } ob && ob.observe(this, { attributes: true }) } } }
/** * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/apiCustomElement.ts#L487-L520
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
VueElement._parseSlots
private _parseSlots() { const slots: VueElement['_slots'] = (this._slots = {}) let n while ((n = this.firstChild)) { const slotName = (n.nodeType === 1 && (n as Element).getAttribute('slot')) || 'default' ;(slots[slotName] || (slots[slotName] = [])).push(n) this.removeChild(n) } }
/** * Only called when shadowRoot is false */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/apiCustomElement.ts#L617-L626
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
VueElement._renderSlots
private _renderSlots() { const outlets = (this._teleportTarget || this).querySelectorAll('slot') const scopeId = this._instance!.type.__scopeId for (let i = 0; i < outlets.length; i++) { const o = outlets[i] as HTMLSlotElement const slotName = o.getAttribute('name') || 'default' const content = this._slots![slotName] const parent = o.parentNode! if (content) { for (const n of content) { // for :slotted css if (scopeId && n.nodeType === 1) { const id = scopeId + '-s' const walker = document.createTreeWalker(n, 1) ;(n as Element).setAttribute(id, '') let child while ((child = walker.nextNode())) { ;(child as Element).setAttribute(id, '') } } parent.insertBefore(n, o) } } else { while (o.firstChild) parent.insertBefore(o.firstChild, o) } parent.removeChild(o) } }
/** * Only called when shadowRoot is false */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/apiCustomElement.ts#L631-L658
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
VueElement._injectChildStyle
_injectChildStyle(comp: ConcreteComponent & CustomElementOptions): void { this._applyStyles(comp.styles, comp) }
/** * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/apiCustomElement.ts#L663-L665
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
VueElement._removeChildStyle
_removeChildStyle(comp: ConcreteComponent): void { if (__DEV__) { this._styleChildren.delete(comp) if (this._childStyles && comp.__hmrId) { // clear old styles const oldStyles = this._childStyles.get(comp.__hmrId) if (oldStyles) { oldStyles.forEach(s => this._root.removeChild(s)) oldStyles.length = 0 } } } }
/** * @internal */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/apiCustomElement.ts#L670-L682
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
injectCompilerOptionsCheck
function injectCompilerOptionsCheck(app: App) { if (isRuntimeOnly()) { const isCustomElement = app.config.isCustomElement Object.defineProperty(app.config, 'isCustomElement', { get() { return isCustomElement }, set() { warn( `The \`isCustomElement\` config option is deprecated. Use ` + `\`compilerOptions.isCustomElement\` instead.`, ) }, }) const compilerOptions = app.config.compilerOptions const msg = `The \`compilerOptions\` config option is only respected when using ` + `a build of Vue.js that includes the runtime compiler (aka "full build"). ` + `Since you are using the runtime-only build, \`compilerOptions\` ` + `must be passed to \`@vue/compiler-dom\` in the build setup instead.\n` + `- For vue-loader: pass it via vue-loader's \`compilerOptions\` loader option.\n` + `- For vue-cli: see https://cli.vuejs.org/guide/webpack.html#modifying-options-of-a-loader\n` + `- For vite: pass it via @vitejs/plugin-vue options. See https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue#example-for-passing-options-to-vuecompiler-sfc` Object.defineProperty(app.config, 'compilerOptions', { get() { warn(msg) return compilerOptions }, set() { warn(msg) }, }) } }
// dev only
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/index.ts#L191-L226
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
decorate
const decorate = (t: typeof Transition) => { t.displayName = 'Transition' t.props = TransitionPropsValidators if (__COMPAT__) { t.__isBuiltIn = true } return t }
/** * Wrap logic that attaches extra properties to Transition in a function * so that it can be annotated as pure */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/components/Transition.ts#L74-L81
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
callHook
const callHook = ( hook: Function | Function[] | undefined, args: any[] = [], ) => { if (isArray(hook)) { hook.forEach(h => h(...args)) } else if (hook) { hook(...args) } }
/** * #3227 Incoming hooks may be merged into arrays when wrapping Transition * with custom HOCs. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/components/Transition.ts#L96-L105
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
hasExplicitCallback
const hasExplicitCallback = ( hook: Function | Function[] | undefined, ): boolean => { return hook ? isArray(hook) ? hook.some(h => h.length > 1) : hook.length > 1 : false }
/** * Check if a hook expects a callback (2nd arg), which means the user * intends to explicitly control the end of the transition. */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/components/Transition.ts#L111-L119
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getStyleProperties
const getStyleProperties = (key: StylePropertiesKey) => (styles[key] || '').split(', ')
// JSDOM may return undefined for transition properties
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/components/Transition.ts#L410-L411
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
toMs
function toMs(s: string): number { // #8409 default value for CSS durations can be 'auto' if (s === 'auto') return 0 return Number(s.slice(0, -1).replace(',', '.')) * 1000 }
// Old versions of Chromium (below 61.0.3163.100) formats floating pointer
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/components/Transition.ts#L472-L476
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
decorate
const decorate = (t: typeof TransitionGroupImpl) => { // TransitionGroup does not support "mode" so we need to remove it from the // props declarations, but direct delete operation is considered a side effect delete t.props.mode if (__COMPAT__) { t.__isBuiltIn = true } return t }
/** * Wrap logic that modifies TransitionGroup properties in a function * so that it can be annotated as pure */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/components/TransitionGroup.ts#L46-L54
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getValue
function getValue(el: HTMLOptionElement | HTMLInputElement) { return '_value' in el ? (el as any)._value : el.value }
// retrieve raw value set via :value bindings
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/directives/vModel.ts#L280-L282
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getCheckboxValue
function getCheckboxValue( el: HTMLInputElement & { _trueValue?: any; _falseValue?: any }, checked: boolean, ) { const key = checked ? '_trueValue' : '_falseValue' return key in el ? el[key] : checked }
// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-dom/src/directives/vModel.ts#L285-L291
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
mockElementWithStyle
function mockElementWithStyle() { const store: any = {} return { style: { display: '', WebkitTransition: '', setProperty(key: string, val: string) { store[key] = val }, getPropertyValue(key: string) { return store[key] }, }, } }
// JSDOM doesn't support custom properties on style object so we have to
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/__tests__/dom/prop.spec.ts#L156-L170
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getSequence
function getSequence(arr: number[]): number[] { const p = arr.slice() const result = [0] let i, j, u, v, c const len = arr.length for (i = 0; i < len; i++) { const arrI = arr[i] if (arrI !== 0) { j = result[result.length - 1] if (arr[j] < arrI) { p[i] = j result.push(i) continue } u = 0 v = result.length - 1 while (u < v) { c = (u + v) >> 1 if (arr[result[c]] < arrI) { u = c + 1 } else { v = c } } if (arrI < arr[result[u]]) { if (u > 0) { p[i] = result[u - 1] } result[u] = i } } } u = result.length v = result[u - 1] while (u-- > 0) { result[u] = v v = p[v] } return result }
// https://en.wikipedia.org/wiki/Longest_increasing_subsequence
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/apiCreateFor.ts#L392-L431
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
inferFromRegistry
const inferFromRegistry = (registry: Record<string, any> | undefined) => { for (const key in registry) { if (registry[key] === Component) { return key } } }
// try to infer the name based on reverse resolution
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/component.ts#L399-L405
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
validateProps
function validateProps( rawProps: NormalizedRawProps, props: Data, options: NormalizedProps, ) { const presentKeys: string[] = [] for (const props of rawProps) { presentKeys.push(...Object.keys(isFunction(props) ? props() : props)) } for (const key in options) { const opt = options[key] if (opt != null) validateProp( key, props[key], opt, props, !presentKeys.some(k => camelize(k) === key), ) } }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/componentProps.ts#L336-L357
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
validateProp
function validateProp( name: string, value: unknown, option: PropOptions, props: Data, isAbsent: boolean, ) { const { required, validator } = option // required! if (required && isAbsent) { warn('Missing required prop: "' + name + '"') return } // missing but optional if (value == null && !required) { return } // NOTE: type check is not supported in vapor // // type check // if (type != null && type !== true) { // let isValid = false // const types = isArray(type) ? type : [type] // const expectedTypes = [] // // value is valid as long as one of the specified types match // for (let i = 0; i < types.length && !isValid; i++) { // const { valid, expectedType } = assertType(value, types[i]) // expectedTypes.push(expectedType || '') // isValid = valid // } // if (!isValid) { // warn(getInvalidTypeMessage(name, value, expectedTypes)) // return // } // } // custom validator if (validator && !validator(value, props)) { warn('Invalid prop: custom validator check failed for prop "' + name + '".') } }
/** * dev only */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/componentProps.ts#L362-L401
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
createDevtoolsComponentHook
function createDevtoolsComponentHook( hook: DevtoolsHooks, ): DevtoolsComponentHook { return (component: ComponentInternalInstance) => { emit( hook, component.appContext.app, component.uid, component.parent ? component.parent.uid : undefined, component, ) } }
/*! #__NO_SIDE_EFFECTS__ */
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/devtools.ts#L123-L135
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
flushJobs
function flushJobs() { if (__BENCHMARK__) performance.mark('flushJobs-start') isFlushPending = false isFlushing = true // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child so its render effect will have smaller // priority number) // 2. If a component is unmounted during a parent component's update, // its update can be skipped. queue.sort(comparator) try { for (let i = 0; i < queue!.length; i++) { queue[i]() queue[i].flags! &= ~VaporSchedulerJobFlags.QUEUED } } finally { flushIndex = 0 queue.length = 0 flushPostFlushCbs() isFlushing = false currentFlushPromise = null // some postFlushCb queued jobs! // keep flushing until it drains. if (queue.length || pendingPostFlushCbs.length) { flushJobs() } if (__BENCHMARK__) performance.mark('flushJobs-end') } }
// TODO: dev mode and checkRecursiveUpdates
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/scheduler.ts#L141-L175
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
findInsertionIndex
function findInsertionIndex(id: number) { // the start index should be `flushIndex + 1` let start = flushIndex + 1 let end = queue.length while (start < end) { const middle = (start + end) >>> 1 const middleJob = queue[middle] const middleJobId = getId(middleJob) if ( middleJobId < id || (middleJobId === id && middleJob.flags! & VaporSchedulerJobFlags.PRE) ) { start = middle + 1 } else { end = middle } } return start }
// #2768
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/scheduler.ts#L189-L209
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getValue
function getValue(el: HTMLOptionElement | HTMLInputElement) { const metadata = getMetadata(el) return (metadata && metadata[MetadataKind.prop].value) || el.value }
// retrieve raw value set via :value bindings
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/directives/vModel.ts#L216-L219
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
getCheckboxValue
function getCheckboxValue(el: HTMLInputElement, checked: boolean) { const metadata = getMetadata(el) const props = metadata && metadata[MetadataKind.prop] const key = checked ? 'true-value' : 'false-value' if (props && key in props) { return props[key] } if (el.hasAttribute(key)) { return el.getAttribute(key) } return checked }
// retrieve raw value for true-value and false-value set via :true-value or :false-value bindings
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/directives/vModel.ts#L222-L233
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
shouldSetAsProp
function shouldSetAsProp( el: Element, key: string, value: unknown, isSVG: boolean, ) { if (isSVG) { // most keys must be set as attribute on svg elements to work // ...except innerHTML & textContent if (key === 'innerHTML' || key === 'textContent') { return true } // or native onclick with function values if (key in el && isNativeOn(key) && isFunction(value)) { return true } return false } const attrCacheKey = `${el.tagName}_${key}` if ( attributeCache[attrCacheKey] === undefined ? (attributeCache[attrCacheKey] = shouldSetAsAttr(el.tagName, key)) : attributeCache[attrCacheKey] ) { return false } // native onclick with string value, must be set as attribute if (isNativeOn(key) && isString(value)) { return false } return key in el }
// TODO copied from runtime-dom
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/dom/prop.ts#L219-L253
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
resolveAsset
function resolveAsset(type: AssetTypes, name: string, warnMissing = true) { const instance = currentInstance if (instance) { const Component = instance.type // explicit self name has highest priority if (type === COMPONENTS) { const selfName = getComponentName(Component) if ( selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name))) ) { return Component } } const res = // global registration resolve(instance.appContext[type], name) if (__DEV__ && warnMissing && !res) { const extra = type === COMPONENTS ? `\nIf this is a native custom element, make sure to exclude it from ` + `component resolution via compilerOptions.isCustomElement.` : `` warn(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`) } return res } else if (__DEV__) { warn( `resolve${capitalize(type.slice(0, -1))} ` + `can only be used in render() or setup().`, ) } }
// implementation
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/runtime-vapor/src/helpers/resolveAssets.ts#L35-L73
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
isRef
const isRef = (val: any): val is { value: unknown } => { return !!(val && val[ReactiveFlags.IS_REF] === true) }
// can't use isRef here since @vue/shared has no deps
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/shared/src/toDisplayString.ts#L16-L18
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
assertPolygon
async function assertPolygon(total: number) { expect( await page().evaluate( ([total]) => { const points = globalStats .map((stat, i) => { const point = valueToPoint(stat.value, i, total) return point.x + ',' + point.y }) .join(' ') return ( document.querySelector('polygon')!.attributes[0].value === points ) }, [total], ), ).toBe(true) }
// assert the shape of the polygon is correct
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/vue/__tests__/e2e/svg.spec.ts#L22-L39
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
assertLabels
async function assertLabels(total: number) { const positions = await page().evaluate( ([total]) => { return globalStats.map((stat, i) => { const point = valueToPoint(+stat.value + 10, i, total) return [point.x, point.y] }) }, [total], ) for (let i = 0; i < total; i++) { const textPosition = await page().$eval( `text:nth-child(${i + 3})`, node => [+node.attributes[0].value, +node.attributes[1].value], ) expect(textPosition).toEqual(positions[i]) } }
// assert the position of each label is correct
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/vue/__tests__/e2e/svg.spec.ts#L42-L59
da75dd9131958ff4fb0f9b592c99cd76c761e272
vue-vapor
github_2023
vuejs
typescript
assertStats
async function assertStats(expected: number[]) { const statsValue = await page().evaluate(() => { return globalStats.map(stat => +stat.value) }) expect(statsValue).toEqual(expected) }
// assert each value of stats is correct
https://github.com/vuejs/vue-vapor/blob/da75dd9131958ff4fb0f9b592c99cd76c761e272/packages/vue/__tests__/e2e/svg.spec.ts#L62-L67
da75dd9131958ff4fb0f9b592c99cd76c761e272
three-vue-tres
github_2023
hawk86104
typescript
echartsUpdateHandle
const echartsUpdateHandle = (dataset: any) => { if (chartFrame === ChartFrameEnum.ECHARTS) { if (vChartRef.value) { setOption(vChartRef.value, { dataset: dataset }) } } }
// eCharts 组件配合 vChart 库更新方式
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/useChartDataFetch.hook.ts#L36-L42
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
newPondItemInterval
const newPondItemInterval = ( requestGlobalConfig: RequestGlobalConfigType, requestDataPondItem: ComputedRef<RequestDataPondItemType>, dataPondMapItem?: DataPondMapType[] ) => { if (!dataPondMapItem) return let fetchInterval: any = 0 clearInterval(fetchInterval) // 请求 const fetchFn = async () => { try { const res = await customizeHttp(toRaw(requestDataPondItem.value.dataPondRequestConfig), toRaw(requestGlobalConfig)) if (res) { try { // 遍历更新回调函数 dataPondMapItem.forEach(item => { item.updateCallback(newFunctionHandle(res?.data, res, item.filter)) }) } catch (error) { console.error(error) return error } } } catch (error) { return error } } watch( () => requestDataPondItem.value.dataPondRequestConfig.requestParams.Params, () => { fetchFn() }, { immediate: false, deep: true } ) // 立即调用 fetchFn() const targetInterval = requestDataPondItem.value.dataPondRequestConfig.requestInterval const targetUnit = requestDataPondItem.value.dataPondRequestConfig.requestIntervalUnit const globalRequestInterval = requestGlobalConfig.requestInterval const globalUnit = requestGlobalConfig.requestIntervalUnit // 定时时间 const time = targetInterval ? targetInterval : globalRequestInterval // 单位 const unit = targetInterval ? targetUnit : globalUnit // 开启轮询 if (time) fetchInterval = setInterval(fetchFn, intervalUnitHandle(time, unit)) }
// 创建单个数据项轮询接口
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/useChartDataPondFetch.hook.ts#L21-L79
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
fetchFn
const fetchFn = async () => { try { const res = await customizeHttp(toRaw(requestDataPondItem.value.dataPondRequestConfig), toRaw(requestGlobalConfig)) if (res) { try { // 遍历更新回调函数 dataPondMapItem.forEach(item => { item.updateCallback(newFunctionHandle(res?.data, res, item.filter)) }) } catch (error) { console.error(error) return error } } } catch (error) { return error } }
// 请求
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/useChartDataPondFetch.hook.ts#L32-L49
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
addGlobalDataInterface
const addGlobalDataInterface = ( targetComponent: CreateComponentType, useChartEditStore: ChartEditStoreType, updateCallback: (...args: any) => any ) => { const chartEditStore = useChartEditStore() const { requestDataPond } = chartEditStore.getRequestGlobalConfig // 组件对应的数据池 Id const requestDataPondId = targetComponent.request.requestDataPondId as string // 新增数据项 const mittPondIdArr = mittDataPondMap.get(requestDataPondId) || [] mittPondIdArr.push({ updateCallback: updateCallback, filter: targetComponent.filter }) mittDataPondMap.set(requestDataPondId, mittPondIdArr) }
// 新增全局接口
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/useChartDataPondFetch.hook.ts#L86-L103
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
clearMittDataPondMap
const clearMittDataPondMap = () => { mittDataPondMap.clear() }
// 清除旧数据
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/useChartDataPondFetch.hook.ts#L106-L108
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
initDataPond
const initDataPond = (useChartEditStore: ChartEditStoreType) => { const { requestGlobalConfig } = useChartEditStore() const chartEditStore = useChartEditStore() // 根据 mapId 查找对应的数据池配置 for (let pondKey of mittDataPondMap.keys()) { const requestDataPondItem = computed(() => { return requestGlobalConfig.requestDataPond.find(item => item.dataPondId === pondKey) }) as ComputedRef<RequestDataPondItemType> if (requestDataPondItem) { newPondItemInterval(chartEditStore.requestGlobalConfig, requestDataPondItem, mittDataPondMap.get(pondKey)) } } }
// 初始化数据池
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/useChartDataPondFetch.hook.ts#L111-L123
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
generateFunc
function generateFunc(fnStr: string, e: any) { try { // npmPkgs 便于拷贝 echarts 示例时设置option 的formatter等相关内容 Function(` "use strict"; return ( async function(e, components, node_modules){ const {${Object.keys(npmPkgs).join()}} = node_modules; ${fnStr} } )`)().bind(e?.component)(e, components, npmPkgs) } catch (error) { console.error(error) } }
/** * 生成高级函数 * @param fnStr 用户方法体代码 * @param e 执行生命周期的动态组件实例 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/useLifeHandler.hook.ts#L65-L79
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
windowResize
const windowResize = () => { window.addEventListener('resize', resize) }
// * 改变窗口大小重新绘制
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/usePreviewScale.hook.ts#L53-L55
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
unWindowResize
const unWindowResize = () => { window.removeEventListener('resize', resize) }
// * 卸载监听
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/gHooks/usePreviewScale.hook.ts#L58-L60
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
windowResize
const windowResize = () => { window.addEventListener('resize', resize) }
// * 改变窗口大小重新绘制
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/hooks/usePreviewScale.hook.ts#L53-L55
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
unWindowResize
const unWindowResize = () => { window.removeEventListener('resize', resize) }
// * 卸载监听
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/hooks/usePreviewScale.hook.ts#L58-L60
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
useAddWheelHandle
const useAddWheelHandle = (removeEvent: Function) => { addEventListener( 'wheel', (e: any) => { if (window?.$KeyboardActive?.ctrl) { e.preventDefault() e.stopPropagation() removeEvent() const transform = previewRef.value?.style.transform const regRes = transform.match(/scale\((\d+\.?\d*)*/) as RegExpMatchArray const width = regRes[1] const previewBoxDom = document.querySelector('.go-preview') as HTMLElement const entityDom = document.querySelector('.go-preview-entity') as HTMLElement if (previewBoxDom) { previewBoxDom.style.overflow = 'unset' previewBoxDom.style.position = 'absolute' } if (entityDom) { entityDom.style.overflow = 'unset' } if (e.wheelDelta > 0) { const resNum = parseFloat(Number(width).toFixed(2)) previewRef.value.style.transform = `scale(${resNum > 5 ? 5 : resNum + 0.1})` } else { const resNum = parseFloat(Number(width).toFixed(2)) previewRef.value.style.transform = `scale(${resNum < 0.2 ? 0.2 : resNum - 0.1})` } } }, { passive: false } ) }
// 监听鼠标滚轮 +ctrl 键
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/hooks/useScale.hook.ts#L17-L49
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
fetchComponent
const fetchComponent = (chartName: string, flag: FetchComFlagType) => { const module = flag === FetchComFlagType.VIEW ? indexModules : configModules for (const key in module) { const urlSplit = key.split('/') if (urlSplit[urlSplit.length - 2] === chartName) { return module[key] } } }
/** * * 获取组件 * @param {string} chartName 名称 * @param {FetchComFlagType} flag 标识 0为展示组件, 1为配置组件 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/index.ts#L60-L68
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
createFlyLine
function createFlyLine(radius, startAngle, endAngle, color) { const geometry = new BufferGeometry() //声明一个几何体对象BufferGeometry // ArcCurve创建圆弧曲线 const arc = new ArcCurve(0, 0, radius, startAngle, endAngle, false) //getSpacedPoints是基类Curve的方法,返回一个vector2对象作为元素组成的数组 const pointsArr = arc.getSpacedPoints(100) //分段数80,返回81个顶点 geometry.setFromPoints(pointsArr) // setFromPoints方法从pointsArr中提取数据改变几何体的顶点属性vertices // 每个顶点对应一个百分比数据attributes.percent 用于控制点的渲染大小 const percentArr = [] //attributes.percent的数据 for (let i = 0; i < pointsArr.length; i++) { percentArr.push(i / pointsArr.length) } const percentAttribue = new BufferAttribute(new Float32Array(percentArr), 1) // 通过顶点数据percent点模型从大到小变化,产生小蝌蚪形状飞线 geometry.attributes.percent = percentAttribue // 批量计算所有顶点颜色数据 const colorArr = [] for (let i = 0; i < pointsArr.length; i++) { const color1 = new Color(0xec8f43) //轨迹线颜色 青色 const color2 = new Color(0xf3ae76) //黄色 const color = color1.lerp(color2, i / pointsArr.length) colorArr.push(color.r, color.g, color.b) } // 设置几何体顶点颜色数据 geometry.attributes.color = new BufferAttribute(new Float32Array(colorArr), 3) const size = 1.3 // 点模型渲染几何体每个顶点 const material = new PointsMaterial({ size, //点大小 // vertexColors: VertexColors, //使用顶点颜色渲染 transparent: true, depthWrite: false }) // 修改点材质的着色器源码(注意:不同版本细节可能会稍微会有区别,不过整体思路是一样的) material.onBeforeCompile = function (shader) { // 顶点着色器中声明一个attribute变量:百分比 shader.vertexShader = shader.vertexShader.replace( 'void main() {', [ 'attribute float percent;', //顶点大小百分比变量,控制点渲染大小 'void main() {' ].join('\n') // .join()把数组元素合成字符串 ) // 调整点渲染大小计算方式 shader.vertexShader = shader.vertexShader.replace( 'gl_PointSize = size;', ['gl_PointSize = percent * size;'].join('\n') // .join()把数组元素合成字符串 ) } const FlyLine = new Points(geometry, material) material.color = new Color(color) FlyLine.name = '飞行线' return FlyLine }
/* * 绘制一条圆弧飞线 * 5个参数含义:( 飞线圆弧轨迹半径, 开始角度, 结束角度) */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/Utils/arc.ts#L20-L74
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
flyArc
function flyArc(radius, lon1, lat1, lon2, lat2, options) { const sphereCoord1 = lon2xyz(radius, lon1, lat1) //经纬度坐标转球面坐标 // startSphereCoord:轨迹线起点球面坐标 const startSphereCoord = new Vector3(sphereCoord1.x, sphereCoord1.y, sphereCoord1.z) const sphereCoord2 = lon2xyz(radius, lon2, lat2) // startSphereCoord:轨迹线结束点球面坐标 const endSphereCoord = new Vector3(sphereCoord2.x, sphereCoord2.y, sphereCoord2.z) //计算绘制圆弧需要的关于y轴对称的起点、结束点和旋转四元数 const startEndQua = _3Dto2D(startSphereCoord, endSphereCoord) // 调用arcXOY函数绘制一条圆弧飞线轨迹 const arcline = arcXOY(radius, startEndQua.startPoint, startEndQua.endPoint, options) arcline.quaternion.multiply(startEndQua.quaternion) return arcline }
/**输入地球上任意两点的经纬度坐标,通过函数flyArc可以绘制一个飞线圆弧轨迹 * lon1,lat1:轨迹线起点经纬度坐标 * lon2,lat2:轨迹线结束点经纬度坐标 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/Utils/arc.ts#L80-L94
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
_3Dto2D
function _3Dto2D(startSphere, endSphere) { /*计算第一次旋转的四元数:表示从一个平面如何旋转到另一个平面*/ const origin = new Vector3(0, 0, 0) //球心坐标 const startDir = startSphere.clone().sub(origin) //飞线起点与球心构成方向向量 const endDir = endSphere.clone().sub(origin) //飞线结束点与球心构成方向向量 // dir1和dir2构成一个三角形,.cross()叉乘计算该三角形法线normal const normal = startDir.clone().cross(endDir).normalize() const xoyNormal = new Vector3(0, 0, 1) //XOY平面的法线 //.setFromUnitVectors()计算从normal向量旋转达到xoyNormal向量所需要的四元数 // quaternion表示把球面飞线旋转到XOY平面上需要的四元数 const quaternion3D_XOY = new Quaternion().setFromUnitVectors(normal, xoyNormal) /*第一次旋转:飞线起点、结束点从3D空间第一次旋转到XOY平面*/ const startSphereXOY = startSphere.clone().applyQuaternion(quaternion3D_XOY) const endSphereXOY = endSphere.clone().applyQuaternion(quaternion3D_XOY) /*计算第二次旋转的四元数*/ // middleV3:startSphereXOY和endSphereXOY的中点 const middleV3 = startSphereXOY.clone().add(endSphereXOY).multiplyScalar(0.5) const midDir = middleV3.clone().sub(origin).normalize() // 旋转前向量midDir,中点middleV3和球心构成的方向向量 const yDir = new Vector3(0, 1, 0) // 旋转后向量yDir,即y轴 // .setFromUnitVectors()计算从midDir向量旋转达到yDir向量所需要的四元数 // quaternion2表示让第一次旋转到XOY平面的起点和结束点关于y轴对称需要的四元数 const quaternionXOY_Y = new Quaternion().setFromUnitVectors(midDir, yDir) /*第二次旋转:使旋转到XOY平面的点再次旋转,实现关于Y轴对称*/ const startSpherXOY_Y = startSphereXOY.clone().applyQuaternion(quaternionXOY_Y) const endSphereXOY_Y = endSphereXOY.clone().applyQuaternion(quaternionXOY_Y) /**一个四元数表示一个旋转过程 *.invert()方法表示四元数的逆,简单说就是把旋转过程倒过来 * 两次旋转的四元数执行.invert()求逆,然后执行.multiply()相乘 *新版本.invert()对应旧版本.invert() */ const quaternionInverse = quaternion3D_XOY.clone().invert().multiply(quaternionXOY_Y.clone().invert()) return { // 返回两次旋转四元数的逆四元数 quaternion: quaternionInverse, // 范围两次旋转后在XOY平面上关于y轴对称的圆弧起点和结束点坐标 startPoint: startSpherXOY_Y, endPoint: endSphereXOY_Y } }
/* * 把3D球面上任意的两个飞线起点和结束点绕球心旋转到到XOY平面上, * 同时保持关于y轴对称,借助旋转得到的新起点和新结束点绘制 * 一个圆弧,最后把绘制的圆弧反向旋转到原来的起点和结束点即可 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/Utils/arc.ts#L100-L141
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
arcXOY
function arcXOY(radius, startPoint, endPoint, options) { // 计算两点的中点 const middleV3 = new Vector3().addVectors(startPoint, endPoint).multiplyScalar(0.5) // 弦垂线的方向dir(弦的中点和圆心构成的向量) const dir = middleV3.clone().normalize() // 计算球面飞线的起点、结束点和球心构成夹角的弧度值 const earthRadianAngle = radianAOB(startPoint, endPoint, new Vector3(0, 0, 0)) /*设置飞线轨迹圆弧的中间点坐标 弧度值 * radius * 0.2:表示飞线轨迹圆弧顶部距离地球球面的距离 起点、结束点相聚越远,构成的弧线顶部距离球面越高*/ const arcTopCoord = dir.multiplyScalar(radius + earthRadianAngle * radius * 0.2) // 黄色飞行线的高度 //求三个点的外接圆圆心(飞线圆弧轨迹的圆心坐标) const flyArcCenter = threePointCenter(startPoint, endPoint, arcTopCoord) // 飞线圆弧轨迹半径flyArcR const flyArcR = Math.abs(flyArcCenter.y - arcTopCoord.y) /*坐标原点和飞线起点构成直线和y轴负半轴夹角弧度值 参数分别是:飞线圆弧起点、y轴负半轴上一点、飞线圆弧圆心*/ const flyRadianAngle = radianAOB(startPoint, new Vector3(0, -1, 0), flyArcCenter) const startAngle = -Math.PI / 2 + flyRadianAngle //飞线圆弧开始角度 const endAngle = Math.PI - startAngle //飞线圆弧结束角度 // 调用圆弧线模型的绘制函数 const arcline = circleLine(flyArcCenter.x, flyArcCenter.y, flyArcR, startAngle, endAngle, options.color) // const arcline = new Group();// 不绘制轨迹线,使用 Group替换circleLine()即可 arcline.center = flyArcCenter //飞线圆弧自定一个属性表示飞线圆弧的圆心 arcline.topCoord = arcTopCoord //飞线圆弧自定一个属性表示飞线圆弧中间也就是顶部坐标 // const flyAngle = Math.PI/ 10; //飞线圆弧固定弧度 const flyAngle = (endAngle - startAngle) / 7 //飞线圆弧的弧度和轨迹线弧度相关 // 绘制一段飞线,圆心做坐标原点 const flyLine = createFlyLine(flyArcR, startAngle, startAngle + flyAngle, options.flyLineColor) flyLine.position.y = flyArcCenter.y //平移飞线圆弧和飞线轨迹圆弧重合 //飞线段flyLine作为飞线轨迹arcLine子对象,继承飞线轨迹平移旋转等变换 arcline.add(flyLine) //飞线段运动范围startAngle~flyEndAngle flyLine.flyEndAngle = endAngle - startAngle - flyAngle flyLine.startAngle = startAngle // arcline.flyEndAngle:飞线段当前角度位置,这里设置了一个随机值用于演示 flyLine.AngleZ = arcline.flyEndAngle * Math.random() // flyLine.rotation.z = arcline.AngleZ; // arcline.flyLine指向飞线段,便于设置动画是访问飞线段 arcline.userData['flyLine'] = flyLine return arcline }
/**通过函数arcXOY()可以在XOY平面上绘制一个关于y轴对称的圆弧曲线 * startPoint, endPoint:表示圆弧曲线的起点和结束点坐标值,起点和结束点关于y轴对称 * 同时在圆弧轨迹的基础上绘制一段飞线*/
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/Utils/arc.ts#L145-L188
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
radianAOB
function radianAOB(A, B, O) { // dir1、dir2:球面上两个点和球心构成的方向向量 const dir1 = A.clone().sub(O).normalize() const dir2 = B.clone().sub(O).normalize() //点乘.dot()计算夹角余弦值 const cosAngle = dir1.clone().dot(dir2) const radianAngle = Math.acos(cosAngle) //余弦值转夹角弧度值,通过余弦值可以计算夹角范围是0~180度 return radianAngle }
/*计算球面上两点和球心构成夹角的弧度值 参数point1, point2:表示地球球面上两点坐标Vector3 计算A、B两点和顶点O构成的AOB夹角弧度值*/
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/Utils/arc.ts#L192-L200
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
circleLine
function circleLine(x, y, r, startAngle, endAngle, color) { const geometry = new BufferGeometry() //声明一个几何体对象Geometry // ArcCurve创建圆弧曲线 const arc = new ArcCurve(x, y, r, startAngle, endAngle, false) //getSpacedPoints是基类Curve的方法,返回一个vector2对象作为元素组成的数组 const points = arc.getSpacedPoints(80) //分段数50,返回51个顶点 geometry.setFromPoints(points) // setFromPoints方法从points中提取数据改变几何体的顶点属性vertices const material = new LineBasicMaterial({ color: color || 0xd18547 }) //线条材质 const line = new Line(geometry, material) //线条模型对象 return line }
/*绘制一条圆弧曲线模型Line 5个参数含义:(圆心横坐标, 圆心纵坐标, 飞线圆弧轨迹半径, 开始角度, 结束角度)*/
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/Utils/arc.ts#L203-L215
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
threePointCenter
function threePointCenter(p1, p2, p3) { const L1 = p1.lengthSq() //p1到坐标原点距离的平方 const L2 = p2.lengthSq() const L3 = p3.lengthSq() const x1 = p1.x, y1 = p1.y, x2 = p2.x, y2 = p2.y, x3 = p3.x, y3 = p3.y const S = x1 * y2 + x2 * y3 + x3 * y1 - x1 * y3 - x2 * y1 - x3 * y2 const x = (L2 * y3 + L1 * y2 + L3 * y1 - L2 * y1 - L3 * y2 - L1 * y3) / S / 2 const y = (L3 * x2 + L2 * x1 + L1 * x3 - L1 * x2 - L2 * x3 - L3 * x1) / S / 2 // 三点外接圆圆心坐标 const center = new Vector3(x, y, 0) return center }
//求三个点的外接圆圆心,p1, p2, p3表示三个点的坐标Vector3。
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/Utils/arc.ts#L217-L233
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
Basic.initScenes
initScenes() { this.scene = new THREE.Scene() this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 100000) this.camera.position.set(0, 30, -250) this.renderer = new THREE.WebGLRenderer({ // canvas: this.dom, alpha: true, // 透明 antialias: true, // 抗锯齿 preserveDrawingBuffer: true }) this.renderer.setPixelRatio(window.devicePixelRatio) // 设置屏幕像素比 this.renderer.setSize(window.innerWidth, window.innerHeight) // 设置渲染器宽高 this.dom.appendChild(this.renderer.domElement) // 添加到dom中 }
/** * 初始化场景 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/world/Basic.ts#L25-L40
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
Basic.setControls
setControls() { // 鼠标控制 相机,渲染dom this.controls = new OrbitControls(this.camera, this.renderer.domElement) this.controls.autoRotateSpeed = 3 // 使动画循环使用时阻尼或自转 意思是否有惯性 this.controls.enableDamping = true // 动态阻尼系数 就是鼠标拖拽旋转灵敏度 this.controls.dampingFactor = 0.05 // 是否可以缩放 this.controls.enableZoom = true // 设置相机距离原点的最远距离 this.controls.minDistance = 100 // 设置相机距离原点的最远距离 this.controls.maxDistance = 300 // 是否开启右键拖拽 this.controls.enablePan = false }
/** * 设置控制器 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/world/Basic.ts#L45-L62
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
Resources.setLoadingManager
private setLoadingManager() { this.manager = new LoadingManager() // 开始加载 this.manager.onStart = () => { loadingStart() } // 加载完成 this.manager.onLoad = () => { this.callback() } // 正在进行中 this.manager.onProgress = url => { loadingFinish() } this.manager.onError = url => { loadingError() window['$message'].error('数据加载失败,请刷新重试!') } }
/** * 管理加载状态 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/world/Resources.ts#L22-L41
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
Resources.loadResources
private loadResources(): void { this.textureLoader = new TextureLoader(this.manager) resources.textures?.forEach(item => { this.textureLoader.load(item.url, t => { this.textures[item.name] = t }) }) }
/** * 加载资源 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/world/Resources.ts#L46-L53
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
World.render
public render() { requestAnimationFrame(this.render.bind(this)) this.renderer.render(this.scene, this.camera) this.controls && this.controls.update() this.earth && this.earth.render() }
/** * 渲染函数 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/world/Word.ts#L77-L82
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
World.updateSize
public updateSize(width?: number, height?: number) { let w = width || this.option.width let h = height || this.option.height // 取小值 if (w < h) h = w else w = h this.renderer.setSize(w, h) this.camera.aspect = w / h this.camera.updateProjectionMatrix() }
// 更新
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/world/Word.ts#L85-L95
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
World.updateData
public updateData(data?: any) { if (!this.earth.group) return // 先删除旧的 this.scene.remove(this.earth.group) // 递归遍历组对象group释放所有后代网格模型绑定几何体占用内存 this.earth.group.traverse((obj: any) => { if (obj.type === 'Mesh') { obj.geometry.dispose() obj.material.dispose() } }) // 重新创建 this.createEarth(data) }
// 数据更新重新渲染
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/goView/lib/packages/components/Decorates/Three/ThreeEarth01/code/world/Word.ts#L98-L111
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
Resource.constructor
constructor({ decoderPath = './draco/' } = {}) { this.decoderPath = decoderPath // this.setLoadingManager() this.items = {} }
// }
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/resourceManager/lib/Resource.ts#L39-L43
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
HeightCorrection.constructor
constructor(geometry?: BufferGeometry) { this.geometry = geometry; }
/** * @param geometry [BufferGeometry](https://threejs.org/docs/index.html?q=buffer#api/zh/core/BufferGeometry), * 在解码地形时会将地形顶点的高程匹配到几何体上。 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/HeightCorrection/HeightCorrection.ts#L18-L20
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
HeightCorrectionArea.constructor
constructor(path: number[][], height: number) { super(); console.log(path, height); }
/** * @param path GPS坐标点路径 * @param height 目标高程 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/HeightCorrection/HeightCorrectionArea.ts#L10-L13
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
HeightCrrectionPath.constructor
constructor(path: number[][], width: number) { super(); console.log(path, width); }
/** * @param path GPS坐标点路径 * @param width 路径扩展宽度 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/HeightCorrection/HeightCrrectionPath.ts#L11-L14
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
countElements
function countElements(ax: number, ay: number, bx: number, by: number, cx: number, cy: number) { const mx = (ax + bx) >> 1; const my = (ay + by) >> 1; if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) { countElements(cx, cy, ax, ay, mx, my); countElements(bx, by, cx, cy, mx, my); } else { indices[ay * size + ax] = indices[ay * size + ax] || ++numVertices; indices[by * size + bx] = indices[by * size + bx] || ++numVertices; indices[cy * size + cx] = indices[cy * size + cx] || ++numVertices; numTriangles++; } }
// retrieve mesh in two stages that both traverse the error map:
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/MartiniTerrainProvider/Martini.ts#L127-L140
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
MartiniTile.getMeshWithSkirts
getMeshWithSkirts(maxError = 0) { const { gridSize: size, indices } = this.martini; const { errors } = this; let numVertices = 0; let numTriangles = 0; const max = size - 1; let aIndex, bIndex, cIndex = 0; // Skirt indices let leftSkirtIndices: number[] = []; let rightSkirtIndices: number[] = []; let bottomSkirtIndices: number[] = []; let topSkirtIndices: number[] = []; // use an index grid to keep track of vertices that were already used to avoid duplication indices.fill(0); // retrieve mesh in two stages that both traverse the error map: // - countElements: find used vertices (and assign each an index), and count triangles (for minimum allocation) // - processTriangle: fill the allocated vertices & triangles typed arrays function countElements(ax: number, ay: number, bx: number, by: number, cx: number, cy: number) { const mx = (ax + bx) >> 1; const my = (ay + by) >> 1; if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) { countElements(cx, cy, ax, ay, mx, my); countElements(bx, by, cx, cy, mx, my); } else { aIndex = ay * size + ax; bIndex = by * size + bx; cIndex = cy * size + cx; if (indices[aIndex] === 0) { if (ax === 0) leftSkirtIndices.push(numVertices); else if (ax === max) { rightSkirtIndices.push(numVertices); } if (ay === 0) bottomSkirtIndices.push(numVertices); else if (ay === max) topSkirtIndices.push(numVertices); indices[aIndex] = ++numVertices; } if (indices[bIndex] === 0) { if (bx === 0) leftSkirtIndices.push(numVertices); else if (bx === max) rightSkirtIndices.push(numVertices); if (by === 0) bottomSkirtIndices.push(numVertices); else if (by === max) topSkirtIndices.push(numVertices); indices[bIndex] = ++numVertices; } if (indices[cIndex] === 0) { if (cx === 0) leftSkirtIndices.push(numVertices); else if (cx === max) rightSkirtIndices.push(numVertices); if (cy === 0) bottomSkirtIndices.push(numVertices); else if (cy === max) topSkirtIndices.push(numVertices); indices[cIndex] = ++numVertices; } numTriangles++; } } countElements(0, 0, max, max, max, 0); countElements(max, max, 0, 0, 0, max); const numTotalVertices = ( numVertices + leftSkirtIndices.length + rightSkirtIndices.length + bottomSkirtIndices.length + topSkirtIndices.length) * 2; const numTotalTriangles = ( numTriangles + ((leftSkirtIndices.length - 1) * 2) + ((rightSkirtIndices.length - 1) * 2) + ((bottomSkirtIndices.length - 1) * 2) + ((topSkirtIndices.length - 1) * 2)) * 3; const vertices = new Uint16Array(numTotalVertices); const triangles = new Uint32Array(numTotalTriangles); let triIndex = 0; function processTriangle(ax: number, ay: number, bx: number, by: number, cx: number, cy: number) { const mx = (ax + bx) >> 1; const my = (ay + by) >> 1; if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) { // triangle doesn't approximate the surface well enough; drill down further processTriangle(cx, cy, ax, ay, mx, my); processTriangle(bx, by, cx, cy, mx, my); } else { // add a triangle const a = indices[ay * size + ax] - 1; const b = indices[by * size + bx] - 1; const c = indices[cy * size + cx] - 1; vertices[2 * a] = ax; vertices[2 * a + 1] = ay; vertices[2 * b] = bx; vertices[2 * b + 1] = by; vertices[2 * c] = cx; vertices[2 * c + 1] = cy; triangles[triIndex++] = a; triangles[triIndex++] = b; triangles[triIndex++] = c; } } processTriangle(0, 0, max, max, max, 0); processTriangle(max, max, 0, 0, 0, max); // Sort skirt indices to create adjacent triangles leftSkirtIndices.sort((a, b) => { return vertices[2 * a + 1] - vertices[2 * b + 1]; }); rightSkirtIndices.sort((a, b) => { // Reverse (b - a) to match triangle winding return vertices[2 * b + 1] - vertices[2 * a + 1]; }); bottomSkirtIndices.sort((a, b) => { return vertices[2 * b] - vertices[2 * a]; }); topSkirtIndices.sort((a, b) => { // Reverse (b - a) to match triangle winding return vertices[2 * a] - vertices[2 * b]; }); let skirtIndex = numVertices * 2; let currIndex, nextIndex, currentSkirt, nextSkirt, skirtLength = 0; // Add skirt vertices from index of last mesh vertex function constructSkirt(skirt: number[]) { skirtLength = skirt.length; // Loop through indices in groups of two to generate triangles for (var i = 0; i < skirtLength - 1; i++) { currIndex = skirt[i]; nextIndex = skirt[i + 1]; currentSkirt = skirtIndex / 2; nextSkirt = (skirtIndex + 2) / 2; vertices[skirtIndex++] = vertices[2 * currIndex]; vertices[skirtIndex++] = vertices[2 * currIndex + 1]; triangles[triIndex++] = currIndex; triangles[triIndex++] = currentSkirt; triangles[triIndex++] = nextIndex; triangles[triIndex++] = currentSkirt; triangles[triIndex++] = nextSkirt; triangles[triIndex++] = nextIndex; } // Add vertices of last skirt not added above (i < skirtLength - 1) vertices[skirtIndex++] = vertices[2 * skirt[skirtLength - 1]]; vertices[skirtIndex++] = vertices[2 * skirt[skirtLength - 1] + 1]; } constructSkirt(leftSkirtIndices); constructSkirt(rightSkirtIndices); constructSkirt(bottomSkirtIndices); constructSkirt(topSkirtIndices); // Return vertices and triangles and index into vertices array where skirts start return { vertices, triangles, numVerticesWithoutSkirts: numVertices }; }
// https://github.com/mapbox/martini/pull/12/commits/4677d0c5cfe446ccc96d3982ff4f442cddba5063
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/MartiniTerrainProvider/Martini.ts#L184-L357
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
countElements
function countElements(ax: number, ay: number, bx: number, by: number, cx: number, cy: number) { const mx = (ax + bx) >> 1; const my = (ay + by) >> 1; if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && errors[my * size + mx] > maxError) { countElements(cx, cy, ax, ay, mx, my); countElements(bx, by, cx, cy, mx, my); } else { aIndex = ay * size + ax; bIndex = by * size + bx; cIndex = cy * size + cx; if (indices[aIndex] === 0) { if (ax === 0) leftSkirtIndices.push(numVertices); else if (ax === max) { rightSkirtIndices.push(numVertices); } if (ay === 0) bottomSkirtIndices.push(numVertices); else if (ay === max) topSkirtIndices.push(numVertices); indices[aIndex] = ++numVertices; } if (indices[bIndex] === 0) { if (bx === 0) leftSkirtIndices.push(numVertices); else if (bx === max) rightSkirtIndices.push(numVertices); if (by === 0) bottomSkirtIndices.push(numVertices); else if (by === max) topSkirtIndices.push(numVertices); indices[bIndex] = ++numVertices; } if (indices[cIndex] === 0) { if (cx === 0) leftSkirtIndices.push(numVertices); else if (cx === max) rightSkirtIndices.push(numVertices); if (cy === 0) bottomSkirtIndices.push(numVertices); else if (cy === max) topSkirtIndices.push(numVertices); indices[cIndex] = ++numVertices; } numTriangles++; } }
// retrieve mesh in two stages that both traverse the error map:
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/MartiniTerrainProvider/Martini.ts#L202-L251
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
constructSkirt
function constructSkirt(skirt: number[]) { skirtLength = skirt.length; // Loop through indices in groups of two to generate triangles for (var i = 0; i < skirtLength - 1; i++) { currIndex = skirt[i]; nextIndex = skirt[i + 1]; currentSkirt = skirtIndex / 2; nextSkirt = (skirtIndex + 2) / 2; vertices[skirtIndex++] = vertices[2 * currIndex]; vertices[skirtIndex++] = vertices[2 * currIndex + 1]; triangles[triIndex++] = currIndex; triangles[triIndex++] = currentSkirt; triangles[triIndex++] = nextIndex; triangles[triIndex++] = currentSkirt; triangles[triIndex++] = nextSkirt; triangles[triIndex++] = nextIndex; } // Add vertices of last skirt not added above (i < skirtLength - 1) vertices[skirtIndex++] = vertices[2 * skirt[skirtLength - 1]]; vertices[skirtIndex++] = vertices[2 * skirt[skirtLength - 1] + 1]; }
// Add skirt vertices from index of last mesh vertex
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/MartiniTerrainProvider/Martini.ts#L326-L348
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
MartiniTileUtil.findAncestorTerrainData
static findAncestorTerrainData(tileNo: number[], maxZ: number) { const z = tileNo[2]; let terrain: Float32Array | undefined = undefined; let parentTileNo = tileNo; const maxClip = z >= maxZ ? z - maxZ : 5; for (let i = 0; i < maxClip; i++) { parentTileNo = getParent(parentTileNo); const _terrain = this.terrainDataMap.get(parentTileNo.join('-')); if (_terrain) { terrain = _terrain; break; } } return { terrain, tileNo: parentTileNo }; }
/** * 从缓存的地形里找到指定瓦片编号的祖先地形数据及其编号 * @param tileNo 瓦片编号 * @param maxZ 瓦片数据源所能提供的最大层级 * @returns 地形数据,及地形所对应的瓦片编号 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/MartiniTerrainProvider/MartiniTileUtil.ts#L30-L44
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
MartiniTileUtil.getTerrainData
static async getTerrainData(tileNo: number[], url: string, maxZ: number) { const id = tileNo.join('-'); const { baseSize } = this; const { terrain, tileNo: parentTileNo } = this.findAncestorTerrainData(tileNo, maxZ); if (terrain) { let clipTimes = tileNo[2] - parentTileNo[2]; let size = this.baseSize; while(clipTimes > 0) { size = size / 2; clipTimes--; } const { x, y, smallBbox } = TerrainUtil.getChildPosition(parentTileNo, baseSize, tileNo); const _terrain = TerrainUtil.clip(terrain, baseSize, x, y, size); return { terrain: _terrain, size, bbox: smallBbox }; } const fetch = new Fetch(url, { cache: 'force-cache', mode: 'cors' }); this.fetchingMap.set(id, fetch); try { const res = await fetch.ready(); const blob = await res.blob(); const bitmap = await createImageBitmap(blob); const _terrain = TerrainUtil.getFromBitmap(bitmap, baseSize); this.terrainDataMap.set(id, _terrain); return { terrain: _terrain, size: baseSize, bbox: tileToBBOX(tileNo) }; } finally { this.fetchingMap.delete(id); } }
/** * 获取地形数据,根据情况从缓存读取祖先地形并切割,或直接从url获取地形图片并解码 * @param tileNo 瓦片编号 * @param url 瓦片下载地址 * @param maxZ 瓦片数据源所能提供的最大层级,大于此层级将从缓存切割瓦片而非下载 * @returns 地形数据,地形大小,及地形对应的bbox */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/MartiniTerrainProvider/MartiniTileUtil.ts#L53-L82
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
MartiniTileUtil.getTileGeometryAttributes
static async getTileGeometryAttributes(tileNo: number[], url: string, maxZ: number, coordType = MERC, utmZone?: number) { const { terrain, size, bbox } = await this.getTerrainData(tileNo, url, maxZ); const martini = this.getMartini(size); const martiniTile = martini.createTile(terrain); const { vertices, triangles, numVerticesWithoutSkirts } = martiniTile.getMeshWithSkirts(10); const numOfVertices = vertices.length / 2; const positions = new Float32Array(numOfVertices * 3); const uv = new Float32Array(numOfVertices * 2); const z = tileNo[2]; const gridSize = size + 1; const coordConvertMethod = coordType === MERC ? lonLatToWebMerctor : lonLatToUtm; for (let i = 0; i < numOfVertices; i++) { const x = vertices[2 * i]; const y = vertices[2 * i + 1]; const pixelIdx = y * gridSize + x; const lon = (bbox[2] - bbox[0]) * x / size + bbox[0]; const lat = (bbox[3] - bbox[1]) * (size - y) / size + bbox[1]; const [vx, vy] = coordConvertMethod(lon, lat, utmZone); const vz = terrain[pixelIdx]; const skirtsHeight = (21 - z) * 10; positions[3 * i] = vx; positions[3 * i + 1] = vy; positions[3 * i + 2] = i >= numVerticesWithoutSkirts ? vz - skirtsHeight : vz; uv[2 * i + 0] = x / size; uv[2 * i + 1] = (size - y) / size; } return { positions, uv, triangles }; }
/** * 根据瓦片编号获取模型数据 * @param tileNo 瓦片编号 * @param url 瓦片下载地址 * @param maxZ 瓦片数据源所能提供的最大层级 * @param coordType 坐标类型,默认 MERC * @param utmZone 当坐标类型为utm时的区号。 * @returns 几何体顶点、UV、顶点索引 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/MartiniTerrainProvider/MartiniTileUtil.ts#L93-L128
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
QuantizedMeshTerrainProvider.clip
clip(data: QuantizedMeshData, fromTileNo: number[], toTileNo: number[]): QuantizedMeshData { const fromBBox = tileToBBox(fromTileNo); const toBBox = tileToBBOX(toTileNo); const left = fromBBox[0] / toBBox[2] * vertexMaxPos; const right = fromBBox[2] / toBBox[2] * vertexMaxPos; const bottom = fromBBox[1] / toBBox[3] * vertexMaxPos; const top = fromBBox[3] / toBBox[3] * vertexMaxPos; console.log(left, right, bottom, top); // const { vertexData, triangleIndices } = data; // const triangleCount = triangleIndices.length / 3; // for (let i = 0; i < triangleCount; i++) { // // const v1 = // } return data; }
/** * 裁切地形数据 * @param data 量化网格地形数据 * @param fromTileNo 84瓦片坐标 * @param toTileNo 墨卡托瓦片坐标 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Providers/QuantizedMeshTerrainProvider/QuantizedMeshTerrainProvider.ts#L63-L81
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
TerrainUtil.getFromBitmap
static getFromBitmap(bitmap: ImageBitmap, size = 256) { if (!this.offscreencanvas) { this.offscreencanvas = new OffscreenCanvas(512, 512); } const ctx = this.offscreencanvas.getContext('2d'); if (!ctx) { throw new Error('Get context 2d error.'); } ctx.drawImage(bitmap, 0, 0, size, size); const data = ctx.getImageData(0, 0, size, size).data; const gridSize = size + 1; const terrain = new Float32Array(gridSize * gridSize); for (let y = 0; y < size; y++) { for (let x = 0; x < size; x++) { const k = (y * size + x) * 4; const r = data[k + 0]; const g = data[k + 1]; const b = data[k + 2]; terrain[y * gridSize + x] = (r * 256 * 256 + g * 256 + b) / 10 - 10000; } } for (let x = 0; x < gridSize - 1; x++) { terrain[gridSize * (gridSize - 1) + x] = terrain[gridSize * (gridSize - 2) + x]; } for (let y = 0; y < gridSize; y++) { terrain[gridSize * y + gridSize - 1] = terrain[gridSize * y + gridSize - 2]; } return terrain; }
/** * 从图片中解码地形数据 * @param bitmap 图像数据 * @param size 瓦片大小 * @returns 地形数据 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Utils/TerrainUtil.ts#L11-L40
918e54f5f6d262da3243a98b3dfc43430801bf1b
three-vue-tres
github_2023
hawk86104
typescript
TerrainUtil.clip
static clip(sourceTerrain: Float32Array, sourceSize: number, x: number, y: number, size: number) { if (x + size > sourceSize + 1 || y + size > sourceSize + 1) { console.log('clip: ', x, y, size); throw new RangeError('Clip terrain error'); } const gridSize = size + 1; const sourceGridSize = sourceSize + 1; const terrain = new Float32Array(gridSize * gridSize); for (let row = 0; row < gridSize; row++) { for (let col = 0; col < gridSize; col++) { terrain[row * gridSize + col] = sourceTerrain[(row + y) * sourceGridSize + (col + x)]; } } return terrain; }
/** * 从源地形数据中裁切出一部分 * @param sourceTerrain 源地形数据 * @param sourceSize 源地形大小 * @param x 裁切开始位置 x 坐标 * @param y 裁切开始位置 y 坐标 * @param size 裁切大小 * @returns 裁切后的地形数据 */
https://github.com/hawk86104/three-vue-tres/blob/918e54f5f6d262da3243a98b3dfc43430801bf1b/src/plugins/simpleGIS/lib/threeSatelliteMap/Utils/TerrainUtil.ts#L51-L66
918e54f5f6d262da3243a98b3dfc43430801bf1b
AiEditor
github_2023
aieditor-team
typescript
getCommandLineArgs
function getCommandLineArgs() { const args: Record<string, string | boolean> = {}; process.argv.slice(2).forEach((arg, index, array) => { if (arg.startsWith('--')) { const key = arg.slice(2); const value = array[index + 1] && !array[index + 1].startsWith('--') ? array[index + 1] : ""; args[key] = value; } }); return args; }
// 简单解析命令行参数 支持命令: npm run docs:dev -- --domain=http://localhost:3000
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/docs/.vitepress/config.ts#L24-L34
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
AbstractMenuButton.onClick
onClick(commands: ChainedCommands) { //do nothing }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/AbstractMenuButton.ts#L29-L31
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
AbstractMenuButton.onActive
onActive(editor: Editor): boolean { return false }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/AbstractMenuButton.ts#L49-L51
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Footer.onEditableChange
onEditableChange(editable: boolean) { }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/Footer.ts#L98-L99
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Attachment.onClick
onClick(commands) { if (this.options?.attachment?.customMenuInvoke) { this.options.attachment.customMenuInvoke((this.editor as InnerEditor).aiEditor); } else { this.fileInput?.click(); } }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Attachment.ts#L40-L46
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Bold.onClick
onClick(commands) { commands.toggleBold(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Bold.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Break.onClick
onClick(commands) { commands.setHardBreak(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Break.ts#L15-L17
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
BulletList.onClick
onClick(commands) { commands.toggleBulletList(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/BulletList.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Code.onClick
onClick(commands) { commands.toggleCode(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Code.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
CodeBlock.onClick
onClick(commands) { commands.toggleCodeBlock(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/CodeBlock.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Container.onClick
onClick(commands) { if (this.editor?.isActive("container")) { commands.unsetContainer() } else { commands.setContainer("") } commands.focus() }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Container.ts#L16-L23
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Eraser.onClick
onClick(commands) { commands.unsetAllMarks(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Eraser.ts#L15-L17
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Fullscreen.onClick
onClick(commands) { const container = this.closest(".aie-container") as HTMLDivElement; if (!this.isFullscreen) { container.style.height = "calc(100vh - 2px)"; container.style.width = "calc(100% - 2px)"; container.style.position = "fixed"; container.style.top = "0"; container.style.left = "0"; container.style.zIndex = "9999"; } else { container.style.height = "100%"; container.style.width = ""; container.style.background = ""; container.style.position = ""; container.style.top = ""; container.style.left = ""; container.style.zIndex = ""; } this.isFullscreen = !this.isFullscreen; this.querySelector("div")!.innerHTML = this.isFullscreen ? this.fullscreenExitSvg : this.fullscreenSvg; if (this.options?.onFullscreen) { this.options.onFullscreen(this.isFullscreen); } }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Fullscreen.ts#L21-L46
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Hr.onClick
onClick(commands) { commands.setHorizontalRule(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Hr.ts#L15-L17
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Image.onClick
onClick(commands) { if (this.options?.image?.customMenuInvoke) { setTimeout(() => { this.options!.image!.customMenuInvoke!((this.editor as InnerEditor).aiEditor); }) } else { this.fileInput?.click(); } }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Image.ts#L40-L48
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
IndentDecrease.onClick
onClick(commands) { commands.outdent(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/IndentDecrease.ts#L15-L17
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
IndentIncrease.onClick
onClick(commands) { commands.indent(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/IndentIncrease.ts#L15-L17
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Italic.onClick
onClick(commands) { commands.toggleItalic(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Italic.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
OrderedList.onClick
onClick(commands) { commands.toggleOrderedList(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/OrderedList.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Painter.onClick
onClick(commands) { commands.setPainter(this.editor?.state.selection.$head.marks()) }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Painter.ts#L12-L14
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Printer.onClick
onClick(commands) { let html = this.closest(".aie-container")!.querySelector(".aie-content")!.innerHTML; html = `<div class="aie-container" style="border: none;padding: 0;margin: 0"><div class="aie-content" style="border: none;height: auto;overflow: visible">${html}</div></div>` const style :string = Array.from(document.querySelectorAll('style, link')) .map((el) => el.outerHTML).join(''); const content: string = style + html; const iframe: HTMLIFrameElement = document.createElement('iframe'); iframe.id = 'aie-print-iframe'; iframe.setAttribute('style', 'position: absolute; width: 0; height: 0; top: -10px; left: -10px;'); document.body.appendChild(iframe); const frameWindow = iframe.contentWindow; const frameDoc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document); if (frameDoc) { frameDoc.open(); frameDoc.write(content); frameDoc.close(); } if (frameWindow) { iframe.onload = function() { try { setTimeout(() => { frameWindow.focus(); try { if (!frameWindow.document.execCommand('print', false)) { frameWindow.print(); } } catch (e) { frameWindow.print(); } frameWindow.close(); }, 10); } catch (err) { console.error(err) } setTimeout(function() { document.body.removeChild(iframe); }, 100); }; } }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Printer.ts#L15-L61
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Quote.onClick
onClick(commands) { commands.toggleBlockquote(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Quote.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Redo.onClick
onClick(commands) { commands.redo(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Redo.ts#L15-L17
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Strike.onClick
onClick(commands) { commands.toggleStrike(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Strike.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Subscript.onClick
onClick(commands) { commands.toggleSubscript(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Subscript.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0
AiEditor
github_2023
aieditor-team
typescript
Superscript.onClick
onClick(commands) { commands.toggleSuperscript(); }
// @ts-ignore
https://github.com/aieditor-team/AiEditor/blob/3ee22e6953a0dad22c3415c9f145f682aa354ef0/src/components/menus/Superscript.ts#L16-L18
3ee22e6953a0dad22c3415c9f145f682aa354ef0