text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import functions from 'lodash/functions' import omit from 'lodash/omit' import { push } from 'connected-react-router' // @ts-expect-error(sa, 2021-05-17): api client is not typed yet import { client } from '../api-client/client' // @ts-expect-error(sa, 2021-05-17): rpc client is not typed yet import { Client as RpcClient } from '../../../rpc/client' import { actions, constants } from '../' import * as AdminActions from '../../robot-admin/actions' import { MockSession, MockSessionNoStateInfo, MockSessionNoDoorInfo, } from './__fixtures__/session' import { MockCalibrationManager } from './__fixtures__/calibration-manager' import { mockConnectableRobot } from '../../discovery/__fixtures__' import * as discoSelectors from '../../discovery/selectors' import * as protocolSelectors from '../../protocol/selectors' import * as customLwSelectors from '../../custom-labware/selectors' import type { Dispatch } from 'redux' import type { State, Action } from '../../types' jest.mock('../../../rpc/client') jest.mock('../../discovery/selectors') jest.mock('../../protocol/selectors') jest.mock('../../custom-labware/selectors') const getLabwareDefBySlot = protocolSelectors.getLabwareDefBySlot as jest.MockedFunction< typeof protocolSelectors.getLabwareDefBySlot > const getCustomLabwareDefinitions = customLwSelectors.getCustomLabwareDefinitions as jest.MockedFunction< typeof customLwSelectors.getCustomLabwareDefinitions > const getConnectableRobots = discoSelectors.getConnectableRobots as jest.MockedFunction< typeof discoSelectors.getConnectableRobots > const delay = (ms: number): Promise<ReturnType<typeof setTimeout>> => new Promise(resolve => setTimeout(resolve, ms)) describe('api client', () => { let dispatch: jest.MockedFunction<Dispatch> let sendToClient: (state: State, action: Action) => Promise<unknown> let rpcClient: any let session: any let sessionManager: any let calibrationManager: any let _global: { [key: string]: unknown } = {} beforeAll(() => { _global = { setInterval, clearInterval } global.setInterval = jest.fn() global.clearInterval = jest.fn() }) afterAll(() => { Object.keys(_global).forEach(method => (global[method] = _global[method])) }) beforeEach(() => { // TODO(mc, 2017-08-29): this is a pretty nasty mock. Probably a sign we // need to simplify the RPC client // mock robot, session, and session manager session = MockSession() calibrationManager = MockCalibrationManager() // mock rpc client sessionManager = { session, create: jest.fn(), create_from_bundle: jest.fn(), } rpcClient = { on: jest.fn(() => rpcClient), removeAllListeners: jest.fn(() => rpcClient), close: jest.fn(), remote: { session_manager: sessionManager, calibration_manager: calibrationManager, }, } dispatch = jest.fn() RpcClient.mockResolvedValue(rpcClient) getLabwareDefBySlot.mockReturnValue({}) getCustomLabwareDefinitions.mockReturnValue([]) getConnectableRobots.mockReturnValue([mockConnectableRobot]) const _receive = client(dispatch) sendToClient = (state, action) => { _receive(state, action) return delay(1) } }) afterEach(() => { RpcClient.mockReset() jest.resetAllMocks() }) const ROBOT_NAME = mockConnectableRobot.name const ROBOT_IP = mockConnectableRobot.ip const STATE: State = { robot: { connection: { connectedTo: '', connectRequest: { inProgress: false }, }, }, } as any const sendConnect = (): Promise<unknown> => sendToClient(STATE, actions.legacyConnect(ROBOT_NAME)) const sendDisconnect = (): Promise<unknown> => sendToClient(STATE, actions.disconnect()) const sendNotification = (topic: any, payload: any): void => { expect(rpcClient.on).toHaveBeenCalledWith( 'notification', expect.any(Function) ) const handler = rpcClient.on.mock.calls.find((args: any) => { return args[0] === 'notification' })[1] // only send properties, not methods handler({ topic, payload: omit(payload, functions(payload)) }) } describe('connect and disconnect', () => { it('connect RpcClient on CONNECT message', () => { const expectedResponse = actions.connectResponse(null, expect.any(Array)) expect(RpcClient).toHaveBeenCalledTimes(0) return sendConnect().then(() => { expect(RpcClient).toHaveBeenCalledWith(`ws://${ROBOT_IP}:31950`) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('dispatch CONNECT_RESPONSE error if connection fails', () => { const error = new Error('AHH get_root') const expectedResponse = actions.connectResponse(error) RpcClient.mockRejectedValue(error) return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse) ) }) it('send CONNECT_RESPONSE w/ capabilities from remote.session_manager', () => { const expectedResponse = actions.connectResponse(null, [ 'create', 'create_from_bundle', ]) rpcClient.monitoring = true return sendConnect().then(() => { expect(RpcClient).toHaveBeenCalledWith(`ws://${ROBOT_IP}:31950`) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('dispatch DISCONNECT_RESPONSE if already disconnected', () => { const expected = actions.disconnectResponse() return sendDisconnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('disconnects RPC client on DISCONNECT message', () => { const expected = actions.disconnectResponse() return sendConnect() .then(() => sendDisconnect()) .then(() => expect(rpcClient.close).toHaveBeenCalled()) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('disconnects RPC client on robotAdmin:RESTART message', () => { const state: State = { ...STATE, robot: { ...STATE.robot, connection: { connectedTo: ROBOT_NAME } }, } as any const expected = actions.disconnectResponse() return sendConnect() .then(() => sendToClient(state, AdminActions.restartRobot(ROBOT_NAME))) .then(() => expect(rpcClient.close).toHaveBeenCalled()) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) // TODO(mc, 2018-03-01): rethink / remove this behavior it('dispatch push to /run if connect to running session', () => { const expected = push('/run') session.state = constants.RUNNING return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('dispatch push to /run if connect to paused session', () => { const expected = push('/run') session.state = constants.PAUSED return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('will not try to connect multiple RpcClients at one time', () => { const state: State = { ...STATE, robot: { ...STATE.robot, connection: { connectRequest: { inProgress: true } }, }, } as any return sendToClient(state, actions.legacyConnect(ROBOT_NAME)).then(() => { expect(RpcClient).toHaveBeenCalledTimes(0) }) }) }) describe('running', () => { it('calls session.run and dispatches RUN_RESPONSE success', () => { const expected = actions.runResponse() session.run.mockResolvedValue() return sendConnect() .then(() => sendToClient({} as any, actions.run())) .then(() => { expect(session.run).toHaveBeenCalled() expect(dispatch).toHaveBeenCalledWith(expected) }) }) it('calls session.run and dispatches RUN_RESPONSE failure', () => { const expected = actions.runResponse(new Error('AH')) session.run.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient({} as any, actions.run())) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('calls session.pause and dispatches PAUSE_RESPONSE success', () => { const expected = actions.pauseResponse() session.pause.mockResolvedValue() return sendConnect() .then(() => sendToClient({} as any, actions.pause())) .then(() => { expect(session.pause).toHaveBeenCalled() expect(dispatch).toHaveBeenCalledWith(expected) }) }) it('calls session.stop and dispatches PAUSE_RESPONSE failure', () => { const expected = actions.pauseResponse(new Error('AH')) session.pause.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient({} as any, actions.pause())) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('calls session.resume and dispatches RESUME_RESPONSE success', () => { const expected = actions.resumeResponse() session.resume.mockResolvedValue() return sendConnect() .then(() => sendToClient({} as any, actions.resume())) .then(() => { expect(session.resume).toHaveBeenCalled() expect(dispatch).toHaveBeenCalledWith(expected) }) }) it('calls session.resume and dispatches RESUME_RESPONSE failure', () => { const expected = actions.resumeResponse(new Error('AH')) session.resume.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient({} as any, actions.resume())) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('calls session.resume + stop and dispatches CANCEL_RESPONSE', () => { const expected = actions.cancelResponse() session.resume.mockResolvedValue() session.stop.mockResolvedValue() return sendConnect() .then(() => sendToClient({} as any, actions.cancel())) .then(() => { expect(session.resume).toHaveBeenCalled() expect(session.stop).toHaveBeenCalled() expect(dispatch).toHaveBeenCalledWith(expected) }) }) it('calls session.stop and dispatches CANCEL_RESPONSE failure', () => { const expected = actions.cancelResponse(new Error('AH')) session.resume.mockResolvedValue() session.stop.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient({} as any, actions.cancel())) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('calls session.refresh with REFRESH_SESSION', () => { session.refresh.mockResolvedValue() return sendConnect() .then(() => sendToClient({} as any, actions.refreshSession())) .then(() => expect(session.refresh).toHaveBeenCalled()) }) }) describe('session responses', () => { let expectedInitial: ReturnType<typeof actions.sessionResponse> beforeEach(() => { expectedInitial = actions.sessionResponse( null, { name: session.name, state: session.state, statusInfo: { message: null, userMessage: null, changedAt: null, estimatedDuration: null, }, doorState: null, blocked: false, protocolText: session.protocol_text, protocolCommands: [], protocolCommandsById: {}, pipettesByMount: {}, labwareBySlot: {}, modulesBySlot: {}, apiLevel: [1, 0], }, false ) }) it('dispatches sessionResponse on connect', () => { return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expectedInitial) ) }) it('dispatches sessionResponse on full session notification', () => { return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', session) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedInitial)) }) it('handles sessionResponses without status info', () => { session = MockSessionNoStateInfo() sessionManager.session = session return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', session) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedInitial)) }) it('handles sessionResponses with some status info set', () => { session.stateInfo.changedAt = 2 session.stateInfo.message = 'test message' const expected = actions.sessionResponse( null, { name: session.name, state: session.state, statusInfo: { message: 'test message', userMessage: null, changedAt: 2, estimatedDuration: null, }, doorState: null, blocked: false, protocolText: session.protocol_text, protocolCommands: [], protocolCommandsById: {}, pipettesByMount: {}, labwareBySlot: {}, modulesBySlot: {}, apiLevel: [1, 0], }, false ) return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', session) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('handles sessionResponses without door state and blocked info', () => { session = MockSessionNoDoorInfo() sessionManager.session = session return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', session) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedInitial)) }) it('handles sessionResponses with door and blocked info', () => { session.blocked = true session.door_state = 'open' const expected = actions.sessionResponse( null, { name: session.name, state: session.state, statusInfo: { message: null, userMessage: null, changedAt: null, estimatedDuration: null, }, doorState: 'open', blocked: true, protocolText: session.protocol_text, protocolCommands: [], protocolCommandsById: {}, pipettesByMount: {}, labwareBySlot: {}, modulesBySlot: {}, apiLevel: [1, 0], }, false ) return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', session) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('handles connnect without session', () => { const notExpected = actions.sessionResponse( null, expect.anything(), false ) sessionManager.session = null return sendConnect().then(() => expect(dispatch).not.toHaveBeenCalledWith(notExpected) ) }) it('maps api session commands and command log to commands', () => { const expected = actions.sessionResponse( null, expect.objectContaining({ protocolCommands: [0, 4], protocolCommandsById: { 0: { id: 0, description: 'a', handledAt: 0, children: [1] }, 1: { id: 1, description: 'b', handledAt: 1, children: [2, 3] }, 2: { id: 2, description: 'c', handledAt: 2, children: [] }, 3: { id: 3, description: 'd', handledAt: null, children: [] }, 4: { id: 4, description: 'e', handledAt: null, children: [] }, }, }), false ) session.commands = [ { id: 0, description: 'a', children: [ { id: 1, description: 'b', children: [ { id: 2, description: 'c', children: [] }, { id: 3, description: 'd', children: [] }, ], }, ], }, { id: 4, description: 'e', children: [] }, ] session.command_log = { 0: 0, 1: 1, 2: 2, } return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('maps api instruments and instruments by mount', () => { const expected = actions.sessionResponse( null, expect.objectContaining({ pipettesByMount: { left: { _id: 2, mount: 'left', name: 'p200', channels: 1, tipRacks: [4, 5], requestedAs: 'bar', }, right: { _id: 1, mount: 'right', name: 'p50', channels: 8, tipRacks: [3, 4], requestedAs: 'foo', }, }, }), false ) session.instruments = [ { _id: 1, mount: 'right', name: 'p50', channels: 8, tip_racks: [{ _id: 3 }, { _id: 4 }], requested_as: 'foo', }, { _id: 2, mount: 'left', name: 'p200', channels: 1, tip_racks: [{ _id: 4 }, { _id: 5 }], requested_as: 'bar', }, ] session.containers = [{ _id: 3 }, { _id: 4 }, { _id: 5 }] return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('maps api containers to labware by slot', () => { const expected = actions.sessionResponse( null, expect.objectContaining({ labwareBySlot: { 1: { _id: 1, slot: '1', name: 'a', type: 'tiprack', isTiprack: true, calibratorMount: 'right', definitionHash: null, }, 5: { _id: 2, slot: '5', name: 'b', type: 'B', isTiprack: false, definitionHash: null, }, 9: { _id: 3, slot: '9', name: 'c', type: 'C', isTiprack: false, definitionHash: null, }, }, }), false ) session.containers = [ { _id: 1, slot: '1', name: 'a', type: 'tiprack', instruments: [ { mount: 'left', channels: 8 }, { mount: 'right', channels: 1 }, ], }, { _id: 2, slot: '5', name: 'b', type: 'B' }, { _id: 3, slot: '9', name: 'c', type: 'C' }, ] return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('reconciles reported tiprack / pipette usage', () => { const expected = actions.sessionResponse( null, expect.objectContaining({ pipettesByMount: { left: { _id: 123, mount: 'left', name: 'p200', channels: 1, tipRacks: [789], requestedAs: 'bar', }, right: { _id: 456, mount: 'right', name: 'p50', channels: 8, tipRacks: [789], requestedAs: 'foo', }, }, labwareBySlot: { 1: { _id: 789, slot: '1', name: 'a', type: 'tiprack', isTiprack: true, calibratorMount: 'left', definitionHash: null, }, }, }), false ) session.instruments = [ { _id: 456, mount: 'right', name: 'p50', channels: 8, // guard against bogus tipracks in this array, which RPC API has been // observed doing as of 3.16 tip_racks: [{ _id: 888 }], requested_as: 'foo', }, { _id: 123, mount: 'left', name: 'p200', channels: 1, tip_racks: [{ _id: 999 }], requested_as: 'bar', }, ] session.containers = [ { _id: 789, slot: '1', name: 'a', type: 'tiprack', instruments: [ { mount: 'left', channels: 1 }, { mount: 'right', channels: 8 }, ], }, ] return sendConnect().then(() => { expect(dispatch).toHaveBeenCalledWith(expected) }) }) it('maps api modules to modules by slot', () => { const expected = actions.sessionResponse( null, expect.objectContaining({ modulesBySlot: { 1: { _id: 1, slot: '1', model: 'temperatureModuleV1', protocolLoadOrder: 0, }, 9: { _id: 9, slot: '9', model: 'magneticModuleV2', protocolLoadOrder: 1, }, }, }), false ) session.modules = [ { _id: 1, slot: '1', name: 'tempdeck', }, { _id: 9, slot: '9', name: 'magdeck', model: 'magneticModuleV2', }, ] return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('maps api metadata to session metadata', () => { const expected = actions.sessionResponse( null, expect.objectContaining({ metadata: { 'protocol-name': 'foo', description: 'bar', author: 'baz', source: 'qux', }, }), false ) session.metadata = { _id: 1234, some: () => {}, rpc: () => {}, cruft: () => {}, protocolName: 'foo', description: 'bar', author: 'baz', source: 'qux', } return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('sends error if received malformed session from API', () => { const expected = actions.sessionResponse(expect.anything(), null, false) session.commands = [{ foo: 'bar' }] session.command_log = null return sendConnect().then(() => expect(dispatch).toHaveBeenCalledWith(expected) ) }) it('sends SESSION_UPDATE if session notification has lastCommand', () => { const update = { state: 'running', startTime: 1, lastCommand: null, stateInfo: {}, door_state: null, blocked: false, } const actionInput = { state: 'running', startTime: 1, lastCommand: null, statusInfo: { message: null, userMessage: null, changedAt: null, estimatedDuration: null, }, doorState: null, blocked: false, } as any const expected = actions.sessionUpdate(actionInput, expect.any(Number)) return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', update) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('handles SESSION_UPDATEs with no stateInfo', () => { const update = { state: 'running', startTime: 2, lastCommand: null, door_state: 'closed', blocked: false, } const actionInput = { state: 'running', startTime: 2, lastCommand: null, doorState: 'closed', blocked: false, statusInfo: { message: null, userMessage: null, changedAt: null, estimatedDuration: null, }, } as any const expected = actions.sessionUpdate(actionInput, expect.any(Number)) return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', update) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('handles SESSION_UPDATEs with values in stateInfo', () => { const update = { state: 'running', startTime: 2, lastCommand: null, blocked: false, door_state: 'closed', stateInfo: { message: 'hi and hello football fans', userMessage: 'whos ready for some FOOTBALL', changedAt: 2, }, } const actionInput = { state: 'running', startTime: 2, lastCommand: null, blocked: false, doorState: 'closed', statusInfo: { message: 'hi and hello football fans', userMessage: 'whos ready for some FOOTBALL', changedAt: 2, estimatedDuration: null, }, } as any const expected = actions.sessionUpdate(actionInput, expect.any(Number)) return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', update) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) it('handles SESSION_UPDATEs with no door or blocked info', () => { const update = { state: 'paused', startTime: 2, lastCommand: null, stateInfo: {}, } const actionInput = { state: 'paused', startTime: 2, lastCommand: null, blocked: false, doorState: null, statusInfo: { message: null, userMessage: null, changedAt: null, estimatedDuration: null, }, } as any const expected = actions.sessionUpdate(actionInput, expect.any(Number)) return sendConnect() .then(() => { dispatch.mockClear() sendNotification('session', update) }) .then(() => expect(dispatch).toHaveBeenCalledWith(expected)) }) }) describe('calibration', () => { let state: State beforeEach(() => { state = { robot: { calibration: { calibrationRequest: {}, confirmedBySlot: {}, labwareBySlot: {}, }, session: { pipettesByMount: { left: { _id: 'inst-2' }, right: { _id: 'inst-1' }, }, labwareBySlot: { 1: { _id: 'lab-1', type: '96-flat' }, 5: { _id: 'lab-2', type: 'tiprack-200ul', isTiprack: true, calibratorMount: 'left', }, 9: { _id: 'lab-3', type: 'tiprack-200ul', isTiprack: true, calibratorMount: 'right', }, }, }, }, } as any }) it('handles MOVE_TO_FRONT success', () => { const action = actions.moveToFront('left') const expectedResponse = actions.moveToFrontResponse() calibrationManager.move_to_front.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.move_to_front).toHaveBeenCalledWith({ _id: 'inst-2', }) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles MOVE_TO_FRONT failure', () => { const action = actions.moveToFront('left') const expectedResponse = actions.moveToFrontResponse(new Error('AH')) calibrationManager.move_to_front.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles PROBE_TIP success', () => { const action = actions.probeTip('right') const expectedResponse = actions.probeTipResponse() calibrationManager.tip_probe.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.tip_probe).toHaveBeenCalledWith({ _id: 'inst-1', }) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles PROBE_TIP failure', () => { const action = actions.probeTip('right') const expectedResponse = actions.probeTipResponse(new Error('AH')) calibrationManager.tip_probe.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles MOVE_TO success', () => { const action = actions.moveTo('left', '5') const expectedResponse = actions.moveToResponse() calibrationManager.move_to.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.move_to).toHaveBeenCalledWith( { _id: 'inst-2' }, { _id: 'lab-2' } ) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles MOVE_TO failure', () => { const action = actions.moveTo('left', '5') const expectedResponse = actions.moveToResponse(new Error('AH')) calibrationManager.move_to.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles PICKUP_AND_HOME success', () => { const action = actions.pickupAndHome('left', '5') const expectedResponse = actions.pickupAndHomeResponse() calibrationManager.update_container_offset.mockResolvedValue() calibrationManager.pick_up_tip.mockResolvedValue() calibrationManager.home.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.pick_up_tip).toHaveBeenCalledWith( { _id: 'inst-2' }, { _id: 'lab-2' } ) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles PICKUP_AND_HOME failure update offset', () => { const action = actions.pickupAndHome('left', '5') const expectedResponse = actions.pickupAndHomeResponse(new Error('AH')) calibrationManager.update_container_offset.mockRejectedValue( new Error('AH') ) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles PICKUP_AND_HOME failure during pickup', () => { const action = actions.pickupAndHome('left', '5') const expectedResponse = actions.pickupAndHomeResponse(new Error('AH')) calibrationManager.update_container_offset.mockResolvedValue() calibrationManager.pick_up_tip.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles DROP_TIP_AND_HOME success', () => { const action = actions.dropTipAndHome('right', '9') const expectedResponse = actions.dropTipAndHomeResponse() calibrationManager.drop_tip.mockResolvedValue() calibrationManager.home.mockResolvedValue() calibrationManager.move_to.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.drop_tip).toHaveBeenCalledWith( { _id: 'inst-1' }, { _id: 'lab-3' } ) expect(calibrationManager.home).toHaveBeenCalledWith({ _id: 'inst-1', }) expect(calibrationManager.move_to).toHaveBeenCalledWith( { _id: 'inst-1' }, { _id: 'lab-3' } ) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles DROP_TIP_AND_HOME failure in drop_tip', () => { const action = actions.dropTipAndHome('right', '9') const expectedResponse = actions.dropTipAndHomeResponse(new Error('AH')) calibrationManager.drop_tip.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles DROP_TIP_AND_HOME failure in home', () => { const action = actions.dropTipAndHome('right', '9') const expectedResponse = actions.dropTipAndHomeResponse(new Error('AH')) calibrationManager.drop_tip.mockResolvedValue() calibrationManager.home.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles DROP_TIP_AND_HOME failure in move_to', () => { const action = actions.dropTipAndHome('right', '9') const expectedResponse = actions.dropTipAndHomeResponse(new Error('AH')) calibrationManager.drop_tip.mockResolvedValue() calibrationManager.home.mockResolvedValue() calibrationManager.move_to.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('CONFIRM_TIPRACK drops tip if not last tiprack', () => { const action = actions.confirmTiprack('left', '9') const expectedResponse = actions.confirmTiprackResponse() calibrationManager.drop_tip.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.drop_tip).toHaveBeenCalledWith( { _id: 'inst-2' }, { _id: 'lab-3' } ) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('CONFIRM_TIPRACK noops and keeps tip if last tiprack', () => { state.robot.calibration.confirmedBySlot[5] = true const action = actions.confirmTiprack('left', '9') const expectedResponse = actions.confirmTiprackResponse(null, true) calibrationManager.drop_tip.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.drop_tip).not.toHaveBeenCalled() expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles CONFIRM_TIPRACK drop tip failure', () => { const action = actions.confirmTiprack('left', '9') const expectedResponse = actions.confirmTiprackResponse(new Error('AH')) calibrationManager.drop_tip.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles JOG success', () => { const action = actions.jog('left', 'y', -1, 10) const expectedResponse = actions.jogResponse() calibrationManager.jog.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect(calibrationManager.jog).toHaveBeenCalledWith( { _id: 'inst-2' }, -10, 'y' ) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles JOG failure', () => { const action = actions.jog('left', 'x', 1, 10) const expectedResponse = actions.jogResponse(new Error('AH')) calibrationManager.jog.mockRejectedValue(new Error('AH')) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) it('handles UPDATE_OFFSET success', () => { const action = actions.updateOffset('left', 1 as any) // @ts-expect-error actions.updateOffsetResponse only takes one arg but we're giving two here const expectedResponse = actions.updateOffsetResponse(null, false) calibrationManager.update_container_offset.mockResolvedValue() return sendConnect() .then(() => sendToClient(state, action)) .then(() => { expect( calibrationManager.update_container_offset ).toHaveBeenCalledWith({ _id: 'lab-1' }, { _id: 'inst-2' }) expect(dispatch).toHaveBeenCalledWith(expectedResponse) }) }) it('handles UPDATE_OFFSET failure', () => { const action = actions.updateOffset('left', 9 as any) const expectedResponse = actions.updateOffsetResponse(new Error('AH')) calibrationManager.update_container_offset.mockRejectedValue( new Error('AH') ) return sendConnect() .then(() => sendToClient(state, action)) .then(() => expect(dispatch).toHaveBeenCalledWith(expectedResponse)) }) }) })
the_stack
import fetch, { Response } from 'node-fetch'; import { zip } from 'zip-a-folder'; import * as unzipper from 'unzipper'; import { Uri, CancellationToken, commands, window, } from 'vscode'; import { CodeQLCliServer } from './cli'; import * as fs from 'fs-extra'; import * as path from 'path'; import { DatabaseManager, DatabaseItem } from './databases'; import { showAndLogInformationMessage, } from './helpers'; import { reportStreamProgress, ProgressCallback, } from './commandRunner'; import { logger } from './logging'; import { tmpDir } from './run-queries'; /** * Prompts a user to fetch a database from a remote location. Database is assumed to be an archive file. * * @param databaseManager the DatabaseManager * @param storagePath where to store the unzipped database. */ export async function promptImportInternetDatabase( databaseManager: DatabaseManager, storagePath: string, progress: ProgressCallback, token: CancellationToken, cli?: CodeQLCliServer ): Promise<DatabaseItem | undefined> { const databaseUrl = await window.showInputBox({ prompt: 'Enter URL of zipfile of database to download', }); if (!databaseUrl) { return; } validateHttpsUrl(databaseUrl); const item = await databaseArchiveFetcher( databaseUrl, databaseManager, storagePath, progress, token, cli ); if (item) { await commands.executeCommand('codeQLDatabases.focus'); void showAndLogInformationMessage('Database downloaded and imported successfully.'); } return item; } /** * Prompts a user to fetch a database from lgtm. * User enters a project url and then the user is asked which language * to download (if there is more than one) * * @param databaseManager the DatabaseManager * @param storagePath where to store the unzipped database. */ export async function promptImportLgtmDatabase( databaseManager: DatabaseManager, storagePath: string, progress: ProgressCallback, token: CancellationToken, cli?: CodeQLCliServer ): Promise<DatabaseItem | undefined> { progress({ message: 'Choose project', step: 1, maxStep: 2 }); const lgtmUrl = await window.showInputBox({ prompt: 'Enter the project slug or URL on LGTM (e.g., g/github/codeql or https://lgtm.com/projects/g/github/codeql)', }); if (!lgtmUrl) { return; } if (looksLikeLgtmUrl(lgtmUrl)) { const databaseUrl = await convertToDatabaseUrl(lgtmUrl, progress); if (databaseUrl) { const item = await databaseArchiveFetcher( databaseUrl, databaseManager, storagePath, progress, token, cli ); if (item) { await commands.executeCommand('codeQLDatabases.focus'); void showAndLogInformationMessage('Database downloaded and imported successfully.'); } return item; } } else { throw new Error(`Invalid LGTM URL: ${lgtmUrl}`); } return; } /** * Imports a database from a local archive. * * @param databaseUrl the file url of the archive to import * @param databaseManager the DatabaseManager * @param storagePath where to store the unzipped database. */ export async function importArchiveDatabase( databaseUrl: string, databaseManager: DatabaseManager, storagePath: string, progress: ProgressCallback, token: CancellationToken, cli?: CodeQLCliServer, ): Promise<DatabaseItem | undefined> { try { const item = await databaseArchiveFetcher( databaseUrl, databaseManager, storagePath, progress, token, cli ); if (item) { await commands.executeCommand('codeQLDatabases.focus'); void showAndLogInformationMessage('Database unzipped and imported successfully.'); } return item; } catch (e) { if (e.message.includes('unexpected end of file')) { throw new Error('Database is corrupt or too large. Try unzipping outside of VS Code and importing the unzipped folder instead.'); } else { // delegate throw e; } } } /** * Fetches an archive database. The database might be on the internet * or in the local filesystem. * * @param databaseUrl URL from which to grab the database * @param databaseManager the DatabaseManager * @param storagePath where to store the unzipped database. * @param progress callback to send progress messages to * @param token cancellation token */ async function databaseArchiveFetcher( databaseUrl: string, databaseManager: DatabaseManager, storagePath: string, progress: ProgressCallback, token: CancellationToken, cli?: CodeQLCliServer, ): Promise<DatabaseItem> { progress({ message: 'Getting database', step: 1, maxStep: 4, }); if (!storagePath) { throw new Error('No storage path specified.'); } await fs.ensureDir(storagePath); const unzipPath = await getStorageFolder(storagePath, databaseUrl); if (isFile(databaseUrl)) { await readAndUnzip(databaseUrl, unzipPath, cli, progress); } else { await fetchAndUnzip(databaseUrl, unzipPath, cli, progress); } progress({ message: 'Opening database', step: 3, maxStep: 4, }); // find the path to the database. The actual database might be in a sub-folder const dbPath = await findDirWithFile( unzipPath, '.dbinfo', 'codeql-database.yml' ); if (dbPath) { progress({ message: 'Validating and fixing source location', step: 4, maxStep: 4, }); await ensureZippedSourceLocation(dbPath); const item = await databaseManager.openDatabase(progress, token, Uri.file(dbPath)); await databaseManager.setCurrentDatabaseItem(item); return item; } else { throw new Error('Database not found in archive.'); } } async function getStorageFolder(storagePath: string, urlStr: string) { // we need to generate a folder name for the unzipped archive, // this needs to be human readable since we may use this name as the initial // name for the database const url = Uri.parse(urlStr); // MacOS has a max filename length of 255 // and remove a few extra chars in case we need to add a counter at the end. let lastName = path.basename(url.path).substring(0, 250); if (lastName.endsWith('.zip')) { lastName = lastName.substring(0, lastName.length - 4); } const realpath = await fs.realpath(storagePath); let folderName = path.join(realpath, lastName); // avoid overwriting existing folders let counter = 0; while (await fs.pathExists(folderName)) { counter++; folderName = path.join(realpath, `${lastName}-${counter}`); if (counter > 100) { throw new Error('Could not find a unique name for downloaded database.'); } } return folderName; } function validateHttpsUrl(databaseUrl: string) { let uri; try { uri = Uri.parse(databaseUrl, true); } catch (e) { throw new Error(`Invalid url: ${databaseUrl}`); } if (uri.scheme !== 'https') { throw new Error('Must use https for downloading a database.'); } } async function readAndUnzip( zipUrl: string, unzipPath: string, cli?: CodeQLCliServer, progress?: ProgressCallback ) { // TODO: Providing progress as the file is unzipped is currently blocked // on https://github.com/ZJONSSON/node-unzipper/issues/222 const zipFile = Uri.parse(zipUrl).fsPath; progress?.({ maxStep: 10, step: 9, message: `Unzipping into ${path.basename(unzipPath)}` }); if (cli && await cli.cliConstraints.supportsDatabaseUnbundle()) { // Use the `database unbundle` command if the installed cli version supports it await cli.databaseUnbundle(zipFile, unzipPath); } else { // Must get the zip central directory since streaming the // zip contents may not have correct local file headers. // Instead, we can only rely on the central directory. const directory = await unzipper.Open.file(zipFile); await directory.extract({ path: unzipPath }); } } async function fetchAndUnzip( databaseUrl: string, unzipPath: string, cli?: CodeQLCliServer, progress?: ProgressCallback ) { // Although it is possible to download and stream directly to an unzipped directory, // we need to avoid this for two reasons. The central directory is located at the // end of the zip file. It is the source of truth of the content locations. Individual // file headers may be incorrect. Additionally, saving to file first will reduce memory // pressure compared with unzipping while downloading the archive. const archivePath = path.join(tmpDir.name, `archive-${Date.now()}.zip`); progress?.({ maxStep: 3, message: 'Downloading database', step: 1, }); const response = await checkForFailingResponse(await fetch(databaseUrl)); const archiveFileStream = fs.createWriteStream(archivePath); const contentLength = response.headers.get('content-length'); const totalNumBytes = contentLength ? parseInt(contentLength, 10) : undefined; reportStreamProgress(response.body, 'Downloading database', totalNumBytes, progress); await new Promise((resolve, reject) => response.body.pipe(archiveFileStream) .on('finish', resolve) .on('error', reject) ); await readAndUnzip(Uri.file(archivePath).toString(true), unzipPath, cli, progress); // remove archivePath eagerly since these archives can be large. await fs.remove(archivePath); } async function checkForFailingResponse(response: Response): Promise<Response | never> { if (response.ok) { return response; } // An error downloading the database. Attempt to extract the resaon behind it. const text = await response.text(); let msg: string; try { const obj = JSON.parse(text); msg = obj.error || obj.message || obj.reason || JSON.stringify(obj, null, 2); } catch (e) { msg = text; } throw new Error(`Error downloading database.\n\nReason: ${msg}`); } function isFile(databaseUrl: string) { return Uri.parse(databaseUrl).scheme === 'file'; } /** * Recursively looks for a file in a directory. If the file exists, then returns the directory containing the file. * * @param dir The directory to search * @param toFind The file to recursively look for in this directory * * @returns the directory containing the file, or undefined if not found. */ // exported for testing export async function findDirWithFile( dir: string, ...toFind: string[] ): Promise<string | undefined> { if (!(await fs.stat(dir)).isDirectory()) { return; } const files = await fs.readdir(dir); if (toFind.some((file) => files.includes(file))) { return dir; } for (const file of files) { const newPath = path.join(dir, file); const result = await findDirWithFile(newPath, ...toFind); if (result) { return result; } } return; } /** * The URL pattern is https://lgtm.com/projects/{provider}/{org}/{name}/{irrelevant-subpages}. * There are several possibilities for the provider: in addition to GitHub.com (g), * LGTM currently hosts projects from Bitbucket (b), GitLab (gl) and plain git (git). * * This function accepts any url that matches the pattern above. It also accepts the * raw project slug, e.g., `g/myorg/myproject` * * After the `{provider}/{org}/{name}` path components, there may be the components * related to sub pages. * * @param lgtmUrl The URL to the lgtm project * * @return true if this looks like an LGTM project url */ // exported for testing export function looksLikeLgtmUrl(lgtmUrl: string | undefined): lgtmUrl is string { if (!lgtmUrl) { return false; } if (convertRawLgtmSlug(lgtmUrl)) { return true; } try { const uri = Uri.parse(lgtmUrl, true); if (uri.scheme !== 'https') { return false; } if (uri.authority !== 'lgtm.com' && uri.authority !== 'www.lgtm.com') { return false; } const paths = uri.path.split('/').filter((segment) => segment); return paths.length >= 4 && paths[0] === 'projects'; } catch (e) { return false; } } function convertRawLgtmSlug(maybeSlug: string): string | undefined { if (!maybeSlug) { return; } const segments = maybeSlug.split('/'); const providers = ['g', 'gl', 'b', 'git']; if (segments.length === 3 && providers.includes(segments[0])) { return `https://lgtm.com/projects/${maybeSlug}`; } return; } // exported for testing export async function convertToDatabaseUrl( lgtmUrl: string, progress: ProgressCallback) { try { lgtmUrl = convertRawLgtmSlug(lgtmUrl) || lgtmUrl; const uri = Uri.parse(lgtmUrl, true); const paths = ['api', 'v1.0'].concat( uri.path.split('/').filter((segment) => segment) ).slice(0, 6); const projectUrl = `https://lgtm.com/${paths.join('/')}`; const projectResponse = await fetch(projectUrl); const projectJson = await projectResponse.json(); if (projectJson.code === 404) { throw new Error(); } const language = await promptForLanguage(projectJson, progress); if (!language) { return; } return `https://lgtm.com/${[ 'api', 'v1.0', 'snapshots', projectJson.id, language, ].join('/')}`; } catch (e) { void logger.log(`Error: ${e.message}`); throw new Error(`Invalid LGTM URL: ${lgtmUrl}`); } } async function promptForLanguage( projectJson: any, progress: ProgressCallback ): Promise<string | undefined> { progress({ message: 'Choose language', step: 2, maxStep: 2 }); if (!projectJson?.languages?.length) { return; } if (projectJson.languages.length === 1) { return projectJson.languages[0].language; } return await window.showQuickPick( projectJson.languages.map((lang: { language: string }) => lang.language), { placeHolder: 'Select the database language to download:' } ); } /** * Databases created by the old odasa tool will not have a zipped * source location. However, this extension works better if sources * are zipped. * * This function ensures that the source location is zipped. If the * `src` folder exists and the `src.zip` file does not, the `src` * folder will be zipped and then deleted. * * @param databasePath The full path to the unzipped database */ async function ensureZippedSourceLocation(databasePath: string): Promise<void> { const srcFolderPath = path.join(databasePath, 'src'); const srcZipPath = srcFolderPath + '.zip'; if ((await fs.pathExists(srcFolderPath)) && !(await fs.pathExists(srcZipPath))) { await zip(srcFolderPath, srcZipPath); await fs.remove(srcFolderPath); } }
the_stack
import { lstat, exists } from "fs" import glob from "glob" import reflect, { GenericTypeArgumentDecorator, useCache } from "@plumier/reflect" import { promisify } from "util" import { EntityIdDecorator, RelationDecorator } from "./decorator/entity" import { errorMessage } from "./types" import { isAbsolute, join } from "path" const lstatAsync = promisify(lstat) const existsAsync = promisify(exists) // --------------------------------------------------------------------- // // ------------------------------- TYPES ------------------------------- // // --------------------------------------------------------------------- // type Class<T = any> = new (...args: any[]) => T interface ClassWithRoot { root: string, type: Class } // --------------------------------------------------------------------- // // ------------------------------ HELPERS ------------------------------ // // --------------------------------------------------------------------- // declare global { interface String { format(...args: any[]): string } interface Array<T> { flatten(): T } } String.prototype.format = function (this: string, ...args: any[]) { return this.replace(/{(\d+)}/g, (m, i) => args[i]) } Array.prototype.flatten = function <T>(this: Array<T>) { return this.reduce((a, b) => a.concat(b), <T[]>[]) } function ellipsis(str: string, length: number) { if (str.length > length) { const leftPart = str.substring(0, length - 9) const rightPart = str.substring(str.length - 6) return `${leftPart}...${rightPart}` } else return str } function getChildValue(object: any, path: string) { return path .split(/[\.\[\]\'\"]/) .filter(p => p) .reduce((o, p) => o[p], object) } function hasKeyOf<T>(opt: any, key: string): opt is T { return !!opt[key] } function toBoolean(val: string) { const list: { [key: string]: boolean | undefined } = { on: true, true: true, "1": true, yes: true, off: false, false: false, "0": false, no: false } return list[val.toLowerCase()] ?? false } function isCustomClass(type: Function | Function[]) { switch (type && (type as any)[0] || type) { case undefined: case Boolean: case String: case Array: case Number: case Object: case Date: return false default: return true } } function memoize<R, P extends any[]>(fn: (...args: P) => R, getKey: (...args: P) => string|Class): (...args: P) => R { const cache: Map<string|Class, R> = new Map() return useCache(cache, fn, getKey) } // --------------------------------------------------------------------- // // ---------------------------- FILE SYSTEM ---------------------------- // // --------------------------------------------------------------------- // function removeExtension(x: string) { return x.replace(/\.[^/.]+$/, "") } function globAsync(path: string, opts?: glob.IOptions) { return new Promise<string[]>((resolve) => { glob(path, { ...opts }, (e, match) => resolve(match)) }) } async function traverseDirectory(path: string) { const dirs = await globAsync(path, { nodir: true }) const files = dirs.map(x => removeExtension(x)) return Array.from(new Set(files)) } async function findFilesRecursive(path: string): Promise<string[]> { // if file / directory provided if (await existsAsync(path)) { if ((await lstatAsync(path)).isDirectory()) { return traverseDirectory(`${path}/**/*.{ts,js}`) } else return [removeExtension(path)] } // else check if glob provided return traverseDirectory(path) } function appendRoute(...args: string[]): string { return "/" + args .filter(x => !!x) .map(x => x.toLowerCase()) .map(x => x.startsWith("/") ? x.slice(1) : x) .map(x => x.endsWith("/") ? x.slice(0, -1) : x) .filter(x => !!x) .join("/") } function getRoot(rootPath: string, path: string) { // directoryAsPath should not working with glob if (rootPath.indexOf("*") >= 0) return const part = path.slice(rootPath.length).split("/").filter(x => !!x) .slice(0, -1) return (part.length === 0) ? undefined : appendRoute(...part) } async function findClassRecursive(path: string | string[] | Class | Class[], option?: { directoryAsPath?: boolean, rootDir?: string }): Promise<ClassWithRoot[]> { const opt = { rootDir: "", directoryAsPath: false, ...option } if (Array.isArray(path)) { const result = [] for (const p of path) { result.push(...await findClassRecursive(p, opt)) } return result } if (typeof path === "string") { const absPath = isAbsolute(path) ? path : join(opt.rootDir, path) //read all files and get module reflection const files = await findFilesRecursive(absPath) const result = [] for (const file of files) { const root = !!opt.directoryAsPath ? (getRoot(absPath, file) ?? "") : "" for (const member of reflect(file).members) { if (member.kind === "Class") result.push({ root, type: member.type }) } } return result } else return [{ root: "", type: path }] } // --------------------------------------------------------------------- // // ---------------------------- PRINT TABLE ---------------------------- // // --------------------------------------------------------------------- // interface ColumnMeta { align?: "left" | "right", property: string | ((x: any) => string) } interface TableOption<T> { onPrintRow?: (row: string, data: T) => string } function printTable<T>(meta: (ColumnMeta | string | undefined)[], data: T[], option?: TableOption<T>) { const getText = (col: ColumnMeta, row: any): string => { if (typeof col.property === "string") return (row[col.property] ?? "") + "" else return col.property(row) } const metaData = meta.filter((x): x is ColumnMeta | string => !!x).map(x => typeof x === "string" ? <ColumnMeta>{ property: x } : x) .map(x => { const lengths = data.map(row => getText(x, row).length) const length = Math.max(...lengths) return { ...x, margin: x.align || "left", length, } }) const opt: Required<TableOption<T>> = { onPrintRow: x => x, ...option } for (const [i, row] of data.entries()) { // row number let text = `${(i + 1).toString().padStart(data.length.toString().length)}. ` for (const [idx, col] of metaData.entries()) { const exceptLast = idx < metaData.length - 1 const colText = getText(col, row) // margin if (col.margin === "right") text += colText.padStart(col.length) else if (exceptLast) text += colText.padEnd(col.length) else text += colText //padding if (exceptLast) text += " " } console.log(opt.onPrintRow(text, row)) } } // --------------------------------------------------------------------- // // ----------------------------- REFLECTION ---------------------------- // // --------------------------------------------------------------------- // interface TraverseContext<T> { path: string[], parentPath: Class[] } interface AnalysisMessage { issue: "NoProperties" | "TypeMissing" | "ArrayTypeMissing" location: string } type EntityRelationInfo = OneToManyRelationInfo | ManyToOneRelationInfo interface OneToManyRelationInfo { type: "OneToMany" parent: Class child: Class parentProperty: string childProperty?: string } interface ManyToOneRelationInfo { type: "ManyToOne" parent: Class child: Class parentProperty?: string childProperty: string } function analyzeModel<T>(type: Class | Class[], ctx: TraverseContext<T> = { path: [], parentPath: [] }): AnalysisMessage[] { const parentType = ctx.parentPath[ctx.parentPath.length - 1] const propName = ctx.path[ctx.path.length - 1] const location = `${parentType?.name}.${propName}` if (Array.isArray(type)) { if (type[0] === Object) return [{ location, issue: "ArrayTypeMissing" }] return analyzeModel(type[0], ctx) } if (isCustomClass(type)) { // CIRCULAR: check if type already in path, skip immediately if (ctx.parentPath.some(x => x === type)) return [] const meta = reflect(type) if (meta.properties.length === 0) return [{ location: type.name, issue: "NoProperties" }] const result = [] for (const prop of meta.properties) { const path = ctx.path.concat(prop.name) const typePath = ctx.parentPath.concat(type) const msgs = analyzeModel(prop.type, { ...ctx, path, parentPath: typePath }) result.push(...msgs) } return result } if (type === Object) return [{ location, issue: "TypeMissing" }] return [] } namespace entityHelper { export function getIdProp(entity: Class) { const meta = reflect(entity) for (const prop of meta.properties) { const decorator = prop.decorators.find((x: EntityIdDecorator) => x.kind === "plumier-meta:entity-id") if (decorator) return prop } } export function getIdType(entity: Class): Class | undefined { const prop = getIdProp(entity) return prop?.type } export function getRelationInfo([entity, relation]: [Class, string, Class?]): EntityRelationInfo { const meta = reflect(entity) const prop = meta.properties.find(x => x.name === relation) if (!prop) throw new Error(`${entity.name} doesn't have property named ${relation}`) if (prop.type === Array && !prop.type[0]) throw new Error(errorMessage.UnableToGetMemberDataType.format(entity.name, prop.name)) const type = Array.isArray(prop.type) ? "OneToMany" : "ManyToOne" if (type === "OneToMany") { const relDecorator: RelationDecorator = prop.decorators.find((x: RelationDecorator) => x.kind === "plumier-meta:relation") if (!relDecorator) throw new Error(`${entity.name}.${relation} is not a valid relation, make sure its decorated with @entity.relation() decorator`) const child = prop.type[0] as Class return { type, parent: entity, child, parentProperty: relation, childProperty: relDecorator.inverseProperty, } } else { const parent: Class = prop.type if (!parent) throw new Error(errorMessage.UnableToGetMemberDataType.format(entity.name, prop.name)) const parentMeta = reflect(parent) let parentProperty: string | undefined for (const prop of parentMeta.properties) { const relDecorator: RelationDecorator = prop.decorators.find((x: RelationDecorator) => x.kind === "plumier-meta:relation") if (!relDecorator) continue if (relDecorator.inverseProperty === relation) { parentProperty = prop.name break } } return { type, parent, child: entity, childProperty: relation, parentProperty } } } } export { ellipsis, toBoolean, getChildValue, Class, hasKeyOf, isCustomClass, entityHelper, findFilesRecursive, memoize, printTable, analyzeModel, AnalysisMessage, globAsync, EntityRelationInfo, OneToManyRelationInfo, ManyToOneRelationInfo, appendRoute, findClassRecursive, ClassWithRoot }
the_stack
import ts from "typescript"; import { apply, chain, externalSchematic, MergeStrategy, mergeWith, move, noop, Rule, SchematicContext, template, Tree, url, } from "@angular-devkit/schematics"; import { join, normalize, Path } from "@angular-devkit/core"; import { Schema } from "./schema"; import { addLintFiles, findNodes, generateProjectLint, getNpmScope, insert, offsetFromRoot, toFileName, updateJsonInTree, updateWorkspaceInTree, } from "@nrwl/workspace"; import init from "../init/init"; import { existsSync } from "fs"; import path from "path"; import { InsertChange } from "@nrwl/workspace/src/utils/ast-utils"; interface INormalizedSchema extends Schema { appProjectRoot: Path; parsedTags: string[]; } function updateNxJson(options: INormalizedSchema): Rule { return updateJsonInTree(`/nx.json`, (json) => { return { ...json, projects: { ...json.projects, [options.name]: { tags: options.parsedTags }, }, }; }); } function getBuildConfig(project: any, options: INormalizedSchema) { return { builder: "@apployees-nx/webserver:build", options: { outputPath: join(normalize("dist"), options.appProjectRoot), appHtml: join(project.sourceRoot, "public", "app.html"), serverMain: join(project.sourceRoot, "index.ts"), clientMain: join(project.sourceRoot, "client", "index.tsx"), favicon: join(project.sourceRoot, "public", "logo512.png"), manifestJson: join(project.sourceRoot, "public", "manifest.json"), clientOtherEntries: { // eslint-disable-next-line @typescript-eslint/camelcase anotherClientEntry_head: join(project.sourceRoot, "client", "anotherClientEntry.ts"), }, clientWebpackConfig: join(options.appProjectRoot, "webpack.client.overrides.js"), lessStyleVariables: join(options.appProjectRoot, "antd-theme.less"), tsConfig: join(options.appProjectRoot, "tsconfig.app.json"), assets: [join(project.sourceRoot, "public")], }, configurations: { production: { extractLicenses: true, inspect: false, watch: false, dev: false, fileReplacements: [ { replace: join(project.sourceRoot, "environments/environment.ts"), with: join(project.sourceRoot, "environments/environment.prod.ts"), }, ], }, development: { dev: true, inspect: true, extractLicenses: false, notifier: { excludeWarnings: true, }, }, }, }; } function updateWorkspaceJson(options: INormalizedSchema): Rule { return updateWorkspaceInTree((workspaceJson) => { const project = { root: options.appProjectRoot, sourceRoot: join(options.appProjectRoot, "src"), projectType: "application", prefix: options.name, schematics: {}, architect: {} as any, }; project.architect.build = getBuildConfig(project, options); project.architect.lint = generateProjectLint( normalize(project.root), join(normalize(project.root), "tsconfig.app.json"), options.linter, ); workspaceJson.projects[options.name] = project; workspaceJson.defaultProject = workspaceJson.defaultProject || options.name; return workspaceJson; }); } function addAppFiles(options: INormalizedSchema, npmScope: string): Rule { let appDir = path.resolve(__dirname, path.normalize(`schematics/application/files/app`)); if (!existsSync(appDir)) { appDir = path.resolve(__dirname, path.normalize(`files/app`)); } return mergeWith( apply(url(appDir), [ template({ tmpl: "", name: options.name, npmScope: npmScope, root: options.appProjectRoot, offset: offsetFromRoot(options.appProjectRoot), }), move(options.appProjectRoot), ]), ); } function addWorkspaceFiles(options: INormalizedSchema, npmScope: string): Rule { let workspaceFilesDir = path.resolve(__dirname, path.normalize(`schematics/application/workspace-files`)); if (!existsSync(workspaceFilesDir)) { workspaceFilesDir = path.resolve(__dirname, path.normalize(`workspace-files`)); } return (host: Tree, context: SchematicContext) => { if ( !host.exists(path.join("config", "jest", "cssTransform.js")) && !host.exists(path.join("config", "jest", "fileTransform.js")) ) { return mergeWith( apply(url(workspaceFilesDir), [ template({ tmpl: "", name: options.name, npmScope: npmScope, }), move(`/`), ]), ); } }; } function modifyRootJestConfig(options: INormalizedSchema, npmScope: string): Rule { return (host: Tree, context: SchematicContext) => { const jestConfigFilePath = `/jest.config.js`; const cssTransformLine = `\t'^.+\\.(css|sass|scss|less)$': \`\${__dirname}/config/jest/cssTransform.js\`,`; const fileTransformLine = `\t'^(?!.*\\.(js|jsx|ts|tsx|css|json)$)': \`\${__dirname}/config/jest/fileTransform.js\``; const otherLines = `, setupFiles: [ "react-app-polyfill/jsdom" ], testEnvironment: "jest-environment-jsdom-fourteen"`; if (host.exists(jestConfigFilePath)) { const jestConfigSource = host.read(jestConfigFilePath)!.toString("utf-8"); if (jestConfigSource.indexOf("react-app-polyfill/jsdom") >= 0) { // already added. return; } let insertTransformChange, insertOtherLinesChange; const jestConfigSourceFile = ts.createSourceFile( jestConfigFilePath, jestConfigSource, ts.ScriptTarget.Latest, true, ); const propertyAssignments = findNodes(jestConfigSourceFile, ts.SyntaxKind.PropertyAssignment); if (propertyAssignments && propertyAssignments.length > 0) { for (const propAssignment of propertyAssignments) { const firstChild = findNodes(propAssignment, ts.SyntaxKind.Identifier, 1); const secondChild = findNodes(propAssignment, ts.SyntaxKind.ObjectLiteralExpression, 1); /** * For: * * transform: { <-- identifier "transform" and ObjectLiteralExpression value * ... <-- PropertyAssignments * } */ if ( firstChild && firstChild.length > 0 && firstChild[0].getFullText(jestConfigSourceFile).indexOf("transform") >= 0 && secondChild && secondChild.length > 0 ) { // add transform lines after the last child in the value const maybePropertyAssignment = findNodes(secondChild[0], ts.SyntaxKind.PropertyAssignment, 1); if (maybePropertyAssignment && maybePropertyAssignment.length > 0) { insertTransformChange = new InsertChange( jestConfigFilePath, maybePropertyAssignment[0].getEnd(), `,\n${cssTransformLine}\n${fileTransformLine}`, ); // add the other lines after the transform line. insertOtherLinesChange = new InsertChange(jestConfigFilePath, propAssignment.getEnd(), otherLines); break; } } } } if (!insertTransformChange) { const transformChanges = `\n\n/* Add the following lines to your "transform" object in your jest config.\n\n${cssTransformLine},\n${fileTransformLine}\n\n\nAdd the following next to your transform (root level of the exported jest config object):\n\n${otherLines}\n\n*/`; insertTransformChange = new InsertChange(jestConfigFilePath, jestConfigSource.length, transformChanges); context.logger.warn( "Please see your jest.config.js file in the root of the project to make some necessary changes.", ); } insert(host, jestConfigFilePath, [insertTransformChange, insertOtherLinesChange].filter(Boolean)); } else { return updateJsonInTree(`/package.json`, (json) => { if (!json.jest) { return json; } let transform = json.jest.transform; if (!transform) { transform = {}; json.jest.transform = transform; } transform[`^.+\\.(css|sass|scss|less)$`] = `config/jest/cssTransform.js`; transform[`^(?!.*\\.(js|jsx|ts|tsx|css|json)$)`] = `config/jest/fileTransform.js`; return json; }); } }; } function updateRootPackageJson(options: INormalizedSchema): Rule { return (host: Tree) => { return updateJsonInTree(`/package.json`, (json) => { if (!json.scripts) { json.scripts = {}; } json.scripts[`dev-${options.name}`] = `nx build ${options.name} --configuration development`; json.scripts[`build-${options.name}`] = `nx build ${options.name} --configuration production`; json.scripts[`lint-${options.name}`] = `nx lint ${options.name}`; json.scripts[`test-${options.name}`] = `nx test ${options.name}`; return json; }); }; } export default function (schema: Schema): Rule { return (host: Tree, context: SchematicContext) => { const options = normalizeOptions(schema); const npmScope = getNpmScope(host) || "yourOrg"; return chain([ init({ skipFormat: true, }), addLintFiles(options.appProjectRoot, options.linter), addAppFiles(options, npmScope), addWorkspaceFiles(options, npmScope), modifyRootJestConfig(options, npmScope), updateWorkspaceJson(options), updateNxJson(options), updateRootPackageJson(options), options.unitTestRunner === "jest" ? externalSchematic("@nrwl/jest", "jest-project", { project: options.name, setupFile: "none", supportTsx: true, skipSerializers: true, }) : noop(), ])(host, context); }; } function normalizeOptions(options: Schema): INormalizedSchema { const appDirectory = options.directory ? `${toFileName(options.directory)}/${toFileName(options.name)}` : toFileName(options.name); const appProjectName = appDirectory.replace(new RegExp("/", "g"), "-"); const appProjectRoot = join(normalize("apps"), appDirectory); const parsedTags = options.tags ? options.tags.split(",").map((s) => s.trim()) : []; return { ...options, name: toFileName(appProjectName), appProjectRoot, parsedTags, }; }
the_stack
declare module 'github-api' { /** * A Gist can retrieve and modify gists. */ class Gist { /** * A Gist can retrieve and modify gists. */ constructor(id: string, auth?: Requestable.auth, apiBase?: string); /** * Fetch a gist. * @see https://developer.github.com/v3/gists/#get-a-single-gist * @param {Requestable.callback} [cb] - will receive the gist * @return {Promise} - the Promise for the http request */ read(cb?: Requestable.callback): Promise<any>; /** * Create a new gist. * @see https://developer.github.com/v3/gists/#create-a-gist * @param {Object} gist - the data for the new gist * @param {Requestable.callback} [cb] - will receive the new gist upon creation * @return {Promise} - the Promise for the http request */ create(gist: Object, cb?: Requestable.callback): Promise<any>; /** * Delete a gist. * @see https://developer.github.com/v3/gists/#delete-a-gist * @param {Requestable.callback} [cb] - will receive true if the request succeeds * @return {Promise} - the Promise for the http request */ delete(cb?: Requestable.callback): Promise<any>; /** * Fork a gist. * @see https://developer.github.com/v3/gists/#fork-a-gist * @param {Requestable.callback} [cb] - the function that will receive the gist * @return {Promise} - the Promise for the http request */ fork(cb?: Requestable.callback): Promise<any>; /** * Update a gist. * @see https://developer.github.com/v3/gists/#edit-a-gist * @param {Object} gist - the new data for the gist * @param {Requestable.callback} [cb] - the function that receives the API result * @return {Promise} - the Promise for the http request */ update(gist: Object, cb?: Requestable.callback): Promise<any>; /** * Star a gist. * @see https://developer.github.com/v3/gists/#star-a-gist * @param {Requestable.callback} [cb] - will receive true if the request is successful * @return {Promise} - the Promise for the http request */ star(cb?: Requestable.callback): Promise<any>; /** * Unstar a gist. * @see https://developer.github.com/v3/gists/#unstar-a-gist * @param {Requestable.callback} [cb] - will receive true if the request is successful * @return {Promise} - the Promise for the http request */ unstar(cb?: Requestable.callback): Promise<any>; /** * Check if a gist is starred by the user. * @see https://developer.github.com/v3/gists/#check-if-a-gist-is-starred * @param {Requestable.callback} [cb] - will receive true if the gist is starred and false if the gist is not starred * @return {Promise} - the Promise for the http request */ isStarred(cb?: Requestable.callback): Promise<any>; /** * List the gist's comments * @see https://developer.github.com/v3/gists/comments/#list-comments-on-a-gist * @param {Requestable.callback} [cb] - will receive the array of comments * @return {Promise} - the promise for the http request */ listComments(cb?: Requestable.callback): Promise<any>; /** * Fetch one of the gist's comments * @see https://developer.github.com/v3/gists/comments/#get-a-single-comment * @param {number} comment - the id of the comment * @param {Requestable.callback} [cb] - will receive the comment * @return {Promise} - the Promise for the http request */ getComment(comment: number, cb?: Requestable.callback): Promise<any>; /** * Comment on a gist * @see https://developer.github.com/v3/gists/comments/#create-a-comment * @param {string} comment - the comment to add * @param {Requestable.callback} [cb] - the function that receives the API result * @return {Promise} - the Promise for the http request */ createComment(comment: string, cb?: Requestable.callback): Promise<any>; /** * Edit a comment on the gist * @see https://developer.github.com/v3/gists/comments/#edit-a-comment * @param {number} comment - the id of the comment * @param {string} body - the new comment * @param {Requestable.callback} [cb] - will receive the modified comment * @return {Promise} - the promise for the http request */ editComment(comment: number, body: string, cb?: Requestable.callback): Promise<any>; /** * Delete a comment on the gist. * @see https://developer.github.com/v3/gists/comments/#delete-a-comment * @param {number} comment - the id of the comment * @param {Requestable.callback} [cb] - will receive true if the request succeeds * @return {Promise} - the Promise for the http request */ deleteComment(comment: number, cb?: Requestable.callback): Promise<any>; } /** * GitHub encapsulates the functionality to create various API wrapper objects. */ class GitHub { /** * GitHub encapsulates the functionality to create various API wrapper objects. */ constructor(auth?: Requestable.auth, apiBase?: string); /** * Create a new Gist wrapper * @param {string} [id] - the id for the gist, leave undefined when creating a new gist * @return {Gist} */ getGist(id?: string): Gist; /** * Create a new User wrapper * @param {string} [user] - the name of the user to get information about * leave undefined for the authenticated user * @return {User} */ getUser(user?: string): User; /** * Create a new Organization wrapper * @param {string} organization - the name of the organization * @return {Organization} */ getOrganization(organization: string): Organization; /** * create a new Team wrapper * @param {string} teamId - the name of the team * @return {Team} */ getTeam(teamId: string): Team; /** * Create a new Repository wrapper * @param {string} user - the user who owns the respository * @param {string} repo - the name of the repository * @return {Repository} */ getRepo(user: string, repo: string): Repository; /** * Create a new Issue wrapper * @param {string} user - the user who owns the respository * @param {string} repo - the name of the repository * @return {Issue} */ getIssues(user: string, repo: string): Issue; /** * Create a new Search wrapper * @param {string} query - the query to search for * @return {Search} */ search(query: string): Search; /** * Create a new RateLimit wrapper * @return {RateLimit} */ getRateLimit(): RateLimit; /** * Create a new Markdown wrapper * @return {Markdown} */ getMarkdown(): Markdown; /** * Computes the full repository name * @param {string} user - the username (or the full name) * @param {string} repo - the repository name, must not be passed if `user` is the full name * @return {string} the repository's full name */ _getFullName(user: string, repo: string): string; } /** * Issue wraps the functionality to get issues for repositories */ class Issue { /** * Issue wraps the functionality to get issues for repositories */ constructor(repository: string, auth?: Requestable.auth, apiBase?: string); /** * Create a new issue * @see https://developer.github.com/v3/issues/#create-an-issue * @param {Object} issueData - the issue to create * @param {Requestable.callback} [cb] - will receive the created issue * @return {Promise} - the promise for the http request */ createIssue(issueData: Object, cb?: Requestable.callback): Promise<any>; /** * List the issues for the repository * @see https://developer.github.com/v3/issues/#list-issues-for-a-repository * @param {Object} options - filtering options * @param {Requestable.callback} [cb] - will receive the array of issues * @return {Promise} - the promise for the http request */ listIssues(options: Object, cb?: Requestable.callback): Promise<any>; /** * List the events for an issue * @see https://developer.github.com/v3/issues/events/#list-events-for-an-issue * @param {number} issue - the issue to get events for * @param {Requestable.callback} [cb] - will receive the list of events * @return {Promise} - the promise for the http request */ listIssueEvents(issue: number, cb?: Requestable.callback): Promise<any>; /** * List comments on an issue * @see https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue * @param {number} issue - the id of the issue to get comments from * @param {Requestable.callback} [cb] - will receive the comments * @return {Promise} - the promise for the http request */ listIssueComments(issue: number, cb?: Requestable.callback): Promise<any>; /** * Get a single comment on an issue * @see https://developer.github.com/v3/issues/comments/#get-a-single-comment * @param {number} id - the comment id to get * @param {Requestable.callback} [cb] - will receive the comment * @return {Promise} - the promise for the http request */ getIssueComment(id: number, cb?: Requestable.callback): Promise<any>; /** * Comment on an issue * @see https://developer.github.com/v3/issues/comments/#create-a-comment * @param {number} issue - the id of the issue to comment on * @param {string} comment - the comment to add * @param {Requestable.callback} [cb] - will receive the created comment * @return {Promise} - the promise for the http request */ createIssueComment(issue: number, comment: string, cb?: Requestable.callback): Promise<any>; /** * Edit a comment on an issue * @see https://developer.github.com/v3/issues/comments/#edit-a-comment * @param {number} id - the comment id to edit * @param {string} comment - the comment to edit * @param {Requestable.callback} [cb] - will receive the edited comment * @return {Promise} - the promise for the http request */ editIssueComment(id: number, comment: string, cb?: Requestable.callback): Promise<any>; /** * Delete a comment on an issue * @see https://developer.github.com/v3/issues/comments/#delete-a-comment * @param {number} id - the comment id to delete * @param {Requestable.callback} [cb] - will receive true if the request is successful * @return {Promise} - the promise for the http request */ deleteIssueComment(id: number, cb?: Requestable.callback): Promise<any>; /** * Edit an issue * @see https://developer.github.com/v3/issues/#edit-an-issue * @param {number} issue - the issue number to edit * @param {Object} issueData - the new issue data * @param {Requestable.callback} [cb] - will receive the modified issue * @return {Promise} - the promise for the http request */ editIssue(issue: number, issueData: Object, cb?: Requestable.callback): Promise<any>; /** * Get a particular issue * @see https://developer.github.com/v3/issues/#get-a-single-issue * @param {number} issue - the issue number to fetch * @param {Requestable.callback} [cb] - will receive the issue * @return {Promise} - the promise for the http request */ getIssue(issue: number, cb?: Requestable.callback): Promise<any>; /** * List the milestones for the repository * @see https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository * @param {Object} options - filtering options * @param {Requestable.callback} [cb] - will receive the array of milestones * @return {Promise} - the promise for the http request */ listMilestones(options: Object, cb?: Requestable.callback): Promise<any>; /** * Get a milestone * @see https://developer.github.com/v3/issues/milestones/#get-a-single-milestone * @param {string} milestone - the id of the milestone to fetch * @param {Requestable.callback} [cb] - will receive the array of milestones * @return {Promise} - the promise for the http request */ getMilestone(milestone: string, cb?: Requestable.callback): Promise<any>; /** * Create a new milestone * @see https://developer.github.com/v3/issues/milestones/#create-a-milestone * @param {Object} milestoneData - the milestone definition * @param {Requestable.callback} [cb] - will receive the array of milestones * @return {Promise} - the promise for the http request */ createMilestone(milestoneData: Object, cb?: Requestable.callback): Promise<any>; /** * Edit a milestone * @see https://developer.github.com/v3/issues/milestones/#update-a-milestone * @param {string} milestone - the id of the milestone to edit * @param {Object} milestoneData - the updates to make to the milestone * @param {Requestable.callback} [cb] - will receive the array of milestones * @return {Promise} - the promise for the http request */ editMilestone(milestone: string, milestoneData: Object, cb?: Requestable.callback): Promise<any>; /** * Delete a milestone (this is distinct from closing a milestone) * @see https://developer.github.com/v3/issues/milestones/#delete-a-milestone * @param {string} milestone - the id of the milestone to delete * @param {Requestable.callback} [cb] - will receive the array of milestones * @return {Promise} - the promise for the http request */ deleteMilestone(milestone: string, cb?: Requestable.callback): Promise<any>; /** * Create a new label * @see https://developer.github.com/v3/issues/labels/#create-a-label * @param {Object} labelData - the label definition * @param {Requestable.callback} [cb] - will receive the object representing the label * @return {Promise} - the promise for the http request */ createLabel(labelData: Object, cb?: Requestable.callback): Promise<any>; } /** * RateLimit allows users to query their rate-limit status */ class Markdown { /** * RateLimit allows users to query their rate-limit status */ constructor(auth: Requestable.auth, apiBase?: string); /** * Render html from Markdown text. * @see https://developer.github.com/v3/markdown/#render-an-arbitrary-markdown-document * @param {Object} options - conversion options * @param {string} [options.text] - the markdown text to convert * @param {string} [options.mode=markdown] - can be either `markdown` or `gfm` * @param {string} [options.context] - repository name if mode is gfm * @param {Requestable.callback} [cb] - will receive the converted html * @return {Promise} - the promise for the http request */ render(options: { text: string, mode: string, context: string }, cb?: Requestable.callback): Promise<any>; } /** * Organization encapsulates the functionality to create repositories in organizations */ class Organization { /** * Organization encapsulates the functionality to create repositories in organizations */ constructor(organization: string, auth?: Requestable.auth, apiBase?: string); /** * Create a repository in an organization * @see https://developer.github.com/v3/repos/#create * @param {Object} options - the repository definition * @param {Requestable.callback} [cb] - will receive the created repository * @return {Promise} - the promise for the http request */ createRepo(options: Object, cb?: Requestable.callback): Promise<any>; /** * List the repositories in an organization * @see https://developer.github.com/v3/repos/#list-organization-repositories * @param {Requestable.callback} [cb] - will receive the list of repositories * @return {Promise} - the promise for the http request */ getRepos(cb?: Requestable.callback): Promise<any>; /** * Query if the user is a member or not * @param {string} username - the user in question * @param {Requestable.callback} [cb] - will receive true if the user is a member * @return {Promise} - the promise for the http request */ isMember(username: string, cb?: Requestable.callback): Promise<any>; /** * List the users who are members of the company * @see https://developer.github.com/v3/orgs/members/#members-list * @param {object} options - filtering options * @param {string} [options.filter=all] - can be either `2fa_disabled` or `all` * @param {string} [options.role=all] - can be one of: `all`, `admin`, or `member` * @param {Requestable.callback} [cb] - will receive the list of users * @return {Promise} - the promise for the http request */ listMembers(options: { filter: string, role: string }, cb?: Requestable.callback): Promise<any>; /** * List the Teams in the Organization * @see https://developer.github.com/v3/orgs/teams/#list-teams * @param {Requestable.callback} [cb] - will receive the list of teams * @return {Promise} - the promise for the http request */ getTeams(cb?: Requestable.callback): Promise<any>; /** * Create a team * @see https://developer.github.com/v3/orgs/teams/#create-team * @param {object} options - Team creation parameters * @param {string} options.name - The name of the team * @param {string} [options.description] - Team description * @param {string} [options.repo_names] - Repos to add the team to * @param {string} [options.privacy=secret] - The level of privacy the team should have. Can be either one * of: `secret`, or `closed` * @param {Requestable.callback} [cb] - will receive the created team * @return {Promise} - the promise for the http request */ createTeam(options: { name: string, description: string, repo_names: string, privacy: string }, cb?: Requestable.callback): Promise<any>; } /** * RateLimit allows users to query their rate-limit status */ class RateLimit { /** * RateLimit allows users to query their rate-limit status */ constructor(auth: Requestable.auth, apiBase?: string); /** * Query the current rate limit * @see https://developer.github.com/v3/rate_limit/ * @param {Requestable.callback} [cb] - will receive the rate-limit data * @return {Promise} - the promise for the http request */ getRateLimit(cb?: Requestable.callback): Promise<any>; } /** * Respository encapsulates the functionality to create, query, and modify files. * @class Repository */ class Repository { /** * Respository encapsulates the functionality to create, query, and modify files. * @class Repository */ constructor(); /** * Get a reference * @see https://developer.github.com/v3/git/refs/#get-a-reference * @param {string} ref - the reference to get * @param {Requestable.callback} [cb] - will receive the reference's refSpec or a list of refSpecs that match `ref` * @return {Promise} - the promise for the http request */ getRef(ref: string, cb?: Requestable.callback): Promise<any>; /** * Create a reference * @see https://developer.github.com/v3/git/refs/#create-a-reference * @param {Object} options - the object describing the ref * @param {Requestable.callback} [cb] - will receive the ref * @return {Promise} - the promise for the http request */ createRef(options: Object, cb?: Requestable.callback): Promise<any>; /** * Delete a reference * @see https://developer.github.com/v3/git/refs/#delete-a-reference * @param {string} ref - the name of the ref to delte * @param {Requestable.callback} [cb] - will receive true if the request is successful * @return {Promise} - the promise for the http request */ deleteRef(ref: string, cb?: Requestable.callback): Promise<any>; /** * Delete a repository * @see https://developer.github.com/v3/repos/#delete-a-repository * @param {Requestable.callback} [cb] - will receive true if the request is successful * @return {Promise} - the promise for the http request */ deleteRepo(cb?: Requestable.callback): Promise<any>; /** * List the tags on a repository * @see https://developer.github.com/v3/repos/#list-tags * @param {Requestable.callback} [cb] - will receive the tag data * @return {Promise} - the promise for the http request */ listTags(cb?: Requestable.callback): Promise<any>; /** * List the open pull requests on the repository * @see https://developer.github.com/v3/pulls/#list-pull-requests * @param {Object} options - options to filter the search * @param {Requestable.callback} [cb] - will receive the list of PRs * @return {Promise} - the promise for the http request */ listPullRequests(options: Object, cb?: Requestable.callback): Promise<any>; /** * Get information about a specific pull request * @see https://developer.github.com/v3/pulls/#get-a-single-pull-request * @param {number} number - the PR you wish to fetch * @param {Requestable.callback} [cb] - will receive the PR from the API * @return {Promise} - the promise for the http request */ getPullRequest(number: number, cb?: Requestable.callback): Promise<any>; /** * List the files of a specific pull request * @see https://developer.github.com/v3/pulls/#list-pull-requests-files * @param {number|string} number - the PR you wish to fetch * @param {Requestable.callback} [cb] - will receive the list of files from the API * @return {Promise} - the promise for the http request */ listPullRequestFiles(number: (number | string), cb?: Requestable.callback): Promise<any>; /** * Compare two branches/commits/repositories * @see https://developer.github.com/v3/repos/commits/#compare-two-commits * @param {string} base - the base commit * @param {string} head - the head commit * @param {Requestable.callback} cb - will receive the comparison * @return {Promise} - the promise for the http request */ compareBranches(base: string, head: string, cb: Requestable.callback): Promise<any>; /** * List all the branches for the repository * @see https://developer.github.com/v3/repos/#list-branches * @param {Requestable.callback} cb - will receive the list of branches * @return {Promise} - the promise for the http request */ listBranches(cb: Requestable.callback): Promise<any>; /** * Get a raw blob from the repository * @see https://developer.github.com/v3/git/blobs/#get-a-blob * @param {string} sha - the sha of the blob to fetch * @param {Requestable.callback} cb - will receive the blob from the API * @return {Promise} - the promise for the http request */ getBlob(sha: string, cb: Requestable.callback): Promise<any>; /** * Get a single branch * @see https://developer.github.com/v3/repos/branches/#get-branch * @param {string} branch - the name of the branch to fetch * @param {Requestable.callback} cb - will receive the branch from the API * @returns {Promise} - the promise for the http request */ getBranch(branch: string, cb: Requestable.callback): Promise<any>; /** * Get a commit from the repository * @see https://developer.github.com/v3/repos/commits/#get-a-single-commit * @param {string} sha - the sha for the commit to fetch * @param {Requestable.callback} cb - will receive the commit data * @return {Promise} - the promise for the http request */ getCommit(sha: string, cb: Requestable.callback): Promise<any>; /** * List the commits on a repository, optionally filtering by path, author or time range * @see https://developer.github.com/v3/repos/commits/#list-commits-on-a-repository * @param {Object} [options] - the filtering options for commits * @param {string} [options.sha] - the SHA or branch to start from * @param {string} [options.path] - the path to search on * @param {string} [options.author] - the commit author * @param {(Date|string)} [options.since] - only commits after this date will be returned * @param {(Date|string)} [options.until] - only commits before this date will be returned * @param {Requestable.callback} cb - will receive the list of commits found matching the criteria * @return {Promise} - the promise for the http request */ listCommits(options?: { sha: string, path: string, author: string, since: (Date | string), until: (Date | string) }, cb?: Requestable.callback): Promise<any>; /** * Gets a single commit information for a repository * @see https://developer.github.com/v3/repos/commits/#get-a-single-commit * @param {string} ref - the reference for the commit-ish * @param {Requestable.callback} cb - will receive the commit information * @return {Promise} - the promise for the http request */ getSingleCommit(ref: string, cb: Requestable.callback): Promise<any>; /** * Get tha sha for a particular object in the repository. This is a convenience function * @see https://developer.github.com/v3/repos/contents/#get-contents * @param {string} [branch] - the branch to look in, or the repository's default branch if omitted * @param {string} path - the path of the file or directory * @param {Requestable.callback} cb - will receive a description of the requested object, including a `SHA` property * @return {Promise} - the promise for the http request */ getSha(branch?: string, path?: string, cb?: Requestable.callback): Promise<any>; /** * List the commit statuses for a particular sha, branch, or tag * @see https://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref * @param {string} sha - the sha, branch, or tag to get statuses for * @param {Requestable.callback} cb - will receive the list of statuses * @return {Promise} - the promise for the http request */ listStatuses(sha: string, cb: Requestable.callback): Promise<any>; /** * Get a description of a git tree * @see https://developer.github.com/v3/git/trees/#get-a-tree * @param {string} treeSHA - the SHA of the tree to fetch * @param {Requestable.callback} cb - will receive the callback data * @return {Promise} - the promise for the http request */ getTree(treeSHA: string, cb: Requestable.callback): Promise<any>; /** * Create a blob * @see https://developer.github.com/v3/git/blobs/#create-a-blob * @param {string|Buffer|Blob} content - the content to add to the repository * @param {Requestable.callback} cb - will receive the details of the created blob * @return {Promise} - the promise for the http request */ createBlob(content: (string | Buffer | Blob), cb: Requestable.callback): Promise<any>; /** * Get the object that represents the provided content * @param {string|Buffer|Blob} content - the content to send to the server * @return {Object} the representation of `content` for the GitHub API */ _getContentObject(content: (string | Buffer | Blob)): Object; /** * Update a tree in Git * @see https://developer.github.com/v3/git/trees/#create-a-tree * @param {string} baseTreeSHA - the SHA of the tree to update * @param {string} path - the path for the new file * @param {string} blobSHA - the SHA for the blob to put at `path` * @param {Requestable.callback} cb - will receive the new tree that is created * @return {Promise} - the promise for the http request * @deprecated use {@link Repository#createTree} instead */ updateTree(baseTreeSHA: string, path: string, blobSHA: string, cb: Requestable.callback): Promise<any>; /** * Create a new tree in git * @see https://developer.github.com/v3/git/trees/#create-a-tree * @param {Object} tree - the tree to create * @param {string} baseSHA - the root sha of the tree * @param {Requestable.callback} cb - will receive the new tree that is created * @return {Promise} - the promise for the http request */ createTree(tree: Object, baseSHA: string, cb: Requestable.callback): Promise<any>; /** * Add a commit to the repository * @see https://developer.github.com/v3/git/commits/#create-a-commit * @param {string} parent - the SHA of the parent commit * @param {string} tree - the SHA of the tree for this commit * @param {string} message - the commit message * @param {Requestable.callback} cb - will receive the commit that is created * @return {Promise} - the promise for the http request */ commit(parent: string, tree: string, message: string, cb: Requestable.callback): Promise<any>; /** * Update a ref * @see https://developer.github.com/v3/git/refs/#update-a-reference * @param {string} ref - the ref to update * @param {string} commitSHA - the SHA to point the reference to * @param {boolean} force - indicates whether to force or ensure a fast-forward update * @param {Requestable.callback} cb - will receive the updated ref back * @return {Promise} - the promise for the http request */ updateHead(ref: string, commitSHA: string, force: boolean, cb: Requestable.callback): Promise<any>; /** * Get information about the repository * @see https://developer.github.com/v3/repos/#get * @param {Requestable.callback} cb - will receive the information about the repository * @return {Promise} - the promise for the http request */ getDetails(cb: Requestable.callback): Promise<any>; /** * List the contributors to the repository * @see https://developer.github.com/v3/repos/#list-contributors * @param {Requestable.callback} cb - will receive the list of contributors * @return {Promise} - the promise for the http request */ getContributors(cb: Requestable.callback): Promise<any>; /** * List the users who are collaborators on the repository. The currently authenticated user must have * push access to use this method * @see https://developer.github.com/v3/repos/collaborators/#list-collaborators * @param {Requestable.callback} cb - will receive the list of collaborators * @return {Promise} - the promise for the http request */ getCollaborators(cb: Requestable.callback): Promise<any>; /** * Check if a user is a collaborator on the repository * @see https://developer.github.com/v3/repos/collaborators/#check-if-a-user-is-a-collaborator * @param {string} username - the user to check * @param {Requestable.callback} cb - will receive true if the user is a collaborator and false if they are not * @return {Promise} - the promise for the http request {Boolean} [description] */ isCollaborator(username: string, cb: Requestable.callback): Promise<any>; /** * Get the contents of a repository * @see https://developer.github.com/v3/repos/contents/#get-contents * @param {string} ref - the ref to check * @param {string} path - the path containing the content to fetch * @param {boolean} [raw] - `true` if the results should be returned raw instead of GitHub's normalized format * @param {Requestable.callback} [cb] - will receive the fetched data * @return {Promise} - the promise for the http request */ getContents(ref: string, path: string, raw?: boolean, cb?: Requestable.callback): Promise<any>; /** * Get the README of a repository * @see https://developer.github.com/v3/repos/contents/#get-the-readme * @param {string} ref - the ref to check * @param {boolean} raw - `true` if the results should be returned raw instead of GitHub's normalized format * @param {Requestable.callback} cb - will receive the fetched data * @return {Promise} - the promise for the http request */ getReadme(ref: string, raw: boolean, cb: Requestable.callback): Promise<any>; /** * Fork a repository * @see https://developer.github.com/v3/repos/forks/#create-a-fork * @param {Requestable.callback} cb - will receive the information about the newly created fork * @return {Promise} - the promise for the http request */ fork(cb: Requestable.callback): Promise<any>; /** * List a repository's forks * @see https://developer.github.com/v3/repos/forks/#list-forks * @param {Requestable.callback} cb - will receive the list of repositories forked from this one * @return {Promise} - the promise for the http request */ listForks(cb: Requestable.callback): Promise<any>; /** * Create a new branch from an existing branch. * @param {string} [oldBranch=master] - the name of the existing branch * @param {string} newBranch - the name of the new branch * @param {Requestable.callback} cb - will receive the commit data for the head of the new branch * @return {Promise} - the promise for the http request */ createBranch(oldBranch?: string, newBranch?: string, cb?: Requestable.callback): Promise<any>; /** * Create a new pull request * @see https://developer.github.com/v3/pulls/#create-a-pull-request * @param {Object} options - the pull request description * @param {Requestable.callback} cb - will receive the new pull request * @return {Promise} - the promise for the http request */ createPullRequest(options: Object, cb: Requestable.callback): Promise<any>; /** * Update a pull request * @deprecated since version 2.4.0 * @see https://developer.github.com/v3/pulls/#update-a-pull-request * @param {number|string} number - the number of the pull request to update * @param {Object} options - the pull request description * @param {Requestable.callback} [cb] - will receive the pull request information * @return {Promise} - the promise for the http request */ updatePullRequst(number: (number | string), options: Object, cb?: Requestable.callback): Promise<any>; /** * Update a pull request * @see https://developer.github.com/v3/pulls/#update-a-pull-request * @param {number|string} number - the number of the pull request to update * @param {Object} options - the pull request description * @param {Requestable.callback} [cb] - will receive the pull request information * @return {Promise} - the promise for the http request */ updatePullRequest(number: (number | string), options: Object, cb?: Requestable.callback): Promise<any>; /** * List the hooks for the repository * @see https://developer.github.com/v3/repos/hooks/#list-hooks * @param {Requestable.callback} cb - will receive the list of hooks * @return {Promise} - the promise for the http request */ listHooks(cb: Requestable.callback): Promise<any>; /** * Get a hook for the repository * @see https://developer.github.com/v3/repos/hooks/#get-single-hook * @param {number} id - the id of the webook * @param {Requestable.callback} cb - will receive the details of the webook * @return {Promise} - the promise for the http request */ getHook(id: number, cb: Requestable.callback): Promise<any>; /** * Add a new hook to the repository * @see https://developer.github.com/v3/repos/hooks/#create-a-hook * @param {Object} options - the configuration describing the new hook * @param {Requestable.callback} cb - will receive the new webhook * @return {Promise} - the promise for the http request */ createHook(options: Object, cb: Requestable.callback): Promise<any>; /** * Edit an existing webhook * @see https://developer.github.com/v3/repos/hooks/#edit-a-hook * @param {number} id - the id of the webhook * @param {Object} options - the new description of the webhook * @param {Requestable.callback} cb - will receive the updated webhook * @return {Promise} - the promise for the http request */ updateHook(id: number, options: Object, cb: Requestable.callback): Promise<any>; /** * Delete a webhook * @see https://developer.github.com/v3/repos/hooks/#delete-a-hook * @param {number} id - the id of the webhook to be deleted * @param {Requestable.callback} cb - will receive true if the call is successful * @return {Promise} - the promise for the http request */ deleteHook(id: number, cb: Requestable.callback): Promise<any>; /** * List the deploy keys for the repository * @see https://developer.github.com/v3/repos/keys/#list-deploy-keys * @param {Requestable.callback} cb - will receive the list of deploy keys * @return {Promise} - the promise for the http request */ listKeys(cb: Requestable.callback): Promise<any>; /** * Get a deploy key for the repository * @see https://developer.github.com/v3/repos/keys/#get-a-deploy-key * @param {number} id - the id of the deploy key * @param {Requestable.callback} cb - will receive the details of the deploy key * @return {Promise} - the promise for the http request */ getKey(id: number, cb: Requestable.callback): Promise<any>; /** * Add a new deploy key to the repository * @see https://developer.github.com/v3/repos/keys/#add-a-new-deploy-key * @param {Object} options - the configuration describing the new deploy key * @param {Requestable.callback} cb - will receive the new deploy key * @return {Promise} - the promise for the http request */ createKey(options: Object, cb: Requestable.callback): Promise<any>; /** * Delete a deploy key * @see https://developer.github.com/v3/repos/keys/#remove-a-deploy-key * @param {number} id - the id of the deploy key to be deleted * @param {Requestable.callback} cb - will receive true if the call is successful * @return {Promise} - the promise for the http request */ deleteKey(id: number, cb: Requestable.callback): Promise<any>; /** * Delete a file from a branch * @see https://developer.github.com/v3/repos/contents/#delete-a-file * @param {string} branch - the branch to delete from, or the default branch if not specified * @param {string} path - the path of the file to remove * @param {Requestable.callback} cb - will receive the commit in which the delete occurred * @return {Promise} - the promise for the http request */ deleteFile(branch: string, path: string, cb: Requestable.callback): Promise<any>; /** * Change all references in a repo from oldPath to new_path * @param {string} branch - the branch to carry out the reference change, or the default branch if not specified * @param {string} oldPath - original path * @param {string} newPath - new reference path * @param {Requestable.callback} cb - will receive the commit in which the move occurred * @return {Promise} - the promise for the http request */ move(branch: string, oldPath: string, newPath: string, cb: Requestable.callback): Promise<any>; /** * Write a file to the repository * @see https://developer.github.com/v3/repos/contents/#update-a-file * @param {string} branch - the name of the branch * @param {string} path - the path for the file * @param {string} content - the contents of the file * @param {string} message - the commit message * @param {Object} [options] - commit options * @param {Object} [options.author] - the author of the commit * @param {Object} [options.commiter] - the committer * @param {boolean} [options.encode] - true if the content should be base64 encoded * @param {Requestable.callback} cb - will receive the new commit * @return {Promise} - the promise for the http request */ writeFile(branch: string, path: string, content: string, message: string, options?: { author: Object, commiter: Object, encode: boolean }, cb?: Requestable.callback): Promise<any>; /** * Check if a repository is starred by you * @see https://developer.github.com/v3/activity/starring/#check-if-you-are-starring-a-repository * @param {Requestable.callback} cb - will receive true if the repository is starred and false if the repository * is not starred * @return {Promise} - the promise for the http request {Boolean} [description] */ isStarred(cb: Requestable.callback): Promise<any>; /** * Star a repository * @see https://developer.github.com/v3/activity/starring/#star-a-repository * @param {Requestable.callback} cb - will receive true if the repository is starred * @return {Promise} - the promise for the http request */ star(cb: Requestable.callback): Promise<any>; /** * Unstar a repository * @see https://developer.github.com/v3/activity/starring/#unstar-a-repository * @param {Requestable.callback} cb - will receive true if the repository is unstarred * @return {Promise} - the promise for the http request */ unstar(cb: Requestable.callback): Promise<any>; /** * Create a new release * @see https://developer.github.com/v3/repos/releases/#create-a-release * @param {Object} options - the description of the release * @param {Requestable.callback} cb - will receive the newly created release * @return {Promise} - the promise for the http request */ createRelease(options: Object, cb: Requestable.callback): Promise<any>; /** * Edit a release * @see https://developer.github.com/v3/repos/releases/#edit-a-release * @param {string} id - the id of the release * @param {Object} options - the description of the release * @param {Requestable.callback} cb - will receive the modified release * @return {Promise} - the promise for the http request */ updateRelease(id: string, options: Object, cb: Requestable.callback): Promise<any>; /** * Get information about all releases * @see https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository * @param {Requestable.callback} cb - will receive the release information * @return {Promise} - the promise for the http request */ listReleases(cb: Requestable.callback): Promise<any>; /** * Get information about a release * @see https://developer.github.com/v3/repos/releases/#get-a-single-release * @param {string} id - the id of the release * @param {Requestable.callback} cb - will receive the release information * @return {Promise} - the promise for the http request */ getRelease(id: string, cb: Requestable.callback): Promise<any>; /** * Delete a release * @see https://developer.github.com/v3/repos/releases/#delete-a-release * @param {string} id - the release to be deleted * @param {Requestable.callback} cb - will receive true if the operation is successful * @return {Promise} - the promise for the http request */ deleteRelease(id: string, cb: Requestable.callback): Promise<any>; /** * Merge a pull request * @see https://developer.github.com/v3/pulls/#merge-a-pull-request-merge-button * @param {number|string} number - the number of the pull request to merge * @param {Object} options - the merge options for the pull request * @param {Requestable.callback} [cb] - will receive the merge information if the operation is successful * @return {Promise} - the promise for the http request */ mergePullRequest(number: (number | string), options: Object, cb?: Requestable.callback): Promise<any>; } /** * @todo Define a better type for Blob * @typedef Blob */ type Blob = any; /** * The error structure returned when a network call fails */ class ResponseError { /** * The error structure returned when a network call fails */ constructor(); } namespace Requestable { /** * A function that receives the result of the API request. * @callback Requestable.callback * @param {Requestable.Error} error - the error returned by the API or `null` * @param {any | boolean} result - the data returned by the API or `true` if the API returns `204 No Content` * @param {any} response - the raw {@linkcode https://github.com/mzabriskie/axios#response-schema Response} */ type callback = ( error: Requestable.Error, result: (any | boolean), response: any ) => void; /** * @typedef {ResponseError} Requestable.Error * @param {string} message - an message to return instead of the the default error message * @param {string} path - the requested path * @param {Object} response - the object returned by Axios */ type Error = ResponseError; type auth = any; } /** * Requestable wraps the logic for making http requests to the API * @class Requestable */ class Requestable { /** * Requestable wraps the logic for making http requests to the API * @class Requestable */ constructor(); /** * Compute the URL to use to make a request. * @private * @param {string} path - either a URL relative to the API base or an absolute URL * @return {string} - the URL to use */ private __getURL(path: string): string; /** * Compute the headers required for an API request. * @private * @param {boolean} raw - if the request should be treated as JSON or as a raw request * @return {Object} - the headers to use in the request */ private __getRequestHeaders(raw: boolean): Object; /** * Sets the default options for API requests * @protected * @param {Object} [requestOptions={}] - the current options for the request * @return {Object} - the options to pass to the request */ protected _getOptionsWithDefaults(requestOptions?: Object): Object; /** * if a `Date` is passed to this function it will be converted to an ISO string * @param {Date} date - the object to attempt to cooerce into an ISO date string * @return {string} - the ISO representation of `date` or whatever was passed in if it was not a date */ _dateToISO(date: Date): string; /** * Make a request. * @param {string} method - the method for the request (GET, PUT, POST, DELETE) * @param {string} path - the path for the request * @param {any} [data] - the data to send to the server. For HTTP methods that don't have a body the data * will be sent as query parameters * @param {Requestable.callback} [cb] - the callback for the request * @param {boolean} [raw=false] - if the request should be sent as raw. If this is a falsy value then the * request will be made as JSON * @return {Promise} - the Promise for the http request */ _request(method: string, path: string, data?: any, cb?: Requestable.callback, raw?: boolean): Promise<any>; /** * Make a request to an endpoint the returns 204 when true and 404 when false * @param {string} path - the path to request * @param {Object} data - any query parameters for the request * @param {Requestable.callback} cb - the callback that will receive `true` or `false` * @param {method} [method=GET] - HTTP Method to use * @return {Promise} - the promise for the http request */ _request204or404(path: string, data: Object, cb: Requestable.callback, method?: string): Promise<any>; /** * Make a request and fetch all the available data. Github will paginate responses so for queries * that might span multiple pages this method is preferred to {@link Requestable#request} * @param {string} path - the path to request * @param {Object} options - the query parameters to include * @param {Requestable.callback} [cb] - the function to receive the data. The returned data will always be an array. * @param [_results] - the partial results. This argument is intended for interal use only. * @return {Promise} - a promise which will resolve when all pages have been fetched * @deprecated This will be folded into {@link Requestable#_request} in the 2.0 release. */ _requestAllPages(path: string, options: Object, cb?: Requestable.callback, results?: any): Promise<any>; } namespace Search { type Params = any; } /** * Wrap the Search API * @class Search * @extends Requestable */ class Search extends Requestable { /** * Wrap the Search API * @class Search * @extends Requestable */ constructor(); /** * Available search options * @see https://developer.github.com/v3/search/#parameters * @member Search.Params * @property {string} q - the query to make * @property {string} sort - the sort field, one of `stars`, `forks`, or `updated`. * Default is [best match](https://developer.github.com/v3/search/#ranking-search-results) * @property {string} order - the ordering, either `asc` or `desc` */ static Params: any; /** * Perform a search on the GitHub API * @private * @param {string} path - the scope of the search * @param {Search.Params} [withOptions] - additional parameters for the search * @param {Requestable.callback} [cb] - will receive the results of the search * @return {Promise} - the promise for the http request */ private _search(path: string, withOptions?: Search.Params, cb?: Requestable.callback): Promise<any>; /** * Search for repositories * @see https://developer.github.com/v3/search/#search-repositories * @param {Search.Params} [options] - additional parameters for the search * @param {Requestable.callback} [cb] - will receive the results of the search * @return {Promise} - the promise for the http request */ forRepositories(options?: Search.Params, cb?: Requestable.callback): Promise<any>; /** * Search for code * @see https://developer.github.com/v3/search/#search-code * @param {Search.Params} [options] - additional parameters for the search * @param {Requestable.callback} [cb] - will receive the results of the search * @return {Promise} - the promise for the http request */ forCode(options?: Search.Params, cb?: Requestable.callback): Promise<any>; /** * Search for issues * @see https://developer.github.com/v3/search/#search-issues * @param {Search.Params} [options] - additional parameters for the search * @param {Requestable.callback} [cb] - will receive the results of the search * @return {Promise} - the promise for the http request */ forIssues(options?: Search.Params, cb?: Requestable.callback): Promise<any>; /** * Search for users * @see https://developer.github.com/v3/search/#search-users * @param {Search.Params} [options] - additional parameters for the search * @param {Requestable.callback} [cb] - will receive the results of the search * @return {Promise} - the promise for the http request */ forUsers(options?: Search.Params, cb?: Requestable.callback): Promise<any>; } /** * A Team allows scoping of API requests to a particular Github Organization Team. */ class Team { /** * A Team allows scoping of API requests to a particular Github Organization Team. */ constructor(teamId?: string, auth?: Requestable.auth, apiBase?: string); /** * Get Team information * @see https://developer.github.com/v3/orgs/teams/#get-team * @param {Requestable.callback} [cb] - will receive the team * @return {Promise} - the promise for the http request */ getTeam(cb?: Requestable.callback): Promise<any>; /** * List the Team's repositories * @see https://developer.github.com/v3/orgs/teams/#list-team-repos * @param {Requestable.callback} [cb] - will receive the list of repositories * @return {Promise} - the promise for the http request */ listRepos(cb?: Requestable.callback): Promise<any>; /** * Edit Team information * @see https://developer.github.com/v3/orgs/teams/#edit-team * @param {object} options - Parameters for team edit * @param {string} options.name - The name of the team * @param {string} [options.description] - Team description * @param {string} [options.repo_names] - Repos to add the team to * @param {string} [options.privacy=secret] - The level of privacy the team should have. Can be either one * of: `secret`, or `closed` * @param {Requestable.callback} [cb] - will receive the updated team * @return {Promise} - the promise for the http request */ editTeam(options: { name: string, description: string, repo_names: string, privacy: string }, cb?: Requestable.callback): Promise<any>; /** * List the users who are members of the Team * @see https://developer.github.com/v3/orgs/teams/#list-team-members * @param {object} options - Parameters for listing team users * @param {string} [options.role=all] - can be one of: `all`, `maintainer`, or `member` * @param {Requestable.callback} [cb] - will receive the list of users * @return {Promise} - the promise for the http request */ listMembers(options: { role: string }, cb?: Requestable.callback): Promise<any>; /** * Get Team membership status for a user * @see https://developer.github.com/v3/orgs/teams/#get-team-membership * @param {string} username - can be one of: `all`, `maintainer`, or `member` * @param {Requestable.callback} [cb] - will receive the membership status of a user * @return {Promise} - the promise for the http request */ getMembership(username: string, cb?: Requestable.callback): Promise<any>; /** * Add a member to the Team * @see https://developer.github.com/v3/orgs/teams/#add-team-membership * @param {string} username - can be one of: `all`, `maintainer`, or `member` * @param {object} options - Parameters for adding a team member * @param {string} [options.role=member] - The role that this user should have in the team. Can be one * of: `member`, or `maintainer` * @param {Requestable.callback} [cb] - will receive the membership status of added user * @return {Promise} - the promise for the http request */ addMembership(username: string, options: { role: string }, cb?: Requestable.callback): Promise<any>; /** * Get repo management status for team * @see https://developer.github.com/v3/orgs/teams/#remove-team-membership * @param {string} owner - Organization name * @param {string} repo - Repo name * @param {Requestable.callback} [cb] - will receive the membership status of added user * @return {Promise} - the promise for the http request */ isManagedRepo(owner: string, repo: string, cb?: Requestable.callback): Promise<any>; /** * Add or Update repo management status for team * @see https://developer.github.com/v3/orgs/teams/#add-or-update-team-repository * @param {string} owner - Organization name * @param {string} repo - Repo name * @param {object} options - Parameters for adding or updating repo management for the team * @param {string} [options.permission] - The permission to grant the team on this repository. Can be one * of: `pull`, `push`, or `admin` * @param {Requestable.callback} [cb] - will receive the membership status of added user * @return {Promise} - the promise for the http request */ manageRepo(owner: string, repo: string, options: { permission: string }, cb?: Requestable.callback): Promise<any>; /** * Remove repo management status for team * @see https://developer.github.com/v3/orgs/teams/#remove-team-repository * @param {string} owner - Organization name * @param {string} repo - Repo name * @param {Requestable.callback} [cb] - will receive the membership status of added user * @return {Promise} - the promise for the http request */ unmanageRepo(owner: string, repo: string, cb?: Requestable.callback): Promise<any>; /** * Delete Team * @see https://developer.github.com/v3/orgs/teams/#delete-team * @param {Requestable.callback} [cb] - will receive the list of repositories * @return {Promise} - the promise for the http request */ deleteTeam(cb?: Requestable.callback): Promise<any>; } /** * A User allows scoping of API requests to a particular Github user. */ class User { /** * A User allows scoping of API requests to a particular Github user. */ constructor(username?: string, auth?: Requestable.auth, apiBase?: string); /** * Get the url for the request. (dependent on if we're requesting for the authenticated user or not) * @private * @param {string} endpoint - the endpoint being requested * @return {string} - the resolved endpoint */ private __getScopedUrl(endpoint: string): string; /** * List the user's repositories * @see https://developer.github.com/v3/repos/#list-user-repositories * @param {Object} [options={}] - any options to refine the search * @param {Requestable.callback} [cb] - will receive the list of repositories * @return {Promise} - the promise for the http request */ listRepos(options?: Object, cb?: Requestable.callback): Promise<any>; /** * List the orgs that the user belongs to * @see https://developer.github.com/v3/orgs/#list-user-organizations * @param {Requestable.callback} [cb] - will receive the list of organizations * @return {Promise} - the promise for the http request */ listOrgs(cb?: Requestable.callback): Promise<any>; /** * List the user's gists * @see https://developer.github.com/v3/gists/#list-a-users-gists * @param {Requestable.callback} [cb] - will receive the list of gists * @return {Promise} - the promise for the http request */ listGists(cb?: Requestable.callback): Promise<any>; /** * List the user's notifications * @see https://developer.github.com/v3/activity/notifications/#list-your-notifications * @param {Object} [options={}] - any options to refine the search * @param {Requestable.callback} [cb] - will receive the list of repositories * @return {Promise} - the promise for the http request */ listNotifications(options?: Object, cb?: Requestable.callback): Promise<any>; /** * Show the user's profile * @see https://developer.github.com/v3/users/#get-a-single-user * @param {Requestable.callback} [cb] - will receive the user's information * @return {Promise} - the promise for the http request */ getProfile(cb?: Requestable.callback): Promise<any>; /** * Gets the list of starred repositories for the user * @see https://developer.github.com/v3/activity/starring/#list-repositories-being-starred * @param {Requestable.callback} [cb] - will receive the list of starred repositories * @return {Promise} - the promise for the http request */ listStarredRepos(cb?: Requestable.callback): Promise<any>; /** * Have the authenticated user follow this user * @see https://developer.github.com/v3/users/followers/#follow-a-user * @param {string} username - the user to follow * @param {Requestable.callback} [cb] - will receive true if the request succeeds * @return {Promise} - the promise for the http request */ follow(username: string, cb?: Requestable.callback): Promise<any>; /** * Have the currently authenticated user unfollow this user * @see https://developer.github.com/v3/users/followers/#follow-a-user * @param {string} username - the user to unfollow * @param {Requestable.callback} [cb] - receives true if the request succeeds * @return {Promise} - the promise for the http request */ unfollow(username: string, cb?: Requestable.callback): Promise<any>; /** * Create a new repository for the currently authenticated user * @see https://developer.github.com/v3/repos/#create * @param {object} options - the repository definition * @param {Requestable.callback} [cb] - will receive the API response * @return {Promise} - the promise for the http request */ createRepo(options: Object, cb?: Requestable.callback): Promise<any>; } namespace GitHub {} export = GitHub; }
the_stack
import { Kind, GraphQLError, GraphQLScalarType } from 'graphql'; interface Specification { length: number; structure: string; example: string; } interface CountryStructure { [key: string]: Specification; } /* These are IBAN the specifications for all countries using IBAN The key is the countrycode, the second item is the length of the IBAN, The third item is the structure of the underlying BBAN (for validation and formatting) */ const IBAN_SPECIFICATIONS: CountryStructure = { AD: { length: 24, structure: 'F04F04A12', example: 'AD1200012030200359100100', }, AE: { length: 23, structure: 'F03F16', example: 'AE070331234567890123456' }, AL: { length: 28, structure: 'F08A16', example: 'AL47212110090000000235698741', }, AO: { length: 25, structure: 'F21', example: 'AO69123456789012345678901' }, AT: { length: 20, structure: 'F05F11', example: 'AT611904300234573201' }, AZ: { length: 28, structure: 'U04A20', example: 'AZ21NABZ00000000137010001944', }, BA: { length: 20, structure: 'F03F03F08F02', example: 'BA391290079401028494', }, BE: { length: 16, structure: 'F03F07F02', example: 'BE68539007547034' }, BF: { length: 27, structure: 'F23', example: 'BF2312345678901234567890123' }, BG: { length: 22, structure: 'U04F04F02A08', example: 'BG80BNBG96611020345678', }, BH: { length: 22, structure: 'U04A14', example: 'BH67BMAG00001299123456' }, BI: { length: 16, structure: 'F12', example: 'BI41123456789012' }, BJ: { length: 28, structure: 'F24', example: 'BJ39123456789012345678901234' }, BR: { length: 29, structure: 'F08F05F10U01A01', example: 'BR9700360305000010009795493P1', }, BY: { length: 28, structure: 'A04F04A16', example: 'BY13NBRB3600900000002Z00AB00', }, CH: { length: 21, structure: 'F05A12', example: 'CH9300762011623852957' }, CI: { length: 28, structure: 'U02F22', example: 'CI70CI1234567890123456789012', }, CM: { length: 27, structure: 'F23', example: 'CM9012345678901234567890123' }, CR: { length: 22, structure: 'F04F14', example: 'CR72012300000171549015' }, CV: { length: 25, structure: 'F21', example: 'CV30123456789012345678901' }, CY: { length: 28, structure: 'F03F05A16', example: 'CY17002001280000001200527600', }, CZ: { length: 24, structure: 'F04F06F10', example: 'CZ6508000000192000145399', }, DE: { length: 22, structure: 'F08F10', example: 'DE89370400440532013000' }, DK: { length: 18, structure: 'F04F09F01', example: 'DK5000400440116243' }, DO: { length: 28, structure: 'U04F20', example: 'DO28BAGR00000001212453611324', }, DZ: { length: 24, structure: 'F20', example: 'DZ8612345678901234567890' }, EE: { length: 20, structure: 'F02F02F11F01', example: 'EE382200221020145685', }, ES: { length: 24, structure: 'F04F04F01F01F10', example: 'ES9121000418450200051332', }, FI: { length: 18, structure: 'F06F07F01', example: 'FI2112345600000785' }, FO: { length: 18, structure: 'F04F09F01', example: 'FO6264600001631634' }, FR: { length: 27, structure: 'F05F05A11F02', example: 'FR1420041010050500013M02606', }, GB: { length: 22, structure: 'U04F06F08', example: 'GB29NWBK60161331926819' }, GE: { length: 22, structure: 'U02F16', example: 'GE29NB0000000101904917' }, GI: { length: 23, structure: 'U04A15', example: 'GI75NWBK000000007099453' }, GL: { length: 18, structure: 'F04F09F01', example: 'GL8964710001000206' }, GR: { length: 27, structure: 'F03F04A16', example: 'GR1601101250000000012300695', }, GT: { length: 28, structure: 'A04A20', example: 'GT82TRAJ01020000001210029690', }, HR: { length: 21, structure: 'F07F10', example: 'HR1210010051863000160' }, HU: { length: 28, structure: 'F03F04F01F15F01', example: 'HU42117730161111101800000000', }, IE: { length: 22, structure: 'U04F06F08', example: 'IE29AIBK93115212345678' }, IL: { length: 23, structure: 'F03F03F13', example: 'IL620108000000099999999', }, IS: { length: 26, structure: 'F04F02F06F10', example: 'IS140159260076545510730339', }, IT: { length: 27, structure: 'U01F05F05A12', example: 'IT60X0542811101000000123456', }, IQ: { length: 23, structure: 'U04F03A12', example: 'IQ98NBIQ850123456789012', }, IR: { length: 26, structure: 'F22', example: 'IR861234568790123456789012' }, JO: { length: 30, structure: 'A04F22', example: 'JO15AAAA1234567890123456789012', }, KW: { length: 30, structure: 'U04A22', example: 'KW81CBKU0000000000001234560101', }, KZ: { length: 20, structure: 'F03A13', example: 'KZ86125KZT5004100100' }, LB: { length: 28, structure: 'F04A20', example: 'LB62099900000001001901229114', }, LC: { length: 32, structure: 'U04F24', example: 'LC07HEMM000100010012001200013015', }, LI: { length: 21, structure: 'F05A12', example: 'LI21088100002324013AA' }, LT: { length: 20, structure: 'F05F11', example: 'LT121000011101001000' }, LU: { length: 20, structure: 'F03A13', example: 'LU280019400644750000' }, LV: { length: 21, structure: 'U04A13', example: 'LV80BANK0000435195001' }, MC: { length: 27, structure: 'F05F05A11F02', example: 'MC5811222000010123456789030', }, MD: { length: 24, structure: 'U02A18', example: 'MD24AG000225100013104168' }, ME: { length: 22, structure: 'F03F13F02', example: 'ME25505000012345678951' }, MG: { length: 27, structure: 'F23', example: 'MG1812345678901234567890123' }, MK: { length: 19, structure: 'F03A10F02', example: 'MK07250120000058984' }, ML: { length: 28, structure: 'U01F23', example: 'ML15A12345678901234567890123', }, MR: { length: 27, structure: 'F05F05F11F02', example: 'MR1300020001010000123456753', }, MT: { length: 31, structure: 'U04F05A18', example: 'MT84MALT011000012345MTLCAST001S', }, MU: { length: 30, structure: 'U04F02F02F12F03U03', example: 'MU17BOMM0101101030300200000MUR', }, MZ: { length: 25, structure: 'F21', example: 'MZ25123456789012345678901' }, NL: { length: 18, structure: 'U04F10', example: 'NL91ABNA0417164300' }, NO: { length: 15, structure: 'F04F06F01', example: 'NO9386011117947' }, PK: { length: 24, structure: 'U04A16', example: 'PK36SCBL0000001123456702' }, PL: { length: 28, structure: 'F08F16', example: 'PL61109010140000071219812874', }, PS: { length: 29, structure: 'U04A21', example: 'PS92PALS000000000400123456702', }, PT: { length: 25, structure: 'F04F04F11F02', example: 'PT50000201231234567890154', }, QA: { length: 29, structure: 'U04A21', example: 'QA30AAAA123456789012345678901', }, RO: { length: 24, structure: 'U04A16', example: 'RO49AAAA1B31007593840000' }, RS: { length: 22, structure: 'F03F13F02', example: 'RS35260005601001611379' }, SA: { length: 24, structure: 'F02A18', example: 'SA0380000000608010167519' }, SC: { length: 31, structure: 'U04F04F16U03', example: 'SC18SSCB11010000000000001497USD', }, SE: { length: 24, structure: 'F03F16F01', example: 'SE4550000000058398257466', }, SI: { length: 19, structure: 'F05F08F02', example: 'SI56263300012039086' }, SK: { length: 24, structure: 'F04F06F10', example: 'SK3112000000198742637541', }, SM: { length: 27, structure: 'U01F05F05A12', example: 'SM86U0322509800000000270100', }, SN: { length: 28, structure: 'U01F23', example: 'SN52A12345678901234567890123', }, ST: { length: 25, structure: 'F08F11F02', example: 'ST68000100010051845310112', }, SV: { length: 28, structure: 'U04F20', example: 'SV62CENR00000000000000700025', }, TL: { length: 23, structure: 'F03F14F02', example: 'TL380080012345678910157', }, TN: { length: 24, structure: 'F02F03F13F02', example: 'TN5910006035183598478831', }, TR: { length: 26, structure: 'F05F01A16', example: 'TR330006100519786457841326', }, UA: { length: 29, structure: 'F25', example: 'UA511234567890123456789012345', }, VA: { length: 22, structure: 'F18', example: 'VA59001123000012345678' }, VG: { length: 24, structure: 'U04F16', example: 'VG96VPVG0000012345678901' }, XK: { length: 20, structure: 'F04F10F02', example: 'XK051212012345678906' }, }; const A = 'A'.charCodeAt(0); const Z = 'Z'.charCodeAt(0); function parseStructure(structure: string): RegExp { // split in blocks of 3 chars const regex = structure.match(/(.{3})/g).map(function (block: string) { // parse each structure block (1-char + 2-digits) let format; const pattern = block.slice(0, 1); const repeats = parseInt(block.slice(1), 10); switch (pattern) { case 'A': format = '0-9A-Za-z'; break; case 'B': format = '0-9A-Z'; break; case 'C': format = 'A-Za-z'; break; case 'F': format = '0-9'; break; case 'L': format = 'a-z'; break; case 'U': format = 'A-Z'; break; case 'W': format = '0-9a-z'; break; } return '([' + format + ']{' + repeats + '})'; }); return /*#__PURE__*/ new RegExp('^' + regex.join('') + '$'); } /** * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. * */ function iso13616Prepare(iban: string): string { iban = iban.toUpperCase(); iban = iban.substr(4) + iban.substr(0, 4); return iban .split('') .map(function (n) { const code = n.charCodeAt(0); if (code >= A && code <= Z) { // A = 10, B = 11, ... Z = 35 return code - A + 10; } else { return n; } }) .join(''); } /** * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. * * @param iban * @returns {number} */ function iso7064Mod97_10(iban: string): number { let remainder = iban; let block; while (remainder.length > 2) { block = remainder.slice(0, 9); remainder = (parseInt(block, 10) % 97) + remainder.slice(block.length); } return parseInt(remainder, 10) % 97; } function _testIBAN( iban: string, countryCode: string, structure: Specification, ): boolean { return ( structure.length === iban.length && countryCode === iban.slice(0, 2) && parseStructure(structure.structure).test(iban.slice(4)) && iso7064Mod97_10(iso13616Prepare(iban)) === 1 ); } function validate(iban: string): boolean { // Make uppercase and remove whitespace for matching iban = iban.toUpperCase().replace(/\s+/g, ''); const countryCode = iban.slice(0, 2); const countryStructure = IBAN_SPECIFICATIONS[countryCode]; return !!countryStructure && _testIBAN(iban, countryCode, countryStructure); } export const GraphQLIBAN = /*#__PURE__*/ new GraphQLScalarType({ name: `IBAN`, description: `A field whose value is an International Bank Account Number (IBAN): https://en.wikipedia.org/wiki/International_Bank_Account_Number.`, serialize(value: string) { if (typeof value !== 'string') { throw new TypeError(`Value is not string: ${value}`); } if (!validate(value)) { throw new TypeError(`Value is not a valid IBAN: ${value}`); } return value; }, parseValue(value: string) { if (typeof value !== 'string') { throw new TypeError(`Value is not string: ${value}`); } if (!validate(value)) { throw new TypeError(`Value is not a valid IBAN: ${value}`); } return value; }, parseLiteral(ast: { kind: any; value: string }) { if (ast.kind !== Kind.STRING) { throw new GraphQLError( `Can only validate strings as IBANs but got a: ${ast.kind}`, ); } if (!validate(ast.value)) { throw new TypeError(`Value is not a valid IBAN: ${ast.value}`); } return ast.value; }, extensions: { codegenScalarType: 'string', }, });
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Provides an AppStream image builder. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const testFleet = new aws.appstream.ImageBuilder("testFleet", { * description: "Description of a ImageBuilder", * displayName: "Display name of a ImageBuilder", * enableDefaultInternetAccess: false, * imageName: "AppStream-WinServer2012R2-07-19-2021", * instanceType: "stream.standard.large", * vpcConfig: { * subnetIds: [aws_subnet.example.id], * }, * tags: { * Name: "Example Image Builder", * }, * }); * ``` * * ## Import * * `aws_appstream_image_builder` can be imported using the `name`, e.g. * * ```sh * $ pulumi import aws:appstream/imageBuilder:ImageBuilder example imageBuilderExample * ``` */ export class ImageBuilder extends pulumi.CustomResource { /** * Get an existing ImageBuilder resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ImageBuilderState, opts?: pulumi.CustomResourceOptions): ImageBuilder { return new ImageBuilder(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:appstream/imageBuilder:ImageBuilder'; /** * Returns true if the given object is an instance of ImageBuilder. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is ImageBuilder { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ImageBuilder.__pulumiType; } /** * Set of interface VPC endpoint (interface endpoint) objects. Maximum of 4. See below. */ public readonly accessEndpoints!: pulumi.Output<outputs.appstream.ImageBuilderAccessEndpoint[] | undefined>; /** * The version of the AppStream 2.0 agent to use for this image builder. */ public readonly appstreamAgentVersion!: pulumi.Output<string>; /** * ARN of the appstream image builder. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * Date and time, in UTC and extended RFC 3339 format, when the image builder was created. */ public /*out*/ readonly createdTime!: pulumi.Output<string>; /** * Description to display. */ public readonly description!: pulumi.Output<string>; /** * Human-readable friendly name for the AppStream image builder. */ public readonly displayName!: pulumi.Output<string>; /** * Configuration block for the name of the directory and organizational unit (OU) to use to join the image builder to a Microsoft Active Directory domain. See below. */ public readonly domainJoinInfo!: pulumi.Output<outputs.appstream.ImageBuilderDomainJoinInfo>; /** * Enables or disables default internet access for the image builder. */ public readonly enableDefaultInternetAccess!: pulumi.Output<boolean>; /** * ARN of the IAM role to apply to the image builder. */ public readonly iamRoleArn!: pulumi.Output<string>; /** * ARN of the public, private, or shared image to use. */ public readonly imageArn!: pulumi.Output<string>; /** * Name of the image used to create the image builder. */ public readonly imageName!: pulumi.Output<string>; /** * The instance type to use when launching the image builder. */ public readonly instanceType!: pulumi.Output<string>; /** * Unique name for the image builder. */ public readonly name!: pulumi.Output<string>; /** * State of the image builder. Can be: `PENDING`, `UPDATING_AGENT`, `RUNNING`, `STOPPING`, `STOPPED`, `REBOOTING`, `SNAPSHOTTING`, `DELETING`, `FAILED`, `UPDATING`, `PENDING_QUALIFICATION` */ public /*out*/ readonly state!: pulumi.Output<string>; /** * A map of tags to assign to the instance. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). */ public readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Configuration block for the VPC configuration for the image builder. See below. */ public readonly vpcConfig!: pulumi.Output<outputs.appstream.ImageBuilderVpcConfig>; /** * Create a ImageBuilder resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: ImageBuilderArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ImageBuilderArgs | ImageBuilderState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ImageBuilderState | undefined; inputs["accessEndpoints"] = state ? state.accessEndpoints : undefined; inputs["appstreamAgentVersion"] = state ? state.appstreamAgentVersion : undefined; inputs["arn"] = state ? state.arn : undefined; inputs["createdTime"] = state ? state.createdTime : undefined; inputs["description"] = state ? state.description : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["domainJoinInfo"] = state ? state.domainJoinInfo : undefined; inputs["enableDefaultInternetAccess"] = state ? state.enableDefaultInternetAccess : undefined; inputs["iamRoleArn"] = state ? state.iamRoleArn : undefined; inputs["imageArn"] = state ? state.imageArn : undefined; inputs["imageName"] = state ? state.imageName : undefined; inputs["instanceType"] = state ? state.instanceType : undefined; inputs["name"] = state ? state.name : undefined; inputs["state"] = state ? state.state : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["vpcConfig"] = state ? state.vpcConfig : undefined; } else { const args = argsOrState as ImageBuilderArgs | undefined; if ((!args || args.instanceType === undefined) && !opts.urn) { throw new Error("Missing required property 'instanceType'"); } inputs["accessEndpoints"] = args ? args.accessEndpoints : undefined; inputs["appstreamAgentVersion"] = args ? args.appstreamAgentVersion : undefined; inputs["description"] = args ? args.description : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["domainJoinInfo"] = args ? args.domainJoinInfo : undefined; inputs["enableDefaultInternetAccess"] = args ? args.enableDefaultInternetAccess : undefined; inputs["iamRoleArn"] = args ? args.iamRoleArn : undefined; inputs["imageArn"] = args ? args.imageArn : undefined; inputs["imageName"] = args ? args.imageName : undefined; inputs["instanceType"] = args ? args.instanceType : undefined; inputs["name"] = args ? args.name : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["tagsAll"] = args ? args.tagsAll : undefined; inputs["vpcConfig"] = args ? args.vpcConfig : undefined; inputs["arn"] = undefined /*out*/; inputs["createdTime"] = undefined /*out*/; inputs["state"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ImageBuilder.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ImageBuilder resources. */ export interface ImageBuilderState { /** * Set of interface VPC endpoint (interface endpoint) objects. Maximum of 4. See below. */ accessEndpoints?: pulumi.Input<pulumi.Input<inputs.appstream.ImageBuilderAccessEndpoint>[]>; /** * The version of the AppStream 2.0 agent to use for this image builder. */ appstreamAgentVersion?: pulumi.Input<string>; /** * ARN of the appstream image builder. */ arn?: pulumi.Input<string>; /** * Date and time, in UTC and extended RFC 3339 format, when the image builder was created. */ createdTime?: pulumi.Input<string>; /** * Description to display. */ description?: pulumi.Input<string>; /** * Human-readable friendly name for the AppStream image builder. */ displayName?: pulumi.Input<string>; /** * Configuration block for the name of the directory and organizational unit (OU) to use to join the image builder to a Microsoft Active Directory domain. See below. */ domainJoinInfo?: pulumi.Input<inputs.appstream.ImageBuilderDomainJoinInfo>; /** * Enables or disables default internet access for the image builder. */ enableDefaultInternetAccess?: pulumi.Input<boolean>; /** * ARN of the IAM role to apply to the image builder. */ iamRoleArn?: pulumi.Input<string>; /** * ARN of the public, private, or shared image to use. */ imageArn?: pulumi.Input<string>; /** * Name of the image used to create the image builder. */ imageName?: pulumi.Input<string>; /** * The instance type to use when launching the image builder. */ instanceType?: pulumi.Input<string>; /** * Unique name for the image builder. */ name?: pulumi.Input<string>; /** * State of the image builder. Can be: `PENDING`, `UPDATING_AGENT`, `RUNNING`, `STOPPING`, `STOPPED`, `REBOOTING`, `SNAPSHOTTING`, `DELETING`, `FAILED`, `UPDATING`, `PENDING_QUALIFICATION` */ state?: pulumi.Input<string>; /** * A map of tags to assign to the instance. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Configuration block for the VPC configuration for the image builder. See below. */ vpcConfig?: pulumi.Input<inputs.appstream.ImageBuilderVpcConfig>; } /** * The set of arguments for constructing a ImageBuilder resource. */ export interface ImageBuilderArgs { /** * Set of interface VPC endpoint (interface endpoint) objects. Maximum of 4. See below. */ accessEndpoints?: pulumi.Input<pulumi.Input<inputs.appstream.ImageBuilderAccessEndpoint>[]>; /** * The version of the AppStream 2.0 agent to use for this image builder. */ appstreamAgentVersion?: pulumi.Input<string>; /** * Description to display. */ description?: pulumi.Input<string>; /** * Human-readable friendly name for the AppStream image builder. */ displayName?: pulumi.Input<string>; /** * Configuration block for the name of the directory and organizational unit (OU) to use to join the image builder to a Microsoft Active Directory domain. See below. */ domainJoinInfo?: pulumi.Input<inputs.appstream.ImageBuilderDomainJoinInfo>; /** * Enables or disables default internet access for the image builder. */ enableDefaultInternetAccess?: pulumi.Input<boolean>; /** * ARN of the IAM role to apply to the image builder. */ iamRoleArn?: pulumi.Input<string>; /** * ARN of the public, private, or shared image to use. */ imageArn?: pulumi.Input<string>; /** * Name of the image used to create the image builder. */ imageName?: pulumi.Input<string>; /** * The instance type to use when launching the image builder. */ instanceType: pulumi.Input<string>; /** * Unique name for the image builder. */ name?: pulumi.Input<string>; /** * A map of tags to assign to the instance. If configured with a provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block) present, tags with matching keys will overwrite those defined at the provider-level. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * A map of tags assigned to the resource, including those inherited from the provider [`defaultTags` configuration block](https://www.terraform.io/docs/providers/aws/index.html#default_tags-configuration-block). */ tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Configuration block for the VPC configuration for the image builder. See below. */ vpcConfig?: pulumi.Input<inputs.appstream.ImageBuilderVpcConfig>; }
the_stack
import { Component, DebugElement, ElementRef, TemplateRef, ViewChild } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { DomHelper } from '../utils/testing/dom-helper'; import * as EventHelper from '../utils/testing/event-helper'; import { DatepickerModule } from './datepicker.module'; @Component({ template: ` <div class="devui-input-group devui-dropdown-origin"> <input class="devui-input devui-form-control" dDateRangePicker (focus)="dateRangePicker.toggle()" [(ngModel)]="dateRange" #dateRangePicker="dateRangePicker" (selectedRangeChange)="getValue($event)" [cssClass]="cssClass" [showTime]="showTime" [disabled]="disabled" [dateConfig]="dateConfig" [dateFormat]="dateFormat" [minDate]="minDate" [maxDate]="maxDate" [splitter]="splitter" [selectedRange]="selectedRange" [customViewTemplate]="customViewTemplate" [hideOnRangeSelected]="hideOnRangeSelected" #inputEle /> <div *ngIf="everyRange(dateRange)" class="devui-input-group-addon close-icon-wrapper" (click)="dateRangePicker.clearAll()"> <i class="icon icon-close"></i> </div> <div class="devui-input-group-addon" (click)="$event.stopPropagation();dateRangePicker.toggle(toggle);toggle=!toggle" #icon> <i class="icon icon-calendar"></i> </div> <ng-template #myCustomView let-chooseDate="chooseDate"> <div class="test-template" (click)="chooseToday(chooseDate)">test template</div> </ng-template> </div> `, }) class TestDateRangePickerComponent { dateRange = [null, null]; @ViewChild('inputEle', { read: ElementRef }) inputEle: ElementRef; @ViewChild('myCustomView') myCustomView: TemplateRef<any>; @ViewChild('icon', { read: ElementRef }) icon: ElementRef; cssClass = ''; showTime = false; disabled = false; dateConfig; dateFormat = 'y/MM/dd'; minDate = new Date('01/01/1900 00:00:00'); maxDate = new Date('11/31/2099 23:59:59'); splitter = ' - '; selectedRange = [null, null]; customViewTemplate; hideOnRangeSelected = false; getValue = jasmine.createSpy('get value'); toggle = true; everyRange(range) { return range.every(_ => !!_); } chooseToday(fn) { fn([new Date(), new Date()], undefined, false); } constructor() { } } @Component({ template: ` <div [style.height]="placeHolderHeight ? '900px' : '0'">this is place holder</div> <input class="devui-input devui-form-control" [ngClass]="{'devui-dropdown-origin' : isOrigin}" dDateRangePicker (focus)="dateRangePicker.toggle()" #dateRangePicker="dateRangePicker" #inputEle /> `, }) class TestDateRangePickerOriginComponent { @ViewChild('inputEle', { read: ElementRef }) inputEle: ElementRef; placeHolderHeight = false; isOrigin = false; constructor() { } } @Component({ template: ` <d-date-range-picker [dateConfig]="dateConfig" [selectedRange]="selectedRange" [customViewTemplate]="customViewTemplate" ></d-date-range-picker> <ng-template #myCustomView let-chooseDate="chooseDate" let-clearAll="clearAll"> <div class="test-template choose" (click)="chooseDate(today())">choose</div> <div class="test-template clear" (click)="clearAll(reason)">clear</div> </ng-template> `, }) class TestDateRangePickerCmpComponent { dateConfig; selectedRange; customViewTemplate; reason; @ViewChild('myCustomView') myCustomView: TemplateRef<any>; constructor() { } today() { return [new Date(), new Date()]; } } describe('dateRangePicker', () => { let fixture: ComponentFixture<TestDateRangePickerComponent>; let debugEl: DebugElement; let component: TestDateRangePickerComponent; let domHelper: DomHelper<TestDateRangePickerComponent>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [DatepickerModule, NoopAnimationsModule, FormsModule], declarations: [TestDateRangePickerComponent] }).compileComponents(); })); describe('basic param', () => { beforeEach(() => { fixture = TestBed.createComponent(TestDateRangePickerComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; domHelper = new DomHelper(fixture); fixture.detectChanges(); }); it('should datePicker show, should hideOnRangeSelected works', fakeAsync(() => { openDatePicker(fixture); const classList = [ '.devui-date-range-wrapper', '.devui-date-range-picker', '.devui-date-picker', '.devui-month-view', '.devui-month-view-table', '.devui-calender-header', '.devui-week-header', '.devui-date-title', '.devui-day', '.devui-out-of-month', '.devui-in-month-day', '.devui-calendar-date' ]; expect(domHelper.judgeAppendToBodyStyleClasses(classList)).toBeTruthy(); let dateRangePicker = document.querySelector('.devui-date-range-wrapper'); expect(dateRangePicker).toBeTruthy(); closeDatePicker(fixture); dateRangePicker = document.querySelector('.devui-date-range-wrapper'); expect(dateRangePicker).toBeFalsy(); tickEvent(component.icon.nativeElement, new Event('click'), fixture); tick(); fixture.detectChanges(); dateRangePicker = document.querySelector('.devui-date-range-wrapper'); expect(dateRangePicker).toBeTruthy(); tickEvent(component.icon.nativeElement, new Event('click'), fixture); tick(); fixture.detectChanges(); dateRangePicker = document.querySelector('.devui-date-range-wrapper'); expect(dateRangePicker).toBeFalsy(); component.hideOnRangeSelected = true; fixture.detectChanges(); openDatePicker(fixture); const leftDayListEle = document.querySelectorAll('tbody')[0]; const rightDayListEle = document.querySelectorAll('tbody')[1]; const leftCurrentDayInListEle = leftDayListEle.querySelectorAll('.devui-day')[7]; const rightCurrentDayInListEle = rightDayListEle.querySelectorAll('.devui-day')[7]; tickEvent(leftCurrentDayInListEle, new Event('click'), fixture); tickEvent(rightCurrentDayInListEle, new Event('click'), fixture); expect(component.getValue).toHaveBeenCalled(); dateRangePicker = document.querySelector('.devui-date-range-wrapper'); expect(dateRangePicker).toBeFalsy(); })); it('should ngModel works, should change year and month works', fakeAsync(() => { testNgModelAndYearMonth(fixture, document, component); })); it('should @Input works', fakeAsync(() => { testInputParam(fixture, document, component); })); }); describe('param need change when init', () => { beforeEach(() => { fixture = TestBed.createComponent(TestDateRangePickerComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; domHelper = new DomHelper(fixture); }); describe('first component change', () => { beforeEach(() => { component.showTime = true; component.dateFormat = 'y/MM/dd HH:mm:ss'; }); it('should showTime works', fakeAsync(() => { testTimePicker(fixture, document, component); })); }); describe('second component change', () => { beforeEach(() => { component.showTime = undefined; component.dateFormat = undefined; component.dateConfig = { timePicker: true, dateConverter: null, min: 2020, max: 2020, format: { date: 'MM.dd.y', time: 'MM.dd.y mm-ss-HH' } }; }); it('should dateConfig works', fakeAsync(() => { testDateConfig(fixture, document, component); })); }); describe('test disabled', () => { beforeEach(() => { component.disabled = true; }); it('should disabled works', fakeAsync(() => { fixture.detectChanges(); openDatePicker(fixture); const leftDayListEle = document.querySelectorAll('tbody')[0]; const rightDayListEle = document.querySelectorAll('tbody')[1]; const leftCurrentDayInListEle = leftDayListEle.querySelectorAll('.devui-day')[7]; const rightCurrentDayInListEle = rightDayListEle.querySelectorAll('.devui-day')[7]; tickEvent(leftCurrentDayInListEle, new Event('click'), fixture); tickEvent(rightCurrentDayInListEle, new Event('click'), fixture); expect(component.getValue).not.toHaveBeenCalled(); closeDatePicker(fixture); })); }); describe('test wrong control', () => { beforeEach(() => { component.dateConfig = { timePicker: true }; }); it('should not wrong dateConfig works', fakeAsync(() => { fixture.detectChanges(); openDatePicker(fixture); expect(document.querySelector('.devui-time')).toBeFalsy(); closeDatePicker(fixture); })); }); }); }); describe('dateRangePickerOrigin', () => { let fixture: ComponentFixture<TestDateRangePickerOriginComponent>; let debugEl: DebugElement; let component: TestDateRangePickerOriginComponent; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [DatepickerModule, NoopAnimationsModule, FormsModule], declarations: [TestDateRangePickerOriginComponent] }).compileComponents(); })); describe('param need change when init', () => { beforeEach(() => { fixture = TestBed.createComponent(TestDateRangePickerOriginComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; }); describe('datePickerOrigin', () => { beforeEach(() => { component.placeHolderHeight = true; }); it('datePickerOrigin', fakeAsync(() => { fixture.detectChanges(); openDatePicker(fixture); expect(document.querySelector('.devui-date-range-wrapper')).toBeTruthy(); })); }); describe('isOrigin', () => { beforeEach(() => { component.isOrigin = true; }); it('isOrigin', fakeAsync(() => { fixture.detectChanges(); openDatePicker(fixture); expect(document.querySelector('.devui-date-range-wrapper')).toBeTruthy(); })); }); }); }); describe('dateRangePickerComponent', () => { let fixture: ComponentFixture<TestDateRangePickerCmpComponent>; let debugEl: DebugElement; let component: TestDateRangePickerCmpComponent; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [DatepickerModule, NoopAnimationsModule, FormsModule], declarations: [TestDateRangePickerCmpComponent] }).compileComponents(); })); describe('basic param', () => { beforeEach(() => { fixture = TestBed.createComponent(TestDateRangePickerCmpComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; }); it('should ngModel works', fakeAsync(() => { fixture.detectChanges(); tick(); fixture.detectChanges(); component.selectedRange = [new Date(), new Date()]; fixture.detectChanges(); expect(debugEl.queryAll(By.css('.active.devui-in-month-day')).length).toBe(1); })); it('should template works', fakeAsync(() => { fixture.detectChanges(); tick(); fixture.detectChanges(); component.customViewTemplate = component.myCustomView; fixture.detectChanges(); expect(debugEl.query(By.css('.test-template'))).toBeTruthy(); debugEl.query(By.css('.choose')).nativeElement.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(debugEl.queryAll(By.css('.active.devui-in-month-day')).length).toBe(1); debugEl.query(By.css('.clear')).nativeElement.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(debugEl.queryAll(By.css('.active.devui-in-month-day')).length).toBe(0); debugEl.query(By.css('.choose')).nativeElement.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(debugEl.queryAll(By.css('.active.devui-in-month-day')).length).toBe(1); component.reason = 4; fixture.detectChanges(); debugEl.query(By.css('.clear')).nativeElement.dispatchEvent(new Event('click')); fixture.detectChanges(); expect(debugEl.queryAll(By.css('.active.devui-in-month-day')).length).toBe(0); })); }); describe('param need change when init', () => { beforeEach(() => { fixture = TestBed.createComponent(TestDateRangePickerCmpComponent); debugEl = fixture.debugElement; component = debugEl.componentInstance; }); describe('first component change', () => { beforeEach(() => { component.dateConfig = { timePicker: true, dateConverter: null, min: 2020, max: 2020, format: { date: 'MM.dd.y', time: 'MM.dd.y mm-ss-HH' } }; }); it('should showTime works', fakeAsync(() => { fixture.detectChanges(); tick(); fixture.detectChanges(); expect(debugEl.query(By.css('.devui-time'))).toBeTruthy(); })); }); describe('test wrong control', () => { beforeEach(() => { component.dateConfig = { timePicker: true }; }); it('should not wrong dateConfig works', fakeAsync(() => { fixture.detectChanges(); tick(); fixture.detectChanges(); expect(document.querySelector('.devui-time')).toBeFalsy(); })); }); }); }); function padZero(value) { return (String(value)).padStart(2, '0'); } function resolveMonth(str) { if (str.length === 3) { return str.slice(0, 2); } else if (str.length === 2) { if (isNaN(Number(str))) { return str.slice(0, 1); } else { return str; } } else if (str.length === 1) { return str; } } function strDate(addYear, addMonth, addDate, date?, arr = ['yy', 'mm', 'dd'], splitter = '/') { const newArr = []; const currentDate = typeof date === 'string' ? date : new Date().getDate() + addDate; const fullDate = new Date(new Date().getFullYear() + addYear, new Date().getMonth() + addMonth, currentDate); return EventHelper.dateToStrWithArr(fullDate, arr, splitter); } function closeDatePicker(fixture) { tickEvent(document, new Event('click'), fixture); tick(); fixture.detectChanges(); } function openDatePicker(fixture) { const el = fixture.debugElement.componentInstance.inputEle.nativeElement; tickEvent(el, new Event('focus'), fixture); tick(); fixture.detectChanges(); } function tickEvent(el, event, fixture, delay?: number): void { el.dispatchEvent(event); fixture.detectChanges(); if (delay) { tick(delay); } else { tick(); } fixture.detectChanges(); } function testNgModelAndYearMonth(fixture, wrapperEle, component) { openDatePicker(fixture); const fun = { showEles: wrapperEle.querySelectorAll('.devui-date-title'), btnEles: (side, type) => { return wrapperEle.querySelectorAll('.devui-calender-header')[side].querySelectorAll('.devui-btn-link')[type]; }, yearShow: (ele) => { return ele.textContent.trim().slice(0, 4); }, monthShow: (ele) => { return resolveMonth(ele.textContent.trim()); } }; const showEle = { left: { year: fun.showEles[0], month: fun.showEles[1] }, right: { year: fun.showEles[2], month: fun.showEles[3] } }; const currentShowNum = { left: { year: fun.yearShow(showEle.left.year), month: fun.monthShow(showEle.left.month) }, right: { year: fun.yearShow(showEle.right.year), month: fun.monthShow(showEle.right.month) } }; const btnEle = { left: { year: { last: fun.btnEles(0, 0), next: fun.btnEles(0, 3) }, month: { last: fun.btnEles(0, 1), next: fun.btnEles(0, 2) } }, right: { year: { next: fun.btnEles(1, 3), last: fun.btnEles(1, 0) }, month: { next: fun.btnEles(1, 2), last: fun.btnEles(1, 1) } } }; for (const side in btnEle) { if (side) { for (const time in btnEle[side]) { if (time) { let current = 0; for (const type in btnEle[side][time]) { if (type) { current = type === 'next' ? (current + 1) : (current - 1); btnEle[side][time][type].dispatchEvent(new Event('click')); fixture.detectChanges(); let currentMonth = Number(currentShowNum[side][time]) + current; if (time === 'month') { currentMonth = currentMonth % 12 || 12; } expect(fun[`${time}Show`](showEle[side][time])).toBe(String(currentMonth)); } } } } } } let leftDayListEle = wrapperEle.querySelectorAll('tbody')[0]; let rightDayListEle = wrapperEle.querySelectorAll('tbody')[1]; let leftCurrentDayInListEle = leftDayListEle.querySelectorAll('.devui-day')[7]; let rightCurrentDayInListEle = rightDayListEle.querySelectorAll('.devui-day')[7]; const rightCurrentLastDayInListEle = rightDayListEle.querySelectorAll('.devui-day')[6]; let leftCurrentDay = leftCurrentDayInListEle.querySelector('.devui-calendar-date').textContent.trim(); let rightCurrentDay = rightCurrentDayInListEle.querySelector('.devui-calendar-date').textContent.trim(); tickEvent(leftCurrentDayInListEle, new Event('click'), fixture); tickEvent(rightCurrentDayInListEle, new Event('mouseover'), fixture); expect(rightCurrentLastDayInListEle.classList).toContain('devui-in-range'); tickEvent(rightCurrentDayInListEle, new Event('click'), fixture); expect(component.getValue).toHaveBeenCalled(); expect(component.inputEle.nativeElement.value).toBe( `${strDate(0, 0, 0, leftCurrentDay)}${component.splitter}${strDate(0, 1, 0, rightCurrentDay)}` ); expect(component.dateRange).toEqual( [ new Date(new Date().getFullYear(), new Date().getMonth(), leftCurrentDay), new Date(new Date().getFullYear(), new Date().getMonth() + 1, rightCurrentDay, 23, 59, 59) ] ); closeDatePicker(fixture); component.dateRange = [new Date(), new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())]; fixture.detectChanges(); tick(); fixture.detectChanges(); openDatePicker(fixture); leftDayListEle = wrapperEle.querySelectorAll('tbody')[0]; rightDayListEle = wrapperEle.querySelectorAll('tbody')[1]; leftCurrentDayInListEle = leftDayListEle.querySelector('.active'); rightCurrentDayInListEle = rightDayListEle.querySelector('.active'); leftCurrentDay = leftCurrentDayInListEle.querySelector('.devui-calendar-date').textContent.trim(); rightCurrentDay = rightCurrentDayInListEle.querySelector('.devui-calendar-date').textContent.trim(); expect(component.inputEle.nativeElement.value).toBe( `${strDate(0, 0, 0)}${component.splitter}${strDate(0, 1, 0)}` ); expect(Number(leftCurrentDay)).toBe(new Date().getDate()); expect(Number(rightCurrentDay)).toBe(new Date(strDate(0, 1, 0)).getDate()); closeDatePicker(fixture); component.inputEle.nativeElement.value = `${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`; tickEvent(component.inputEle.nativeElement, new KeyboardEvent('keyup', { key: 'Enter' }), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); openDatePicker(fixture); leftDayListEle = wrapperEle.querySelectorAll('tbody')[0]; rightDayListEle = wrapperEle.querySelectorAll('tbody')[1]; leftCurrentDayInListEle = leftDayListEle.querySelector('.active'); rightCurrentDayInListEle = rightDayListEle.querySelector('.active'); leftCurrentDay = leftCurrentDayInListEle.querySelector('.devui-calendar-date').textContent.trim(); rightCurrentDay = rightCurrentDayInListEle.querySelector('.devui-calendar-date').textContent.trim(); expect(component.dateRange).toEqual( [ new Date(new Date().getFullYear(), new Date().getMonth(), 5), new Date(new Date().getFullYear(), new Date().getMonth() + 1, 5) ] ); expect(leftCurrentDay).toBe('05'); expect(rightCurrentDay).toBe('05'); closeDatePicker(fixture); component.inputEle.nativeElement.value = ''; tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); expect(component.getValue).toHaveBeenCalled(); expect(component.inputEle.nativeElement.value).toBe(''); component.splitter = '/'; fixture.detectChanges(); component.inputEle.nativeElement.value = `${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`; tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); expect(component.getValue).toHaveBeenCalled(); expect(component.inputEle.nativeElement.value).toBe(`${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`); component.inputEle.nativeElement.value = `${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`; tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); expect(component.inputEle.nativeElement.value).toBe(`${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`); component.minDate = new Date(); component.maxDate = new Date(); component.selectedRange = [new Date(`${strDate(0, 0, 0, '05')}`), new Date(`${strDate(0, 0, 0, '05')}`)]; fixture.detectChanges(); openDatePicker(fixture); component.selectedRange = [new Date(`${strDate(0, 0, 0, '05')}`), new Date(`${strDate(0, 1, 0, '05')}`)]; fixture.detectChanges(); component.inputEle.nativeElement.value = `${strDate(0, -1, 0)}${component.splitter}${strDate(0, 1, 0)}`; tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); expect(component.getValue).toHaveBeenCalled(); expect(component.inputEle.nativeElement.value).toBe(`${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`); component.inputEle.nativeElement.value = `${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`; tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); expect(component.inputEle.nativeElement.value).toBe(`${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`); component.inputEle.nativeElement.value = `${strDate(0, 0, 0, '05')}${component.splitter}2020`; tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); expect(component.inputEle.nativeElement.value).toBe(`${strDate(0, 0, 0, '05')}${component.splitter}${strDate(0, 1, 0, '05')}`); } function testInputParam(fixture, wrapperEle, component) { component.cssClass = 'test-class'; component.minDate = new Date(); component.maxDate = new Date(); component.maxDate.setMonth(component.maxDate.getMonth() + 1); component.dateFormat = 'MM.dd.y'; component.splitter = '~'; component.customViewTemplate = component.myCustomView; fixture.detectChanges(); openDatePicker(fixture); // cssClass expect(wrapperEle.querySelector('.test-class')).toBeTruthy(); // minDate、maxDate const minDate = component.minDate; const maxDate = new Date(component.maxDate); maxDate.setDate(maxDate.getDate() + 1); const leftDayListEle = wrapperEle.querySelectorAll('tbody')[0]; const rightDayListEle = wrapperEle.querySelectorAll('tbody')[1]; let leftCurrentDayInListEle; let rightCurrentDayInListEle; for (const dayEl of leftDayListEle.querySelectorAll('.devui-in-month-day')) { const dayNumber = Number(dayEl.querySelector('.devui-calendar-date').textContent.trim()); if (dayNumber === (minDate.getDate() - 1)) { expect(dayEl.classList).toContain('disabled'); tickEvent(dayEl, new Event('mouseover'), fixture); dayEl.dispatchEvent(new Event('click')); } else if (dayNumber === (minDate.getDate())) { leftCurrentDayInListEle = dayEl; } } const rightMonth = resolveMonth(wrapperEle.querySelectorAll('.devui-date-title')[3].textContent.trim()); if (String(component.maxDate.getMonth() + 1) !== rightMonth) { const nextMonthBtn = wrapperEle.querySelectorAll('.devui-calender-header')[1].querySelectorAll('.devui-btn-link')[2]; tickEvent(nextMonthBtn, new Event('click'), fixture); } for (const dayEl of rightDayListEle.querySelectorAll('.devui-in-month-day')) { const dayNumber = Number(dayEl.querySelector('.devui-calendar-date').textContent.trim()); if (dayNumber === (component.maxDate.getDate() + 1)) { expect(dayEl.classList).toContain('disabled'); tickEvent(dayEl, new Event('mouseover'), fixture); dayEl.dispatchEvent(new Event('click')); } else if (dayNumber === (component.maxDate.getDate())) { rightCurrentDayInListEle = dayEl; } } // dateFormat、splitter tickEvent(leftCurrentDayInListEle, new Event('click'), fixture); tickEvent(rightCurrentDayInListEle, new Event('click'), fixture); expect(component.getValue).toHaveBeenCalled(); expect(component.inputEle.nativeElement.value).toBe( `${strDate(0, 0, 0, undefined, ['mm', 'dd', 'yy'], '.')}${component.splitter}${strDate(0, 1, 0, undefined, ['mm', 'dd', 'yy'], '.')}` ); // customViewTemplate const testTemplate = wrapperEle.querySelector('.test-template'); expect(testTemplate).toBeTruthy(); // ToDo: click后会直接进入组件的ngOnDestroy,并且没有走chooseDate,但是toHaveBeenCalled没有报错也没有执行,预测detectChanges直接结束了it // testTemplate.dispatchEvent(new Event('click')); // fixture.detectChanges(); // expect(component.getValue).toHaveBeenCalled(); tickEvent(document.querySelector('.devui-date-range-custom'), new Event('click'), fixture); expect(wrapperEle.querySelector('.test-class')).toBeTruthy(); closeDatePicker(fixture); } function testTimePicker(fixture, wrapperEle, component) { fixture.detectChanges(); component.selectedRange = [new Date(`${strDate(0, 0, 0)}`), new Date(`${strDate(0, 1, 0)}`)]; fixture.detectChanges(); component.inputEle.nativeElement.value = `${strDate(0, -1, 0)}${component.splitter}${strDate(0, 1, 0)}`; tickEvent(component.inputEle.nativeElement, new Event('input'), fixture, 1000); tickEvent(component.inputEle.nativeElement, new Event('blur'), fixture, 1000); openDatePicker(fixture); const leftDayListEle = wrapperEle.querySelectorAll('tbody')[0]; const rightDayListEle = wrapperEle.querySelectorAll('tbody')[1]; const leftCurrentDayInListEle = leftDayListEle.querySelectorAll('.devui-day')[7]; const rightCurrentDayInListEle = rightDayListEle.querySelectorAll('.devui-day')[7]; tickEvent(leftCurrentDayInListEle, new Event('click'), fixture); tickEvent(rightCurrentDayInListEle, new Event('click'), fixture); let picker = { left: wrapperEle.querySelectorAll('.devui-date-picker')[0], right: wrapperEle.querySelectorAll('.devui-date-picker')[1] }; expect(picker['left'].querySelector('.devui-timepicker')).toBeTruthy(); expect(picker['right'].querySelector('.devui-timepicker')).toBeTruthy(); closeDatePicker(fixture); component.dateRange = [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())]; fixture.detectChanges(); tick(); fixture.detectChanges(); openDatePicker(fixture); picker = { left: wrapperEle.querySelectorAll('.devui-date-picker')[0], right: wrapperEle.querySelectorAll('.devui-date-picker')[1] }; function timeEles(whichPicker, type) { const index = ['hours', 'minutes', 'seconds'].indexOf(type); return whichPicker.querySelector('.devui-timepicker').querySelectorAll('.devui-time')[index]; } function timeInputEles(whichPicker, type) { return timeEles(whichPicker, type).querySelector('input'); } function timeBtnEles(whichPicker, type, t) { return timeEles(whichPicker, type).querySelector(`.btn-${t}`); } const timeInputEle = { left: { hours: timeInputEles(picker['left'], 'hours'), minutes: timeInputEles(picker['left'], 'minutes'), seconds: timeInputEles(picker['left'], 'seconds') }, right: { hours: timeInputEles(picker['right'], 'hours'), minutes: timeInputEles(picker['right'], 'minutes'), seconds: timeInputEles(picker['right'], 'seconds') } }; const timeBtnEle = { left: { hours: { up: timeBtnEles(picker['left'], 'hours', 'up'), down: timeBtnEles(picker['left'], 'hours', 'down') }, minutes: { up: timeBtnEles(picker['left'], 'minutes', 'up'), down: timeBtnEles(picker['left'], 'minutes', 'down') }, seconds: { up: timeBtnEles(picker['left'], 'seconds', 'up'), down: timeBtnEles(picker['left'], 'seconds', 'down') } }, right: { hours: { up: timeBtnEles(picker['right'], 'hours', 'up'), down: timeBtnEles(picker['right'], 'hours', 'down') }, minutes: { up: timeBtnEles(picker['right'], 'minutes', 'up'), down: timeBtnEles(picker['right'], 'minutes', 'down') }, seconds: { up: timeBtnEles(picker['right'], 'seconds', 'up'), down: timeBtnEles(picker['right'], 'seconds', 'down') } } }; for (const side in timeBtnEle) { if (side) { for (const time in timeBtnEle[side]) { if (time) { for (const t in timeBtnEle[side][time]) { if (t) { timeBtnEle[side][time][t].dispatchEvent(new Event('click')); } } } } } } for (const side in timeInputEle) { if (side) { for (const time in timeInputEle[side]) { if (time) { expect(timeInputEle[side][time].value).toBe('00'); } } } } const timeEvent = '5'; for (const side in timeInputEle) { if (side) { for (const time in timeInputEle[side]) { if (time) { testTimePickerInput(timeInputEle[side][time], fixture, timeEvent); } } } } for (const side in timeInputEle) { if (side) { for (const time in timeInputEle[side]) { if (time) { const arr = ['hours', 'minutes', 'seconds']; testTimePickerBtn(picker[side].querySelectorAll('.devui-btn-nav')[arr.indexOf(time)], fixture, timeEvent, timeInputEle[side][time], component); } } } } const confirmBtn = wrapperEle.querySelector('.devui-btn-wrapper').querySelector('button'); tickEvent(confirmBtn, new Event('click'), fixture); expect(component.getValue).toHaveBeenCalled(); expect(component.inputEle.nativeElement.value).toBe( /* eslint-disable-next-line max-len*/ `${strDate(0, 0, 0)} 0${timeEvent}:0${timeEvent}:0${timeEvent}${component.splitter}${strDate(0, 1, 0)} 0${timeEvent}:0${timeEvent}:0${timeEvent}` ); expect(component.dateRange).toEqual( [ new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate(), Number(timeEvent), Number(timeEvent), Number(timeEvent)), new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate(), Number(timeEvent), Number(timeEvent), Number(timeEvent)) ] ); } function testTimePickerInput(inputEle, fixture, timeEvent) { const backSpaceKeyboard = EventHelper.createKeyBoardEvent('keydown', { key: 'Backspace', keyCode: 8 }); const keyBoardEvent = EventHelper.createKeyBoardEvent('keydown', { key: timeEvent, code: `Digit${timeEvent}`, charCode: 48 + Number(timeEvent) }); const changeEvent = new Event('change'); tickEvent(inputEle, backSpaceKeyboard, fixture); tickEvent(inputEle, changeEvent, fixture); tickEvent(inputEle, backSpaceKeyboard, fixture); tickEvent(inputEle, changeEvent, fixture); expect(inputEle.value).toBe('00'); tickEvent(inputEle, keyBoardEvent, fixture); tickEvent(inputEle, changeEvent, fixture); expect(inputEle.value).toBe(`0${timeEvent}`); } function testTimePickerBtn(btnWrapperEle, fixture, timeEvent, inputEle, component) { const inBtnEle = btnWrapperEle.querySelector('.btn-up'); const deBtnEle = btnWrapperEle.querySelector('.btn-down'); tickEvent(inBtnEle, new Event('click'), fixture); tick(300); expect(inputEle.value).toBe(padZero(Number(timeEvent) + 1)); expect(component.getValue).toHaveBeenCalled(); tickEvent(deBtnEle, new Event('click'), fixture); tick(300); expect(inputEle.value).toBe(padZero(timeEvent)); expect(component.getValue).toHaveBeenCalled(); } function testDateConfig(fixture, wrapperEle, component) { component.dateRange = [new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()), new Date(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate())]; fixture.detectChanges(); tick(); fixture.detectChanges(); openDatePicker(fixture); const confirmBtn = wrapperEle.querySelector('.devui-btn-wrapper').querySelector('button'); fixture.detectChanges(); tick(); fixture.detectChanges(); tickEvent(confirmBtn, new Event('click'), fixture); expect(component.inputEle.nativeElement.value).toBe( /* eslint-disable-next-line max-len*/ `${strDate(0, 0, 0, undefined, ['mm', 'dd', 'yy'], '.')} 00-00-00${component.splitter}${strDate(0, 1, 0, undefined, ['mm', 'dd', 'yy'], '.')} 00-00-00` ); }
the_stack
import {Xliff2MessageParser} from './xliff2-message-parser'; import {ParsedMessage} from './parsed-message'; /** * Created by martin on 14.05.2017. * Testcases for parsing normalized messages to XLIFF 2.0 and vive versa. */ describe('message parse XLIFF 2.0 test spec', () => { /** * Helperfunction to create a parsed message from normalized string. * @param normalizedString normalizedString * @param sourceMessage sourceMessage * @return ParsedMessage */ function parsedMessageFor(normalizedString: string, sourceMessage?: ParsedMessage): ParsedMessage { const parser = new Xliff2MessageParser(); return parser.parseNormalizedString(normalizedString, sourceMessage); } /** * Helperfunction to create a parsed message from native xml. * @param xmlContent xmlContent * @param sourceMessage sourceMessage * @return ParsedMessage */ function parsedMessageFromXML(xmlContent: string, sourceMessage?: ParsedMessage): ParsedMessage { const parser = new Xliff2MessageParser(); return parser.createNormalizedMessageFromXMLString(xmlContent, sourceMessage); } /** * create normalized message from string, then create one from generated xml. * Check that it is the same. * @param normalizedMessage normalizedMessage */ function checkToXmlAndBack(normalizedMessage: string) { const xml = parsedMessageFor(normalizedMessage).asNativeString(); expect(parsedMessageFromXML('<source>' + xml + '</source>').asDisplayString()).toBe(normalizedMessage); } describe('normalized message to xml', () => { it('should parse plain text', () => { const normalizedMessage = 'a text without anything special'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()).toBe(normalizedMessage); }); it('should parse text with placeholder', () => { const normalizedMessage = 'a placeholder: {{0}}'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()).toBe('a placeholder: <ph id="0" equiv="INTERPOLATION"/>'); checkToXmlAndBack(normalizedMessage); }); it('should parse text with 2 placeholders', () => { const normalizedMessage = '{{1}}: a placeholder: {{0}}'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()) .toBe('<ph id="0" equiv="INTERPOLATION_1"/>: a placeholder: <ph id="1" equiv="INTERPOLATION"/>'); checkToXmlAndBack(normalizedMessage); }); it('should parse simple bold tag', () => { const normalizedMessage = 'a text <b>with</b> a bold text'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()) .toBe('a text <pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b>"' + ' dispEnd="&lt;/b>">with</pc> a bold text'); }); it('should parse simple italic tag', () => { const normalizedMessage = 'a text <i>with</i> emphasis'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()) .toBe('a text <pc id="0" equivStart="START_ITALIC_TEXT" equivEnd="CLOSE_ITALIC_TEXT" type="fmt" dispStart="&lt;i>"' + ' dispEnd="&lt;/i>">with</pc> emphasis'); checkToXmlAndBack(normalizedMessage); }); it('should parse unknown tag', () => { const normalizedMessage = 'a text with <strange>strange emphasis</strange>'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()) .toBe('a text with <pc id="0" equivStart="START_TAG_STRANGE" equivEnd="CLOSE_TAG_STRANGE" type="other"' + ' dispStart="&lt;strange>" dispEnd="&lt;/strange>">strange emphasis</pc>'); checkToXmlAndBack(normalizedMessage); }); it('should parse embedded tags with placeholder inside', () => { const normalizedMessage = '<b><i><strange>Placeholder {{0}}</strange></i></b>'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()) .toBe('<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b>"' + ' dispEnd="&lt;/b>"><pc id="1" equivStart="START_ITALIC_TEXT" equivEnd="CLOSE_ITALIC_TEXT" type="fmt"' + ' dispStart="&lt;i>" dispEnd="&lt;/i>"><pc id="2" equivStart="START_TAG_STRANGE"' + ' equivEnd="CLOSE_TAG_STRANGE" type="other" dispStart="&lt;strange>" dispEnd="&lt;/strange>">' + 'Placeholder <ph id="3" equiv="INTERPOLATION"/></pc></pc></pc>'); checkToXmlAndBack(normalizedMessage); }); it('should parse ICU Refs', () => { const normalizedMessage = 'a text with <ICU-Message-Ref_0/>'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); // old syntax before angular #17344 // expect(parsedMessage.asNativeString()).toBe('a text with <ph id="0"/>'); // new syntax after angular #17344 expect(parsedMessage.asNativeString()).toBe('a text with <ph id="0" equiv="ICU"/>'); checkToXmlAndBack(normalizedMessage); }); }); describe('xml to normalized message', () => { it('should parse simple text content', () => { const parsedMessage = parsedMessageFromXML('a simple content'); expect(parsedMessage.asDisplayString()).toBe('a simple content'); }); it('should parse strange tag with placeholder content', () => { const parsedMessage = parsedMessageFromXML('Diese Nachricht ist <pc id="0" equivStart="START_TAG_STRANGE"' + ' equivEnd="CLOSE_TAG_STRANGE" type="other" dispStart="&lt;strange&gt;" dispEnd="&lt;/strange&gt;">' + '<ph id="1" equiv="INTERPOLATION" disp="{{strangeness}}"/></pc>'); expect(parsedMessage.asDisplayString()).toBe('Diese Nachricht ist <strange>{{0}}</strange>'); }); it('should parse embedded tags', () => { const parsedMessage = parsedMessageFromXML('Diese Nachricht ist <pc id="0" equivStart="START_BOLD_TEXT"' + ' equivEnd="CLOSE_BOLD_TEXT" type="fmt" dispStart="&lt;b&gt;" dispEnd="&lt;/b&gt;"><pc id="1"' + ' equivStart="START_TAG_STRONG" equivEnd="CLOSE_TAG_STRONG" type="other" dispStart="&lt;strong&gt;"' + ' dispEnd="&lt;/strong&gt;">SEHR WICHTIG</pc></pc>'); expect(parsedMessage.asDisplayString()).toBe('Diese Nachricht ist <b><strong>SEHR WICHTIG</strong></b>'); }); it('should parse complex message with embedded placeholder', () => { const parsedMessage = parsedMessageFromXML('<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link"' + ' dispStart="&lt;a>" dispEnd="&lt;/a>">link1 with placeholder <ph id="1" equiv="INTERPOLATION"' + ' disp="{{placeholder}}"/></pc>'); expect(parsedMessage.asDisplayString()).toBe('<a>link1 with placeholder {{0}}</a>'); }); it('should report an error when xml string is not correct (TODO, does not work)', () => { const parsedMessage = parsedMessageFromXML('</dummy></dummy>'); expect(parsedMessage.asDisplayString()).toBe(''); // TODO xmldoc does not report any error }); it('should parse message with embedded ICU message reference', () => { const parsedMessage = parsedMessageFromXML('first: <ph id="0"/>'); expect(parsedMessage.asDisplayString()).toBe('first: <ICU-Message-Ref_0/>'); }); it('should parse message with embedded ICU message reference (new syntax after angular #17344)', () => { const parsedMessage = parsedMessageFromXML('first: <ph id="0" equiv="ICU" disp="{count, plural, =0 {...} =1 {...}' + ' other {...}}"/>'); expect(parsedMessage.asDisplayString()).toBe('first: <ICU-Message-Ref_0/>'); }); it('should parse message with 2 embedded ICU message reference', () => { const parsedMessage = parsedMessageFromXML('first: <ph id="0"/>, second <ph id="1"/>'); expect(parsedMessage.asDisplayString()).toBe('first: <ICU-Message-Ref_0/>, second <ICU-Message-Ref_1/>'); }); it('should parse message with 2 embedded ICU message reference (new syntax after angular #17344)', () => { const parsedMessage = parsedMessageFromXML('first: <ph id="0" equiv="ICU" disp="{count, plural, =0 {...} =1 {...}' + ' other {...}}"/>, second <ph id="1" equiv="ICU_1" disp="{gender, select, m {...} f {...}}"/>'); expect(parsedMessage.asDisplayString()).toBe('first: <ICU-Message-Ref_0/>, second <ICU-Message-Ref_1/>'); }); it('should parse empty tag like <br>', () => { const normalizedMessage = 'one line<br>second line'; const parsedMessage = parsedMessageFor(normalizedMessage); expect(parsedMessage.asDisplayString()).toBe(normalizedMessage); expect(parsedMessage.asNativeString()).toBe('one line<ph id="0" equiv="LINE_BREAK" type="fmt" disp="&lt;br/>"/>second line'); checkToXmlAndBack(normalizedMessage); }); }); });
the_stack
import {tensor2d} from '@tensorflow/tfjs-core'; import * as tfl from './index'; import {describeMathCPUAndGPU} from './utils/test_utils'; describe('EarlyStopping', () => { function createDummyModel(): tfl.LayersModel { const model = tfl.sequential(); model.add(tfl.layers.dense({units: 1, inputShape: [1]})); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); return model; } it('Default monitor, default mode, increasing val_loss', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping(); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 9}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(2); await callback.onEpochEnd(2, {val_loss: 9.5}); expect(model.stopTraining).toEqual(true); }); it('Default monitor, default mode, holding val_loss', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping(); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 9}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(2); await callback.onEpochEnd(2, {val_loss: 9}); expect(model.stopTraining).toEqual(true); }); it('Default monitor, default mode, custom minDelta', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping({minDelta: 1}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 8}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(2); // An decrease of 0.5 is < minDelta (1) and should trigger stop. await callback.onEpochEnd(2, {val_loss: 7.5}); expect(model.stopTraining).toEqual(true); }); it('Default monitor, default mode, custom baseline, stopping', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping({baseline: 5}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(1); // Failure to go below the baseline will stop the training immediately. await callback.onEpochEnd(1, {val_loss: 6}); expect(model.stopTraining).toEqual(true); }); it('Default monitor, default mode, custom baseline, not stopping', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping({baseline: 5}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(1); // If the loss value goes below the baseline, training should continue. await callback.onEpochEnd(1, {val_loss: 4}); expect(model.stopTraining).toBeUndefined(); // If the loss value increases, training should stop; await callback.onEpochEnd(1, {val_loss: 4.5}); expect(model.stopTraining).toEqual(true); }); it('Custom monitor, default model, increasing', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping({monitor: 'aux_loss'}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10, aux_loss: 100}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 9, aux_loss: 120}); expect(model.stopTraining).toEqual(true); }); it('Custom monitor, max, increasing', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping({monitor: 'aux_metric', mode: 'max'}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10, aux_metric: 100}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 9, aux_metric: 120}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(2); await callback.onEpochEnd(2, {val_loss: 9, aux_metric: 110}); expect(model.stopTraining).toEqual(true); }); it('Custom monitor, max, custom minDelta', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping( {monitor: 'aux_metric', mode: 'max', minDelta: 5}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10, aux_metric: 100}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 9, aux_metric: 120}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(2); // An increase of 2 is < minDelta (5) and should cause stopping. await callback.onEpochEnd(2, {val_loss: 9, aux_metric: 122}); expect(model.stopTraining).toEqual(true); }); it('Custom monitor, max, custom negative minDelta', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping( {monitor: 'aux_metric', mode: 'max', minDelta: -5}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10, aux_metric: 100}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 9, aux_metric: 120}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(2); // An increase of 2 is < minDelta (5) and should cause stopping. await callback.onEpochEnd(2, {val_loss: 9, aux_metric: 122}); expect(model.stopTraining).toEqual(true); }); it('Patience = 2', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping({patience: 2}); callback.setModel(model); await callback.onTrainBegin(); await callback.onEpochBegin(0); await callback.onEpochEnd(0, {val_loss: 10}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {val_loss: 9}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(2); await callback.onEpochEnd(2, {val_loss: 9.5}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(3); await callback.onEpochEnd(3, {val_loss: 9.6}); expect(model.stopTraining).toEqual(true); }); it('Missing monitor leads to warning', async () => { const model = createDummyModel(); const callback = tfl.callbacks.earlyStopping(); callback.setModel(model); const warnMessages: string[] = []; function fakeWarn(message: string) { warnMessages.push(message); } spyOn(console, 'warn').and.callFake(fakeWarn); await callback.onTrainBegin(); await callback.onEpochBegin(0); // Note that the default monitor (val_loss) is missing. await callback.onEpochEnd(0, {loss: 100}); expect(model.stopTraining).toBeUndefined(); await callback.onEpochBegin(1); await callback.onEpochEnd(1, {loss: 100}); expect(model.stopTraining).toBeUndefined(); expect(warnMessages.length).toEqual(2); expect(warnMessages[0]).toMatch(/val_loss is not available/); expect(warnMessages[1]).toMatch(/val_loss is not available/); }); }); describeMathCPUAndGPU('EarlyStopping LayersModel.fit() integration', () => { it('Functional model, monitor loss, With minDelta', async () => { const input = tfl.input({shape: [1]}); const output = tfl.layers.dense({units: 1, kernelInitializer: 'ones'}).apply(input) as tfl.SymbolicTensor; const model = tfl.model({inputs: input, outputs: output}); const xs = tensor2d([1, 2, 3, 4], [4, 1]); const ys = tensor2d([2, 3, 4, 5], [4, 1]); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); // Without the EarlyStopping callback, the loss value would be: // 1, 0.734, 0.549, 0.421, 0.332, ... // With loss being monitored and minDelta set to 0.25, the training should // stop after the 3rd epoch. const history = await model.fit(xs, ys, { epochs: 10, callbacks: tfl.callbacks.earlyStopping({monitor: 'loss', minDelta: 0.25}) }); expect(history.history.loss.length).toEqual(3); }); it('Sequential model, monitor val_acc', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 3, activation: 'softmax', kernelInitializer: 'ones', inputShape: [2] })); const xs = tensor2d([1, 2, 3, 4], [2, 2]); const ys = tensor2d([[1, 0, 0], [0, 1, 0]], [2, 3]); const xsVal = tensor2d([4, 3, 2, 1], [2, 2]); const ysVal = tensor2d([[0, 0, 1], [0, 1, 0]], [2, 3]); model.compile( {loss: 'categoricalCrossentropy', optimizer: 'sgd', metrics: ['acc']}); // Without the EarlyStopping callback, the val_acc value would be: // 0.5, 0.5, 0.5, 0.5, ... // With val_acc being monitored, training should stop after the 2nd epoch. const history = await model.fit(xs, ys, { epochs: 10, validationData: [xsVal, ysVal], callbacks: tfl.callbacks.earlyStopping({monitor: 'val_acc'}) }); expect(history.history.loss.length).toEqual(2); }); it('Sequential model, monitor val_acc, custom patience', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 3, activation: 'softmax', kernelInitializer: 'ones', inputShape: [2] })); const xs = tensor2d([1, 2, 3, 4], [2, 2]); const ys = tensor2d([[1, 0, 0], [0, 1, 0]], [2, 3]); const xsVal = tensor2d([4, 3, 2, 1], [2, 2]); const ysVal = tensor2d([[0, 0, 1], [0, 1, 0]], [2, 3]); model.compile( {loss: 'categoricalCrossentropy', optimizer: 'sgd', metrics: ['acc']}); // Without the EarlyStopping callback, the val_acc value would be: // 0.5, 0.5, 0.5, 0.5, ... // With val_acc being monitored and patience set to 4, training should stop // after the 5th epoch. const history = await model.fit(xs, ys, { epochs: 10, validationData: [xsVal, ysVal], callbacks: tfl.callbacks.earlyStopping({monitor: 'val_acc', patience: 4}) }); expect(history.history.loss.length).toEqual(5); }); });
the_stack
import { Gulp, TaskFunction } from 'gulp'; declare namespace seq { type Step = string | string[]; type Done = (error?: any) => void; function use(gulp: Gulp): typeof seq; } /* Sequence functions (apart from the one returning TaskFunction) generated using the following (requires lodash for the padding): const fnBase = `declare function seq(`; const argPad = _.pad('', fnBase.length, ' '); const maxArgs = 25; const outDone = []; for (let i = 1; i <= maxArgs; i++) { let def = []; for (let j = 1; j <= i; j++) { def.push(`s${j}: seq.Step`); } def.push(`done: seq.Done): void;`); outDone.push(def.join(`,\n${argPad}`)); } console.log(fnBase + outDone.join(`\n${fnBase}`)); */ declare function seq(firstTask: seq.Step, ...additionalTasks: seq.Step[]): TaskFunction; declare function seq(s1: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, s19: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, s19: seq.Step, s20: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, s19: seq.Step, s20: seq.Step, s21: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, s19: seq.Step, s20: seq.Step, s21: seq.Step, s22: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, s19: seq.Step, s20: seq.Step, s21: seq.Step, s22: seq.Step, s23: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, s19: seq.Step, s20: seq.Step, s21: seq.Step, s22: seq.Step, s23: seq.Step, s24: seq.Step, done: seq.Done): void; declare function seq(s1: seq.Step, s2: seq.Step, s3: seq.Step, s4: seq.Step, s5: seq.Step, s6: seq.Step, s7: seq.Step, s8: seq.Step, s9: seq.Step, s10: seq.Step, s11: seq.Step, s12: seq.Step, s13: seq.Step, s14: seq.Step, s15: seq.Step, s16: seq.Step, s17: seq.Step, s18: seq.Step, s19: seq.Step, s20: seq.Step, s21: seq.Step, s22: seq.Step, s23: seq.Step, s24: seq.Step, s25: seq.Step, done: seq.Done): void; export = seq;
the_stack
'use strict'; import * as authorization from './authorization'; import { ArgumentError, FormatError } from './errors'; import { createDictionary } from './dictionary'; /** * Shared access signature tokens are used to authenticate the connection when using symmetric keys (as opposed to x509 certificates) to secure the connection with the Azure IoT hub. */ export class SharedAccessSignature { /** * @private */ sr: string; /** * @private */ se: string | number; /** * @private */ sig: string; /** * @private */ skn: string; private _key: string; /** * @method module:azure-iot-common.SharedAccessSignature.extend * @description Extend the Sas and return the string form of it. * * @param {Integer} expiry an integer value representing the number of seconds since the epoch 00:00:00 UTC on 1 January 1970. * * @throws {ReferenceError} Will be thrown if the argument is falsy. * * @returns {string} The string form of the shared access signature. * */ extend(expiry: number): string { if (!expiry) throw new ReferenceError('expiry' + ' is ' + expiry); this.se = expiry; this.sig = authorization.encodeUriComponentStrict(authorization.hmacHash(this._key, authorization.stringToSign(this.sr, this.se.toString()))); return this.toString(); } /** * @method module:azure-iot-common.SharedAccessSignature#toString * @description Formats a SharedAccessSignatureObject into a properly formatted string. * * @returns {String} A properly formatted shared access signature token. */ toString(): string { /*Codes_SRS_NODE_COMMON_SAS_05_019: [The toString method shall return a shared-access signature token of the form: SharedAccessSignature sr=<url-encoded resourceUri>&sig=<urlEncodedSignature>&se=<expiry>&skn=<urlEncodedKeyName>]*/ let sas = 'SharedAccessSignature '; ['sr', 'sig', 'skn', 'se'].forEach((key: string): void => { /*Codes_SRS_NODE_COMMON_SAS_05_020: [The skn segment is not part of the returned string if the skn property is not defined.]*/ if (this[key]) { if (sas[sas.length - 1] !== ' ') sas += '&'; sas += key + '=' + this[key]; } }); return sas; } /** * @method module:azure-iot-common.SharedAccessSignature.create * @description Instantiate a SharedAccessSignature token with the given parameters. * * @param {String} resourceUri the resource URI to encode into the token. * @param {String} keyName an identifier associated with the key. * @param {String} key a base64-encoded key value. * @param {Integer} expiry an integer value representing the number of seconds since the epoch 00:00:00 UTC on 1 January 1970. * * @throws {ReferenceError} Will be thrown if one of the arguments is falsy. * * @returns {SharedAccessSignature} A shared access signature token. */ /*Codes_SRS_NODE_COMMON_SAS_05_008: [The create method shall accept four arguments: resourceUri - the resource URI to encode into the token keyName - an identifier associated with the key key - a base64-encoded key value expiry - an integer value representing the number of seconds since the epoch 00:00:00 UTC on 1 January 1970.]*/ static create(resourceUri: string, keyName: string, key: string, expiry: number | string): SharedAccessSignature { function throwRef(name: string, value: any): void { throw new ReferenceError('Argument \'' + name + '\' is ' + value); } /*Codes_SRS_NODE_COMMON_SAS_05_009: [If resourceUri, key, or expiry are falsy (i.e., undefined, null, or empty), create shall throw ReferenceException.]*/ if (!resourceUri) throwRef('resourceUri', resourceUri); if (!key) throwRef('key', key); if (!expiry) throwRef('expiry', expiry); /*Codes_SRS_NODE_COMMON_SAS_05_010: [The create method shall create a new instance of SharedAccessSignature with properties: sr, sig, se, and optionally skn.]*/ let sas = new SharedAccessSignature(); sas._key = key; /*Codes_SRS_NODE_COMMON_SAS_05_011: [The sr property shall have the value of resourceUri.]*/ sas.sr = resourceUri; /*Codes_SRS_NODE_COMMON_SAS_05_018: [If the keyName argument to the create method was falsy, skn shall not be defined.]*/ /*Codes_SRS_NODE_COMMON_SAS_05_017: [<urlEncodedKeyName> shall be the URL-encoded value of keyName.]*/ /*Codes_SRS_NODE_COMMON_SAS_05_016: [The skn property shall be the value <urlEncodedKeyName>.]*/ if (keyName) sas.skn = authorization.encodeUriComponentStrict(keyName); /*Codes_SRS_NODE_COMMON_SAS_05_015: [The se property shall have the value of expiry.]*/ sas.se = expiry; /*Codes_SRS_NODE_COMMON_SAS_05_013: [<signature> shall be an HMAC-SHA256 hash of the value <stringToSign>, which is then base64-encoded.]*/ /*Codes_SRS_NODE_COMMON_SAS_05_014: [<stringToSign> shall be a concatenation of resourceUri + '\n' + expiry.]*/ /*Codes_SRS_NODE_COMMON_SAS_05_012: [The sig property shall be the result of URL-encoding the value <signature>.]*/ sas.sig = authorization.encodeUriComponentStrict(authorization.hmacHash(sas._key, authorization.stringToSign(sas.sr, sas.se.toString()))); return sas; } /** * @private */ static createWithSigningFunction(credentials: authorization.TransportConfig, expiry: number, signingFunction: Function, callback: (err: Error, sas?: SharedAccessSignature) => void): void { function throwRef(name: string, value: any): void { throw new ReferenceError('Argument \'' + name + '\' is ' + value); } /*Codes_SRS_NODE_COMMON_SAS_06_001: [If `credentials`, `expiry`, `signingFunction`, or `callback` are falsy, `createWithSigningFunction` shall throw `ReferenceError`.] */ if (!credentials) throwRef('credentials', credentials); if (!expiry) throwRef('expiry', expiry); if (!signingFunction) throwRef('signingFunction', signingFunction); if (!callback) throwRef('callback', callback); let sas = new SharedAccessSignature(); /*Codes_SRS_NODE_COMMON_SAS_06_002: [The `createWithSigningFunction` shall create a `SharedAccessSignature` object with an `sr` property formed by url encoding `credentials.host` + `/devices/` + `credentials.deviceId` + `/modules/` + `credentials.moduleId`.] */ let resource = credentials.host + '/devices/' + credentials.deviceId; if (credentials.moduleId) { resource += `/modules/${credentials.moduleId}`; } sas.sr = authorization.encodeUriComponentStrict(resource); /*Codes_SRS_NODE_COMMON_SAS_06_003: [** The `createWithSigningFunction` shall create a `SharedAccessSignature` object with an `se` property containing the value of the parameter `expiry`.] */ sas.se = expiry; /*Codes_SRS_NODE_COMMON_SAS_06_004: [The `createWithSigningFunction` shall create a `SharedAccessSignature` object with an optional property `skn`, if the `credentials.sharedAccessKeyName` is not falsy, The value of the `skn` property will be the url encoded value of `credentials.sharedAccessKeyName`.] */ if (credentials.sharedAccessKeyName) { sas.skn = authorization.encodeUriComponentStrict(credentials.sharedAccessKeyName); } signingFunction(Buffer.from(authorization.stringToSign(sas.sr, sas.se.toString())), (err, signed) => { if (err) { /*Codes_SRS_NODE_COMMON_SAS_06_006: [** The `createWithSigningFunction` will invoke the `callback` function with an error value if an error occurred during the signing. **] */ callback(err); } else { /*Codes_SRS_NODE_COMMON_SAS_06_005: [The `createWithSigningFunction` shall create a `SharedAccessSignature` object with a `sig` property with the SHA256 hash of the string sr + `\n` + se. The `sig` value will first be base64 encoded THEN url encoded.] */ sas.sig = authorization.encodeUriComponentStrict(signed.toString('base64')); callback(null, sas); } }); } /** * @method module:azure-iot-common.SharedAccessSignature.parse * @description Instantiate a SharedAccessSignature token from a string. * * @param {String} source the string to parse in order to create the SharedAccessSignature token. * @param {Array} requiredFields an array of fields that we expect to find in the source string. * * @throws {FormatError} Will be thrown if the source string is malformed. * * @returns {SharedAccessSignature} A shared access signature token. */ static parse(source: string, requiredFields?: string[]): SharedAccessSignature { /*Codes_SRS_NODE_COMMON_SAS_05_001: [The input argument source shall be converted to string if necessary.]*/ const parts = String(source).split(/\s/); /*Codes_SRS_NODE_COMMON_SAS_05_005: [The parse method shall throw FormatError if the shared access signature string does not start with 'SharedAccessSignature<space>'.]*/ if (parts.length !== 2 || !parts[0].match(/SharedAccessSignature/)) { throw new FormatError('Malformed signature'); } const dict = createDictionary(parts[1], '&'); const err = 'The shared access signature is missing the property: '; requiredFields = requiredFields || []; /*Codes_SRS_NODE_COMMON_SAS_05_006: [The parse method shall throw ArgumentError if any of fields in the requiredFields argument are not found in the source argument.]*/ requiredFields.forEach((key: string): void => { if (!(key in dict)) throw new ArgumentError(err + key); }); /*Codes_SRS_NODE_COMMON_SAS_05_002: [The parse method shall create a new instance of SharedAccessSignature.]*/ let sas = new SharedAccessSignature(); /*Codes_SRS_NODE_COMMON_SAS_05_003: [It shall accept a string argument of the form 'name=value[&name=value…]' and for each name extracted it shall create a new property on the SharedAccessSignature object instance.]*/ /*Codes_SRS_NODE_COMMON_SAS_05_004: [The value of the property shall be the value extracted from the source argument for the corresponding name.]*/ Object.keys(dict).forEach((key: string): void => { sas[key] = dict[key]; }); /*Codes_SRS_NODE_COMMON_SAS_05_007: [The generated SharedAccessSignature object shall be returned to the caller.]*/ return sas; } }
the_stack
import * as dateFns from 'date-fns' import * as R from 'ramda' import * as React from 'react' import * as RRDom from 'react-router-dom' import type { ResultOf } from '@graphql-typed-document-node/core' import * as M from '@material-ui/core' import { fade } from '@material-ui/core/styles' import JsonDisplay from 'components/JsonDisplay' import Skeleton from 'components/Skeleton' import Sparkline from 'components/Sparkline' import * as BucketPreferences from 'utils/BucketPreferences' import MetaTitle from 'utils/MetaTitle' import * as NamedRoutes from 'utils/NamedRoutes' import * as SVG from 'utils/SVG' import StyledLink from 'utils/StyledLink' import copyToClipboard from 'utils/clipboard' import * as Format from 'utils/format' import parseSearch from 'utils/parseSearch' import { readableBytes, readableQuantity } from 'utils/string' import usePrevious from 'utils/usePrevious' import useQuery from 'utils/useQuery' import * as PD from '../PackageDialog' import Pagination from '../Pagination' import WithPackagesSupport from '../WithPackagesSupport' import { displayError } from '../errors' import REVISION_COUNT_QUERY from './gql/RevisionCount.generated' import REVISION_LIST_QUERY from './gql/RevisionList.generated' const PER_PAGE = 30 type RevisionFields = NonNullable< NonNullable< ResultOf<typeof REVISION_LIST_QUERY>['package'] >['revisions']['page'][number] > type AccessCounts = NonNullable<RevisionFields['accessCounts']> interface SparklineSkelProps { width: number height: number } function SparklineSkel({ width, height }: SparklineSkelProps) { const [data] = React.useState(() => R.times((i) => i + Math.random() * i, 30)) const t = M.useTheme() const c0 = fade(t.palette.action.hover, 0) const c1 = t.palette.action.hover const c2 = fade(t.palette.action.hover, t.palette.action.hoverOpacity * 0.4) return ( <Sparkline boxProps={{ position: 'absolute', right: 0, bottom: 0, width, height, }} data={data} width={width} height={height} pb={8} pt={5} px={10} extendL extendR stroke={SVG.Paint.Color(t.palette.action.hover)} fill={SVG.Paint.Server( <linearGradient> <stop offset="0" stopColor={c0} /> <stop offset="30%" stopColor={c1}> <animate attributeName="stop-color" values={`${c1}; ${c2}; ${c1}`} dur="3s" repeatCount="indefinite" /> </stop> </linearGradient>, )} contourThickness={1.5} /> ) } interface CountsProps { sparklineW: number sparklineH: number } function Counts({ counts, total, sparklineW, sparklineH }: CountsProps & AccessCounts) { const [cursor, setCursor] = React.useState<number | null>(null) return ( <> <M.Box position="absolute" right={16} top={0}> <M.Typography variant="body2" color={cursor === null ? 'textSecondary' : 'textPrimary'} component="span" noWrap > {cursor === null ? 'Total views' : dateFns.format(counts[cursor].date, `MMM do`)} : </M.Typography> <M.Box component="span" textAlign="right" ml={1} minWidth={30} display="inline-block" > <M.Typography variant="subtitle2" color={cursor === null ? 'textSecondary' : 'textPrimary'} component="span" > {readableQuantity(cursor === null ? total : counts[cursor].value)} </M.Typography> </M.Box> </M.Box> <Sparkline boxProps={{ position: 'absolute', right: 0, bottom: 0, width: sparklineW, height: sparklineH, }} data={R.pluck('value', counts)} onCursor={setCursor} width={sparklineW} height={sparklineH} pb={8} pt={5} px={10} extendL extendR stroke={SVG.Paint.Color(M.colors.blue[500])} fill={SVG.Paint.Server( <linearGradient> <stop offset="0" stopColor={fade(M.colors.blue[500], 0)} /> <stop offset="30%" stopColor={fade(M.colors.blue[500], 0.3)} /> </linearGradient>, )} contourThickness={1.5} cursorLineExtendUp={false} cursorCircleR={3} cursorCircleFill={SVG.Paint.Color(M.colors.common.white)} /> </> ) } const useRevisionLayoutStyles = M.makeStyles((t) => ({ root: { position: 'relative', [t.breakpoints.down('xs')]: { borderRadius: 0, }, [t.breakpoints.up('sm')]: { marginTop: t.spacing(1), }, }, })) interface RevisionLayoutProps { link: React.ReactNode msg: React.ReactNode meta?: React.ReactNode hash: React.ReactNode stats: React.ReactNode counts: (props: CountsProps) => React.ReactNode } function RevisionLayout({ link, msg, meta, hash, stats, counts }: RevisionLayoutProps) { const classes = useRevisionLayoutStyles() const t = M.useTheme() const xs = M.useMediaQuery(t.breakpoints.down('xs')) const sm = M.useMediaQuery(t.breakpoints.down('sm')) // eslint-disable-next-line no-nested-ternary const sparklineW = xs ? 176 : sm ? 300 : 400 const sparklineH = xs ? 32 : 48 return ( <M.Paper className={classes.root}> <M.Box pt={2} pl={2} pr={25}> {link} </M.Box> <M.Box py={1} pl={2} pr={xs ? 2 : Math.ceil(sparklineW / t.spacing(1) + 1)}> {msg} </M.Box> {!!meta && ( <M.Hidden xsDown> <M.Divider /> {meta} </M.Hidden> )} <M.Hidden xsDown> <M.Divider /> </M.Hidden> <M.Box pl={2} pr={xs ? Math.ceil(sparklineW / t.spacing(1)) : 30} height={{ xs: 64, sm: 48 }} display="flex" alignItems="center" > {hash} </M.Box> <M.Box position="absolute" right={16} bottom={{ xs: 'auto', sm: 0 }} top={{ xs: 16, sm: 'auto' }} height={{ xs: 20, sm: 48 }} display="flex" alignItems="center" color="text.secondary" > {stats} </M.Box> <M.Box position="absolute" right={0} bottom={{ xs: 0, sm: 49 }} top={{ xs: 'auto', sm: 16 }} height={{ xs: 64, sm: 'auto' }} width={sparklineW} > {counts({ sparklineW, sparklineH })} </M.Box> </M.Paper> ) } function RevisionSkel() { const t = M.useTheme() const xs = M.useMediaQuery(t.breakpoints.down('xs')) return ( <RevisionLayout link={ <M.Box height={20} display="flex" alignItems="center"> <Skeleton borderRadius="borderRadius" height={16} width={200} /> </M.Box> } msg={ <> <M.Box height={20} display="flex" alignItems="center"> <Skeleton borderRadius="borderRadius" height={16} width="100%" /> </M.Box> {!xs && ( <M.Box height={20} display="flex" alignItems="center"> <Skeleton borderRadius="borderRadius" height={16} width="90%" /> </M.Box> )} </> } hash={ <Skeleton borderRadius="borderRadius" height={16} width="100%" maxWidth={550} /> } stats={ <M.Box display="flex" alignItems="center"> <Skeleton borderRadius="borderRadius" width={70} height={16} mr={2} /> <Skeleton borderRadius="borderRadius" width={70} height={16} /> </M.Box> } counts={({ sparklineW, sparklineH }) => ( <> <M.Box position="absolute" right={16} top={0} display="flex" alignItems="center" height={20} width={120} > <Skeleton height={16} width="100%" borderRadius="borderRadius" /> </M.Box> <SparklineSkel width={sparklineW} height={sparklineH} /> </> )} /> ) } const useRevisionStyles = M.makeStyles((t) => ({ mono: { // @ts-expect-error fontFamily: t.typography.monospace.fontFamily, }, time: { ...t.typography.body1, fontWeight: t.typography.fontWeightMedium, lineHeight: t.typography.pxToRem(20), whiteSpace: 'nowrap', }, msg: { ...(t.mixins as $TSFixMe).lineClamp(2), overflowWrap: 'break-word', [t.breakpoints.up('sm')]: { minHeight: 40, }, }, hash: { color: t.palette.text.secondary, // @ts-expect-error fontFamily: t.typography.monospace.fontFamily, fontSize: t.typography.body2.fontSize, maxWidth: 'calc(100% - 48px)', overflow: 'hidden', textOverflow: 'ellipsis', }, })) interface RevisionProps extends RevisionFields { bucket: string name: string } function Revision({ bucket, name, hash, modified, message, userMeta, totalEntries, totalBytes, accessCounts, }: RevisionProps) { const classes = useRevisionStyles() const { urls } = NamedRoutes.use() const t = M.useTheme() const xs = M.useMediaQuery(t.breakpoints.down('xs')) const dateFmt = xs ? 'MMM d yyyy - h:mmaaaaa' : 'MMMM do yyyy - h:mma' return ( <RevisionLayout link={ <RRDom.Link className={classes.time} to={urls.bucketPackageTree(bucket, name, hash)} > {dateFns.format(modified, dateFmt)} </RRDom.Link> } msg={ <M.Typography variant="body2" className={classes.msg}> {message || <i>No message</i>} </M.Typography> } meta={ !!userMeta && !R.isEmpty(userMeta) && ( // @ts-expect-error <JsonDisplay name="Metadata" value={userMeta} pl={1.5} py={1.75} pr={2} /> ) } hash={ <> <M.Box className={classes.hash} component="span" order={{ xs: 1, sm: 0 }}> {hash} </M.Box> <M.IconButton onClick={() => copyToClipboard(hash)} edge={xs ? 'start' : false}> <M.Icon>file_copy</M.Icon> </M.IconButton> </> } stats={ <> <M.Icon color="disabled">storage</M.Icon> &nbsp;&nbsp; <M.Typography component="span" variant="body2"> {readableBytes(totalBytes)} </M.Typography> <M.Box pr={2} /> <M.Icon color="disabled">insert_drive_file</M.Icon> &nbsp; <M.Typography component="span" variant="body2"> {readableQuantity(totalEntries)} &nbsp; <Format.Plural value={totalEntries ?? 0} one="file" other="files" /> </M.Typography> </> } counts={({ sparklineW, sparklineH }) => !!accessCounts && <Counts {...{ sparklineW, sparklineH, ...accessCounts }} /> } /> ) } const renderRevisionSkeletons = R.times((i) => <RevisionSkel key={i} />) interface PackageRevisionsProps { bucket: string name: string page?: number } export function PackageRevisions({ bucket, name, page }: PackageRevisionsProps) { const preferences = BucketPreferences.use() const { urls } = NamedRoutes.use() const actualPage = page || 1 const makePageUrl = React.useCallback( (newP: number) => urls.bucketPackageRevisions(bucket, name, { p: newP !== 1 ? newP : undefined }), [urls, bucket, name], ) const scrollRef = React.useRef<HTMLSpanElement>(null) // scroll to top on page change usePrevious(actualPage, (prev) => { if (prev && actualPage !== prev && scrollRef.current) { scrollRef.current.scrollIntoView() } }) const revisionCountQuery = useQuery({ query: REVISION_COUNT_QUERY, variables: { bucket, name }, }) const revisionListQuery = useQuery({ query: REVISION_LIST_QUERY, variables: { bucket, name, page: actualPage, perPage: PER_PAGE }, }) const updateDialog = PD.usePackageCreationDialog({ bucket, src: { name } }) return ( <M.Box pb={{ xs: 0, sm: 5 }} mx={{ xs: -2, sm: 0 }}> {updateDialog.render({ resetFiles: 'Undo changes', submit: 'Push', successBrowse: 'Browse', successTitle: 'Push complete', successRenderMessage: ({ packageLink }) => ( <>Package revision {packageLink} successfully created</> ), title: 'Push package revision', })} <M.Box pt={{ xs: 2, sm: 3 }} pb={{ xs: 2, sm: 1 }} px={{ xs: 2, sm: 0 }} display="flex" > <M.Typography variant="h5" ref={scrollRef}> <StyledLink to={urls.bucketPackageDetail(bucket, name)}>{name}</StyledLink>{' '} revisions </M.Typography> <M.Box flexGrow={1} /> {preferences?.ui?.actions?.revisePackage && ( <M.Button variant="contained" color="primary" style={{ marginTop: -3, marginBottom: -3 }} onClick={updateDialog.open} > Revise package </M.Button> )} </M.Box> {revisionCountQuery.case({ error: displayError(), fetching: () => renderRevisionSkeletons(10), data: (d) => { const revisionCount = d.package?.revisions.total if (!revisionCount) { return ( <M.Box py={5} textAlign="center"> <M.Typography variant="h4">No such package</M.Typography> </M.Box> ) } const pages = Math.ceil(revisionCount / PER_PAGE) return ( <> {revisionListQuery.case({ error: displayError(), fetching: () => { const items = actualPage < pages ? PER_PAGE : revisionCount % PER_PAGE return renderRevisionSkeletons(items) }, data: (dd) => (dd.package?.revisions.page || []).map((r) => ( <Revision key={`${r.hash}:${r.modified.valueOf()}`} {...{ bucket, name, ...r }} /> )), })} {pages > 1 && <Pagination {...{ pages, page: actualPage, makePageUrl }} />} </> ) }, })} </M.Box> ) } export default function PackageRevisionsWrapper({ match: { params: { bucket, name }, }, location, }: RRDom.RouteComponentProps<{ bucket: string; name: string }>) { const { p } = parseSearch(location.search, true) const page = p ? parseInt(p, 10) : undefined return ( <> <MetaTitle>{[name, bucket]}</MetaTitle> <WithPackagesSupport bucket={bucket}> <PackageRevisions {...{ bucket, name, page }} /> </WithPackagesSupport> </> ) } // TODO: restore linked data /* {!!bucketCfg && AsyncResult.case( { _: () => null, Ok: ({ hash, modified, header }) => ( <React.Suspense fallback={null}> <LinkedData.PackageData {...{ bucket: bucketCfg, name, revision: r, hash, modified, header, }} /> </React.Suspense> ), }, res, )} */
the_stack
function doFail(streamState: JSONStreamState, msg: string): void { // console.log('Near offset ' + streamState.pos + ': ' + msg + ' ~~~' + streamState.source.substr(streamState.pos, 50) + '~~~'); throw new Error('Near offset ' + streamState.pos + ': ' + msg + ' ~~~' + streamState.source.substr(streamState.pos, 50) + '~~~'); } export interface ILocation { readonly filename: string; readonly line: number; readonly char: number; } export function parse(source: string, filename: string, withMetadata: boolean): any { let streamState = new JSONStreamState(source); let token = new JSONToken(); let state = JSONState.ROOT_STATE; let cur: any = null; let stateStack: JSONState[] = []; let objStack: any[] = []; function pushState(): void { stateStack.push(state); objStack.push(cur); } function popState(): void { state = stateStack.pop(); cur = objStack.pop(); } function fail(msg: string): void { doFail(streamState, msg); } while (nextJSONToken(streamState, token)) { if (state === JSONState.ROOT_STATE) { if (cur !== null) { fail('too many constructs in root'); } if (token.type === JSONTokenType.LEFT_CURLY_BRACKET) { cur = {}; if (withMetadata) { cur.$vscodeTextmateLocation = token.toLocation(filename); } pushState(); state = JSONState.DICT_STATE; continue; } if (token.type === JSONTokenType.LEFT_SQUARE_BRACKET) { cur = []; pushState(); state = JSONState.ARR_STATE; continue; } fail('unexpected token in root'); } if (state === JSONState.DICT_STATE_COMMA) { if (token.type === JSONTokenType.RIGHT_CURLY_BRACKET) { popState(); continue; } if (token.type === JSONTokenType.COMMA) { state = JSONState.DICT_STATE_NO_CLOSE; continue; } fail('expected , or }'); } if (state === JSONState.DICT_STATE || state === JSONState.DICT_STATE_NO_CLOSE) { if (state === JSONState.DICT_STATE && token.type === JSONTokenType.RIGHT_CURLY_BRACKET) { popState(); continue; } if (token.type === JSONTokenType.STRING) { let keyValue = token.value; if (!nextJSONToken(streamState, token) || (/*TS bug*/<any>token.type) !== JSONTokenType.COLON) { fail('expected colon'); } if (!nextJSONToken(streamState, token)) { fail('expected value'); } state = JSONState.DICT_STATE_COMMA; if (token.type === JSONTokenType.STRING) { cur[keyValue] = token.value; continue; } if (token.type === JSONTokenType.NULL) { cur[keyValue] = null; continue; } if (token.type === JSONTokenType.TRUE) { cur[keyValue] = true; continue; } if (token.type === JSONTokenType.FALSE) { cur[keyValue] = false; continue; } if (token.type === JSONTokenType.NUMBER) { cur[keyValue] = parseFloat(token.value); continue; } if (token.type === JSONTokenType.LEFT_SQUARE_BRACKET) { let newArr: any[] = []; cur[keyValue] = newArr; pushState(); state = JSONState.ARR_STATE; cur = newArr; continue; } if (token.type === JSONTokenType.LEFT_CURLY_BRACKET) { let newDict: any = {}; if (withMetadata) { newDict.$vscodeTextmateLocation = token.toLocation(filename); } cur[keyValue] = newDict; pushState(); state = JSONState.DICT_STATE; cur = newDict; continue; } } fail('unexpected token in dict'); } if (state === JSONState.ARR_STATE_COMMA) { if (token.type === JSONTokenType.RIGHT_SQUARE_BRACKET) { popState(); continue; } if (token.type === JSONTokenType.COMMA) { state = JSONState.ARR_STATE_NO_CLOSE; continue; } fail('expected , or ]'); } if (state === JSONState.ARR_STATE || state === JSONState.ARR_STATE_NO_CLOSE) { if (state === JSONState.ARR_STATE && token.type === JSONTokenType.RIGHT_SQUARE_BRACKET) { popState(); continue; } state = JSONState.ARR_STATE_COMMA; if (token.type === JSONTokenType.STRING) { cur.push(token.value); continue; } if (token.type === JSONTokenType.NULL) { cur.push(null); continue; } if (token.type === JSONTokenType.TRUE) { cur.push(true); continue; } if (token.type === JSONTokenType.FALSE) { cur.push(false); continue; } if (token.type === JSONTokenType.NUMBER) { cur.push(parseFloat(token.value)); continue; } if (token.type === JSONTokenType.LEFT_SQUARE_BRACKET) { let newArr: any[] = []; cur.push(newArr); pushState(); state = JSONState.ARR_STATE; cur = newArr; continue; } if (token.type === JSONTokenType.LEFT_CURLY_BRACKET) { let newDict: any = {}; if (withMetadata) { newDict.$vscodeTextmateLocation = token.toLocation(filename); } cur.push(newDict); pushState(); state = JSONState.DICT_STATE; cur = newDict; continue; } fail('unexpected token in array'); } fail('unknown state'); } if (objStack.length !== 0) { fail('unclosed constructs'); } return cur; } class JSONStreamState { source: string; pos: number; len: number; line: number; char: number; constructor(source: string) { this.source = source; this.pos = 0; this.len = source.length; this.line = 1; this.char = 0; } } const enum JSONTokenType { UNKNOWN = 0, STRING = 1, LEFT_SQUARE_BRACKET = 2, // [ LEFT_CURLY_BRACKET = 3, // { RIGHT_SQUARE_BRACKET = 4, // ] RIGHT_CURLY_BRACKET = 5, // } COLON = 6, // : COMMA = 7, // , NULL = 8, TRUE = 9, FALSE = 10, NUMBER = 11 } const enum JSONState { ROOT_STATE = 0, DICT_STATE = 1, DICT_STATE_COMMA = 2, DICT_STATE_NO_CLOSE = 3, ARR_STATE = 4, ARR_STATE_COMMA = 5, ARR_STATE_NO_CLOSE = 6, } const enum ChCode { SPACE = 0x20, HORIZONTAL_TAB = 0x09, CARRIAGE_RETURN = 0x0D, LINE_FEED = 0x0A, QUOTATION_MARK = 0x22, BACKSLASH = 0x5C, LEFT_SQUARE_BRACKET = 0x5B, LEFT_CURLY_BRACKET = 0x7B, RIGHT_SQUARE_BRACKET = 0x5D, RIGHT_CURLY_BRACKET = 0x7D, COLON = 0x3A, COMMA = 0x2C, DOT = 0x2E, D0 = 0x30, D9 = 0x39, MINUS = 0x2D, PLUS = 0x2B, E = 0x45, a = 0x61, e = 0x65, f = 0x66, l = 0x6C, n = 0x6E, r = 0x72, s = 0x73, t = 0x74, u = 0x75, } class JSONToken { value: string; type: JSONTokenType; offset: number; len: number; line: number; /* 1 based line number */ char: number; constructor() { this.value = null; this.offset = -1; this.len = -1; this.line = -1; this.char = -1; } toLocation(filename: string): ILocation { return { filename: filename, line: this.line, char: this.char }; } } /** * precondition: the string is known to be valid JSON (https://www.ietf.org/rfc/rfc4627.txt) */ function nextJSONToken(_state: JSONStreamState, _out: JSONToken): boolean { _out.value = null; _out.type = JSONTokenType.UNKNOWN; _out.offset = -1; _out.len = -1; _out.line = -1; _out.char = -1; let source = _state.source; let pos = _state.pos; let len = _state.len; let line = _state.line; let char = _state.char; //------------------------ skip whitespace let chCode: number; do { if (pos >= len) { return false; /*EOS*/ } chCode = source.charCodeAt(pos); if (chCode === ChCode.SPACE || chCode === ChCode.HORIZONTAL_TAB || chCode === ChCode.CARRIAGE_RETURN) { // regular whitespace pos++; char++; continue; } if (chCode === ChCode.LINE_FEED) { // newline pos++; line++; char = 0; continue; } // not whitespace break; } while (true); _out.offset = pos; _out.line = line; _out.char = char; if (chCode === ChCode.QUOTATION_MARK) { //------------------------ strings _out.type = JSONTokenType.STRING; pos++; char++; do { if (pos >= len) { return false; /*EOS*/ } chCode = source.charCodeAt(pos); pos++; char++; if (chCode === ChCode.BACKSLASH) { // skip next char pos++; char++; continue; } if (chCode === ChCode.QUOTATION_MARK) { // end of the string break; } } while (true); _out.value = source.substring(_out.offset + 1, pos - 1).replace(/\\u([0-9A-Fa-f]{4})/g, (_, m0) => { return (<any>String).fromCodePoint(parseInt(m0, 16)); }).replace(/\\(.)/g, (_, m0) => { switch (m0) { case '"': return '"'; case '\\': return '\\'; case '/': return '/'; case 'b': return '\b'; case 'f': return '\f'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; default: doFail(_state, 'invalid escape sequence'); } }); } else if (chCode === ChCode.LEFT_SQUARE_BRACKET) { _out.type = JSONTokenType.LEFT_SQUARE_BRACKET; pos++; char++; } else if (chCode === ChCode.LEFT_CURLY_BRACKET) { _out.type = JSONTokenType.LEFT_CURLY_BRACKET; pos++; char++; } else if (chCode === ChCode.RIGHT_SQUARE_BRACKET) { _out.type = JSONTokenType.RIGHT_SQUARE_BRACKET; pos++; char++; } else if (chCode === ChCode.RIGHT_CURLY_BRACKET) { _out.type = JSONTokenType.RIGHT_CURLY_BRACKET; pos++; char++; } else if (chCode === ChCode.COLON) { _out.type = JSONTokenType.COLON; pos++; char++; } else if (chCode === ChCode.COMMA) { _out.type = JSONTokenType.COMMA; pos++; char++; } else if (chCode === ChCode.n) { //------------------------ null _out.type = JSONTokenType.NULL; pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.u) { return false; /* INVALID */ } pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.l) { return false; /* INVALID */ } pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.l) { return false; /* INVALID */ } pos++; char++; } else if (chCode === ChCode.t) { //------------------------ true _out.type = JSONTokenType.TRUE; pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.r) { return false; /* INVALID */ } pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.u) { return false; /* INVALID */ } pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.e) { return false; /* INVALID */ } pos++; char++; } else if (chCode === ChCode.f) { //------------------------ false _out.type = JSONTokenType.FALSE; pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.a) { return false; /* INVALID */ } pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.l) { return false; /* INVALID */ } pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.s) { return false; /* INVALID */ } pos++; char++; chCode = source.charCodeAt(pos); if (chCode !== ChCode.e) { return false; /* INVALID */ } pos++; char++; } else { //------------------------ numbers _out.type = JSONTokenType.NUMBER; do { if (pos >= len) { return false; /*EOS*/ } chCode = source.charCodeAt(pos); if ( chCode === ChCode.DOT || (chCode >= ChCode.D0 && chCode <= ChCode.D9) || (chCode === ChCode.e || chCode === ChCode.E) || (chCode === ChCode.MINUS || chCode === ChCode.PLUS) ) { // looks like a piece of a number pos++; char++; continue; } // pos--; char--; break; } while (true); } _out.len = pos - _out.offset; if (_out.value === null) { _out.value = source.substr(_out.offset, _out.len); } _state.pos = pos; _state.line = line; _state.char = char; // console.log('PRODUCING TOKEN: ', _out.value, JSONTokenType[_out.type]); return true; }
the_stack
import type { ContextMenuCommandBuilder, SlashCommandBuilder, SlashCommandSubcommandsOnlyBuilder, SlashCommandOptionsOnlyBuilder } from '@discordjs/builders'; import { container } from '@sapphire/pieces'; import { ApplicationCommandType, RESTPostAPIChatInputApplicationCommandsJSONBody, RESTPostAPIContextMenuApplicationCommandsJSONBody } from 'discord-api-types/v9'; import type { ApplicationCommand, ApplicationCommandManager, ChatInputApplicationCommandData, Collection, Constants, MessageApplicationCommandData, UserApplicationCommandData } from 'discord.js'; import { InternalRegistryAPIType, RegisterBehavior } from '../../types/Enums'; import { getDefaultBehaviorWhenNotIdentical } from './ApplicationCommandRegistries'; import { CommandDifference, getCommandDifferences } from './computeDifferences'; import { convertApplicationCommandToApiData, normalizeChatInputCommand, normalizeContextMenuCommand } from './normalizeInputs'; export class ApplicationCommandRegistry { public readonly commandName: string; public readonly chatInputCommands = new Set<string>(); public readonly contextMenuCommands = new Set<string>(); private readonly apiCalls: InternalAPICall[] = []; public constructor(commandName: string) { this.commandName = commandName; } public get command() { return container.stores.get('commands').get(this.commandName); } public registerChatInputCommand( command: | ChatInputApplicationCommandData | SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder | SlashCommandOptionsOnlyBuilder | Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'> | (( builder: SlashCommandBuilder ) => | SlashCommandBuilder | SlashCommandSubcommandsOnlyBuilder | SlashCommandOptionsOnlyBuilder | Omit<SlashCommandBuilder, 'addSubcommand' | 'addSubcommandGroup'>), options?: ApplicationCommandRegistryRegisterOptions ) { const builtData = normalizeChatInputCommand(command); this.chatInputCommands.add(builtData.name); this.apiCalls.push({ builtData, registerOptions: options ?? { registerCommandIfMissing: true, behaviorWhenNotIdentical: getDefaultBehaviorWhenNotIdentical() }, type: InternalRegistryAPIType.ChatInput }); if (options?.idHints) { for (const hint of options.idHints) { this.chatInputCommands.add(hint); } } return this; } public registerContextMenuCommand( command: | UserApplicationCommandData | MessageApplicationCommandData | ContextMenuCommandBuilder | ((builder: ContextMenuCommandBuilder) => ContextMenuCommandBuilder), options?: ApplicationCommandRegistryRegisterOptions ) { const builtData = normalizeContextMenuCommand(command); this.contextMenuCommands.add(builtData.name); this.apiCalls.push({ builtData, registerOptions: options ?? { registerCommandIfMissing: true, behaviorWhenNotIdentical: getDefaultBehaviorWhenNotIdentical() }, type: InternalRegistryAPIType.ContextMenu }); if (options?.idHints) { for (const hint of options.idHints) { this.contextMenuCommands.add(hint); } } return this; } public addChatInputCommandNames(...names: string[] | string[][]) { const flattened = names.flat(Infinity) as string[]; for (const command of flattened) { this.debug(`Registering name "${command}" to internal chat input map`); this.warn( `Registering the chat input command "${command}" using a name is not recommended.`, 'Please use the "addChatInputCommandIds" method instead with a command id.' ); this.chatInputCommands.add(command); } return this; } public addContextMenuCommandNames(...names: string[] | string[][]) { const flattened = names.flat(Infinity) as string[]; for (const command of flattened) { this.debug(`Registering name "${command}" to internal context menu map`); this.warn( `Registering the context menu command "${command}" using a name is not recommended.`, 'Please use the "addContextMenuCommandIds" method instead with a command id.' ); this.contextMenuCommands.add(command); } return this; } public addChatInputCommandIds(...commandIds: string[] | string[][]) { const flattened = commandIds.flat(Infinity) as string[]; for (const entry of flattened) { try { BigInt(entry); this.debug(`Registering id "${entry}" to internal chat input map`); } catch { // Don't be silly, save yourself the headaches and do as we say this.debug(`Registering name "${entry}" to internal chat input map`); this.warn( `Registering the chat input command "${entry}" using a name *and* trying to bypass this warning by calling "addChatInputCommandIds" is not recommended.`, 'Please use the "addChatInputCommandIds" method with a valid command id instead.' ); } this.chatInputCommands.add(entry); } return this; } public addContextMenuCommandIds(...commandIds: string[] | string[][]) { const flattened = commandIds.flat(Infinity) as string[]; for (const entry of flattened) { try { BigInt(entry); this.debug(`Registering id "${entry}" to internal context menu map`); } catch { this.debug(`Registering name "${entry}" to internal context menu map`); // Don't be silly, save yourself the headaches and do as we say this.warn( `Registering the context menu command "${entry}" using a name *and* trying to bypass this warning by calling "addContextMenuCommandIds" is not recommended.`, 'Please use the "addContextMenuCommandIds" method with a valid command id instead.' ); } this.contextMenuCommands.add(entry); } return this; } protected async runAPICalls( applicationCommands: ApplicationCommandManager, globalCommands: Collection<string, ApplicationCommand>, guildCommands: Map<string, Collection<string, ApplicationCommand>> ) { this.debug(`Preparing to process ${this.apiCalls.length} possible command registrations / updates...`); const results = await Promise.allSettled( this.apiCalls.map((call) => this.handleAPICall(applicationCommands, globalCommands, guildCommands, call)) ); const errored = results.filter((result) => result.status === 'rejected') as PromiseRejectedResult[]; if (errored.length) { this.error(`Received ${errored.length} errors while processing command registrations / updates`); for (const error of errored) { this.error(error.reason.stack ?? error.reason); } } } private async handleAPICall( commandsManager: ApplicationCommandManager, globalCommands: Collection<string, ApplicationCommand>, allGuildsCommands: Map<string, Collection<string, ApplicationCommand>>, apiCall: InternalAPICall ) { const { builtData, registerOptions } = apiCall; const commandName = builtData.name; const behaviorIfNotEqual = registerOptions.behaviorWhenNotIdentical ?? getDefaultBehaviorWhenNotIdentical(); const findCallback = (entry: ApplicationCommand) => { // If the command is a chat input command, we need to check if the entry is a chat input command if (apiCall.type === InternalRegistryAPIType.ChatInput && entry.type !== 'CHAT_INPUT') return false; // If the command is a context menu command, we need to check if the entry is a context menu command of the same type if (apiCall.type === InternalRegistryAPIType.ContextMenu) { if (entry.type === 'CHAT_INPUT') return false; let apiCallType: keyof typeof Constants['ApplicationCommandTypes']; switch (apiCall.builtData.type) { case ApplicationCommandType.Message: apiCallType = 'MESSAGE'; break; case ApplicationCommandType.User: apiCallType = 'USER'; break; default: throw new Error(`Unhandled context command type: ${apiCall.builtData.type}`); } if (apiCallType !== entry.type) return false; } // Find the command by name or by id hint (mostly useful for context menus) const isInIdHint = registerOptions.idHints?.includes(entry.id); return typeof isInIdHint === 'boolean' ? isInIdHint || entry.name === commandName : entry.name === commandName; }; let type: string; switch (apiCall.type) { case InternalRegistryAPIType.ChatInput: type = 'chat input'; break; case InternalRegistryAPIType.ContextMenu: switch (apiCall.builtData.type) { case ApplicationCommandType.Message: type = 'message context menu'; break; case ApplicationCommandType.User: type = 'user context menu'; break; default: type = 'unknown-type context menu'; } break; default: type = 'unknown'; } if (!registerOptions.guildIds?.length) { const globalCommand = globalCommands.find(findCallback); if (globalCommand) { switch (apiCall.type) { case InternalRegistryAPIType.ChatInput: this.addChatInputCommandIds(globalCommand.id); break; case InternalRegistryAPIType.ContextMenu: this.addContextMenuCommandIds(globalCommand.id); break; } this.debug(`Checking if command "${commandName}" is identical with global ${type} command with id "${globalCommand.id}"`); await this.handleCommandPresent(globalCommand, builtData, behaviorIfNotEqual); } else if (registerOptions.registerCommandIfMissing ?? true) { this.debug(`Creating new global ${type} command with name "${commandName}"`); await this.createMissingCommand(commandsManager, builtData, type); } else { this.debug(`Doing nothing about missing global ${type} command with name "${commandName}"`); } return; } for (const guildId of registerOptions.guildIds) { const guildCommands = allGuildsCommands.get(guildId); if (!guildCommands) { this.debug(`There are no commands for guild with id "${guildId}". Will create ${type} command "${commandName}".`); await this.createMissingCommand(commandsManager, builtData, type, guildId); continue; } const existingGuildCommand = guildCommands.find(findCallback); if (existingGuildCommand) { this.debug(`Checking if guild ${type} command "${commandName}" is identical to command "${existingGuildCommand.id}"`); switch (apiCall.type) { case InternalRegistryAPIType.ChatInput: this.addChatInputCommandIds(existingGuildCommand.id); break; case InternalRegistryAPIType.ContextMenu: this.addContextMenuCommandIds(existingGuildCommand.id); break; } await this.handleCommandPresent(existingGuildCommand, builtData, behaviorIfNotEqual); } else if (registerOptions.registerCommandIfMissing ?? true) { this.debug(`Creating new guild ${type} command with name "${commandName}" for guild "${guildId}"`); await this.createMissingCommand(commandsManager, builtData, type, guildId); } else { this.debug(`Doing nothing about missing guild ${type} command with name "${commandName}" for guild "${guildId}"`); } } } private async handleCommandPresent( applicationCommand: ApplicationCommand, apiData: InternalAPICall['builtData'], behaviorIfNotEqual: RegisterBehavior, guildId?: string ) { const now = Date.now(); // Step 0: compute differences const differences = getCommandDifferences(convertApplicationCommandToApiData(applicationCommand), apiData); const later = Date.now() - now; this.debug(`Took ${later}ms to process differences`); // Step 1: if there are no differences, return if (!differences.length) { this.debug( `${guildId ? 'Guild command' : 'Command'} "${apiData.name}" is identical to command "${applicationCommand.name}" (${ applicationCommand.id })` ); return; } this.logCommandDifferences(differences, applicationCommand, behaviorIfNotEqual === RegisterBehavior.LogToConsole); // Step 2: if the behavior is to log to console, log the differences if (behaviorIfNotEqual === RegisterBehavior.LogToConsole) { return; } // Step 3: if the behavior is to update, update the command try { await applicationCommand.edit(apiData as ChatInputApplicationCommandData); this.debug(`Updated command ${applicationCommand.name} (${applicationCommand.id}) with new api data`); } catch (error) { this.error(`Failed to update command ${applicationCommand.name} (${applicationCommand.id})`, error); } } private logCommandDifferences(differences: CommandDifference[], applicationCommand: ApplicationCommand, logAsWarn: boolean) { const finalMessage: string[] = []; const pad = ' '.repeat(5); for (const difference of differences) { finalMessage.push( [ `└── At path: ${difference.key}`, // `${pad}├── Received: ${difference.original}`, `${pad}└── Expected: ${difference.expected}`, '' ].join('\n') ); } const header = `Found differences for command "${applicationCommand.name}" (${applicationCommand.id}) versus provided api data\n`; logAsWarn ? this.warn(header, ...finalMessage) : this.debug(header, ...finalMessage); } private async createMissingCommand( commandsManager: ApplicationCommandManager, apiData: InternalAPICall['builtData'], type: string, guildId?: string ) { try { const result = await commandsManager.create(apiData, guildId); this.info( `Successfully created ${type}${guildId ? ' guild' : ''} command "${apiData.name}" with id "${ result.id }". You should add the id to the "idHints" property of the register method you used!` ); switch (apiData.type) { case undefined: case ApplicationCommandType.ChatInput: this.addChatInputCommandIds(result.id); break; case ApplicationCommandType.Message: case ApplicationCommandType.User: this.addContextMenuCommandIds(result.id); break; } } catch (err) { this.error( `Failed to register${guildId ? ' guild' : ''} application command with name "${apiData.name}"${ guildId ? ` for guild "${guildId}"` : '' }`, err ); } } private info(message: string, ...other: unknown[]) { container.logger.info(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other); } private error(message: string, ...other: unknown[]) { container.logger.error(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other); } private warn(message: string, ...other: unknown[]) { container.logger.warn(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other); } private debug(message: string, ...other: unknown[]) { container.logger.debug(`ApplicationCommandRegistry[${this.commandName}] ${message}`, ...other); } } export namespace ApplicationCommandRegistry { export interface RegisterOptions { /** * If this is specified, the application commands will only be registered for these guild ids. */ guildIds?: string[]; /** * If we should register the command when it is missing * @default true */ registerCommandIfMissing?: boolean; /** * Specifies what we should do when the command is present, but not identical with the data you provided * @default `ApplicationCommandRegistries.getDefaultBehaviorWhenNotIdentical` */ behaviorWhenNotIdentical?: RegisterBehavior; /** * Specifies a list of command ids that we should check in the event of a name mismatch * @default [] */ idHints?: string[]; } } export type ApplicationCommandRegistryRegisterOptions = ApplicationCommandRegistry.RegisterOptions; export type InternalAPICall = | { builtData: RESTPostAPIChatInputApplicationCommandsJSONBody; registerOptions: ApplicationCommandRegistryRegisterOptions; type: InternalRegistryAPIType.ChatInput; } | { builtData: RESTPostAPIContextMenuApplicationCommandsJSONBody; registerOptions: ApplicationCommandRegistryRegisterOptions; type: InternalRegistryAPIType.ContextMenu; };
the_stack
namespace annie { /** * annie引擎核心类 * @class annie.MovieClip * @since 1.0.0 * @public * @extends annie.Sprite */ export class MovieClip extends Sprite { //Events /** * annie.MovieClip 播放完成事件 * @event annie.Event.END_FRAME * @type {string} * @static * @public * @since 1.0.0 */ /** * annie.MovieClip 帧标签事件 * @event annie.Event.CALL_FRAME * @type {string} * @static * @public * @since 1.0.0 */ // /** * mc的当前帧 * @property currentFrame * @public * @since 1.0.0 * @type {number} * @default 1 * @readonly */ public get currentFrame(): number { let s = this; return s._wantFrame > 0 ? s._wantFrame : s._curFrame; } private _curFrame: number = 0; private _wantFrame: number = 1; private _lastFrameObj: any = null; /** * 当前动画是否处于播放状态 * @property isPlaying * @readOnly * @public * @since 1.0.0 * @type {boolean} * @default true * @readonly */ public get isPlaying(): boolean { return this._isPlaying; } private _isPlaying: boolean = true; /** * 动画的播放方向,是顺着播还是在倒着播 * @property isFront * @public * @since 1.0.0 * @type {boolean} * @default true * @readonly */ get isFront(): boolean { return this._isFront; } private _isFront: boolean = true; /** * 当前动画的总帧数 * @property totalFrames * @public * @since 1.0.0 * @type {number} * @default 1 * @readonly */ public get totalFrames(): number { return (<any>this)._a2x_res_class.tf; } //有可能帧数带有小数点 private _floatFrame: number = 0; /** * 构造函数 * @method MovieClip * @public * @since 1.0.0 */ public constructor() { super(); let s: any = this; s._instanceType = "annie.MovieClip"; } //sprite 和 moveClip的类资源信息 private _a2x_res_class: any = {tf: 1}; private _a2x_res_children: any = []; /** * 调用止方法将停止当前帧 * @method stop * @public * @since 1.0.0 * @return {void} */ public stop(): void { let s = this; if(s._wantFrame==0&&s._curFrame==0){ s._wantFrame=1; } s._isPlaying = false; } private _a2x_script: any = null; /** * 给时间轴添加回调函数,当时间轴播放到当前帧时,此函数将被调用.注意,之前在此帧上添加的所有代码将被覆盖,包括Fla文件中当前帧的代码. * @method addFrameScript * @public * @since 1.0.0 * @param {number|string} frameIndex {number|string} 要将代码添加到哪一帧,从0开始.0就是第一帧,1是第二帧... * @param {Function}frameScript {Function} 时间轴播放到当前帧时要执行回调方法 */ public addFrameScript(frameIndex: number|string, frameScript: Function): void { let s = this; var timeLineObj = s._a2x_res_class; if (typeof (frameIndex) == "string") { if (timeLineObj.label[frameIndex] != undefined) { frameIndex = timeLineObj.label[frameIndex]; } } if (!(s._a2x_script instanceof Object)) s._a2x_script = {}; s._a2x_script[frameIndex] = frameScript; } /** * 移除帧上的回调方法 * @method removeFrameScript * @public * @since 1.0.0 * @param {number|string} frameIndex */ public removeFrameScript(frameIndex: number|string): void { let s = this; var timeLineObj = s._a2x_res_class; if (typeof (frameIndex) == "string") { if (timeLineObj.label[frameIndex] != undefined) { frameIndex = timeLineObj.label[frameIndex]; } } if (s._a2x_script instanceof Object) s._a2x_script[frameIndex] = null; } /** * 确认是不是按钮形态 * @property isButton * @type {boolean} * @public * @since 2.0.0 * @default false */ public get isButton(): boolean { return this._a2x_mode == -1; } //动画模式 按钮 剪辑 图形 private _a2x_mode: number = -2; /** * 将一个mc变成按钮来使用 如果mc在于2帧,那么点击此mc将自动有被按钮的状态,无需用户自己写代码. * 此方法不可逆,设置后不再能设置回剪辑,一定要这么做的话,请联系作者,看作者答不答应 * @method initButton * @public * @since 1.0.0 * @return {void} */ public initButton(): void { let s: any = this; if (s._a2x_mode != -1&&s._a2x_res_class.tf > 1) { s.mouseChildren = false; //将mc设置成按钮形式 s.addEventListener("onMouseDown", s._mouseEvent.bind(s)); s.addEventListener("onMuseOver", s._mouseEvent.bind(s)); s.addEventListener("onMouseUp", s._mouseEvent.bind(s)); s.addEventListener("onMouseOut", s._mouseEvent.bind(s)); s._a2x_mode = -1; if(s._clicked) { if (s.totalFrames > 2) { s.gotoAndStop(3); }else{ s.gotoAndStop(2); } }else{ s.gotoAndStop(1); } } } public set clicked(value: boolean) { let s = this; if (value != s._clicked) { if (value) { s._mouseEvent({type: "onMouseDown"}); } else { s.gotoAndStop(1); } s._clicked = value; } } /** * 如果MovieClip设置成了按钮,则通过此属性可以让它定在按下后的状态上,哪怕再点击它并离开它的时候,他也不会变化状态 * @property clicked * @return {boolean} * @public * @since 2.0.0 */ public get clicked(): boolean { return this._clicked; } private _clicked = false; private _mouseEvent(e: any): void { let s = this; if (!s._clicked) { let frame = 2; if (e.type == "onMouseDown") { if (s.totalFrames > 2) { frame = 3; } } else if (e.type == "onMouseOver") { if (s.totalFrames > 1) { frame = 2; } } else { frame = 1; } s.gotoAndStop(frame); } }; /** * movieClip的当前帧的标签数组,没有则为null * @method getCurrentLabel * @public * @since 1.0.0 * @return {Array} * */ public getCurrentLabel(): any { let s: any = this; if (s._a2x_res_class.tf > 1 && s._a2x_res_class.l[s._curFrame - 1]) { return s._a2x_res_class.l[s._curFrame - 1]; } return null; } /** * 将播放头向后移一帧并停在下一帧,如果本身在最后一帧则不做任何反应 * @method nextFrame * @since 1.0.0 * @public * @return {void} */ public nextFrame(): void { let s = this; s._wantFrame += s._cMcSpeed; if (s._wantFrame > s._a2x_res_class.tf) { s._wantFrame = s._a2x_res_class.tf; } s._isPlaying = false; s._onCheckUpdateFrame(); } /** * 将播放头向前移一帧并停在下一帧,如果本身在第一帧则不做任何反应 * @method prevFrame * @since 1.0.0 * @public * @return {void} */ public prevFrame(): void { let s = this; s._wantFrame -= s._cMcSpeed; if (s._wantFrame < 1) { s._wantFrame = 1; } s._isPlaying = false; s._onCheckUpdateFrame(); } /** * 将播放头跳转到指定帧并停在那一帧,如果本身在第一帧则不做任何反应 * @method gotoAndStop * @public * @since 1.0.0 * @param {number|string} frameIndex 批定帧的帧数或指定帧的标签名 * @return {void} */ public gotoAndStop(frameIndex: number | string): void { let s: any = this; let timeLineObj = s._a2x_res_class; let isOkFrameIndex=false; if (typeof(frameIndex) == "string") { if (timeLineObj.label[frameIndex] != undefined) { frameIndex = timeLineObj.label[frameIndex]; isOkFrameIndex=true; } } else if (typeof(frameIndex) == "number") { if (frameIndex>=1&&frameIndex <=timeLineObj.tf) { isOkFrameIndex=true; } } if (isOkFrameIndex) { s._isPlaying = false; s._floatFrame = 0; s._wantFrame = <number>frameIndex; s._onCheckUpdateFrame(); } } /** * 如果当前时间轴停在某一帧,调用此方法将继续播放. * @method play * @param {boolean} isFront true向前播放,false 向后播放。默认向前 * @public * @since 1.0.0 * @return {void} */ public play(isFront: boolean = true): void { let s = this; s._isPlaying = true; s._isFront = isFront; } /** * 将播放头跳转到指定帧并从那一帧开始继续播放 * @method gotoAndPlay * @public * @since 1.0.0 * @param {number|string} frameIndex 批定帧的帧数或指定帧的标签名 * @param {boolean} isFront 跳到指定帧后是向前播放, 还是向后播放.不设置些参数将默认向前播放 * @return {void} */ public gotoAndPlay(frameIndex: number | string, isFront: boolean = true): void { let s: any = this; let timeLineObj = s._a2x_res_class; let isOkFrameIndex=false; if (typeof(frameIndex) == "string") { if (timeLineObj.label[frameIndex] != undefined) { frameIndex = timeLineObj.label[frameIndex]; isOkFrameIndex=true; } } else if (typeof(frameIndex) == "number") { if (frameIndex>=1&&frameIndex <=timeLineObj.tf){ isOkFrameIndex=true; } } if (isOkFrameIndex) { s._isPlaying = true; s._isFront=isFront; s._floatFrame = 0; s._wantFrame = <number>frameIndex; s._onCheckUpdateFrame(); } } private _onCheckUpdateFrame(): void { let s = this; if (s._wantFrame != s._curFrame) { if (s._isOnStage) { s._updateTimeline(); } } } //flash声音管理 private _a2x_sounds: any = null; public _onAddEvent(): void { super._onAddEvent(); this._onCheckUpdateFrame(); } public _updateTimeline(): void { let s: any = this; if (s._a2x_res_class.tf > 1) { if (s._a2x_mode >= 0) { s._isPlaying = false; if (s.parent instanceof annie.MovieClip) { s._wantFrame = s.parent._wantFrame - s._a2x_mode; } else { s._wantFrame = 1; } } else { if (s._isPlaying && s._wantFrame == s._curFrame && s._visible) { if (s._isFront) { s._wantFrame += s._cMcSpeed; if (s._wantFrame > s._a2x_res_class.tf) { s._wantFrame = 1; } } else { s._wantFrame -= s._cMcSpeed; if (s._wantFrame < 1) { s._wantFrame = s._a2x_res_class.tf; } } } } if (s._wantFrame != s._curFrame){ let curFrame = Math.floor(s._curFrame); let wantFrame = Math.floor(s._wantFrame); s._floatFrame = s._wantFrame - wantFrame; s._curFrame = s._wantFrame; if (curFrame != wantFrame) { // s.a2x_uf=true; let timeLineObj = s._a2x_res_class; //先确定是哪一帧 let allChildren = s._a2x_res_children; let childCount = allChildren.length; let objId: number = 0; let obj: any = null; let objInfo: any = null; let frameIndex = wantFrame - 1; let curFrameScript: any; let isFront = s._isFront; let curFrameObj: any = timeLineObj.f[timeLineObj.timeLine[frameIndex]]; let addChildren: Array<DisplayObject> = []; let remChildren: Array<DisplayObject> = []; if (s._lastFrameObj != curFrameObj) { s._lastFrameObj = curFrameObj; s.children.length = 0; let maskObj: any = null; let maskTillId: number = -1; for (let i = childCount - 1; i >= 0; i--) { objId = allChildren[i][0]; obj = allChildren[i][1]; if (curFrameObj instanceof Object && curFrameObj.c instanceof Object) { objInfo = curFrameObj.c[objId]; } else { objInfo = null; } if (objInfo instanceof Object) { //这个对象有可能是新来的,有可能是再次进入帧里的。需要对他进行初始化 annie.d(obj, objInfo, true); // 检查是否有遮罩 if (objInfo.ma != undefined) { maskObj = obj; maskTillId = objInfo.ma; } else if (maskObj instanceof Object) { obj.mask = maskObj; if (objId == maskTillId) { maskObj = null; } } s.children.unshift(obj); if (!obj._isOnStage) { //证明是这一帧新添加进来的,所以需要执行添加事件 addChildren.unshift(obj); } } else if (obj._isOnStage) { //这个对象在上一帧存在,这一帧不存在,所以需要执行删除事件 remChildren.unshift(obj); } } if (s._floatFrame > 0) { //帧数带小数点的,所以执行微调 s._updateFrameGap(); } let count: number = addChildren.length; for (let i = 0; i < count; i++) { obj = addChildren[i]; if (!obj._isOnStage && s._isOnStage) { obj._cp = true; obj.parent = s; obj.stage = s.stage; obj._onAddEvent(); } } count = remChildren.length; for (let i = 0; i < count; i++) { obj = remChildren[i]; if (obj._isOnStage && s._isOnStage) { obj._onRemoveEvent(true); obj.stage = null; obj.parent = null; } } } //如果发现不是图形动画,则执行脚本 if (s._a2x_mode < 0) { //更新完所有后再来确定事件和脚本 let isCodeScript = false; //有没有用户后期通过代码调用加入的脚本,有就直接调用然后不再调用时间轴代码 if (s._a2x_script instanceof Object) { curFrameScript = s._a2x_script[frameIndex]; if (curFrameScript instanceof Function) { curFrameScript(); isCodeScript = true; } } //有没有用户后期通过代码调用加入的脚本,没有再检查有没有时间轴代码 if (!isCodeScript) { curFrameScript = timeLineObj.a[frameIndex]; if (curFrameScript instanceof Array) { s[curFrameScript[0]](curFrameScript[1] == undefined ? true : curFrameScript[1], curFrameScript[2] == undefined ? true : curFrameScript[2]); } } //有没有帧事件 curFrameScript = timeLineObj.e[frameIndex]; if (curFrameScript instanceof Array) { for (let i = 0; i < curFrameScript.length; i++) { //抛事件 s.dispatchEvent(Event.CALL_FRAME, { frameIndex: s._curFrame, frameName: curFrameScript[i] }); } } //有没有去到帧的最后一帧 if (((s._curFrame == 1 && !isFront) || (s._curFrame == s._a2x_res_class.tf && isFront)) && s.hasEventListener(Event.END_FRAME)) { s.dispatchEvent(Event.END_FRAME, { frameIndex: s._curFrame, frameName: "endFrame" }); } } //有没有声音 let curFrameSound = timeLineObj.s[frameIndex]; if (curFrameSound instanceof Object) { for (let sound in curFrameSound) { s._a2x_sounds[<any>sound - 1].play(0, curFrameSound[sound]); } } } else if (s._floatFrame > 0) { //帧数带小数点的,所以执行微调 s._updateFrameGap(); } } } } public _onUpdateFrame(mcSpeed: number = 1, isOffCanvas: boolean = false): void { let s = this; let playStatus: boolean; if (isOffCanvas) { playStatus = s._isPlaying; s._isPlaying = false; } s._updateTimeline(); if (isOffCanvas) { s._isPlaying = playStatus; } super._onUpdateFrame(mcSpeed, isOffCanvas); } public _onRemoveEvent(isReSetMc: boolean) { super._onRemoveEvent(isReSetMc); if (isReSetMc) MovieClip._resetMC(this); } private _updateFrameGap() { let s = this; /*s.a2x_uf=true;*/ let timeLineObj = s._a2x_res_class; //先确定是哪一帧 let allChildren = s._a2x_res_children; let childCount = allChildren.length; let objId: number = 0; let obj: any = null; let nextObjInfo: any = null; let curObjInfo: any = null; let nextFrameIndex = Math.floor(s._curFrame); let curFrameObj: any = s._lastFrameObj; let ff = s._floatFrame; let nextFrameObj: any = timeLineObj.f[timeLineObj.timeLine[nextFrameIndex]]; for (let i = childCount - 1; i >= 0; i--) { objId = allChildren[i][0]; obj = allChildren[i][1]; if (nextFrameObj && nextFrameObj.c && curFrameObj && curFrameObj.c) { nextObjInfo = nextFrameObj.c[objId]; curObjInfo = curFrameObj.c[objId]; //更新对象信息 if (curObjInfo != void 0 && nextObjInfo != void 0) { if (nextObjInfo.tr == void 0 || nextObjInfo.tr.length == 1) { nextObjInfo.tr = [0, 0, 1, 1, 0, 0]; } if (nextObjInfo.al == void 0) { nextObjInfo.al = 1; } if (!obj._changeTransformInfo[0]) { obj._x = curObjInfo.tr[0] + (nextObjInfo.tr[0] - curObjInfo.tr[0]) * ff; } if (!obj._changeTransformInfo[1]) { obj._y = curObjInfo.tr[1] + (nextObjInfo.tr[1] - curObjInfo.tr[1]) * ff; } if (!obj._changeTransformInfo[2]) { obj._scaleX = curObjInfo.tr[2] + (nextObjInfo.tr[2] - curObjInfo.tr[2]) * ff; } if (!obj._changeTransformInfo[3]) { obj._scaleY = curObjInfo.tr[3] + (nextObjInfo.tr[3] - curObjInfo.tr[3]) * ff; } if (!obj._changeTransformInfo[4]) { let sx = nextObjInfo.tr[4] - curObjInfo.tr[4]; let sy = nextObjInfo.tr[5] - curObjInfo.tr[5]; if (sx > 180) { sx -= 360; } else if (sx < -180) { sx += 360; } if (sy > 180) { sy -= 360; } else if (sy < -180) { sy += 360; } obj._skewX = curObjInfo.tr[4] + sx * ff; obj._skewY = curObjInfo.tr[5] + sy * ff; } if (!obj._changeTransformInfo[5]) { obj._alpha = curObjInfo.al + (nextObjInfo.al - curObjInfo.al) * ff; obj.a2x_ua = true; } obj.a2x_um = true; } } } s._floatFrame = 0; } private static _resetMC(obj: any) { //判断obj是否是动画,是的话则还原成动画初始时的状态 obj._wantFrame = 1; obj._curFrame = 0; obj._isFront = true; obj._floatFrame = 0; if (obj._a2x_mode < -1) { obj._isPlaying = true; } else { obj._isPlaying = false; } } public destroy(): void { //清除相应的数据引用 let s = this; super.destroy(); s._lastFrameObj = null; s._a2x_script = null; s._a2x_res_children = null; s._a2x_res_class = null; s._a2x_sounds = null; } } }
the_stack
module Kiwi.HUD { /** * The HUDWidget is an abstract class containing the fundamental properties and methods that every HUDWidget needs to have. * This class is designed to be extended from and thus objects should not directly instantiate it. * * @class HUDWidget * @namespace Kiwi.HUD * @constructor * @param game {Kiwi.Game} The game that this HUDWidget belongs to. * @param name {string} Name of the type of HUDWidget. * @param x {number} The coordinates of this HUDWidget on the x-axis. * @param y {number} The coordinates of this HUDWidget on the y-axis. * @return {Kiwi.HUD.HUDWidget} */ export class HUDWidget { constructor(game:Kiwi.Game,name: string,x:number,y:number) { this.name = name; this.game = game; this._manager = this.game.huds; this._device = this.game.deviceTargetOption; this.components = new Kiwi.ComponentManager(Kiwi.HUD_WIDGET, this); if (this._manager.supported) { if(this._device === Kiwi.TARGET_BROWSER) { this.container = <HTMLDivElement>document.createElement("div"); this.container.id = 'HUD-widget-' + this.game.rnd.uuid(); this.container.className = 'HUD-widget'; this.container.style.position = "absolute"; } this.onCoordsUpdate = new Kiwi.Signal(); this.x = x; this.y = y; } } /** * Returns the type of object that this is. * @method objType * @return {String} "HUDWidget" * @public */ public objType(): string { return 'HUDWidget'; } /** * The HUDManager that this widget 'belongs' to. * This is mainly indented for INTERNAL Kiwi use only and is public so that sub classes can have a reference to it. * @property _manager * @type Kiwi.HUD.HUDManager * @protected */ public _manager: Kiwi.HUD.HUDManager; /** * The type of device that this game is being targeted at. Same as the deviceTargetOption on the game class. * Used to detirmine how the HUD is to be managed behind the scenes. * This is mainly indented for INTERNAL Kiwi use only and is public so that sub classes can have a reference to it. * @property _device * @type _device * @protected */ public _device: number; /** * The game that this HUDWidget belongs to. * @property game * @type Kiwi.Game * @public */ public game: Kiwi.Game; /** * A quick way to reference the style object that exists on the container element of this widget. * @property style * @type any * @public */ public get style():any { if (this._device === Kiwi.TARGET_BROWSER) { return this.container.style; } } public set style(val: any) { if (this._device === Kiwi.TARGET_BROWSER) { this.container.style = val; } } /** * Called when the coordinates of the HUD Widget updates. * @property onCoordsUpdate * @type Kiwi.Signal * @public */ public onCoordsUpdate: Kiwi.Signal; /** * The x coordinate of the widget * @property _x * @type number * @private */ private _x: number; /** * Get the x coordinate of the widget * @property x * @type number * @public */ public get x():number { return this._x; } public set x(value: number) { if (this._manager.supported) { this._x = value; if(this._device == Kiwi.TARGET_BROWSER) this.container.style[this._horizontalOrigin] = this.x + "px"; this.onCoordsUpdate.dispatch(this.x, this.y); } } /** * The y coordinate of the widget * @property _y * @type number * @private */ private _y: number; /** * Get the y coordinate of the widget * @property y * @type number * @public */ public get y(): number { return this._y; } public set y(value: number) { if (this._manager.supported) { this._y = value; if(this._device == Kiwi.TARGET_BROWSER) this.container.style[this._verticalOrigin] = this.y + "px"; this.onCoordsUpdate.dispatch(this.x, this.y); } } /** * The list of components that the HUDWidget use's. * @property components * @type Kiwi.ComponentManager * @public */ public components: Kiwi.ComponentManager; /** * The HTMLDivElement that this widget is using. * @property * @type HTMLDivElement * @public */ public container: HTMLDivElement; /** * The name of the widget which is used to identify the type of widget. * @property * @type string * @public */ public name: string; /** * When a template has been set, this property will have a reference to the HTMLElement we can place the HUDWidget information into. * Currently doesn't have that great support. * @property tempElement * @type HTMLElement * @public */ public tempElement: HTMLElement; /** * The parent of the template container. So that when removing a template we can place it in the right spot * Currently doesn't have that great support. * @property _tempParent * @type HTMLElement * @private */ private _tempParent: HTMLElement; /** * The container element for the template * Currently doesn't have that great support. * @property _tempContainer * @type HTMLElement * @private */ private _tempContainer: HTMLElement; /** * This method is used to remove existing DOM elements and place them inside a HUDWidget's container element. * Useful so that when making HUD Widgets the developer can style HUDWidgets without having to create/write to much javascript. * * Can be used by itself but maybe more useful if you customise it to suit your own needs. * Currently doesn't have that great support. * * @method setTemplate * @param main {string} main - ID of an HTMLElement. This element should contain all of the elements you would like to place inside the HUDWidget. * @param [element] {string} element - ID of an HTMLElement that resides inside of the main param. This is the element that the HUDWidget can use to populate with information. E.g. Your score, health remaining, the icon, e.t.c. * @public */ public setTemplate(main: string, element?: string, ...paramsArr: any[]) { if (this._device == Kiwi.TARGET_BROWSER) { var containerElement: HTMLElement = document.getElementById(main); if (containerElement === undefined) { return; } if (element === undefined) { var fieldElement = containerElement; } else { var fieldElement: HTMLElement = document.getElementById(element); if (fieldElement === undefined || containerElement.contains(fieldElement) === false) { return; } } this.tempElement = fieldElement; this._tempContainer = containerElement; this._tempParent = containerElement.parentElement; this._tempParent.removeChild(containerElement); this.container.appendChild(containerElement); } } /** * Used to remove any the template HTML from this HUDWidget. * Currently doesn't have that great support. * * @method removeTemplate * @public */ public removeTemplate() { if (this._device == Kiwi.TARGET_BROWSER) { if (this.tempElement !== undefined) { this.container.removeChild(this._tempContainer); this._tempParent.appendChild(this._tempContainer); this.tempElement = null; this._tempParent = null; this._tempContainer = null; } } } /** * The class name/s that the container element that this HUDWidget current has. * @property class * @type {String} * @public */ public set class(cssClass: string) { if (this._device == Kiwi.TARGET_BROWSER) { this.container.className = cssClass; } } public get class(): string { if (this._device == Kiwi.TARGET_BROWSER) { return this.container.className; } } /** * The game update loop. * @method update * @public */ public update() { this.components.update(); } /** * Contains the current CSS style that will used for the x position. * Should either be `LEFT` or `RIGHT` but these values are not checked upon assignment. * * @property _horizontalOrigin * @type string * @default 'left' * @since 1.3.0 * @protected */ protected _horizontalOrigin: string = HUDWidget.LEFT; /** * Contains the current CSS style that will used for the x position. * Should either be `LEFT` or `RIGHT` but these values are not checked upon assignment. * * @property horizontalOrigin * @type string * @default 'left' * @since 1.3.0 * @public */ public get horizontalOrigin(): string { return this._horizontalOrigin; } public set horizontalOrigin(val: string) { //Reset the current this.container.style[this._horizontalOrigin] = 'auto'; //Set the new value this._horizontalOrigin = val; this.container.style[this._horizontalOrigin] = this.x + 'px'; } /** * Contains the current CSS style that will used for the y position. * Should either be `TOP` or `BOTTOM` but these values are not checked upon assignment. * * @property _verticalOrigin * @type string * @default 'top' * @since 1.3.0 * @protected */ protected _verticalOrigin: string = HUDWidget.TOP; /** * Contains the current CSS style that will used for the y position. * Should either be `TOP` or `BOTTOM` but these values are not checked upon assignment. * * @property vertical * @type string * @default 'top' * @since 1.3.0 * @public */ public get verticalOrigin(): string { return this._verticalOrigin; } public set verticalOrigin(val: string) { //Reset the current this.container.style[this._verticalOrigin] = 'auto'; //Set the new value this._verticalOrigin = val; this.container.style[this._verticalOrigin] = this.y + 'px'; } /** * Contains the CSS style used to position a HUD element from the top corner. * * @property TOP * @type string * @default 'top' * @since 1.3.0 * @static * @readOnly * @final * @public */ public static TOP: string = 'top'; /** * Contains the CSS style used to position a HUD element from the bottom corner. * * @property BOTTOM * @type string * @default 'bottom' * @since 1.3.0 * @static * @readOnly * @final * @public */ public static BOTTOM: string = 'bottom'; /** * Contains the CSS style used to position a HUD element from the left corner. * * @property LEFT * @type string * @default 'left' * @since 1.3.0 * @static * @readOnly * @final * @public */ public static LEFT: string = 'left'; /** * Contains the CSS style used to position a HUD element from the right corner. * * @property RIGHT * @type string * @default 'right' * @since 1.3.0 * @static * @readOnly * @final * @public */ public static RIGHT: string = 'right'; /** * * @method destroy * @public */ public destroy() { delete this.game; delete this._manager; delete this._device; if (this.onCoordsUpdate) this.onCoordsUpdate.dispose(); delete this.onCoordsUpdate; //remove the elements.... } } }
the_stack
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, forwardRef, HostBinding, Inject, Input, OnDestroy, OnInit, Optional, Output, ViewChild, ViewEncapsulation } from '@angular/core'; import { AbstractControl, ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR, Validator } from '@angular/forms'; import { DatetimeAdapter } from '@fundamental-ngx/core/datetime'; import { DateTimeFormats, DATE_TIME_FORMATS } from '@fundamental-ngx/core/datetime'; import { DateRange } from './models/date-range'; import { CalendarCurrent } from './models/calendar-current'; import { SpecialDayRule } from '@fundamental-ngx/core/shared'; import { CalendarYearGrid } from './models/calendar-year-grid'; import { AggregatedYear } from './models/aggregated-year'; import { CalendarDayViewComponent } from './calendar-views/calendar-day-view/calendar-day-view.component'; import { CalendarYearViewComponent } from './calendar-views/calendar-year-view/calendar-year-view.component'; import { CalendarService } from './calendar.service'; import { createMissingDateImplementationError } from './calendar-errors'; import { CalendarAggregatedYearViewComponent // Comment to fix max-line-length error } from './calendar-views/calendar-aggregated-year-view/calendar-aggregated-year-view.component'; import { Subscription } from 'rxjs'; import { ContentDensityService } from '@fundamental-ngx/core/utils'; let calendarUniqueId = 0; /** Type of calendar */ export type CalendarType = 'single' | 'range'; /** Type for the calendar view */ export type FdCalendarView = 'day' | 'month' | 'year' | 'aggregatedYear'; /** Type for the days of the week. */ export type DaysOfWeek = 1 | 2 | 3 | 4 | 5 | 6 | 7; /** * Months: 1 = January, 12 = december. * Days: 1 = Sunday, 7 = Saturday * * Calendar component used for selecting dates, typically used by the DatePicker and DateTimePicker components. * Supports the Angular forms module, enabling form validity, ngModel, etc. * ```html * <fd-calendar></fd-calendar> * ``` * */ @Component({ selector: 'fd-calendar', templateUrl: './calendar.component.html', styleUrls: ['./calendar.component.scss'], encapsulation: ViewEncapsulation.None, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => CalendarComponent), multi: true }, { provide: NG_VALIDATORS, useExisting: forwardRef(() => CalendarComponent), multi: true }, CalendarService ], host: { '(blur)': 'onTouched()', '[attr.id]': 'id' }, changeDetection: ChangeDetectionStrategy.OnPush }) export class CalendarComponent<D> implements OnInit, ControlValueAccessor, Validator, OnDestroy { /** @hidden */ @ViewChild(CalendarDayViewComponent) dayViewComponent: CalendarDayViewComponent<D>; /** @hidden */ @ViewChild(CalendarYearViewComponent) yearViewComponent: CalendarYearViewComponent<D>; /** @hidden */ @ViewChild(CalendarAggregatedYearViewComponent) aggregatedYearViewComponent: CalendarAggregatedYearViewComponent<D>; /** @hidden */ @HostBinding('class.fd-calendar') fdCalendarClass = true; /** @hidden */ @HostBinding('class.fd-has-display-block') fdHasDisplayBlockClass = true; /** Currently displayed days depending on month and year */ currentlyDisplayed: CalendarCurrent; /** The currently selected date model in single mode. */ @Input() selectedDate: D; /** Whether compact mode should be included into calendar */ @Input() @HostBinding('class.fd-calendar--compact') compact?: boolean; /** * Whether user wants to mark sunday/saturday with `fd-calendar__item--weekend` class */ @Input() markWeekends = true; /** * Whether user wants to show week numbers next to days */ @Input() showWeekNumbers = false; /** Whether calendar is used inside mobile in landscape mode, it also adds close button on right side */ @Input() @HostBinding('class.fd-calendar--mobile-landscape') mobileLandscape = false; /** Whether calendar is used inside mobile in portrait mode */ @Input() @HostBinding('class.fd-calendar--mobile-portrait') mobilePortrait = false; /** The currently selected FdDates model start and end in range mode. */ @Input() selectedRangeDate: DateRange<D>; /** Actually shown active view one of 'day' | 'month' | 'year' */ @Input() activeView: FdCalendarView = 'day'; /** The day of the week the calendar should start on. 1 represents Sunday, 2 is Monday, 3 is Tuesday, and so on. */ @Input() startingDayOfWeek: DaysOfWeek; /** The type of calendar, 'single' for single date selection or 'range' for a range of dates. */ @Input() calType: CalendarType = 'single'; /** Id of the calendar. If none is provided, one will be generated. */ @Input() id = 'fd-calendar-' + calendarUniqueId++; /** * Special days mark, it can be used by passing array of object with * Special day number, list 1-20 [class:`fd-calendar__special-day--{{number}}`] is available there: * https://sap.github.io/fundamental-styles/components/calendar.html calendar special days section * Rule accepts method with D object as a parameter. ex: * `rule: (fdDate: D) => fdDate.getDay() === 1`, which will mark all sundays as special day. */ @Input() specialDaysRules: SpecialDayRule<D>[] = []; /** * Object to customize year grid, * Row, Columns and method to display year can be modified */ @Input() yearGrid: CalendarYearGrid = { rows: 4, cols: 5 }; /** * Object to customize aggregated year grid, * Row, Columns and method to display year can be modified */ @Input() aggregatedYearGrid: CalendarYearGrid = { rows: 4, cols: 3 }; /** * Whether user wants to mark day cells on hover. * Works only on range mode, when start date is selected on Day View. */ @Input() rangeHoverEffect = false; /** Event thrown every time active view is changed */ @Output() readonly activeViewChange: EventEmitter<FdCalendarView> = new EventEmitter<FdCalendarView>(); /** Event thrown every time selected date in single mode is changed */ @Output() readonly selectedDateChange: EventEmitter<D> = new EventEmitter<D>(); /** Event thrown every time selected first or last date in range mode is changed */ @Output() readonly selectedRangeDateChange: EventEmitter<DateRange<D>> = new EventEmitter<DateRange<D>>(); /** Event thrown every time when value is overwritten from outside and throw back isValid */ @Output() readonly isValidDateChange: EventEmitter<boolean> = new EventEmitter<boolean>(); /** Event thrown every time when calendar should be closed */ @Output() readonly closeCalendar: EventEmitter<void> = new EventEmitter<void>(); /** Event thrown, when close button is clicked */ @Output() readonly closeClicked: EventEmitter<void> = new EventEmitter<void>(); /** @hidden */ private _subscriptions = new Subscription(); /** @hidden */ private adapterStartingDayOfWeek: DaysOfWeek; /** @hidden */ onChange: (_: D | DateRange<D>) => void = () => {}; /** @hidden */ onTouched: () => void = () => {}; /** * Function used to disable certain dates in the calendar. * @param date date */ @Input() disableFunction = function (date: D): boolean { return false; }; /** * Function used to disable certain dates in the calendar for the range start selection. * @param date date */ @Input() disableRangeStartFunction = function (date: D): boolean { return false; }; /** * Function used to disable certain dates in the calendar for the range end selection. * @param date date */ @Input() disableRangeEndFunction = function (date: D): boolean { return false; }; /** That allows to define function that should happen, when focus should normally escape of component */ @Input() escapeFocusFunction: Function = (): void => { if (document.getElementById(this.id + '-left-arrow')) { document.getElementById(this.id + '-left-arrow').focus(); } }; /** @hidden */ constructor( private _changeDetectorRef: ChangeDetectorRef, @Optional() private _contentDensityService: ContentDensityService, // Use @Optional to avoid angular injection error message and throw our own which is more precise one @Optional() private _dateTimeAdapter: DatetimeAdapter<D>, @Optional() @Inject(DATE_TIME_FORMATS) private _dateTimeFormats: DateTimeFormats ) { if (!this._dateTimeAdapter) { throw createMissingDateImplementationError('DateTimeAdapter'); } if (!this._dateTimeFormats) { throw createMissingDateImplementationError('DATE_TIME_FORMATS'); } // set default value this.adapterStartingDayOfWeek = (this._dateTimeAdapter.getFirstDayOfWeek() + 1) as DaysOfWeek; this.selectedDate = this._dateTimeAdapter.today(); this._changeDetectorRef.markForCheck(); this._listenToLocaleChanges(); } /** @hidden */ private _listenToLocaleChanges(): void { this._subscriptions.add( this._dateTimeAdapter.localeChanges.subscribe(() => { this.adapterStartingDayOfWeek = (this._dateTimeAdapter.getFirstDayOfWeek() + 1) as DaysOfWeek; this._changeDetectorRef.markForCheck(); }) ); } /** @hidden */ ngOnInit(): void { this._prepareDisplayedView(); if (this.compact === undefined && this._contentDensityService) { this._subscriptions.add( this._contentDensityService._contentDensityListener.subscribe((density) => { this.compact = density !== 'cozy'; }) ); } } getWeekStartDay(): DaysOfWeek { return this.startingDayOfWeek === undefined ? this.adapterStartingDayOfWeek : this.startingDayOfWeek; } /** @hidden */ ngOnDestroy(): void { this._subscriptions.unsubscribe(); } /** * @hidden * Function that provides support for ControlValueAccessor that allows to use [(ngModel)] or forms. */ writeValue(selected: DateRange<D> | D): void { let valid = true; if (this.calType === 'single') { selected = <D>selected; valid = this._dateTimeAdapter.isValid(selected); this.selectedDate = selected; } if (this.calType === 'range' && selected) { selected = <DateRange<D>>selected; if (!this._dateTimeAdapter.isValid(selected.start) || !this._dateTimeAdapter.isValid(selected.end)) { valid = false; } this.selectedRangeDate = { start: selected.start, end: selected.end }; } if (valid) { this._prepareDisplayedView(); } this._changeDetectorRef.detectChanges(); this.isValidDateChange.emit(valid); } /** * @hidden * Function that implements Validator Interface, adds validation support for forms */ validate(control: AbstractControl): { [key: string]: any; } { return this.isModelValid() ? null : { dateValidation: { valid: false } }; } /** @hidden */ registerOnChange(fn: any): void { this.onChange = fn; } /** @hidden */ registerOnTouched(fn: any): void { this.onTouched = fn; } /** @hidden */ setDisabledState?(isDisabled: boolean): void { // Not needed } /** * Method that handle active view change and throws event. */ handleActiveViewChange(activeView: FdCalendarView): void { this.activeView = activeView; this.activeViewChange.emit(activeView); } /** * @hidden * Method that is triggered by events from day view component, when there is selected single date changed */ selectedDateChanged(date: D): void { this.selectedDate = date; this.onChange(date); this.onTouched(); this.selectedDateChange.emit(date); this.closeCalendar.emit(); } /** * @hidden * Method that is triggered by events from day view component, when there is selected range date changed */ selectedRangeDateChanged(dates: DateRange<D>): void { if (dates) { this.selectedRangeDate = { start: dates.start, end: dates.end ? dates.end : dates.start }; this.selectedRangeDateChange.emit(this.selectedRangeDate); this.onChange(this.selectedRangeDate); this.onTouched(); this.closeCalendar.emit(); } } /** Function that handles next arrow icon click, depending on current view it changes month, year or list of years */ handleNextArrowClick(): void { switch (this.activeView) { case 'day': this.displayNextMonth(); break; case 'month': this.displayNextYear(); break; case 'year': this.displayNextYearList(); break; case 'aggregatedYear': this.displayNextYearsList(); break; } this.onTouched(); } /** Function that handles previous arrow icon click, depending on current view it changes month, year or list of years */ handlePreviousArrowClick(): void { switch (this.activeView) { case 'day': this.displayPreviousMonth(); break; case 'month': this.displayPreviousYear(); break; case 'year': this.displayPreviousYearList(); break; case 'aggregatedYear': this.displayPreviousYearsList(); break; } this.onTouched(); } /** Function that allows to switch actual view to next month */ displayNextMonth(): void { if (this.currentlyDisplayed.month === 12) { this.currentlyDisplayed = { year: this.currentlyDisplayed.year + 1, month: 1 }; } else { this.currentlyDisplayed = { year: this.currentlyDisplayed.year, month: this.currentlyDisplayed.month + 1 }; } } /** Function that allows to switch actual view to previous month */ displayPreviousMonth(): void { if (this.currentlyDisplayed.month <= 1) { this.currentlyDisplayed = { year: this.currentlyDisplayed.year - 1, month: 12 }; } else { this.currentlyDisplayed = { year: this.currentlyDisplayed.year, month: this.currentlyDisplayed.month - 1 }; } } /** Function that allows to switch actual view to next year */ displayNextYear(): void { this.currentlyDisplayed = { month: this.currentlyDisplayed.month, year: this.currentlyDisplayed.year + 1 }; } /** Function that allows to switch actual view to previous year */ displayPreviousYear(): void { this.currentlyDisplayed = { month: this.currentlyDisplayed.month, year: this.currentlyDisplayed.year - 1 }; } /** Function that allows to switch actually displayed list of year to next year list*/ displayNextYearList(): void { this.yearViewComponent.loadNextYearList(); } /** Function that allows to switch actually displayed list of year to previous year list*/ displayPreviousYearList(): void { this.yearViewComponent.loadPreviousYearList(); } /** Function that allows to switch actually displayed list of year to next year list*/ displayNextYearsList(): void { this.aggregatedYearViewComponent.loadNextYearsList(); } /** Function that allows to switch actually displayed list of year to previous year list*/ displayPreviousYearsList(): void { this.aggregatedYearViewComponent.loadPreviousYearsList(); } /** * Function that allows to change currently displayed month/year configuration, * which are connected to days displayed */ setCurrentlyDisplayed(date: D): void { if (this._dateTimeAdapter.isValid(date)) { this.currentlyDisplayed = { month: this._dateTimeAdapter.getMonth(date), year: this._dateTimeAdapter.getYear(date) }; } } /** * @hidden * Function that handles changes from month view child component, changes actual view and changes currently displayed month */ handleMonthViewChange(month: number): void { this.currentlyDisplayed = { month: month, year: this.currentlyDisplayed.year }; this.activeView = 'day'; this.activeViewChange.emit(this.activeView); this._changeDetectorRef.detectChanges(); this.dayViewComponent.focusActiveDay(); } selectedYear(yearSelected: number): void { this.activeView = 'day'; this.currentlyDisplayed.year = yearSelected; this._changeDetectorRef.detectChanges(); this.dayViewComponent.focusActiveDay(); } selectedYears(yearsSelected: AggregatedYear): void { this.activeView = 'year'; this.currentlyDisplayed.year = yearsSelected.startYear; this._changeDetectorRef.detectChanges(); } /** Method that provides information if model selected date/dates have properly types and are valid */ isModelValid(): boolean { if (this.calType === 'single') { return this._dateTimeAdapter.isValid(this.selectedDate); } if (this.calType === 'range') { return ( this.selectedRangeDate && this._dateTimeAdapter.isValid(this.selectedRangeDate.start) && this._dateTimeAdapter.isValid(this.selectedRangeDate.end) ); } return false; } /** * @hidden * Method that sets up the currently displayed variables, like shown month and year. * Day grid is based on currently displayed month and year */ private _prepareDisplayedView(): void { if (this.calType === 'single' && this._dateTimeAdapter.isValid(this.selectedDate)) { this.currentlyDisplayed = { year: this._dateTimeAdapter.getYear(this.selectedDate), month: this._dateTimeAdapter.getMonth(this.selectedDate) }; } else if (this.selectedRangeDate && this.selectedRangeDate.start) { this.currentlyDisplayed = { year: this._dateTimeAdapter.getYear(this.selectedRangeDate.start), month: this._dateTimeAdapter.getMonth(this.selectedRangeDate.start) }; } else if (this.selectedRangeDate && this.selectedRangeDate.end) { this.currentlyDisplayed = { year: this._dateTimeAdapter.getYear(this.selectedRangeDate.end), month: this._dateTimeAdapter.getMonth(this.selectedRangeDate.end) }; } else { const today = this._dateTimeAdapter.today(); this.currentlyDisplayed = { year: this._dateTimeAdapter.getYear(today), month: this._dateTimeAdapter.getMonth(today) }; } } }
the_stack
import { Component, ContentChild, ContentChildren, EventEmitter, Input, OnDestroy, Output, QueryList, TemplateRef, AfterContentInit, forwardRef, ElementRef, ViewChild, OnInit, NgZone } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { Subscription, Observable, of, Subject } from 'rxjs'; import { catchError, debounceTime, switchMap } from 'rxjs/operators'; import { get } from '../../../utility/services/object-utility.class'; import { DataTableFilterValueExtractCallback } from '../../models/data-table-filter-value-extract-callback.model'; import { DataTableCellBindEventArgs } from '../../models/data-table-cell-bind-event-args.model'; import { DataTableCellClickEventArgs } from '../../models/data-table-cell-click-event-args.model'; import { DataTableHeaderClickEventArgs } from '../../models/data-table-header-click-event-args.model'; import { DataTableDoubleClickEventArgs } from '../../models/data-table-double-click-event-args.model'; import { DataTableRowClickEventArgs } from '../../models/data-table-row-click-event-args.model'; import { DataTableRow } from '../../models/data-table-row.model'; import { DataTableRequestParams } from '../../models/data-table-request-params.model'; import { DataTableTranslations } from '../../models/data-table-translations.model'; import { DataTableDynamicRowSpanExtractorCallback } from '../../models/data-table-group-field-extractor-callback.model'; import { DataTableQueryResult } from '../../models/data-table-query-result.model'; import { DataTableDataBindCallback } from '../../models/data-table-data-bind-callback.model'; import { DataTableFilterOption } from '../../models/data-table-filter-option.model'; import { DataTableUniqueField } from '../../models/data-table-unique-field.model'; import { DataTableSelectMode } from '../../models/data-table-select-mode.model'; import { DataTableStorageMode } from '../../models/data-table-storage-mode.model'; import { DataTableScrollPoint } from '../../models/data-table-scroll-point.model'; import { DataFetchMode } from '../../models/data-fetch-mode.enum'; import { DataTableColumnComponent } from '../data-table-column/data-table-column.component'; import { DragAndDropService, GlobalRefService } from '../../../utility/utility.module'; import { ValidatorService } from '../../../utility/services/validator.service'; import { DataTableEventStateService } from '../../services/data-table-event.service'; import { DataTableDataStateService } from '../../services/data-table-data-state.service'; import { DataTablePersistenceService } from '../../services/data-table-persistence.service'; import { DataTableConfigService } from '../../services/data-table-config.service'; import { DataTableScrollPositionService } from '../../services/data-table-scroll-position.service'; import { DataTableResourceService } from '../../services/data-table-resource.service'; /** * Data table component; Data table entry component. */ @Component({ selector: 'ng-data-table', templateUrl: './data-table.component.html', providers: [ DataTableConfigService, DataTableEventStateService, DataTablePersistenceService, DataTableDataStateService, DataTableScrollPositionService, DataTableResourceService, { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DataTableComponent), multi: true } ] }) export class DataTableComponent implements OnDestroy, OnInit, AfterContentInit, ControlValueAccessor { private rowSelectChangeSubscription: Subscription; private dataFetchStreamSubscription: Subscription; private scrollPositionSubscription: Subscription; /** * Data table column component collection. */ @ContentChildren(DataTableColumnComponent) public columns: QueryList<DataTableColumnComponent>; /** * Template to display when data row is expanded for detail view. */ @ContentChild('ngDataTableRowExpand', { static: true }) public rowExpandTemplate: TemplateRef<any>; /** * Template to display when data set is empty. */ @ContentChild('ngDataTableNoRecords', { static: true }) public noRecordsTemplate: TemplateRef<any>; /** * Template to display while loading data. */ @ContentChild('ngDataTableLoadingSpinner', { static: true }) public loadingSpinnerTemplate: TemplateRef<any>; /** * Template to display while row is expanding to load detail view. */ @ContentChild('ngDataTableRowExpandLoadingSpinner', { static: true }) public rowExpandLoadingSpinnerTemplate: TemplateRef<any>; /** * Data table self DOM element reference. */ @ViewChild('dataTableElement', { static: true }) public dataTableElement: ElementRef<HTMLDivElement>; // Event handlers /** * Data table initialize event handler. * Triggered after data table initialize. */ @Output() public init: EventEmitter<DataTableComponent>; /** * Row selected state change event handler. * Triggered when table row selected state change. */ @Output() public rowSelectChange: EventEmitter<any | any[]>; /** * Row click event handler. * Triggered when data row is clicked. */ @Output() public rowClick: EventEmitter<DataTableRowClickEventArgs<any>>; /** * Row double click event handler. * Triggered when data row is double clicked. */ @Output() public rowDoubleClick: EventEmitter<DataTableDoubleClickEventArgs<any>>; /** * Header click event handler. * Triggered when header column clicked. */ @Output() public headerClick: EventEmitter<DataTableHeaderClickEventArgs>; /** * All row select change event handler. * Triggered when all row select state changed. */ @Output() public allRowSelectChange: EventEmitter<boolean>; /** * Cell click event handler. * Triggered when clicked on a cell. */ @Output() public cellClick: EventEmitter<DataTableCellClickEventArgs<any>>; /** * Data bound event handler. * Triggered after data bind. */ @Output() public dataBound: EventEmitter<void>; /** * Row bind event handler. * Trigger on each row data bind. */ @Output() public rowBind: EventEmitter<DataTableRow<any>>; /** * Column bind event handler. * Triggered after column data bind. */ @Output() public columnBind: EventEmitter<DataTableColumnComponent>; /** * Cell bind event handler. * Triggered after data table cell data bind. */ @Output() public cellBind: EventEmitter<DataTableCellBindEventArgs<any>>; // Input Events /** * Set data bind event handler callback. This handler is fired on each data fetch request. */ @Input() public set onDataBind(value: DataTableDataBindCallback<any>) { this.dataStateService.onDataBind = value; } /** * Set filter value extract event handler callback. Used to extract filter value collection dynamically when * explicit data bind functionality is used with onDataBind callback. */ @Input() public set onFilterValueExtract(value: DataTableFilterValueExtractCallback) { this.dataStateService.onFilterValueExtract = value; } /** * Set on dynamic row span extract event handler callback. */ @Input() public set onDynamicRowSpanExtract(value: DataTableDynamicRowSpanExtractorCallback<any>) { this.dataStateService.onDynamicRowSpanExtract = value; } // Input parameters /** * Set static data items collection. No need to set data source when static items collection is provided. */ @Input() public set items(value: any[]) { if (!value) { return; } this.eventStateService.staticDataSourceStream.next(value); } /** * Set data source observable. This observable is used to retrieve row data for binding. */ @Input() public set dataSource(source: Observable<any[]>) { this.initDataSource(source); } /** * Set data table unique identifier. */ @Input() public set id(value: string) { if (!ValidatorService.idPatternValidatorExpression.test(value)) { throw Error('Invalid [id] input value. Unique identifier parameter only accept string begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_").'); } this.dataStateService.id = value; } /** * Set persist table state on provided storage mode if true. Depends on storageMode property. */ @Input() public set persistTableState(value: boolean) { this.config.persistTableState = value; } /** * Set storage mode to persist table state. Only applicable when persistTableState is true. */ @Input() public set storageMode(value: DataTableStorageMode) { this.dataTableStateService.storageMode = value; } /** * Set multiple column sortable if true. Only applicable for sortable true columns. */ @Input() public set multiColumnSortable(value: boolean) { this.config.multiColumnSortable = value; } /** * Set table header bar visible if true. */ @Input() public set showHeader(value: boolean) { this.config.showHeader = value; } /** * Set title to be shown in the header. Only applicable when showHeader is true. */ @Input() public set title(value: string) { this.config.title = value; } /** * Set width value in pixels. Can be used to set the width of teh table (responsive if not set). */ @Input() public set width(value: string | number) { this.config.width = value; } /** * Set minimum table content height value in pixels. Can be used to set the minimum height of the table content area. */ @Input() public set minContentHeight(value: string | number) { this.config.minContentHeight = value; } /** * Minimum table content width value in pixels. Can be used to set the minimum width of the table content area. */ @Input() public set minContentWidth(value: string | number) { this.config.minContentWidth = value; } /** * Table content height value in pixels. This configuration can be used to enable table content vertical * scrolling for responsive design. */ @Input() public set contentHeight(value: string | number) { this.config.contentHeight = value; } /** * Show pagination bar if true. Depends on offset and limit values. Trigger dataLoad event with offset * and limit values. */ @Input() public set pageable(value: boolean) { this.config.pageable = value; } /** * Enable scrolling based on-demand data loading functionality if true. Trigger dataLoad event with offset * and limit values when scroll to bottom until data source exhaust. */ @Input() public set loadOnScroll(value: boolean) { this.config.loadOnScroll = value; } /** * Set view height distance ratio to trigger data fetch on scroll. Applicable only when load on scroll mode is enabled. */ @Input() public set loadViewDistanceRatio(value: number) { this.config.loadViewDistanceRatio = value; } /** * Set auto generated index column with row numbering if true. */ @Input() public set showIndexColumn(value: boolean) { this.config.showIndexColumn = value; } /** * Set index column header title. Applicable when showIndexColumn is true. */ @Input() public set indexColumnTitle(value: string) { this.config.indexColumnTitle = value; } /** * Set row select checkbox and select state if true. */ @Input() public set rowSelectable(value: boolean) { this.config.rowSelectable = value; } /** * Data table row select mode. Applicable only when rowSelectable is true. */ @Input() public set selectMode(value: DataTableSelectMode) { this.config.selectMode = value; } /** * Set select all row checkbox on column header visible if true. * Only applicable when showRowSelectCheckbox, rowSelectable is true & item selectMode is multi. */ @Input() public set showRowSelectCheckbox(value: boolean) { this.config.showRowSelectCheckbox = value; } /** * Set select all row checkbox on column header visible if true. * Only applicable when showRowSelectCheckbox, rowSelectable is true & item selectMode is multi. */ @Input() public set showRowSelectAllCheckbox(value: boolean) { this.config.showRowSelectAllCheckbox = value; } /** * Set substitute rows visible if true. Fill with empty rows when row count < limit. */ @Input() public set showSubstituteRows(value: boolean) { this.config.showSubstituteRows = value; } /** * Set row expander visible if true. Render ngDataTableExpand template on expand click. */ @Input() public set expandableRows(value: boolean) { this.config.expandableRows = value; } /** * Set trigger row select on click event if true. Applicable only when rowSelectable is true. */ @Input() public set selectOnRowClick(value: boolean) { this.config.selectOnRowClick = value; } /** * Set expand and render expand template on row click if true. Only applicable when expandableRows is true. */ @Input() public set expandOnRowClick(value: boolean) { this.config.expandOnRowClick = value; } /** * Auto trigger dataLoad event on initialization if true. */ @Input() public set autoFetch(value: boolean) { this.config.autoFetch = value; } /** * Set loading spinner visible if true. Show loading spinner when data fetch operation is triggered. */ @Input() public set showLoadingSpinner(value: boolean) { this.config.showLoadingSpinner = value; } /** * Set select option track by field path which is used to uniquely identify row for selection tracking. * This field support object paths expressions 'root[0].nest'. */ @Input() public set selectTrackBy(value: string) { this.config.selectTrackBy = value; } /** * Set selected row identifier. Select specified row on initial load. * Applicable when row select mode is SINGLE or SINGLE_TOGGLE. */ @Input() public set selectedRow(value: any) { this.dataStateService.selectedRow = value; this.eventStateService.rowSelectChangeStream.emit(this.dataStateService.selectedRow); } /** * Set selected row identifiers collection. Select specified rows on initial load. * Applicable when selectMode is SINGLE or SINGLE_TOGGLE true. */ @Input() public set selectedRows(value: any[]) { this.dataStateService.selectedRows = value || []; this.eventStateService.rowSelectChangeStream.emit(this.dataStateService.selectedRows); } /** * Set filter debounce time in milliseconds. Applicable only when filterDebounce is true. */ @Input() public set filterDebounceTime(value: number) { this.config.filterDebounceTime = value; } /** * Set filter data debounce enabled state with provided filterDebounceTime if true. */ @Input() public set filterDebounce(value: boolean) { this.config.filterDebounce = value; } /** * Set refresh button visible if true. Only applicable when showHeader is true. */ @Input() public set showRefreshButton(value: boolean) { this.config.showRefreshButton = value; } /** * Row selector column width in pixels. Applicable only when showColumnSelector is true. */ @Input() public set showColumnSelector(value: boolean) { this.config.showColumnSelector = value; } /** * Set column selector dropdown width in pixels. Only applicable when showColumnSelector is true. */ @Input() public set columnSelectorWidth(value: number) { this.config.columnSelectorWidth = value; } /** * Set expander column width in pixels. Applicable only when expandableRows is true. */ @Input() public set expanderColumnWidth(value: number | string) { this.config.expanderColumnWidth = value; } /** * Set index column width in pixels. Applicable only when showIndexColumn is true. */ @Input() public set indexColumnWidth(value: number | string) { this.config.indexColumnWidth = value; } /** * Set row selector column width in pixels. Applicable only when showColumnSelector is true. */ @Input() public set selectionColumnWidth(value: number | string) { this.config.selectionColumnWidth = value; } /** * Set translation data object. Used to localize table static label text. */ @Input() public set translations(data: DataTableTranslations) { this.config.translations = data; } /** * Set row expand loading spinner visible if true. Applicable only when row expand is enabled. */ @Input() public set showRowExpandLoadingSpinner(value: boolean) { this.config.showRowExpandLoadingSpinner = value; } /** * Set data offset value (start offset index). Applicable only when pageable is true. */ @Input() public set offset(value: number) { this.config.offset = value; this.eventStateService.dataFetchStream.next(DataFetchMode.SOFT_LOAD); } /** * Set data limit value (page size). Applicable only when pageable is true. */ @Input() public set limit(value: number) { this.config.limit = value; this.eventStateService.dataFetchStream.next(DataFetchMode.SOFT_LOAD); } /** * Set current page number. Auto calculate offset depending on page number, * do not explicitly set offset when page is used. */ @Input() public set page(value: number) { this.offset = (value - 1) * this.config.limit; } /** * Get current page number. */ public get page(): number { return Math.floor(this.config.offset / this.config.limit) + 1; } /** * Get data table header padding in pixels. */ public get headerPadding(): number { return this.config.contentHeight ? this.globalRefService.scrollbarWidth : 0; } /** * Get data loading status. */ public get isLoading(): boolean { return !(this.config.loadOnScroll && this.dataStateService.dataRows.length) && this.config.showLoadingSpinner && this.dataStateService.dataLoading; } constructor( private dragAndDropService: DragAndDropService, private dataTableStateService: DataTablePersistenceService, private globalRefService: GlobalRefService, private eventStateService: DataTableEventStateService, private dataTableResourceService: DataTableResourceService<any>, private zone: NgZone, public dataStateService: DataTableDataStateService, public scrollPositionService: DataTableScrollPositionService, public config: DataTableConfigService ) { this.storageMode = config.storageMode; this.headerClick = this.eventStateService.headerClickStream; this.allRowSelectChange = this.eventStateService.allRowSelectChangeStream; this.rowBind = this.eventStateService.rowBindStream; this.rowClick = this.eventStateService.rowClickStream; this.rowDoubleClick = this.eventStateService.rowDoubleClickStream; this.rowSelectChange = this.eventStateService.rowSelectChangeStream; this.cellBind = this.eventStateService.cellBindStream; this.cellClick = this.eventStateService.cellClickStream; this.init = this.eventStateService.initStream; this.dataBound = this.eventStateService.dataBoundStream; this.columnBind = this.eventStateService.columnBind; } /** * On after data bind event handler * @param queryResult Query result object */ private onAfterDataBind(queryResult: DataTableQueryResult<any>): void { this.dataStateService.itemCount = queryResult.count; this.setDataRows(queryResult.items); if (this.dataStateService.heardReload) { this.eventStateService.fetchFilterOptionsStream.next(false); this.dataStateService.heardReload = false; } this.dataStateService.dataLoading = false; this.eventStateService.dataBoundStream.emit(); } /** * Get data item selected state * @param item Data item object * @return True if item is selected */ private getSelectedState(item: any): boolean { const id = get(item, this.config.selectTrackBy); if (id === undefined) { return false; } if (this.config.selectMode === 'multi') { return this.dataStateService.selectedRows.indexOf(id) > -1; } return this.dataStateService.selectedRow === id; } /** * Set data table item collection * @param items Data table item collection */ private setDataRows(items: any[]): void { const mappedItems = items.map((item: any, index: number) => { let currentIndex; if (this.config.loadOnScroll || this.config.pageable) { currentIndex = this.config.offset + index + 1; } else { currentIndex = index + 1; } return { dataLoaded: false, expanded: false, disabled: false, color: '', cssClass: '', tooltip: '', index: currentIndex, item, selected: this.getSelectedState(item) }; }); if (this.config.loadOnScroll) { this.dataStateService.dataRows = [ ...this.dataStateService.dataRows, ...mappedItems ]; } else { this.dataStateService.dataRows = mappedItems; } if (this.config.selectMode === 'multi') { this.dataStateService.allRowSelected = this.dataStateService.dataRows.length !== 0 && this.dataStateService.dataRows.every((dataRow: DataTableRow<any>) => { return dataRow.selected; }); } if (!this.config.loadOnScroll) { const substituteRowCount = this.config.limit - this.dataStateService.dataRows.length; this.dataStateService.substituteRows = Array.from({ length: substituteRowCount }); } } /** * Initialize data fetch event */ private initDataFetchEvent(): void { const noop = { items: [], count: 0 }; this.dataFetchStreamSubscription = this.eventStateService.dataFetchStream .pipe( debounceTime(20), switchMap((fetchMode: DataFetchMode) => this.mapDataBind(fetchMode)), catchError(() => { return of(noop); }) ) .subscribe( (queryResult: DataTableQueryResult<any>) => { this.onAfterDataBind(queryResult); }, () => { this.onAfterDataBind(noop); } ); } /** * Re-map data binding data * @param fetchMode Data fetch mode * @return Data table query result stream */ private mapDataBind(fetchMode: DataFetchMode): Observable<DataTableQueryResult<any>> { this.dataStateService.dataLoading = true; if (fetchMode === DataFetchMode.HARD_RELOAD) { this.clearRowSelectState(); this.clearColumnState(); this.dataStateService.heardReload = true; this.config.offset = 0; } const params: DataTableRequestParams = { loadData: fetchMode === DataFetchMode.HARD_RELOAD || fetchMode === DataFetchMode.SOFT_RELOAD }; if (this.columns) { params.fields = this.columns .filter(column => { return column.sortable || column.filterable; }) .reduce((acc: DataTableUniqueField[], column: DataTableColumnComponent) => { if (column.sortField || column.filterField) { acc.push({ field: column.sortField || column.filterField, column }); } else { acc.push({ field: column.field, column }); } return acc; }, []) .map((uniqueField: DataTableUniqueField) => { let filter; if (uniqueField.column.showDropdownFilter) { if (uniqueField.column.dropdownFilterSelectMode === 'multi') { filter = uniqueField.column.filter && uniqueField.column.filter.map(filterValue => filterValue.key); } else { filter = uniqueField.column.filter && uniqueField.column.filter.key; } } else { filter = uniqueField.column.filter; } return { field: uniqueField.field, sortable: uniqueField.column.sortable, sortOrder: uniqueField.column.sortOrder, sortPriority: uniqueField.column.sortPriority || (uniqueField.column.sortOrder ? 1 : 0), filterable: uniqueField.column.filterable, filterValue: filter, filterExpression: uniqueField.column.filterExpression, }; }); } if (this.config.pageable || this.config.loadOnScroll) { params.offset = this.config.offset; params.limit = this.config.limit; } if (this.config.persistTableState) { this.dataTableStateService.setState(this.dataStateService.id, params); } return this.dataStateService.onDataBind(params); } /** * Initialize data table state via previous state snapshot; Applicable only when persist table state is enabled */ private initDataTableState(): void { if (this.config.persistTableState) { const dataTableState = this.dataTableStateService.getState(this.dataStateService.id); if (dataTableState) { this.columns.forEach(column => { const field = dataTableState.fields.find(col => { return col.field === column.field; }); if (field) { if (column.filterable && field.filterable) { if (column.showDropdownFilter) { if (field.filterValue) { if (column.dropdownFilterSelectMode === 'multi') { column.filter = field.filterValue.map((filterValue) => { return { key: filterValue, value: filterValue }; }); } else { column.filter = { key: field.filterValue, value: field.filterValue }; } } } else { column.filter = field.filterValue; } } if (column.sortable && field.sortable) { column.sortOrder = field.sortOrder; } } }); this.config.limit = dataTableState.limit; this.config.offset = dataTableState.offset; } } } /** * After component initialize lifecycle event handler */ public ngAfterContentInit(): void { this.dataStateService.relativeParentElement = this.dataTableElement.nativeElement; if (!this.dataStateService.onDataBind) { this.dataSource = this.eventStateService.staticDataSourceStream; } this.initDataTableState(); this.initDataFetchEvent(); if (this.config.autoFetch) { this.eventStateService.dataFetchStream.next(DataFetchMode.SOFT_LOAD); } this.eventStateService.fetchFilterOptionsStream.next(true); this.eventStateService.initStream.emit(this); if (this.config.loadOnScroll) { this.scrollPositionSubscription = this.scrollPositionService.scrollPositionStream.subscribe((pos: DataTableScrollPoint) => { const roundingPixel = 1; const gutterPixel = 1; if ( pos.isVertical && pos.scrollTop >= pos.scrollHeight - (1 + this.config.loadViewDistanceRatio) * pos.clientHeight - roundingPixel - gutterPixel && (this.config.offset + this.config.limit) < this.dataStateService.itemCount && !this.dataStateService.dataLoading ) { this.dataStateService.dataLoading = true; this.zone.run(() => { this.offset = this.config.offset + this.config.limit; }); } }); } } /** * Reset column sort and filter state */ private clearColumnState(): void { this.columns.forEach((column: DataTableColumnComponent) => { column.resetSortOrder(); column.filter = undefined; }); } /** * Clear selected data row status */ private clearRowSelectState(): void { this.dataStateService.selectedRow = undefined; this.dataStateService.selectedRows = []; this.dataStateService.allRowSelected = false; } /** * Fetch data from data source * @param fetchMode Data fetch mode */ public fetchData(fetchMode: DataFetchMode = DataFetchMode.SOFT_RELOAD): void { this.eventStateService.dataFetchStream.next(fetchMode); } /** * Initialize data source * @param source Data source stream */ public initDataSource(source: Observable<any>): void { this.dataTableResourceService.setDataSource(source); this.onDataBind = (params: DataTableRequestParams): Observable<DataTableQueryResult<any>> => { if (params.loadData) { this.dataTableResourceService.setDataSource(source); } return this.dataTableResourceService.query(params); }; this.onFilterValueExtract = (column: DataTableColumnComponent): Observable<DataTableFilterOption[]> => { return this.dataTableResourceService.extractFilterOptions(column); }; } /** * Component value write event handler; Form control support implementation */ public writeValue(value: any): void { if (this.config.selectMode === 'multi') { this.selectedRows = value; } else { this.selectedRow = value; } } /** * Register select change event handler; Form control support implementation * @param onSelectChange Select change event handler callback */ public registerOnChange(onSelectChange: (value: any) => void): void { this.rowSelectChangeSubscription = this.eventStateService.rowSelectChangeStream.subscribe((selectedIds: any | any[]) => { onSelectChange(selectedIds); }); } /** * Register on touch event handler; Form control support implementation * @param fn Touch event callback handler */ public registerOnTouched(fn: any): void {} /** * Get table width in pixels */ public get tableWidth(): number { return this.config.width || this.dataStateService.tableWidth; } public ngOnInit(): void { if (!this.dataStateService.id) { throw Error('Missing required parameter value for [id] input.'); } if (this.config.loadOnScroll) { if (!this.config.minContentHeight) { throw Error('[minContentHeight] is required when [infiniteScrollable] is enabled.'); } if (this.config.pageable) { throw Error('[pageable] and [infiniteScrollable] cannot be enabled at the same time.'); } } } /** * Component destroy lifecycle event handler */ public ngOnDestroy(): void { if (this.dataFetchStreamSubscription) { this.dataFetchStreamSubscription.unsubscribe(); } if (this.rowSelectChangeSubscription) { this.rowSelectChangeSubscription.unsubscribe(); } if (this.scrollPositionSubscription) { this.scrollPositionSubscription.unsubscribe(); } this.dataTableResourceService.dispose(); } }
the_stack
import * as vscode from "vscode"; import { pickClient, pickConsumerGroupId, pickTopic } from "./common"; import { ConsumerCollection, ClientAccessor, createConsumerUri, ConsumerInfoUri, ConsumerLaunchState } from "../client"; import { KafkaExplorer } from "../explorer"; import { ConsumerVirtualTextDocumentProvider } from "../providers"; import { ProgressLocation, window } from "vscode"; import { getErrorMessage } from "../errors"; import { ConsumerValidator } from "../validators/consumer"; export interface LaunchConsumerCommand extends ConsumerInfoUri { } /** * Start or stop a consumer. */ abstract class LaunchConsumerCommandHandler { constructor( private clientAccessor: ClientAccessor, private consumerCollection: ConsumerCollection, private explorer: KafkaExplorer, private start: boolean ) { } async execute(command?: LaunchConsumerCommand): Promise<void> { if (!command) { const client = await pickClient(this.clientAccessor); if (!client) { return; } const topic = await pickTopic(client); if (topic === undefined) { return; } const clusterId = client.cluster.id; const topicId = topic.id; command = { clusterId, consumerGroupId: `vscode-kafka-${clusterId}-${topicId}`, topicId }; } if (!command.consumerGroupId) { const { clusterId, topicId } = command; command.consumerGroupId = `vscode-kafka-${clusterId}-${topicId}`; } try { const consumer = this.consumerCollection.getByConsumerGroupId(command.clusterId, command.consumerGroupId); if (this.start) { // Try to start consumer if (consumer) { // The consumer is already started, just open the document which tracks consumer messages. const consumeUri = createConsumerUri(command); openDocument(consumeUri); return; } // Validate start command ConsumerValidator.validate(command); // Open the document which tracks consumer messages. const consumeUri = createConsumerUri(command); openDocument(consumeUri); // Start the consumer await startConsumerWithProgress(consumeUri, this.consumerCollection, this.explorer); } else { // Stop the consumer if (consumer) { const consumeUri = consumer.uri; await stopConsumerWithProgress(consumeUri, this.consumerCollection, this.explorer); } } } catch (e) { vscode.window.showErrorMessage(`Error while ${this.start ? 'starting' : 'stopping'} the consumer: ${getErrorMessage(e)}`); } } } export class StartConsumerCommandHandler extends LaunchConsumerCommandHandler { public static commandId = 'vscode-kafka.consumer.start'; constructor( clientAccessor: ClientAccessor, consumerCollection: ConsumerCollection, explorer: KafkaExplorer ) { super(clientAccessor, consumerCollection, explorer, true); } } export class StopConsumerCommandHandler extends LaunchConsumerCommandHandler { public static commandId = 'vscode-kafka.consumer.stop'; constructor( clientAccessor: ClientAccessor, consumerCollection: ConsumerCollection, explorer: KafkaExplorer ) { super(clientAccessor, consumerCollection, explorer, false); } } export class ToggleConsumerCommandHandler { public static commandId = 'vscode-kafka.consumer.toggle'; constructor(private consumerCollection: ConsumerCollection) { } async execute(): Promise<void> { if (!vscode.window.activeTextEditor) { return; } const { uri } = vscode.window.activeTextEditor.document; if (uri.scheme !== "kafka") { return; } const started = this.consumerCollection.has(uri); try { if (started) { await stopConsumerWithProgress(uri, this.consumerCollection); } else { await startConsumerWithProgress(uri, this.consumerCollection); } } catch (e) { vscode.window.showErrorMessage(`Error while ${!started ? 'starting' : 'stopping'} the consumer: ${getErrorMessage(e)}`); } } } export class ClearConsumerViewCommandHandler { public static commandId = 'vscode-kafka.consumer.clear'; constructor(private provider: ConsumerVirtualTextDocumentProvider) { } async execute(): Promise<void> { if (!vscode.window.activeTextEditor) { return; } const { document } = vscode.window.activeTextEditor; if (document.uri.scheme !== "kafka") { return; } this.provider.clear(document); } } enum ConsumerOption { // eslint-disable-next-line @typescript-eslint/naming-convention Open, // eslint-disable-next-line @typescript-eslint/naming-convention Close, } export class ListConsumersCommandHandler { private static optionQuickPickItems = [ { label: "Open existing", option: ConsumerOption.Open, }, { label: "Close", option: ConsumerOption.Close, }, ]; constructor(private consumerCollection: ConsumerCollection) { } async execute(): Promise<void> { const consumers = this.consumerCollection.getAll(); const consumerQuickPickItems = consumers.map((c) => { return { label: c.options.topicId, description: c.options.bootstrap, uri: c.uri, }; }); const pickedConsumer = await vscode.window.showQuickPick(consumerQuickPickItems); if (!pickedConsumer) { return; } const pickedOption = await vscode.window.showQuickPick(ListConsumersCommandHandler.optionQuickPickItems); if (!pickedOption) { return; } switch (pickedOption.option) { case ConsumerOption.Open: openDocument(pickedConsumer.uri); break; case ConsumerOption.Close: this.consumerCollection.close(pickedConsumer.uri); break; } } } export interface DeleteConsumerGroupCommand { clusterId: string; consumerGroupId: string; } export class DeleteConsumerGroupCommandHandler { public static commandId = 'vscode-kafka.consumer.deletegroup'; constructor( private clientAccessor: ClientAccessor, private explorer: KafkaExplorer ) { } async execute(command?: DeleteConsumerGroupCommand): Promise<void> { const client = await pickClient(this.clientAccessor, command?.clusterId); if (!client) { return; } const consumerGroupToDelete: string | undefined = command?.consumerGroupId || await pickConsumerGroupId(client); if (!consumerGroupToDelete) { return; } try { const warning = `Are you sure you want to delete consumer group '${consumerGroupToDelete}'?`; const deleteConfirmation = await vscode.window.showWarningMessage(warning, 'Cancel', 'Delete'); if (deleteConfirmation !== 'Delete') { return; } await client.deleteConsumerGroups([consumerGroupToDelete]); this.explorer.refresh(); vscode.window.showInformationMessage(`Consumer group '${consumerGroupToDelete}' deleted successfully`); } catch (error) { if (error.message) { vscode.window.showErrorMessage(error.message); } else { vscode.window.showErrorMessage(error); } } } } async function startConsumerWithProgress(consumeUri: vscode.Uri, consumerCollection: ConsumerCollection, explorer?: KafkaExplorer) { const consumer = consumerCollection.get(consumeUri); if (consumer && consumer.state === ConsumerLaunchState.closing) { vscode.window.showErrorMessage(`The consumer cannot be started because it is stopping.`); return; } await window.withProgress({ location: ProgressLocation.Window, title: `Starting consumer '${consumeUri}'.`, cancellable: false }, (progress, token) => { return new Promise((resolve, reject) => { consumerCollection.create(consumeUri) .then(consumer => { if (explorer) { explorer.refresh(); } resolve(consumer); }) .catch(error => reject(error)); }); }); } async function stopConsumerWithProgress(consumeUri: vscode.Uri, consumerCollection: ConsumerCollection, explorer?: KafkaExplorer) { const consumer = consumerCollection.get(consumeUri); if (consumer && consumer.state === ConsumerLaunchState.starting) { vscode.window.showErrorMessage(`The consumer cannot be stopped because it is starting.`); return; } await window.withProgress({ location: ProgressLocation.Window, title: `Stopping consumer '${consumeUri}'.`, cancellable: false }, (progress, token) => { return new Promise((resolve, reject) => { consumerCollection.close(consumeUri) .then(() => { if (explorer) { explorer.refresh(); } resolve(true); }) .catch(error => reject(error)); }); }); } async function openDocument(uri: vscode.Uri): Promise<void> { const visibleConsumerEditor = vscode.window.visibleTextEditors.find(te => te.document.uri.toString() === uri.toString()); if (visibleConsumerEditor) { //Document already exists and is active, nothing to do return; } // Then we check if the document is already open const docs = vscode.workspace.textDocuments; let document: vscode.TextDocument | undefined = docs.find(doc => doc.uri.toString() === uri.toString()); // If there's no document we open it if (!document) { document = await vscode.workspace.openTextDocument(uri); } // Check if there's an active editor, to later decide in which column the consumer // view will be opened const hasActiveEditor = !!vscode.window.activeTextEditor; // Finally reveal the document // // Caveat #1: For documents opened programatically, then closed from the UI, // VS Code doesn't instantly trigger onDidCloseTextDocument, so there's a // chance the document instance we just retrieved doesn't correspond to an // actual TextEditor. // See https://github.com/microsoft/vscode/issues/15178 // // Caveat #2: if a document is opened in a different panel, it's not revealed. // Instead, a new TextEditor instance is added to the active panel. This is the // default vscode behavior await vscode.window.showTextDocument( document, { preview: false, preserveFocus: true, viewColumn: hasActiveEditor ? vscode.ViewColumn.Beside : vscode.ViewColumn.Active, } ); await vscode.languages.setTextDocumentLanguage(document, "kafka-consumer"); }
the_stack
import { Route, RouteConfig } from 'vue-router'; import { Routes } from './routes'; import { QueryParams } from './params'; import CassQueryView from '@/views/cassandra/query/CassQueryView.vue'; export const cassandraRoutes: RouteConfig = { path: '/cassandra', redirect: { name: Routes.CassandraClusters }, component: () => import( /* webpackChunkName: 'cassandra' */ '@/views/cassandra/CassView.vue' ), children: [ { path: '/', redirect: { name: Routes.CassandraClusters, }, }, { path: 'clusters', name: Routes.CassandraClusters, props: { type: 'cassandra', clusterRouteName: Routes.CassandraKeyspaces, }, component: () => import( /* webpackChunkName: 'common' */ '@/components/common/DatastoreOverview.vue' ), meta: { breadcrumbText: 'C* Clusters', }, }, { path: 'clusters/:clusterName', redirect: { name: Routes.CassandraKeyspaces }, }, { path: 'clusters/:clusterName/explore', component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassExploreView.vue' ), props: true, meta: { breadcrumbText: (route) => route.params.clusterName, }, children: [ { path: '', name: Routes.CassandraKeyspaces, props: true, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassKeyspacesView.vue' ), meta: { breadcrumbText: 'All Keyspaces', }, children: [ { path: '_create', props: true, name: Routes.CassandraKeyspaceCreate, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassCreateKeyspaceView.vue' ), }, ], }, { path: ':keyspaceName', props: true, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassKeyspaceDetailsView.vue' ), meta: { breadcrumbText: (route) => route.params.keyspaceName, }, children: [ { path: '/', props: true, name: Routes.CassandraKeyspace, redirect: { name: Routes.CassandraKeyspaceTables }, }, { path: 'tables', props: true, name: Routes.CassandraKeyspaceTables, component: () => import( /* webpackChunkName: "cassandra-explore" */ '@/views/cassandra/explore/CassKeyspaceTablesView.vue' ), }, { path: 'udts/:udtName?', name: Routes.CassandraKeyspaceUDTs, props: true, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassKeyspaceUdtsView.vue' ), }, ], }, { path: ':keyspaceName/_create', props: true, name: Routes.CassandraTableCreate, component: () => import( /* webpackChunkName: 'cassandra-create-table' */ '@/views/cassandra/explore/CassCreateTableView.vue' ), }, { path: ':keyspaceName/_createAdvanced', props: (route) => ({ ...route.params, statement: route.query.statement, }), name: Routes.CassandraTableCreateAdvanced, component: () => import( /* webpackChunkName: 'cassandra-create-table' */ '@/views/cassandra/explore/CassCreateTableAdvancedView.vue' ), }, { path: ':keyspaceName/tables/:tableName', props: true, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassTableView.vue' ), meta: { breadcrumbText: (route) => `${route.params.keyspaceName} | ${route.params.tableName}`, }, children: [ { path: '/', redirect: { name: Routes.CassandraTableData }, }, { path: 'data', name: Routes.CassandraTableData, props: true, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassTableDataView.vue' ), children: [ { path: '_create', name: Routes.CassandraTableDataCreate, props: (route: Route): any => { return { create: true, cluster: route.params.clusterName, keyspace: route.params.keyspaceName, table: route.params.tableName, }; }, component: () => import( /* webpackChunkName: 'cassandra-explore-edit' */ '@/views/cassandra/explore/CassAddRowDialog.vue' ), }, { path: 'row', name: Routes.CassandraTableDataEdit, props: (route: Route): any => { const primaryKey = route.query[QueryParams.PrimaryKey]; return { cluster: route.params.clusterName, keyspace: route.params.keyspaceName, table: route.params.tableName, primaryKey: primaryKey ? JSON.parse(primaryKey as string) : {}, }; }, component: () => import( /* webpackChunkName: 'cassandra-explore-edit' */ '@/views/cassandra/explore/CassEditRowDialog.vue' ), }, { path: 'drop', name: Routes.CassandraTableDrop, props: (route) => ({ ...route.params, mode: 'drop', }), component: () => import( /* webpackChunkName: 'cassandra-explore-drop' */ '@/views/cassandra/explore/CassDropTableDialog.vue' ), }, { path: 'truncate', name: Routes.CassandraTableTruncate, props: (route) => ({ ...route.params, mode: 'truncate', }), component: () => import( /* webpackChunkName: 'cassandra-explore-drop' */ '@/views/cassandra/explore/CassDropTableDialog.vue' ), }, ], }, { path: 'columns', name: Routes.CassandraTableColumns, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassTableColumnsView.vue' ), }, { path: 'properties', name: Routes.CassandraTableProperties, props: { disabled: true, }, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassTablePropertiesView.vue' ), }, { path: 'samples', name: Routes.CassandraTableSamples, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassTableSampleQueriesView.vue' ), }, { path: 'activity', name: Routes.CassandraTableActivity, props: true, component: () => import( /* webpackChunkName: 'cassandra-explore' */ '@/views/cassandra/explore/CassTableActivityView.vue' ), }, ], }, { path: ':keyspaceName/*', redirect: { name: Routes.CassandraKeyspace }, }, ], }, { path: 'clusters/:clusterName/query', name: Routes.CassandraQuery, component: CassQueryView, // avoid asynchronously loading the query view as it doesn't play well with ace props: true, meta: { breadcrumbText: (route) => `${route.params.clusterName} | Query`, }, children: [ { path: '_create', name: Routes.CassandraQueryDataCreate, props: (route: Route): any => { const { params, query } = route; const { encoding, keyspace, table } = query; return { create: true, cluster: params.clusterName, keyspace, table, encoding, }; }, component: () => import( /* webpackChunkName: 'cassandra-query-edit' */ '@/views/cassandra/explore/CassAddRowDialog.vue' ), }, { path: 'row', name: Routes.CassandraQueryDataEdit, props: (route: Route): any => { const primaryKey = route.query[QueryParams.PrimaryKey]; return { cluster: route.params.clusterName, keyspace: route.query.keyspace, table: route.query.table, primaryKey: primaryKey ? JSON.parse(primaryKey as string) : {}, }; }, component: () => import( /* webpackChunkName: 'cassandra-query-edit' */ '@/views/cassandra/explore/CassEditRowDialog.vue' ), }, ], }, ], };
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { BatchExecuteStatementCommand, BatchExecuteStatementCommandInput, BatchExecuteStatementCommandOutput, } from "./commands/BatchExecuteStatementCommand"; import { BeginTransactionCommand, BeginTransactionCommandInput, BeginTransactionCommandOutput, } from "./commands/BeginTransactionCommand"; import { CommitTransactionCommand, CommitTransactionCommandInput, CommitTransactionCommandOutput, } from "./commands/CommitTransactionCommand"; import { ExecuteSqlCommand, ExecuteSqlCommandInput, ExecuteSqlCommandOutput } from "./commands/ExecuteSqlCommand"; import { ExecuteStatementCommand, ExecuteStatementCommandInput, ExecuteStatementCommandOutput, } from "./commands/ExecuteStatementCommand"; import { RollbackTransactionCommand, RollbackTransactionCommandInput, RollbackTransactionCommandOutput, } from "./commands/RollbackTransactionCommand"; import { RDSDataClient } from "./RDSDataClient"; /** * <fullname>Amazon RDS Data Service</fullname> * <p>Amazon RDS provides an HTTP endpoint to run SQL statements on an Amazon Aurora * Serverless DB cluster. To run these statements, you work with the Data Service * API.</p> * <p>For more information about the Data Service API, see <a href="https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html">Using the Data API for Aurora * Serverless</a> in the <i>Amazon Aurora User Guide</i>.</p> */ export class RDSData extends RDSDataClient { /** * <p>Runs a batch SQL statement over an array of data.</p> * <p>You can run bulk update and insert operations for multiple records using a DML * statement with different parameter sets. Bulk operations can provide a significant * performance improvement over individual insert and update operations.</p> * <important> * <p>If a call isn't part of a transaction because it doesn't include the * <code>transactionID</code> parameter, changes that result from the call are * committed automatically.</p> * </important> */ public batchExecuteStatement( args: BatchExecuteStatementCommandInput, options?: __HttpHandlerOptions ): Promise<BatchExecuteStatementCommandOutput>; public batchExecuteStatement( args: BatchExecuteStatementCommandInput, cb: (err: any, data?: BatchExecuteStatementCommandOutput) => void ): void; public batchExecuteStatement( args: BatchExecuteStatementCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BatchExecuteStatementCommandOutput) => void ): void; public batchExecuteStatement( args: BatchExecuteStatementCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BatchExecuteStatementCommandOutput) => void), cb?: (err: any, data?: BatchExecuteStatementCommandOutput) => void ): Promise<BatchExecuteStatementCommandOutput> | void { const command = new BatchExecuteStatementCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Starts a SQL transaction.</p> * * <important> * <p>A transaction can run for a maximum of 24 hours. A transaction is terminated and * rolled back automatically after 24 hours.</p> * <p>A transaction times out if no calls use its transaction ID in three minutes. * If a transaction times out before it's committed, it's rolled back * automatically.</p> * <p>DDL statements inside a transaction cause an implicit commit. We recommend * that you run each DDL statement in a separate <code>ExecuteStatement</code> call with * <code>continueAfterTimeout</code> enabled.</p> * </important> */ public beginTransaction( args: BeginTransactionCommandInput, options?: __HttpHandlerOptions ): Promise<BeginTransactionCommandOutput>; public beginTransaction( args: BeginTransactionCommandInput, cb: (err: any, data?: BeginTransactionCommandOutput) => void ): void; public beginTransaction( args: BeginTransactionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: BeginTransactionCommandOutput) => void ): void; public beginTransaction( args: BeginTransactionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: BeginTransactionCommandOutput) => void), cb?: (err: any, data?: BeginTransactionCommandOutput) => void ): Promise<BeginTransactionCommandOutput> | void { const command = new BeginTransactionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Ends a SQL transaction started with the <code>BeginTransaction</code> operation and * commits the changes.</p> */ public commitTransaction( args: CommitTransactionCommandInput, options?: __HttpHandlerOptions ): Promise<CommitTransactionCommandOutput>; public commitTransaction( args: CommitTransactionCommandInput, cb: (err: any, data?: CommitTransactionCommandOutput) => void ): void; public commitTransaction( args: CommitTransactionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CommitTransactionCommandOutput) => void ): void; public commitTransaction( args: CommitTransactionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CommitTransactionCommandOutput) => void), cb?: (err: any, data?: CommitTransactionCommandOutput) => void ): Promise<CommitTransactionCommandOutput> | void { const command = new CommitTransactionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * @deprecated * * <p>Runs one or more SQL statements.</p> * <important> * <p>This operation is deprecated. Use the <code>BatchExecuteStatement</code> or * <code>ExecuteStatement</code> operation.</p> * </important> */ public executeSql(args: ExecuteSqlCommandInput, options?: __HttpHandlerOptions): Promise<ExecuteSqlCommandOutput>; public executeSql(args: ExecuteSqlCommandInput, cb: (err: any, data?: ExecuteSqlCommandOutput) => void): void; public executeSql( args: ExecuteSqlCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ExecuteSqlCommandOutput) => void ): void; public executeSql( args: ExecuteSqlCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ExecuteSqlCommandOutput) => void), cb?: (err: any, data?: ExecuteSqlCommandOutput) => void ): Promise<ExecuteSqlCommandOutput> | void { const command = new ExecuteSqlCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Runs a SQL statement against a database.</p> * <important> * <p>If a call isn't part of a transaction because it doesn't include the * <code>transactionID</code> parameter, changes that result from the call are * committed automatically.</p> * </important> * <p>The response size limit is 1 MB. If the call returns more than 1 MB of response data, the call is terminated.</p> */ public executeStatement( args: ExecuteStatementCommandInput, options?: __HttpHandlerOptions ): Promise<ExecuteStatementCommandOutput>; public executeStatement( args: ExecuteStatementCommandInput, cb: (err: any, data?: ExecuteStatementCommandOutput) => void ): void; public executeStatement( args: ExecuteStatementCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ExecuteStatementCommandOutput) => void ): void; public executeStatement( args: ExecuteStatementCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ExecuteStatementCommandOutput) => void), cb?: (err: any, data?: ExecuteStatementCommandOutput) => void ): Promise<ExecuteStatementCommandOutput> | void { const command = new ExecuteStatementCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Performs a rollback of a transaction. Rolling back a transaction cancels its changes.</p> */ public rollbackTransaction( args: RollbackTransactionCommandInput, options?: __HttpHandlerOptions ): Promise<RollbackTransactionCommandOutput>; public rollbackTransaction( args: RollbackTransactionCommandInput, cb: (err: any, data?: RollbackTransactionCommandOutput) => void ): void; public rollbackTransaction( args: RollbackTransactionCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RollbackTransactionCommandOutput) => void ): void; public rollbackTransaction( args: RollbackTransactionCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RollbackTransactionCommandOutput) => void), cb?: (err: any, data?: RollbackTransactionCommandOutput) => void ): Promise<RollbackTransactionCommandOutput> | void { const command = new RollbackTransactionCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { Component, AfterViewInit, ViewChild, OnDestroy, NgZone, ChangeDetectorRef, } from '@angular/core'; import { Project } from '../../shared/models/project.model'; import { Feature, LocationFeature, GeoJsonFeature, PolygonFeature, } from '../../shared/models/feature.model'; import { DrawingToolsService, EditMode, } from '../../services/drawing-tools/drawing-tools.service'; import { ProjectService } from '../../services/project/project.service'; import { FeatureService } from '../../services/feature/feature.service'; import { combineLatest, Observable, Subscription } from 'rxjs'; import { List } from 'immutable'; import { getPinImageSource } from './ground-pin'; import { NavigationService } from '../../services/navigation/navigation.service'; import { GoogleMap } from '@angular/google-maps'; import firebase from 'firebase/app'; import { MatDialog } from '@angular/material/dialog'; import { FeatureData, SelectFeatureDialogComponent, } from '../select-feature-dialog/select-feature-dialog.component'; // To make ESLint happy: /*global google*/ const normalIconScale = 30; const enlargedIconScale = 50; const zoomedInLevel = 13; const normalPolygonStrokeWeight = 3; const enlargedPolygonStrokeWeight = 6; @Component({ selector: 'ground-map', templateUrl: './map.component.html', styleUrls: ['./map.component.scss'], }) export class MapComponent implements AfterViewInit, OnDestroy { private subscription: Subscription = new Subscription(); features$: Observable<List<Feature>>; activeProject$: Observable<Project>; private initialMapOptions: google.maps.MapOptions = { center: new google.maps.LatLng(40.767716, -73.971714), zoom: 3, fullscreenControl: false, mapTypeControl: false, streetViewControl: false, mapTypeId: google.maps.MapTypeId.HYBRID, }; private selectedMarker?: google.maps.Marker; private selectedPolygon?: google.maps.Polygon; private markers: Map<string, google.maps.Marker> = new Map< string, google.maps.Marker >(); private polygons: Map<string, google.maps.Polygon> = new Map< string, google.maps.Polygon >(); private crosshairCursorMapOptions: google.maps.MapOptions = { draggableCursor: 'crosshair', }; private defaultCursorMapOptions: google.maps.MapOptions = { draggableCursor: '', }; mapOptions: google.maps.MapOptions = this.initialMapOptions; showRepositionConfirmDialog = false; newFeatureToReposition?: LocationFeature; oldLatLng?: google.maps.LatLng; newLatLng?: google.maps.LatLng; markerToReposition?: google.maps.Marker; disableMapClicks = false; @ViewChild(GoogleMap) map!: GoogleMap; constructor( private drawingToolsService: DrawingToolsService, private projectService: ProjectService, private featureService: FeatureService, private navigationService: NavigationService, private zone: NgZone, private changeDetectorRef: ChangeDetectorRef, private dialog: MatDialog ) { this.features$ = this.featureService.getFeatures$(); this.activeProject$ = this.projectService.getActiveProject$(); } ngAfterViewInit() { this.subscription.add( combineLatest([ this.activeProject$, this.features$, this.navigationService.getFeatureId$(), ]).subscribe(([project, features, selectedFeatureId]) => this.onProjectAndFeaturesUpdate(project, features, selectedFeatureId) ) ); this.subscription.add( this.drawingToolsService .getEditMode$() .subscribe(editMode => this.onEditModeChange(editMode)) ); this.subscription.add( combineLatest([ this.navigationService.getFeatureId$(), this.navigationService.getObservationId$(), ]).subscribe(() => this.cancelReposition()) ); } ngOnDestroy() { this.subscription.unsubscribe(); } async onMapClick(event: google.maps.MouseEvent) { if (this.disableMapClicks) { return; } const editMode = this.drawingToolsService.getEditMode$().getValue(); const selectedLayerId = this.drawingToolsService.getSelectedLayerId(); switch (editMode) { case EditMode.AddPoint: { if (!selectedLayerId) { return; } this.drawingToolsService.setEditMode(EditMode.None); const newFeature = await this.featureService.addPoint( event.latLng.lat(), event.latLng.lng(), selectedLayerId ); if (newFeature) { this.navigationService.selectFeature(newFeature.id); } return; } case EditMode.AddPolygon: // TODO: Implement adding polygon. return; case EditMode.None: default: this.navigationService.clearFeatureId(); return; } } private onProjectAndFeaturesUpdate( project: Project, features: List<Feature>, selectedFeatureId: string | null ): void { this.removeDeletedFeatures(features); this.addNewFeatures(project, features); this.selectFeature(selectedFeatureId); } /** * Remove deleted features to map. The features that were displayed on * the map but not in the `newFeatures` are considered as deleted. */ private removeDeletedFeatures(newFeatures: List<Feature>) { const newFeatureIds: List<string> = newFeatures.map(f => f.id); this.removeDeletedMarkers(newFeatureIds); this.removeDeletedPolygons(newFeatureIds); } private removeDeletedMarkers(newFeatureIds: List<string>) { for (const id of this.markers.keys()) { if (!newFeatureIds.contains(id)) { this.markers.get(id)!.setMap(null); this.markers.delete(id); } } } private removeDeletedPolygons(newFeatureIds: List<string>) { for (const id of this.polygons.keys()) { if (!newFeatureIds.contains(id)) { this.polygons.get(id)!.setMap(null); this.polygons.delete(id); } } } /** * Add new features to map. The features that were not displayed on * the map but in the `newFeatures` are considered as new. */ private addNewFeatures(project: Project, features: List<Feature>) { const existingFeatureIds = Array.from(this.markers.keys()).concat( Array.from(this.polygons.keys()) ); features.forEach(feature => { if (!project.getLayer(feature.layerId)) { // Ignore features whose layer has been removed. console.debug( `Ignoring feature ${feature.id} with missing layer ${feature.layerId}` ); return; } if (existingFeatureIds.includes(feature.id)) { return; } const color = project.layers.get(feature.layerId)?.color; const layerName = project.layers.get(feature.layerId)?.name?.get('en'); if (feature instanceof LocationFeature) { this.addLocationFeature(color, feature); } if (feature instanceof GeoJsonFeature) { this.addGeoJsonFeature(color, layerName, feature); } if (feature instanceof PolygonFeature) { this.addPolygonFeature(color, layerName, feature); } }); } private addLocationFeature( color: string | undefined, feature: LocationFeature ) { const icon = { url: getPinImageSource(color), scaledSize: { width: normalIconScale, height: normalIconScale, }, } as google.maps.Icon; const options: google.maps.MarkerOptions = { map: this.map.googleMap, position: new google.maps.LatLng( feature.location.latitude, feature.location.longitude ), icon, draggable: false, title: feature.id, }; const marker = new google.maps.Marker(options); marker.addListener('click', () => this.onMarkerClick(feature.id)); marker.addListener('dragstart', (event: google.maps.MouseEvent) => this.onMarkerDragStart(event, marker) ); marker.addListener('dragend', (event: google.maps.MouseEvent) => this.onMarkerDragEnd(event, feature) ); this.markers.set(feature.id, marker); } private onMarkerClick(featureId: string) { if (this.disableMapClicks) { return; } this.navigationService.selectFeature(featureId); } private onMarkerDragStart( event: google.maps.MouseEvent, marker: google.maps.Marker ) { // TODO: Show confirm dialog and disable other components when entering reposition state. // Currently we are figuring out how should the UI trigger this state. this.showRepositionConfirmDialog = true; this.disableMapClicks = true; this.drawingToolsService.setDisabled$(true); this.markerToReposition = marker; this.oldLatLng = new google.maps.LatLng( event.latLng.lat(), event.latLng.lng() ); this.changeDetectorRef.detectChanges(); } private onMarkerDragEnd( event: google.maps.MouseEvent, feature: LocationFeature ) { this.newLatLng = new google.maps.LatLng( event.latLng.lat(), event.latLng.lng() ); this.newFeatureToReposition = new LocationFeature( feature.id, feature.layerId, new firebase.firestore.GeoPoint(event.latLng.lat(), event.latLng.lng()) ); } private panAndZoom(position: google.maps.LatLng | null | undefined) { if (!position) { return; } this.map.panTo(position); if (this.map.getZoom() < zoomedInLevel) { this.map.zoom = zoomedInLevel; } } private onEditModeChange(editMode: EditMode) { if (editMode !== EditMode.None) { this.navigationService.clearFeatureId(); for (const marker of this.markers) { marker[1].setClickable(false); } } else { for (const marker of this.markers) { marker[1].setClickable(true); } } this.mapOptions = editMode === EditMode.AddPoint ? this.crosshairCursorMapOptions : this.defaultCursorMapOptions; } /** * Selecting feature enlarges the marker or border of the polygon, * pans and zooms to the marker/polygon. Selecting null is considered * as deselecting which will change the selected back to normal size. */ private selectFeature(selectedFeatureId: string | null) { const markerToSelect = this.markers.get(selectedFeatureId as string); this.selectMarker(markerToSelect); const polygonToSelect = this.polygons.get(selectedFeatureId as string); this.selectPolygon(polygonToSelect); } private selectMarker(marker: google.maps.Marker | undefined) { if (marker === this.selectedMarker) { return; } if (marker) { this.setIconSize(marker, enlargedIconScale); marker.setDraggable(true); } if (this.selectedMarker) { this.setIconSize(this.selectedMarker, normalIconScale); this.selectedMarker.setDraggable(false); } this.selectedMarker = marker; this.panAndZoom(marker?.getPosition()); } private setIconSize(marker: google.maps.Marker, size: number) { const icon = marker.getIcon() as google.maps.ReadonlyIcon; const newIcon = { url: icon.url, scaledSize: { width: size, height: size, }, } as google.maps.Icon; marker.setIcon(newIcon); } private selectPolygon(polygon: google.maps.Polygon | undefined) { if (polygon === this.selectedPolygon) { return; } if (polygon) { polygon.setOptions({ strokeWeight: enlargedPolygonStrokeWeight }); } if (this.selectedPolygon) { this.selectedPolygon.setOptions({ strokeWeight: normalPolygonStrokeWeight, }); } this.selectedPolygon = polygon; this.panAndZoom(polygon?.getPaths().getAt(0).getAt(0)); } private addGeoJsonFeature( color: string | undefined, layerName: string | undefined, feature: GeoJsonFeature ) { const paths: google.maps.LatLng[][] = []; const layer = new google.maps.Data(); layer.addGeoJson(feature.geoJson); layer.forEach(f => { if (f.getGeometry() instanceof google.maps.Data.Polygon) { paths.push( ...this.geoJsonPolygonToPaths( f.getGeometry() as google.maps.Data.Polygon ) ); } if (f.getGeometry() instanceof google.maps.Data.MultiPolygon) { (f.getGeometry() as google.maps.Data.MultiPolygon) .getArray() .forEach(polygon => paths.push(...this.geoJsonPolygonToPaths(polygon)) ); } }); this.addPolygonToMap(feature.id, color, layerName, paths); } private geoJsonPolygonToPaths( polygon: google.maps.Data.Polygon ): google.maps.LatLng[][] { const paths: google.maps.LatLng[][] = polygon .getArray() .map(linearRing => linearRing.getArray()); return paths; } private addPolygonFeature( color: string | undefined, layerName: string | undefined, feature: PolygonFeature ) { const vertices: google.maps.LatLng[] = feature.polygonVertices.map( vertex => new google.maps.LatLng(vertex.latitude, vertex.longitude) ); this.addPolygonToMap(feature.id, color, layerName, [vertices]); } private addPolygonToMap( featureId: string, color: string | undefined, layerName: string | undefined, paths: google.maps.LatLng[][] ) { const polygon = new google.maps.Polygon({ paths: paths, clickable: true, strokeColor: color, strokeOpacity: 1, strokeWeight: normalPolygonStrokeWeight, fillOpacity: 0, map: this.map.googleMap, }); polygon.set('id', featureId); polygon.set('color', color); polygon.set('layerName', layerName); polygon.addListener('click', (event: google.maps.PolyMouseEvent) => { this.onPolygonClick(event); }); this.polygons.set(featureId, polygon); } private onPolygonClick(event: google.maps.PolyMouseEvent) { if (this.disableMapClicks) { return; } const candidatePolygons: google.maps.Polygon[] = []; for (const polygon of this.polygons.values()) { if (google.maps.geometry.poly.containsLocation(event.latLng, polygon)) { candidatePolygons.push(polygon); } } if (candidatePolygons.length === 1) { this.zone.run(() => { this.navigationService.selectFeature(candidatePolygons[0].get('id')); }); return; } this.openSelectFeatureDialog(candidatePolygons); } private openSelectFeatureDialog(candidatePolygons: google.maps.Polygon[]) { this.zone.run(() => { const dialogRef = this.dialog.open(SelectFeatureDialogComponent, { width: '500px', data: { clickedFeatures: candidatePolygons.map(this.polygonToFeatureData), }, }); dialogRef.afterClosed().subscribe(result => { if (result) { this.navigationService.selectFeature(result); } }); }); } private polygonToFeatureData(polygon: google.maps.Polygon): FeatureData { return { featureId: polygon.get('id'), color: polygon.get('color'), layerName: polygon.get('layerName'), }; } onSaveRepositionClick() { this.markerToReposition?.setPosition(this.newLatLng!); this.featureService.updatePoint(this.newFeatureToReposition!); this.resetReposition(); } onCancelRepositionClick() { this.markerToReposition?.setPosition(this.oldLatLng!); this.resetReposition(); } private resetReposition() { this.showRepositionConfirmDialog = false; this.newFeatureToReposition = undefined; this.oldLatLng = undefined; this.newLatLng = undefined; this.markerToReposition = undefined; this.disableMapClicks = false; this.drawingToolsService.setDisabled$(false); } private cancelReposition() { if (this.showRepositionConfirmDialog) { this.onCancelRepositionClick(); } } }
the_stack
import React from "react"; import styled from "styled-components"; import classNames from "classnames"; import { Size } from "src/theme"; import { RouteName } from "src/shared/constants/routing"; import { getPrimaryColor } from "src/shared/utils/color"; import { SearchParamKey } from "src/shared/constants/search"; import { getReviewCardTags } from "src/shared/utils/misc"; import { IDetailsCardProps, DetailsCard as BaseDetailsCard, MOBILE_MENU_MEDIA_QUERY, Link, Text, Tag, StarRating, UnstyledButton, Icon, IconName, } from "src/components"; import useDarkMode from "use-dark-mode"; import { SalaryPeriod } from "src/api/globalTypes"; /******************************************************************* * **Types** * *******************************************************************/ export interface IReviewDetails { jobName: string; jobId: string; companyName: string; companyId: string; location: string | null; author: string; body: string | null; overallRating: number; meaningfulWorkRating: number; workLifeBalanceRating: number; learningMentorshipRating: number; salary: number; salaryCurrency: string; salaryPeriod: SalaryPeriod; logoSrc: string; color: string; date: InternPlusISODate | null; relativeDate: string; tags: string[] | null; } export interface IReviewDetailsCardProps extends IDetailsCardProps { onExit: (e: React.MouseEvent) => void; reviewDetails?: IReviewDetails; } /******************************************************************* * **Utility functions/constants** * *******************************************************************/ /** * Converts the stored backend value into a readable * format for display. * The reason we use hourly/monthly/weekly is from legacy * internCompass data. * @param salary salary amount * @param salaryCurrency currency * @param salaryPeriod SalaryPeriod */ const getSalaryText = ( salary?: number, salaryCurrency?: string, salaryPeriod?: SalaryPeriod ) => { if (salary === -1) { return "No salary provided"; } switch (salaryPeriod) { case "YEARLY": return `${salaryCurrency}/month`; case "MONTHLY": return `${salaryCurrency}/month`; case "WEEKLY": return `${salaryCurrency}/month`; case "HOURLY": return `${salaryCurrency}/month`; default: throw new Error( `Exhaustive salary period check found unknown value: ${salaryPeriod}` ); } }; /******************************************************************* * **Styles** * *******************************************************************/ const DetailsCard = styled(BaseDetailsCard)` max-width: 700px; margin: auto; ${({ theme }) => theme.mediaQueries.medium` max-width: 80%; `} ${({ theme }) => theme.mediaQueries.tablet` padding: ${theme.padding.displayMobile}; & h1 { font-size: ${theme.fontSize[Size.LARGE]}px; } & .misc-info { flex-direction: column; } `} ${({ theme }) => theme.mediaQueries.xlMobile` top: 5%; max-width: 90%; `} ${({ theme }) => theme.mediaQueries[MOBILE_MENU_MEDIA_QUERY]` width: 100%; left: 0; border-radius: ${theme.borderRadius.large}px; `} `; const FlexRowContainer = styled.div` display: flex; justify-content: space-between; align-items: flex-start; `; const LogoImg = styled.img` margin-left: 20px; max-width: 80px; `; const ReviewRating = styled(StarRating)` display: flex; justify-content: flex-start; & > .rating-text { padding: 0 3px; } `; const SalaryInfo = styled.div` display: flex; flex-direction: column; align-items: flex-end; ${({ theme }) => theme.mediaQueries.tablet` flex-direction: row; margin-top: 10px; & > * { font-size: ${theme.fontSize[Size.SMALL]}px; &:first-child::after { white-space: pre; content: " "; } } `} `; const ReviewPrefixContainer = styled.div` margin: 50px auto 10px 0; `; const ReviewBody = styled(Text)` display: inline-block; margin-top: 20px; `; const ReviewTags = styled.div` padding-top: 10px; & .tag { margin-right: 5px; opacity: 0.85; &:hover { opacity: 1; } } `; const CloseButton = styled(UnstyledButton)` position: absolute; width: 25px; height: 25px; top: -10px; right: -10px; display: flex; justify-content: center; align-items: center; z-index: 1; cursor: pointer; & .bg { z-index: 0; position: absolute; width: 100%; height: 100%; background-color: ${({ theme }) => theme.color.error}; border-radius: 50%; } &:hover > .bg, &:focus > .bg { transition: transform 150ms ease-out; transform: scale(1.1); } & > svg { z-index: 1; } `; /******************************************************************* * **Component** * *******************************************************************/ const ReviewDetailsCard: React.FC<IReviewDetailsCardProps> = ({ className, onExit, reviewDetails, ...rest }) => { const { value: isDark } = useDarkMode(); return ( <DetailsCard className={classNames("company", className)} backgroundColor="backgroundSecondary" {...rest} > {reviewDetails && ( <div> <FlexRowContainer> <div> <Link to={`${RouteName.JOBS}/${reviewDetails.jobId}`} bare> <Text variant="heading1" as="h1"> {reviewDetails.jobName} </Text> </Link> <Link to={`${RouteName.COMPANIES}/${reviewDetails.companyId}`} bare > <Text variant="heading3" color={getPrimaryColor(isDark, reviewDetails.color)} > {reviewDetails.companyName} </Text> </Link> {reviewDetails.location && ( <Text className="subheading location" variant="heading3" color="textSecondary" > {` • ${reviewDetails.location}`} </Text> )} </div> <Link to={`${RouteName.COMPANIES}/${reviewDetails.companyId}`} bare> <LogoImg src={reviewDetails.logoSrc} alt={`Logo of ${reviewDetails.companyName}`} /> </Link> </FlexRowContainer> <ReviewPrefixContainer> <Text variant="subheading">{reviewDetails.author} </Text> <Text variant="subheading" color="textSecondary"> mentioned the following{" "} </Text> <Text variant="subheading" title={reviewDetails.date ?? ""}> {reviewDetails.relativeDate.toLowerCase()}... </Text> </ReviewPrefixContainer> <FlexRowContainer className="misc-info"> <div> <ReviewRating maxStars={5} value={reviewDetails ? reviewDetails.overallRating : 0} readOnly > <Text variant="subheading" className="rating-text"> Overall </Text> </ReviewRating> <ReviewRating maxStars={5} value={reviewDetails ? reviewDetails.meaningfulWorkRating : 0} readOnly > <Text variant="subheading" className="rating-text" color="textSecondary" > Meaningful work </Text> </ReviewRating> <ReviewRating maxStars={5} value={reviewDetails.workLifeBalanceRating} readOnly > <Text variant="subheading" className="rating-text" color="textSecondary" > Work life balance </Text> </ReviewRating> <ReviewRating maxStars={5} value={reviewDetails.learningMentorshipRating} readOnly > <Text variant="subheading" className="rating-text" color="textSecondary" > Learning &amp; mentorship </Text> </ReviewRating> </div> <SalaryInfo> {reviewDetails.salary && reviewDetails.salary >= 0 && ( <Text variant="heading2" className="salary-amt"> {reviewDetails.salary} </Text> )} <Text variant="heading3" className="salary-text"> {getSalaryText( reviewDetails.salary, reviewDetails.salaryCurrency, reviewDetails.salaryPeriod )} </Text> </SalaryInfo> </FlexRowContainer> <ReviewBody variant="body"> {reviewDetails.body?.split("\n").map((text) => ( <p key={text}>{text}</p> ))} </ReviewBody> {reviewDetails.tags && ( <ReviewTags className="tags"> {getReviewCardTags(reviewDetails.tags, isDark).map( ({ label, bgColor }) => ( <Link to={`${RouteName.SEARCH}?${SearchParamKey.QUERY}=${label}`} > <Tag key={label} color={bgColor}> <Text size={12} bold={500}> {label} </Text> </Tag> </Link> ) )} </ReviewTags> )} </div> )} <CloseButton onClick={onExit} tabIndex={1}> <span className="bg" /> <Icon name={IconName.X} color="backgroundPrimary" size={13} /> </CloseButton> </DetailsCard> ); }; export default ReviewDetailsCard;
the_stack
import React, { useState } from 'react'; import { mount } from 'enzyme'; import addDays from 'date-fns/add_days'; import subDays from 'date-fns/sub_days'; import Calendar, { validateProps, normaliseValue, hasAnyPastDays, hasAnyFutureDays } from './index'; test('renders a basic calendar with past date selection allowed', () => { const wrapper = mount( <Calendar disabledDays={null} onChange={(): void => {}} onMonthChange={(): void => {}} value="Tue Sep 16 2017 14:39:00 GMT+0100 (BST)" />, ); expect(wrapper).toMatchSnapshot(); }); describe('calls `onChange` with the correct date', () => { test('single date selection', () => { const onChange = jest.fn(); const onMonthChange = jest.fn(); // This test will break in 2057. ¯\_(ツ)_/¯ const value = 'Tue Sep 3 2057 14:39:00 GMT+0100 (BST)'; const wrapper = mount( <Calendar onChange={onChange} onMonthChange={onMonthChange} value={value} />, ); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 15th first. const day15 = allDays.findWhere(n => n.prop('children') === 15); day15.simulate('click'); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledWith([new Date('2057-09-15T07:00:00.000Z')]); // Click on the 22nd next. const day22 = allDays.findWhere(n => n.prop('children') === 22); day22.simulate('click'); expect(onChange).toHaveBeenCalledTimes(2); expect(onChange).toHaveBeenCalledWith([new Date('2057-09-22T07:00:00.000Z')]); }); test('multi date selection', () => { const onMonthChange = jest.fn(); // Wrapper component to allow us to write integration tests for a controlled component. // // Don't need to write proptypes for a one-off wrapper used inside a test // eslint-disable-next-line react/prop-types function DatePickerExample({ firstDate, onChange, }: { firstDate: Date; onChange: (dates: Date[]) => void; }): JSX.Element { const [value, setValue] = useState<Date[]>([firstDate]); return ( <Calendar value={value} // We need to call these two functions separately here. `onChange` is the // external reference to `jest.fn` that lets us make assertions about how this // function was called. `setValue` is the React Hook that actually updates the // state so we can track changes over the whole integration test. // TODO: maybe extract this out or revisit if this becomes a common pattern onChange={(newValue): void => { onChange(newValue); setValue(newValue); }} onMonthChange={onMonthChange} allowMultiSelection /> ); } const firstDate = new Date('2057-09-03T07:00:00.000Z'); const secondDate = new Date('2057-09-15T07:00:00.000Z'); const thirdDate = new Date('2057-09-22T07:00:00.000Z'); const onChange = jest.fn(); const wrapper = mount(<DatePickerExample firstDate={firstDate} onChange={onChange} />); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 15th first. const day15 = allDays.findWhere(n => n.prop('children') === 15); day15.simulate('click'); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledWith([firstDate, secondDate]); // Click on the 22nd next. const day22 = allDays.findWhere(n => n.prop('children') === 22); day22.simulate('click'); expect(onChange).toHaveBeenCalledTimes(2); expect(onChange).toHaveBeenCalledWith([firstDate, secondDate, thirdDate]); }); }); describe('user tries to unselect a date that was already selected', () => { test('single date selection does not allow them to unselect a date', () => { // Note: This behavior is inconsistent with `allowMultiSelection`. The two should probably // be consistent, but, until then, this test enforces the odd behavior. const onChange = jest.fn(); const onMonthChange = jest.fn(); // The 3rd of September is already chosen. const firstDate = new Date('2057-09-03T07:00:00.000Z'); const wrapper = mount( <Calendar onChange={onChange} onMonthChange={onMonthChange} value={firstDate} />, ); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 3rd day. const day3 = allDays.findWhere(n => n.prop('children') === 3); day3.simulate('click'); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledWith([firstDate]); }); test('multi date selection allows them to unselect the date', () => { const onChange = jest.fn(); const onMonthChange = jest.fn(); // The 3rd of September is already chosen. const firstDate = new Date('2057-09-03T07:00:00.000Z'); const wrapper = mount( <Calendar onChange={onChange} value={firstDate} onMonthChange={onMonthChange} allowMultiSelection />, ); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 3rd day. const day3 = allDays.findWhere(n => n.prop('children') === 3); day3.simulate('click'); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledWith([]); }); }); describe('user tries to click on a disabled date', () => { test('single date selection', () => { const onChange = jest.fn(); const onMonthChange = jest.fn(); const selectedDate = new Date('2057-09-03T07:00:00.000Z'); // The 10th is disabled. const disabledDate = new Date('2057-09-10T07:00:00.000Z'); const wrapper = mount( <Calendar onChange={onChange} onMonthChange={onMonthChange} value={selectedDate} disabledDays={disabledDate} />, ); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 10th, the disabled date. const day10 = allDays.findWhere(n => n.prop('children') === 10); day10.simulate('click'); expect(onChange).toHaveBeenCalledTimes(0); }); test('multi date selection', () => { const onChange = jest.fn(); const onMonthChange = jest.fn(); const selectedDate = new Date('2057-09-03T07:00:00.000Z'); // The 10th is disabled. const disabledDate = new Date('2057-09-10T07:00:00.000Z'); const wrapper = mount( <Calendar onChange={onChange} onMonthChange={onMonthChange} value={selectedDate} disabledDays={disabledDate} allowMultiSelection />, ); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 10th, the disabled date. const day10 = allDays.findWhere(n => n.prop('children') === 10); day10.simulate('click'); expect(onChange).toHaveBeenCalledTimes(0); }); }); describe('user is able to select a date in the past if disabled days is disabled', () => { test('single date selection', () => { const onChange = jest.fn(); const onMonthChange = jest.fn(); // We use the year 2000 since these must be days from the past. const selectedDate = new Date('2000-09-03T07:00:00.000Z'); const dateFromPrevMonth = new Date('2000-08-10T07:00:00.000Z'); const wrapper = mount( <Calendar onChange={onChange} onMonthChange={onMonthChange} value={selectedDate} disabledDays={null} />, ); // Go back a month. const prevMonthButton = wrapper.find('.DayPicker-NavButton--prev'); prevMonthButton.simulate('click'); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 10th, the date from a previous month. const day10 = allDays.findWhere(n => n.prop('children') === 10); day10.simulate('click'); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledWith([dateFromPrevMonth]); }); test('multi date selection', () => { const onChange = jest.fn(); const onMonthChange = jest.fn(); // We use the year 2000 since these must be days from the past. const selectedDate = new Date('2000-09-03T07:00:00.000Z'); const dateFromPrevMonth = new Date('2000-08-10T07:00:00.000Z'); const wrapper = mount( <Calendar onChange={onChange} onMonthChange={onMonthChange} value={selectedDate} disabledDays={null} allowMultiSelection />, ); // Go back a month. const prevMonthButton = wrapper.find('.DayPicker-NavButton--prev'); prevMonthButton.simulate('click'); const allDays = wrapper.find('.DayPicker-Day'); // Click on the 10th, the date from a previous month. const day10 = allDays.findWhere(n => n.prop('children') === 10); day10.simulate('click'); expect(onChange).toHaveBeenCalledTimes(1); expect(onChange).toHaveBeenCalledWith([selectedDate, dateFromPrevMonth]); }); }); describe('`onMonthChange` callback should be called on month change', () => { const onChange = (): void => {}; const year = 2057; const month = 9; const selectedDate = new Date(year, month); test('when next month is clicked', () => { const onMonthChange = jest.fn(); const wrapper = mount( <Calendar value={selectedDate} onChange={onChange} onMonthChange={onMonthChange} />, ); const nextMonthButton = wrapper.find('.DayPicker-NavButton--next'); nextMonthButton.simulate('click'); expect(onMonthChange).toHaveBeenCalledTimes(1); const newMonth = onMonthChange.mock.calls[0][0]; expect(newMonth.getFullYear()).toBe(year); expect(newMonth.getMonth()).toBe(month + 1); }); test('when previous month is clicked', () => { const onMonthChange = jest.fn(); const wrapper = mount( <Calendar value={selectedDate} onChange={onChange} onMonthChange={onMonthChange} />, ); const prevMonthButton = wrapper.find('.DayPicker-NavButton--prev'); prevMonthButton.simulate('click'); expect(onMonthChange).toHaveBeenCalledTimes(1); const newMonth = onMonthChange.mock.calls[0][0]; expect(newMonth.getFullYear()).toBe(year); expect(newMonth.getMonth()).toBe(month - 1); }); }); describe('applying themes to Calendar day cells', () => { const modifierPrefix = '.DayPicker-Day--'; const onChange = (): void => {}; const onMonthChange = jest.fn(); const year = 2057; const month = 8; const day = 3; const selectedDate = new Date(year, month, day); const areDatesEqual = (calDate: Date, expectedDate: Date): boolean => calDate.getFullYear() === expectedDate.getFullYear() && calDate.getMonth() === expectedDate.getMonth() && calDate.getDate() === expectedDate.getDate(); test('`daysThemeDotIndicator` applies modifier styles for dot indicators', () => { const testDay1 = 5; const testDay2 = 16; const jsDate1 = new Date(year, month, testDay1); const jsDate2 = new Date(year, month, testDay2); const wrapper = mount( <Calendar value={selectedDate} onChange={onChange} onMonthChange={onMonthChange} daysThemeDotIndicator={(calDate: Date): boolean => areDatesEqual(calDate, jsDate1) || areDatesEqual(calDate, jsDate2) } />, ); const modifiedDays = wrapper.find(`${modifierPrefix}theme-dot`); expect(modifiedDays).toHaveLength(2); expect(modifiedDays.at(0).text()).toEqual(String(testDay1)); expect(modifiedDays.at(1).text()).toEqual(String(testDay2)); }); test('`daysThemeStrikeout` applies modifier styles for strikeout', () => { const testDay1 = 2; const testDay2 = 12; const testDay3 = 22; const jsDate1 = new Date(year, month, testDay1); const jsDate2 = new Date(year, month, testDay2); const jsDate3 = new Date(year, month, testDay3); const wrapper = mount( <Calendar value={selectedDate} onChange={onChange} onMonthChange={onMonthChange} daysThemeStrikeout={(calDate: Date): boolean => areDatesEqual(calDate, jsDate1) || areDatesEqual(calDate, jsDate2) || areDatesEqual(calDate, jsDate3) } />, ); const modifiedDays = wrapper.find(`${modifierPrefix}theme-strikeout`); expect(modifiedDays).toHaveLength(3); expect(modifiedDays.at(0).text()).toEqual(String(testDay1)); expect(modifiedDays.at(1).text()).toEqual(String(testDay2)); expect(modifiedDays.at(2).text()).toEqual(String(testDay3)); }); }); describe('DatePicker utilities', () => { describe('normaliseValue', () => { test('converts a single item to an array', () => { const date = new Date('Tue Sep 16 2017 15:00:00 GMT+0100 (BST)'); expect(normaliseValue(date)).toEqual([date]); }); test('converts strings and numbers to `Date`s', () => { const dates = [ new Date('Tue Sep 16 2017 15:00:00 GMT+0100 (BST)'), 'Wed Sep 17 2017 15:00:00 GMT+0100 (BST)', 1505570400000, ]; expect(normaliseValue(dates)).toEqual([ new Date('2017-09-16T14:00:00.000Z'), new Date('2017-09-17T14:00:00.000Z'), new Date('2017-09-16T14:00:00.000Z'), ]); }); }); describe('hasAnyPastDays', () => { test('returns false an empty list of days', () => { expect(hasAnyPastDays([])).toBe(false); }); test('returns true for any days before the current day, regardless of time of day', () => { expect(hasAnyPastDays([subDays(new Date(), 10)])).toBe(true); }); test('returns false for dates that are on the same day as the specified target date, but at an earlier time', () => { const targetDate = new Date('Tue Sep 16 2017 15:00:00 GMT+0100 (BST)'); const earlierThatDay = new Date('Tue Sep 16 2017 14:00:00 GMT+0100 (BST)'); expect(hasAnyPastDays([earlierThatDay], targetDate)).toBe(false); }); test('returns false for the exact current date', () => { expect(hasAnyPastDays([new Date()])).toBe(false); }); test('returns false for dates that are all in the future', () => { expect(hasAnyPastDays([addDays(new Date(), 10), addDays(new Date(), 11)])).toBe(false); }); }); describe('hasAnyFutureDays', () => { test('returns false an empty list of days', () => { expect(hasAnyFutureDays([])).toBe(false); }); test('returns true for any days after the current day, regardless of time of day', () => { expect(hasAnyFutureDays([addDays(new Date(), 10)])).toBe(true); }); test('returns false for dates that are on the same day as the specified target date, but at a later time', () => { const targetDate = new Date('Tue Sep 16 2017 15:00:00 GMT+0100 (BST)'); const laterThatDay = new Date('Tue Sep 16 2017 16:00:00 GMT+0100 (BST)'); expect(hasAnyFutureDays([laterThatDay], targetDate)).toBe(false); }); test('returns false for the exact current date', () => { expect(hasAnyFutureDays([new Date()])).toBe(false); }); test('returns false for dates that are all in the past', () => { expect(hasAnyFutureDays([subDays(new Date(), 10), subDays(new Date(), 11)])).toBe( false, ); }); }); describe('validateProps', () => { test('throws an error when multiple selection is disabled and multiple initial dates are provided', () => { expect(() => { validateProps({ onChange: (): void => {}, onMonthChange: (): void => {}, allowMultiSelection: false, value: [new Date(), addDays(new Date(), 1)], }); }).toThrow( 'TUI DatePicker: `allowMultiSelection` is `false` but multiple dates were provided', ); }); test('throws an error when past selection is disabled and one or more initial dates are in the past', () => { expect(() => { validateProps({ onChange: (): void => {}, onMonthChange: (): void => {}, allowMultiSelection: true, disabledDays: { before: new Date() }, value: [new Date(), subDays(new Date(), 1)], }); }).toThrow('are disabled but one or more provided days fall before that'); }); test('throws an error when future selection is disabled and one or more initial dates are in the future', () => { expect(() => { validateProps({ onChange: (): void => {}, onMonthChange: (): void => {}, allowMultiSelection: true, disabledDays: { after: new Date() }, value: [addDays(new Date(), 1), addDays(new Date(), 2)], }); }).toThrow('are disabled but one or more provided days fall after that'); }); test('does not throw an error when past and future selection are disabled, and the initial date is `null`', () => { expect(() => { validateProps({ onChange: (): void => {}, onMonthChange: (): void => {}, allowMultiSelection: true, disabledDays: { before: subDays(new Date(), 5), after: addDays(new Date(), 5) }, value: null, }); }).not.toThrow(); }); test('does not throw an error when past and future selection are disabled, and the initial date is `undefined`', () => { expect(() => { validateProps({ onChange: (): void => {}, onMonthChange: (): void => {}, allowMultiSelection: true, disabledDays: { before: subDays(new Date(), 5), after: addDays(new Date(), 5) }, value: undefined, }); }).not.toThrow(); }); }); });
the_stack
import { hex2b64 } from "./lib/jsbn/base64"; import { Hex } from "./lib/asn1js/hex"; import { Base64 } from "./lib/asn1js/base64"; import { ASN1 } from "./lib/asn1js/asn1"; import { RSAKey } from "./lib/jsbn/rsa"; import { parseBigInt } from "./lib/jsbn/jsbn"; import { KJUR } from "./lib/jsrsasign/asn1-1.0"; /** * Create a new JSEncryptRSAKey that extends Tom Wu's RSA key object. * This object is just a decorator for parsing the key parameter * @param {string|Object} key - The key in string format, or an object containing * the parameters needed to build a RSAKey object. * @constructor */ export class JSEncryptRSAKey extends RSAKey { constructor(key?:string) { super(); // Call the super constructor. // RSAKey.call(this); // If a key key was provided. if (key) { // If this is a string... if (typeof key === "string") { this.parseKey(key); } else if ( JSEncryptRSAKey.hasPrivateKeyProperty(key) || JSEncryptRSAKey.hasPublicKeyProperty(key) ) { // Set the values for the key. this.parsePropertiesFrom(key); } } } /** * Method to parse a pem encoded string containing both a public or private key. * The method will translate the pem encoded string in a der encoded string and * will parse private key and public key parameters. This method accepts public key * in the rsaencryption pkcs #1 format (oid: 1.2.840.113549.1.1.1). * * @todo Check how many rsa formats use the same format of pkcs #1. * * The format is defined as: * PublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * PublicKey BIT STRING * } * Where AlgorithmIdentifier is: * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) * } * and PublicKey is a SEQUENCE encapsulated in a BIT STRING * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * it's possible to examine the structure of the keys obtained from openssl using * an asn.1 dumper as the one used here to parse the components: http://lapo.it/asn1js/ * @argument {string} pem the pem encoded string, can include the BEGIN/END header/footer * @private */ public parseKey(pem:string) { try { let modulus:string | number = 0; let public_exponent:string | number = 0; const reHex = /^\s*(?:[0-9A-Fa-f][0-9A-Fa-f]\s*)+$/; const der = reHex.test(pem) ? Hex.decode(pem) : Base64.unarmor(pem); let asn1 = ASN1.decode(der); // Fixes a bug with OpenSSL 1.0+ private keys if (asn1.sub.length === 3) { asn1 = asn1.sub[2].sub[0]; } if (asn1.sub.length === 9) { // Parse the private key. modulus = asn1.sub[1].getHexStringValue(); // bigint this.n = parseBigInt(modulus, 16); public_exponent = asn1.sub[2].getHexStringValue(); // int this.e = parseInt(public_exponent, 16); const private_exponent = asn1.sub[3].getHexStringValue(); // bigint this.d = parseBigInt(private_exponent, 16); const prime1 = asn1.sub[4].getHexStringValue(); // bigint this.p = parseBigInt(prime1, 16); const prime2 = asn1.sub[5].getHexStringValue(); // bigint this.q = parseBigInt(prime2, 16); const exponent1 = asn1.sub[6].getHexStringValue(); // bigint this.dmp1 = parseBigInt(exponent1, 16); const exponent2 = asn1.sub[7].getHexStringValue(); // bigint this.dmq1 = parseBigInt(exponent2, 16); const coefficient = asn1.sub[8].getHexStringValue(); // bigint this.coeff = parseBigInt(coefficient, 16); } else if (asn1.sub.length === 2) { // Parse the public key. const bit_string = asn1.sub[1]; const sequence = bit_string.sub[0]; modulus = sequence.sub[0].getHexStringValue(); this.n = parseBigInt(modulus, 16); public_exponent = sequence.sub[1].getHexStringValue(); this.e = parseInt(public_exponent, 16); } else { return false; } return true; } catch (ex) { return false; } } /** * Translate rsa parameters in a hex encoded string representing the rsa key. * * The translation follow the ASN.1 notation : * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * } * @returns {string} DER Encoded String representing the rsa private key * @private */ public getPrivateBaseKey() { const options = { array: [ new KJUR.asn1.DERInteger({int: 0}), new KJUR.asn1.DERInteger({bigint: this.n}), new KJUR.asn1.DERInteger({int: this.e}), new KJUR.asn1.DERInteger({bigint: this.d}), new KJUR.asn1.DERInteger({bigint: this.p}), new KJUR.asn1.DERInteger({bigint: this.q}), new KJUR.asn1.DERInteger({bigint: this.dmp1}), new KJUR.asn1.DERInteger({bigint: this.dmq1}), new KJUR.asn1.DERInteger({bigint: this.coeff}) ] }; const seq = new KJUR.asn1.DERSequence(options); return seq.getEncodedHex(); } /** * base64 (pem) encoded version of the DER encoded representation * @returns {string} pem encoded representation without header and footer * @public */ public getPrivateBaseKeyB64() { return hex2b64(this.getPrivateBaseKey()); } /** * Translate rsa parameters in a hex encoded string representing the rsa public key. * The representation follow the ASN.1 notation : * PublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * PublicKey BIT STRING * } * Where AlgorithmIdentifier is: * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, the OID of the enc algorithm * parameters ANY DEFINED BY algorithm OPTIONAL (NULL for PKCS #1) * } * and PublicKey is a SEQUENCE encapsulated in a BIT STRING * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * @returns {string} DER Encoded String representing the rsa public key * @private */ public getPublicBaseKey() { const first_sequence = new KJUR.asn1.DERSequence({ array: [ new KJUR.asn1.DERObjectIdentifier({oid: "1.2.840.113549.1.1.1"}), // RSA Encryption pkcs #1 oid new KJUR.asn1.DERNull() ] }); const second_sequence = new KJUR.asn1.DERSequence({ array: [ new KJUR.asn1.DERInteger({bigint: this.n}), new KJUR.asn1.DERInteger({int: this.e}) ] }); const bit_string = new KJUR.asn1.DERBitString({ hex: "00" + second_sequence.getEncodedHex() }); const seq = new KJUR.asn1.DERSequence({ array: [ first_sequence, bit_string ] }); return seq.getEncodedHex(); } /** * base64 (pem) encoded version of the DER encoded representation * @returns {string} pem encoded representation without header and footer * @public */ public getPublicBaseKeyB64() { return hex2b64(this.getPublicBaseKey()); } /** * wrap the string in block of width chars. The default value for rsa keys is 64 * characters. * @param {string} str the pem encoded string without header and footer * @param {Number} [width=64] - the length the string has to be wrapped at * @returns {string} * @private */ public static wordwrap(str:string, width?:number) { width = width || 64; if (!str) { return str; } const regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})"; return str.match(RegExp(regex, "g")).join("\n"); } /** * Retrieve the pem encoded private key * @returns {string} the pem encoded private key with header/footer * @public */ public getPrivateKey() { let key = "-----BEGIN RSA PRIVATE KEY-----\n"; key += JSEncryptRSAKey.wordwrap(this.getPrivateBaseKeyB64()) + "\n"; key += "-----END RSA PRIVATE KEY-----"; return key; } /** * Retrieve the pem encoded public key * @returns {string} the pem encoded public key with header/footer * @public */ public getPublicKey() { let key = "-----BEGIN PUBLIC KEY-----\n"; key += JSEncryptRSAKey.wordwrap(this.getPublicBaseKeyB64()) + "\n"; key += "-----END PUBLIC KEY-----"; return key; } /** * Check if the object contains the necessary parameters to populate the rsa modulus * and public exponent parameters. * @param {Object} [obj={}] - An object that may contain the two public key * parameters * @returns {boolean} true if the object contains both the modulus and the public exponent * properties (n and e) * @todo check for types of n and e. N should be a parseable bigInt object, E should * be a parseable integer number * @private */ public static hasPublicKeyProperty(obj:object) { obj = obj || {}; return ( obj.hasOwnProperty("n") && obj.hasOwnProperty("e") ); } /** * Check if the object contains ALL the parameters of an RSA key. * @param {Object} [obj={}] - An object that may contain nine rsa key * parameters * @returns {boolean} true if the object contains all the parameters needed * @todo check for types of the parameters all the parameters but the public exponent * should be parseable bigint objects, the public exponent should be a parseable integer number * @private */ public static hasPrivateKeyProperty(obj:object) { obj = obj || {}; return ( obj.hasOwnProperty("n") && obj.hasOwnProperty("e") && obj.hasOwnProperty("d") && obj.hasOwnProperty("p") && obj.hasOwnProperty("q") && obj.hasOwnProperty("dmp1") && obj.hasOwnProperty("dmq1") && obj.hasOwnProperty("coeff") ); } /** * Parse the properties of obj in the current rsa object. Obj should AT LEAST * include the modulus and public exponent (n, e) parameters. * @param {Object} obj - the object containing rsa parameters * @private */ public parsePropertiesFrom(obj:any) { this.n = obj.n; this.e = obj.e; if (obj.hasOwnProperty("d")) { this.d = obj.d; this.p = obj.p; this.q = obj.q; this.dmp1 = obj.dmp1; this.dmq1 = obj.dmq1; this.coeff = obj.coeff; } } }
the_stack
import directionConverter from '@aesthetic/addon-direction'; import vendorPrefixer from '@aesthetic/addon-vendor'; import { RankCache, SheetManager } from '@aesthetic/types'; import { createTestSheetManager, createTestStyleEngine, getRenderedStyles, purgeStyles, } from '../src/test'; import { StyleEngine } from '../src/types'; const fontFace = { fontFamily: '"Open Sans"', fontStyle: 'normal', fontWeight: 800, src: 'url("fonts/OpenSans-Bold.woff2")', }; describe('Engine', () => { let sheetManager: SheetManager; let engine: StyleEngine; beforeEach(() => { sheetManager = createTestSheetManager(); engine = createTestStyleEngine({ directionConverter, sheetManager, vendorPrefixer, }); }); afterEach(() => { purgeStyles(); }); it('inserts at-rules before standard rules', () => { engine.renderRule({ display: 'block' }, { type: 'global' }); engine.renderFontFace(fontFace); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('inserts imports before at-rules', () => { engine.renderFontFace(fontFace); engine.renderImport('"custom.css"'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); describe('renderDeclaration()', () => { it('generates a unique class name for a large number of properties', () => { for (let i = 0; i < 100; i += 1) { engine.renderDeclaration('padding', `${i}px`); } expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses the same class name for the same property value pair', () => { engine.renderDeclaration('display', 'block'); engine.renderDeclaration('display', 'flex'); engine.renderDeclaration('display', 'block'); engine.renderDeclaration('display', 'flex'); engine.renderDeclaration('display', 'inline'); engine.renderDeclaration('display', 'block'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses the same class name for dashed and camel cased properties', () => { engine.renderDeclaration('textDecoration', 'none'); // @ts-expect-error Not allowed with types but works engine.renderDeclaration('text-decoration', 'none'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses the same class name for numeric and string values', () => { engine.renderDeclaration('width', 0); engine.renderDeclaration('width', '0'); engine.renderDeclaration('width', '100em'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports CSS variables', () => { engine.renderDeclaration('color', 'var(--primary-color)'); engine.renderDeclaration('border', '1px solid var(--border-color)'); engine.renderDeclaration('display', 'var(--display, var(--fallback), flex)'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('prefixes properties, values, value functions, and selectors', () => { // Value prefixing (wont show in snapshot because of DOM) engine.renderDeclaration('minWidth', 'fit-content', { vendor: true }); // Value function prefixing (wont show in snapshot because of DOM) engine.renderDeclaration('background', 'image-set()', { vendor: true }); // Property prefixing engine.renderDeclaration('appearance', 'none', { vendor: true }); // Selector prefixing (only shows last in snapshot) engine.renderDeclaration('display', 'none', { selector: ':fullscreen', vendor: true, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('generates a deterministic class name', () => { const className = engine.renderDeclaration('margin', 0, { deterministic: true }); expect(className).toBe('c13kbekr'); }); describe('selectors', () => { it('supports selectors', () => { engine.renderDeclaration('color', 'green', { selector: ':hover' }); engine.renderDeclaration('color', 'red', { selector: '[disabled]' }); engine.renderDeclaration('color', 'blue', { selector: ':nth-child(2)' }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('conditions', () => { it('supports conditionals', () => { engine.renderDeclaration('color', 'green', { media: '(max-size: 100px)' }); engine.renderDeclaration('color', 'red', { supports: '(color: red)' }); engine.renderDeclaration('color', 'blue', { media: '(max-width: 100px) and (min-width: 200px)', supports: '(color: red)', }); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('supports conditionals with selectors', () => { engine.renderDeclaration('color', 'green', { media: '(max-size: 100px)', selector: ':focus', }); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('generates different class names between standard and condition rules, when condition is inserted first', () => { const a = engine.renderDeclaration('width', '100em', { media: '(max-width: 100px)', }); const b = engine.renderDeclaration('width', '100em'); expect(a).toBe('a'); expect(b).toBe('b'); expect(a).not.toBe(b); }); }); describe('directionality', () => { it('converts directional properties', () => { engine.renderDeclaration('marginLeft', 0); engine.renderDeclaration('marginRight', 0); engine.renderDeclaration('marginLeft', 0, { direction: 'ltr' }); engine.renderDeclaration('marginRight', 0, { direction: 'rtl' }); engine.renderDeclaration('marginLeft', 0, { direction: 'ltr' }); engine.renderDeclaration('marginRight', 0, { direction: 'rtl' }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('converts directional values', () => { engine.renderDeclaration('textAlign', 'left'); engine.renderDeclaration('textAlign', 'right'); engine.renderDeclaration('textAlign', 'left', { direction: 'ltr' }); engine.renderDeclaration('textAlign', 'left', { direction: 'rtl' }); engine.renderDeclaration('textAlign', 'right', { direction: 'ltr' }); engine.renderDeclaration('textAlign', 'right', { direction: 'rtl' }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('rankings', () => { it('generates a ranking (insertion order)', () => { const spy = jest.spyOn(sheetManager, 'insertRule'); const rankings: RankCache = {}; engine.renderDeclaration('textAlign', 'center', { rankings }); engine.renderDeclaration('textAlign', 'center', { rankings }); engine.renderDeclaration('textAlign', 'center', { rankings }); expect(rankings).toEqual({ 'text-align': 0 }); expect(spy).toHaveBeenCalledTimes(1); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('inserts the same declaration if the minimum rank is not met (specificity guarantee)', () => { const spy = jest.spyOn(sheetManager, 'insertRule'); const rankings: RankCache = {}; engine.renderDeclaration('textAlign', 'center', { rankings }); rankings['text-align'] = 1; engine.renderDeclaration('textAlign', 'center', { rankings }); rankings['text-align'] = 2; engine.renderDeclaration('textAlign', 'center', { rankings }); expect(rankings).toEqual({ 'text-align': 2 }); expect(spy).toHaveBeenCalledTimes(3); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('can insert the same declaration if using a minimum rank requirement', () => { engine.renderDeclaration('color', 'red'); // 0 engine.renderDeclaration('color', 'green'); // 1 const c = engine.renderDeclaration('color', 'blue'); // 2 const d = engine.renderDeclaration('color', 'blue', { rankings: { color: 10 } }); // 3 expect(c).toBe('c'); expect(d).toBe('d'); expect(c).not.toBe(d); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('can insert the same declaration if using a shared rankings cache', () => { const rankings = {}; engine.renderRule({ color: 'red', display: 'inline' }, { rankings }); engine.renderRule({ color: 'blue' }, { rankings }); engine.renderRule({ color: 'green', display: 'block' }, { rankings }); // Should render again engine.renderRule({ color: 'red', display: 'inline' }, { rankings }); expect(rankings).toEqual({ color: 5, display: 6 }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('wont insert the same declaration if not using a shared rankings cache', () => { engine.renderRule({ color: 'red', display: 'inline' }); engine.renderRule({ color: 'blue' }); engine.renderRule({ color: 'green', display: 'block' }); // Should NOT render again engine.renderRule({ color: 'red', display: 'inline' }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('custom properties', () => { it('can change the value', () => { engine.customProperties = { display(value, add) { add('display', value === 'box' ? 'flex' : 'block'); }, }; engine.renderDeclaration('display', 'box'); engine.renderDeclaration('display', 'block'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('can add a completely different property', () => { engine.customProperties = { display(value, add) { add('flex', 1); }, }; engine.renderDeclaration('display', 'block'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('can add multiple properties', () => { engine.customProperties = { display(value, add) { add('display', value); add('position', 'relative'); add('zIndex', 0); }, }; engine.renderDeclaration('display', 'block'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('ignores properties with invalid values', () => { const spy = jest.spyOn(console, 'warn').mockImplementation(); engine.customProperties = { display(value, add) { add('display', ''); // @ts-expect-error Allow invalid type add('display', undefined); // @ts-expect-error Allow invalid type add('display', null); // @ts-expect-error Allow invalid type add('display', false); // @ts-expect-error Allow invalid type add('display', true); }, }; engine.renderDeclaration('display', 'block'); expect(spy).toHaveBeenCalledTimes(4); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); }); describe('renderFontFace()', () => { it('doesnt insert the same at-rule more than once', () => { engine.renderFontFace(fontFace); engine.renderFontFace(fontFace); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('renders and returns family name', () => { const name = engine.renderFontFace(fontFace); expect(name).toBe('"Open Sans"'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('generates a hashed family name if none provided', () => { const name = engine.renderFontFace({ fontStyle: 'normal', fontWeight: 800, src: 'url("fonts/OpenSans-Bold.woff2")', }); expect(name).toBe('ffweix7s'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('converts an array of `srcPaths` to `src`', () => { const name = engine.renderFontFace({ fontFamily: 'Roboto', fontStyle: 'normal', fontWeight: 'normal', local: ['Robo'], srcPaths: ['fonts/Roboto.woff2', 'fonts/Roboto.ttf'], }); expect(name).toBe('Roboto'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); }); describe('renderImport()', () => { it('doesnt insert the same at-rule more than once', () => { engine.renderImport('"custom.css"'); engine.renderImport('"custom.css"'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('renders all variants', () => { engine.renderImport('"custom.css"'); engine.renderImport({ path: 'common.css', media: 'screen' }); engine.renderImport({ path: 'print.css', media: 'print' }); engine.renderImport('url("chrome://communicator/skin")'); engine.renderImport('"landscape.css" screen'); engine.renderImport({ path: 'a11y.css', media: 'speech', url: true }); engine.renderImport({ path: 'responsive.css', media: 'screen and (orientation: landscape)' }); engine.renderImport({ path: 'fallback-layout.css', media: 'supports(not (display: flex))' }); expect(getRenderedStyles('global')).toMatchSnapshot(); }); }); describe('renderKeyframes()', () => { it('doesnt insert the same at-rule more than once', () => { engine.renderKeyframes({ from: { transform: 'translateX(0%)', }, to: { transform: 'translateX(100%)', }, }); engine.renderKeyframes({ from: { transform: 'translateX(0%)', }, to: { transform: 'translateX(100%)', }, }); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('renders range based and returns animation name', () => { const name = engine.renderKeyframes({ from: { transform: 'translateX(0%)', }, to: { transform: 'translateX(100%)', }, }); expect(name).toBe('kf103rcyx'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('renders percentage based and returns animation name', () => { const name = engine.renderKeyframes({ '0%': { top: 0, left: 0 }, '30%': { top: '50px' }, '68%, 72%': { left: '50px' }, '100%': { top: '100px', left: '100%' }, }); expect(name).toBe('kf22exw8'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('can provide a custom animation name', () => { const name = engine.renderKeyframes( { from: { opacity: 0, }, to: { opacity: 1, }, }, 'fade', ); expect(name).toBe('fade'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); it('converts between LTR and RTL', () => { const ltr = engine.renderKeyframes( { from: { left: '0', }, to: { right: '100px', }, }, '', { direction: 'ltr' }, ); const rtl = engine.renderKeyframes( { from: { left: '0', }, to: { right: '100px', }, }, '', { direction: 'rtl', }, ); expect(ltr).toBe('kf1lt4056'); expect(rtl).toBe('kf944ipm'); expect(getRenderedStyles('global')).toMatchSnapshot(); }); }); describe('renderRule()', () => { it('generates a unique class name for each property', () => { const className = engine.renderRule({ margin: 0, padding: '6px 12px', border: '1px solid #2e6da4', borderRadius: '4px', display: 'inline-block', cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 'normal', lineHeight: 'normal', whiteSpace: 'nowrap', textDecoration: 'none', textAlign: 'left', backgroundColor: '#337ab7', verticalAlign: 'middle', color: 'rgba(0, 0, 0, 0)', animationName: 'fade', animationDuration: '.3s', }); expect(className.result).toBe('a b c d e f g h i j k l m n o p q'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('generates a deterministic class name for each property', () => { const className = engine.renderRule( { margin: 0, cursor: 'pointer', }, { deterministic: true }, ); const cursor = engine.renderDeclaration('cursor', 'pointer', { deterministic: true }); expect(className.result).toBe('c13kbekr c16r1ggk'); expect(className.result).toContain(cursor); expect(cursor).toBe('c16r1ggk'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('generates a unique class name for each selector even if property value pair is the same', () => { const className = engine.renderRule({ background: '#000', ':hover': { background: '#000', }, '[disabled]': { background: '#000', }, }); expect(className.result).toBe('a b c'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('can nest conditionals infinitely', () => { engine.renderRule({ margin: 0, '@media': { '(width: 500px)': { margin: '10px', ':hover': { color: 'red', }, '@media': { '(width: 350px)': { '@supports': { '(color: blue)': { color: 'blue', ':focus': { color: 'darkblue', }, }, }, }, }, }, }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('applies nested conditionals and selectors correctly', () => { engine.renderRule({ '@media': { '(max-width: 1000px)': { ':hover': {}, '@supports': { '(display: flex)': { '[disabled]': {}, '@media': { '(min-width: 500px)': { '@media': { '(prefers-contrast: low)': { '@supports': { '(color: red)': { color: 'red', }, }, }, }, }, }, }, }, }, }, }); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('can nest selectors infinitely', () => { engine.renderRule({ width: '100%', maxWidth: '100%', margin: 0, padding: 0, backgroundColor: '#fff', border: '1px solid #ccc', borderCollapse: 'collapse', borderSpacing: 0, '@selectors': { '> thead': { display: 'table-head', '@selectors': { '> tr': { backgroundColor: '#eee', '@selectors': { '> th': { border: '1px solid #ccc', padding: 8, textAlign: 'center', '@selectors': { '> span': { fontWeight: 'bold', }, '> a': { textDecoration: 'underline', }, }, }, '> td': { border: '1px solid #ccc', padding: 8, textAlign: 'left', }, }, }, }, }, }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('ignores invalid values', () => { const spy = jest.spyOn(console, 'warn').mockImplementation(); const className = engine.renderRule({ // @ts-expect-error Invalid type margin: true, // @ts-expect-error Invalid type padding: null, color: undefined, }); expect(className.result).toBe(''); expect(getRenderedStyles('standard')).toMatchSnapshot(); spy.mockRestore(); }); it('logs a warning for invalid values', () => { const spy = jest.spyOn(console, 'warn').mockImplementation(); engine.renderRule({ // @ts-expect-error Invalid type color: true, }); expect(spy).toHaveBeenCalledWith('Invalid value "true" for "color".'); expect(getRenderedStyles('standard')).toMatchSnapshot(); spy.mockRestore(); }); it('logs a warning for unknown nested selector', () => { const spy = jest.spyOn(console, 'warn').mockImplementation(); engine.renderRule({ background: 'white', // @ts-expect-error Invalid type '$ what is this': { background: 'black', }, }); expect(spy).toHaveBeenCalledWith( 'Unknown property selector or nested block "$ what is this".', ); expect(getRenderedStyles('standard')).toMatchSnapshot(); spy.mockRestore(); }); it('inserts into the appropriate style sheets', () => { engine.renderRule({ background: 'white', '@media': { '(prefers-color-scheme: dark)': { background: 'black', }, }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('supports CSS variables', () => { const className = engine.renderRule({ display: 'block', color: 'var(--color)', '@variables': { '--color': 'red', fontSize: '14px', 'line-height': 1, }, }); expect(className.result).toBe('a b c d e'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); describe('media queries', () => { it('supports @media conditions', () => { const className = engine.renderRule({ background: '#000', padding: '15px', '@media': { '(max-width: 600px)': { padding: '15px', }, 'screen and (min-width: 900px)': { padding: '20px', }, }, }); expect(className.result).toBe('a b c d'); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('can be nested in @supports', () => { const className = engine.renderRule({ padding: '15px', '@supports': { '(display: flex)': { '@media': { '(max-width: 600px)': { padding: '15px', }, }, }, }, }); expect(className.result).toBe('a b'); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); }); describe('support queries', () => { it('supports @supports conditions', () => { const className = engine.renderRule({ display: 'block', '@supports': { '(display: flex)': { display: 'flex', }, }, }); expect(className.result).toBe('a b'); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('can be nested in @media', () => { const className = engine.renderRule({ display: 'block', '@media': { 'screen and (min-width: 900px)': { '@supports': { '(display: flex)': { display: 'flex', }, }, }, }, }); expect(className.result).toBe('a b'); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); }); describe('attributes', () => { it('generates the correct class names with attribute selector', () => { const className = engine.renderRule({ background: '#000', '[disabled]': { backgroundColor: '#286090', borderColor: '#204d74', }, }); expect(className.result).toBe('a b c'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses same class name between both APIs', () => { const classNameA = engine.renderRule({ '[disabled]': { backgroundColor: '#000', }, }); const classNameB = engine.renderDeclaration('backgroundColor', '#000', { selector: '[disabled]', }); expect(classNameA.result).toBe('a'); expect(classNameA.result).toBe(classNameB); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports complex attribute selectors', () => { engine.renderDeclaration('backgroundColor', '#286090', { selector: '[href*="example"]', }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports attributes in @selectors', () => { engine.renderRule({ '@selectors': { '[disabled]': { opacity: 0.5, }, '[href]': { cursor: 'pointer', }, }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('pseudos', () => { it('generates the correct class names with pseudo selector', () => { const className = engine.renderRule({ padding: '5px', ':hover': { padding: '10px', }, '::before': { content: '"★"', display: 'inline-block', }, }); expect(className.result).toBe('a b c d'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses same class name between both APIs', () => { const classNameA = engine.renderRule({ ':focus': { backgroundColor: '#000', }, }); const classNameB = engine.renderDeclaration('backgroundColor', '#000', { selector: ':focus', }); expect(classNameA.result).toBe('a'); expect(classNameA.result).toBe(classNameB); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports complex attribute selectors', () => { engine.renderDeclaration('color', 'white', { selector: ':nth-last-of-type(4n)', }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports pseudos in @selectors', () => { engine.renderRule({ '@selectors': { ':hover': { position: 'static', }, '::before': { position: 'absolute', }, }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('hierarchy', () => { it('generates the correct class names with hierarchy selector', () => { const className = engine.renderRule({ padding: '10px', '@selectors': { '+ div': { padding: '10px', }, '~ SPAN': { padding: '10px', }, '>li': { padding: '10px', }, '*': { padding: '10px', }, }, }); expect(className.result).toBe('a b c d e'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses same class name between both APIs', () => { const classNameA = engine.renderRule({ '@selectors': { '+ div': { backgroundColor: '#000', }, }, }); const classNameB = engine.renderDeclaration('backgroundColor', '#000', { selector: '+ div', }); expect(classNameA.result).toBe('a'); expect(classNameA.result).toBe(classNameB); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports complex attribute selectors', () => { engine.renderDeclaration('color', 'white', { selector: ':first-of-type + li', }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports combinators in @selectors', () => { engine.renderRule({ '@selectors': { '> li': { listStyle: 'bullet', }, '+ div': { display: 'none', }, '~ span': { color: 'black', }, '*': { backgroundColor: 'inherit', }, }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports multiple selectors separated by a comma', () => { engine.renderRule({ ':active': { cursor: 'pointer', }, '@selectors': { ':disabled, [disabled], > span': { cursor: 'default', }, }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('unit suffixes', () => { it('adds suffix to number values', () => { engine.renderRule({ marginLeft: '10px', marginRight: 20, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('doesnt suffix 0 values', () => { engine.renderRule({ margin: 0, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('doesnt suffix unitless values', () => { engine.renderRule({ lineHeight: 1.25, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('can customize with a string `unit` option', () => { engine.renderRule( { marginLeft: '10px', marginRight: 20, }, { unit: 'rem', }, ); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('can customize with a function `unit` option', () => { engine.unitSuffixer = (prop) => { /* eslint-disable jest/no-if */ if (prop.includes('margin')) return '%'; if (prop.includes('padding')) return 'rem'; if (prop === 'font-size') return 'pt'; return 'px'; }; engine.renderRule({ margin: 10, padding: 20, fontSize: 16, width: 100, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('specificity', () => { it('inserts declarations in the order they are defined', () => { engine.renderRule({ margin: 0, padding: '1px', width: '50px', }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('inserts declarations in the order they are defined (reversed)', () => { engine.renderRule({ width: '50px', padding: '1px', margin: 0, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('inserts selectors in the order they are defined', () => { engine.renderRule({ color: 'white', ':active': { color: 'red', }, ':hover': { color: 'blue', }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('inserts selectors in the order they are defined (reversed)', () => { engine.renderRule({ color: 'white', ':hover': { color: 'blue', }, ':active': { color: 'red', }, }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); describe('variants', () => { it('errors if missing a colon', () => { expect(() => { engine.renderRule({ '@variants': { foo: {}, }, }); }).toThrowErrorMatchingSnapshot(); }); it('errors if starts with a number', () => { expect(() => { engine.renderRule({ '@variants': { '9a:value': {}, }, }); }).toThrowErrorMatchingSnapshot(); }); it('errors if enum is empty', () => { expect(() => { engine.renderRule({ '@variants': { 'type:': {}, }, }); }).toThrowErrorMatchingSnapshot(); }); it('errors if contains a space', () => { expect(() => { engine.renderRule({ '@variants': { 'type:va lue': {}, }, }); }).toThrowErrorMatchingSnapshot(); }); it('errors for invalid compound name', () => { expect(() => { engine.renderRule({ '@variants': { 'type:value + broken': {}, }, }); }).toThrowErrorMatchingSnapshot(); }); it('doesnt error for valid variant type', () => { expect(() => { engine.renderRule({ '@variants': { 'type:value': {}, }, }); }).not.toThrow(); }); it('doesnt error for valid compound variant', () => { expect(() => { engine.renderRule({ '@variants': { 'a:value + b:value': {}, 'b:value + c:value + d:value': {}, }, }); }).not.toThrow(); }); it('returns an empty array if no variants', () => { const result = engine.renderRule({ '@variants': {} }); expect(result).toEqual({ result: '', variants: [] }); }); it('returns a result for each variant', () => { const result = engine.renderRule({ display: 'block', '@variants': { 'size:small': { fontSize: 14, padding: 2, }, 'size:default': { fontSize: 16, padding: 3, }, 'size:large': { fontSize: 18, padding: 4, }, }, }); expect(result).toEqual({ result: 'a', variants: [ { result: 'b c', types: ['size:small'], }, { result: 'd e', types: ['size:default'], }, { result: 'f g', types: ['size:large'], }, ], }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('returns a result for each compound variant', () => { const result = engine.renderRule({ '@variants': { 'size:large + palette:negative': { fontWeight: 'bold', }, }, }); expect(result).toEqual({ result: '', variants: [{ result: 'a', types: ['size:large', 'palette:negative'] }], }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); }); }); describe('renderRuleGrouped()', () => { const rule = { display: 'block', background: 'transparent', color: 'black', paddingRight: 0, marginLeft: 0, transition: '200ms all', appearance: 'none', ':hover': { display: 'flex', color: 'blue', }, '::backdrop': { background: 'black', }, '@media': { '(width: 500px)': { margin: '10px', padding: '10px', ':hover': { color: 'darkblue', }, }, }, } as const; it('generates a single class name for all properties', () => { const className = engine.renderRuleGrouped({ margin: 0, padding: '6px 12px', border: '1px solid #2e6da4', borderRadius: '4px', display: 'inline-block', cursor: 'pointer', fontFamily: 'Roboto', fontWeight: 'normal', lineHeight: 'normal', whiteSpace: 'nowrap', textDecoration: 'none', textAlign: 'left', backgroundColor: '#337ab7', verticalAlign: 'middle', color: 'rgba(0, 0, 0, 0)', animationName: 'fade', animationDuration: '.3s', }); expect(className.result).toBe('cj1oomc'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('generates a consistent class name for same properties', () => { const a = engine.renderRuleGrouped(rule); const b = engine.renderRuleGrouped(rule); expect(a.result).toBe(b.result); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('can vendor prefix applicable properties', () => { const className = engine.renderRuleGrouped(rule, { vendor: true }); expect(className.result).toBe('cix1mgi'); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('can convert direction applicable properties', () => { const className = engine.renderRuleGrouped(rule, { direction: 'rtl' }); expect(className.result).toBe('cnaaqpz'); expect(getRenderedStyles('standard')).toMatchSnapshot(); expect(getRenderedStyles('conditions')).toMatchSnapshot(); }); it('handles direction and vendor prefixes at once', () => { const a = engine.renderRuleGrouped(rule, { direction: 'ltr', vendor: true, }); // RTL const b = engine.renderRuleGrouped(rule, { direction: 'rtl', vendor: true, }); expect(a.result).toBe('cix1mgi'); expect(b.result).toBe('c1t3l09e'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('supports CSS variables', () => { const className = engine.renderRuleGrouped({ display: 'block', color: 'var(--color)', '@variables': { '--color': 'red', fontSize: '14px', 'line-height': 1, }, }); expect(className.result).toBe('cng2wkm'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('generates unique class names for each variant', () => { const className = engine.renderRuleGrouped({ display: 'block', '@variants': { 'size:small': { fontSize: 14, padding: 2, }, 'size:default': { fontSize: 16, padding: 3, }, 'size:large': { fontSize: 18, padding: 4, }, }, }); expect(className).toEqual({ result: 'csfd7x3', variants: [ { result: 'c1taja0', types: ['size:small'], }, { result: 'c146gq7v', types: ['size:default'], }, { result: 'czmqclu', types: ['size:large'], }, ], }); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('logs a warning for unknown nested selector', () => { const spy = jest.spyOn(console, 'warn').mockImplementation(); engine.renderRuleGrouped({ background: 'white', // @ts-expect-error Invalid type '$ what is this': { background: 'black', }, }); expect(spy).toHaveBeenCalledWith( 'Unknown property selector or nested block "$ what is this".', ); expect(getRenderedStyles('standard')).toMatchSnapshot(); spy.mockRestore(); }); }); describe('renderVariable()', () => { it('generates a unique class name for a large number of variables', () => { for (let i = 0; i < 100; i += 1) { engine.renderVariable('fontSize', `${i}px`); } expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses the same class name for the same property value pair', () => { engine.renderVariable('fontSize', '16px'); engine.renderVariable('fontSize', '16px'); engine.renderVariable('fontSize', '16px'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('uses the same class name for dashed and camel cased properties', () => { engine.renderVariable('fontSize', '16px'); engine.renderVariable('font-size', '16px'); engine.renderVariable('--font-size', '16px'); expect(getRenderedStyles('standard')).toMatchSnapshot(); }); it('generates a deterministic class name', () => { const className = engine.renderVariable('--font-size', '16px', { deterministic: true }); expect(className).toBe('ca1tahd'); }); }); });
the_stack
import { BoundingBox, EdgeCirculator, FaceCirculator, LineFaceCirculator, LocateType, Sign, TDS, Triangle, } from "./tds"; import type { Point, Vertex } from "./tds"; import { ccw, collinearBetween, cw, edgeInfo, hasInexactNegativeOrientation, intersection, orientation, sideOfOrientedCircle, xyEqual, } from "./triag"; export type Edge = [Triangle, number]; export class CDT { tds: TDS; constructor() { this.tds = new TDS(); } insertConstraint(a: Point, b: Point): { va: Vertex; vb: Vertex } { const va = this.insert(a); const vb = this.insert(b); if (va !== vb) this.insertConstraintV(va, vb); return { va, vb }; } insertConstraintV(va: Vertex, vb: Vertex): void { const stack = [[va, vb]]; while (stack.length > 0) { const v = stack.pop()!; const info = edgeInfo(v[0], v[1]); if (info.includes) { this.markConstraint(info.fr, info.i); if (info.vi !== v[1]) { stack.push([info.vi, v[1]]); } continue; } const intersectionInfo = this.findIntersectedFaces(v[0], v[1]); if (intersectionInfo.found) { if (intersectionInfo.vi !== v[0] && intersectionInfo.vi !== v[1]) { stack.push([v[0], intersectionInfo.vi]); stack.push([intersectionInfo.vi, v[1]]); } else { stack.push(v); } continue; } this.triangulateHole(intersectionInfo.intersectedFaces, intersectionInfo.listAB, intersectionInfo.listBA); if (intersectionInfo.vi !== v[1]) { stack.push([intersectionInfo.vi, v[1]]); } } } triangulateHole(intersectedFaces: Triangle[], listAB: Edge[], listBA: Edge[]): void { const edges: Edge[] = []; this.triangulateHole2(intersectedFaces, listAB, listBA, edges); this.propagatingFlipE(edges); } triangulateHole2(intersectedFaces: Triangle[], listAB: Edge[], listBA: Edge[], edges: Edge[]): void { if (listAB.length > 0) { this.triangulateHalfHole(listAB, edges); this.triangulateHalfHole(listBA, edges); const fl = listAB[0][0]; const fr = listBA[0][0]; fl.neighbours[2] = fr; fr.neighbours[2] = fl; fl.constraints[2] = true; fr.constraints[2] = true; while (intersectedFaces.length > 0) { this.tds.deleteTriangle(intersectedFaces.shift()!); } } } triangulateHalfHole(conflictBoundaries: Edge[], edges: Edge[]): void { let iC = 0; let iN: number; let iT: number; const current = (): [Triangle, number] => conflictBoundaries[iC]; const next = (): [Triangle, number] => conflictBoundaries[iN]; // const tempo = (): [Triangle, number] => conflictBoundaries[iT]; const va = current()[0].vertices[ccw(current()[1])]!; iN = iC; ++iN; let n: Triangle; let n1: Triangle; let n2: Triangle; let ind: number; let ind1: number; let ind2: number; do { n1 = current()[0]; ind1 = current()[1]; if (n1.neighbours[ind1] !== null) { n = n1.neighbours[ind1]!; ind = cw(n.indexV(n1.vertices[cw(ind1)]!)); n1 = n.neighbours[ind]!; ind1 = this.tds.mirrorIndex(n, ind); } n2 = next()[0]; ind2 = next()[1]; if (n2.neighbours[ind2] !== null) { n = n2.neighbours[ind2]!; ind = cw(n.indexV(n2.vertices[cw(ind2)]!)); n2 = n.neighbours[ind]!; ind2 = this.tds.mirrorIndex(n, ind); } const v0 = n1.vertices[ccw(ind1)]!; const v1 = n1.vertices[cw(ind1)]!; const v2 = n2.vertices[cw(ind2)]!; const orient = orientation(v0.point!, v1.point!, v2.point!); switch (orient) { case Sign.RIGHT_TURN: { const newlf = this.tds.createTriangle(v0, v2, v1, null, null, null); edges.push([newlf, 2]); newlf.neighbours[1] = n1; newlf.neighbours[0] = n2; n1.neighbours[ind1] = newlf; n2.neighbours[ind2] = newlf; if (n1.isConstrained(ind1)) newlf.constraints[1] = true; if (n2.isConstrained(ind2)) newlf.constraints[0] = true; v0.triangle = newlf; v1.triangle = newlf; v2.triangle = newlf; iT = iC + 1; conflictBoundaries.splice(iC, 0, [newlf, 2]); conflictBoundaries.splice(Math.max(iT, iN), 1); conflictBoundaries.splice(Math.min(iT, iN), 1); iN = iC; if (v0 !== va) --iC; else ++iN; break; } case Sign.LEFT_TURN: case Sign.COLLINEAR: { ++iC; ++iN; break; } } } while (iN < conflictBoundaries.length); } findIntersectedFaces( vaa: Vertex, vbb: Vertex, ): { found: boolean; vi: Vertex; listAB: Edge[]; listBA: Edge[]; intersectedFaces: Triangle[] } { const aa = vaa.point!; const bb = vbb.point!; const listAB: Edge[] = []; const listBA: Edge[] = []; const intersectedFaces: Triangle[] = []; const lfc = new LineFaceCirculator(vaa, this, bb); let ind = lfc.pos!.indexV(vaa); let vi: Vertex; if (lfc.pos!.isConstrained(ind)) { vi = this.intersect(lfc.pos!, ind, vaa, vbb); return { found: true, vi, listAB, listBA, intersectedFaces }; } let lf = lfc.pos!.neighbours[ccw(ind)]!; let rf = lfc.pos!.neighbours[cw(ind)]!; listAB.push([lf, lf.indexT(lfc.pos!)]); listBA.unshift([rf, rf.indexT(lfc.pos!)]); intersectedFaces.unshift(lfc.pos!); let previousFace = lfc.pos!; lfc.next(); ind = lfc.pos!.indexT(previousFace); let currentVertex = lfc.pos!.vertices[ind]!; let done = false; while (currentVertex !== vbb && !done) { let i1: number; let i2: number; const orient = orientation(aa, bb, currentVertex.point!); switch (orient) { case Sign.COLLINEAR: { done = true; break; } case Sign.LEFT_TURN: case Sign.RIGHT_TURN: { if (orient === Sign.LEFT_TURN) { i1 = ccw(ind); i2 = cw(ind); } else { i1 = cw(ind); i2 = ccw(ind); } if (lfc.pos!.isConstrained(i1)) { vi = this.intersect(lfc.pos!, i1, vaa, vbb); return { found: true, vi, listAB, listBA, intersectedFaces }; } else { lf = lfc.pos!.neighbours[i2]!; intersectedFaces.unshift(lfc.pos!); if (orient === Sign.LEFT_TURN) listAB.push([lf, lf.indexT(lfc.pos!)]); else listBA.unshift([lf, lf.indexT(lfc.pos!)]); previousFace = lfc.pos!; lfc.next(); ind = lfc.pos!.indexT(previousFace); currentVertex = lfc.pos!.vertices[ind]!; } break; } } } vi = currentVertex; intersectedFaces.unshift(lfc.pos!); lf = lfc.pos!.neighbours[cw(ind)]!; listAB.push([lf, lf.indexT(lfc.pos!)]); rf = lfc.pos!.neighbours[ccw(ind)]!; listBA.unshift([rf, rf.indexT(lfc.pos!)]); return { found: false, vi, listAB, listBA, intersectedFaces }; } intersect(t: Triangle, i: number, vaa: Vertex, vbb: Vertex): Vertex { const vcc = t.vertices[cw(i)]!; const vdd = t.vertices[ccw(i)]!; const pa = vaa.point!; const pb = vbb.point!; const pc = vcc.point!; const pd = vdd.point!; let pi = intersection(pa, pb, pc, pd); let vi: Vertex; if (pi === null) { // CGAL limit_intersection returns 0 for exact intersections and no intersections, but has an implementation for exact predicates ?? unsure which path we would like to take const limitIntersection = 0; switch (limitIntersection) { case 0: vi = vaa; break; // case 1: // vi = vbb; // break; // case 2: // vi = vcc; // break; // case 3: // vi = vdd; // break; default: throw new Error("limit_intersection should return 0 to 4"); } if (vi === vaa || vi === vbb) this.removeConstrainedEdge(t, limitIntersection); } else { if (pi !== pa && pi !== pb && pi !== pc && pi !== pd) { // Try to snap to an existing point const bbox = new BoundingBox(pi); bbox.dilate(4); if (bbox.overlaps(new BoundingBox(pa))) pi = pa; if (bbox.overlaps(new BoundingBox(pb))) pi = pb; if (bbox.overlaps(new BoundingBox(pc))) pi = pc; if (bbox.overlaps(new BoundingBox(pd))) pi = pd; } this.removeConstrainedEdge(t, i); vi = this.insert(pi, t); } if (vi !== vcc && vi !== vdd) { this.insertConstraintV(vcc, vi); this.insertConstraintV(vi, vdd); } else { this.insertConstraintV(vcc, vdd); } return vi; } // This is the Constrained Delaunay version removeVertex(v: Vertex): void { if (this.tds.dimension <= 1) this.removeConstrainedVertex(v); else this.remove2D(v); } // This is the normal Constrained version private removeConstrainedVertex(v: Vertex): void { const vertexCount = this.tds.numberOfVertices(false); if (vertexCount === 1 || vertexCount === 2) this.tds.removeDimDown(v); else if (this.tds.dimension === 1) console.warn("NOT IMPLEMENTED."); // this.remove1D(v) else this.remove2D(v); } remove2D(v: Vertex): void { if (this.testDimDown(v)) this.tds.removeDimDown(v); else { const hole: Edge[] = []; this.tds.makeHole(v, hole); const shell: Edge[] = [...hole]; this.tds.fillHoleDelaunay(hole); this.updateConstraints(shell); this.tds.deleteVertex(v); } } testDimDown(v: Vertex): boolean { let dim1 = true; for (const triangle of this.tds.triangles) { if (triangle.isInfinite()) continue; if (!triangle.hasVertex(v)) { dim1 = false; break; } } const fc = new FaceCirculator(v, null); while (fc.t!.isInfinite()) fc.next(); fc.setDone(); const start = fc.t!; let iv = start.indexV(v); const p = start.vertices[cw(iv)]!.point!; const q = start.vertices[ccw(iv)]!.point!; while (dim1 && fc.next()) { iv = fc.t!.indexV(v); if (fc.t!.vertices[ccw(iv)] !== this.tds._infinite) { dim1 = dim1 && orientation(p, q, fc.t!.vertices[ccw(iv)]!.point!) === Sign.COLLINEAR; } } return dim1; } updateConstraints(edgeList: Edge[]): void { let f: Triangle; let i: number; for (const edge of edgeList) { f = edge[0]; i = edge[1]; f.neighbours[i]!.constraints[this.tds.mirrorIndex(f, i)] = f.isConstrained(i); } } removeConstrainedEdge(t: Triangle, i: number): void { t.constraints[i] = false; if (this.tds.dimension === 2) t.neighbours[i]!.constraints[this.tds.mirrorIndex(t, i)] = false; } removeConstrainedEdgeDelaunay(t: Triangle, i: number): [Triangle, number, Triangle, number][] { this.removeConstrainedEdge(t, i); if (this.tds.dimension === 2) { const listEdges: Edge[] = [[t, i]]; return this.propagatingFlipE(listEdges); } return []; } updateConstraintsOpposite(v: Vertex): void { let t = v.triangle!; const start = t; let indf: number; do { indf = t.indexV(v); if (t.neighbours[indf]!.constraints[this.tds.mirrorIndex(t, indf)]) t.constraints[indf] = true; else t.constraints[indf] = false; t = t.neighbours[ccw(indf)]!; } while (t !== start); } markConstraint(t: Triangle, i: number): void { if (this.tds.dimension === 1) t.constraints[2] = true; else { t.constraints[i] = true; t.neighbours[i]!.constraints[this.tds.mirrorIndex(t, i)] = true; } } insert(p: Point, start: Triangle | null = null): Vertex { const locateInfo = this.locate(p, this.iLocate(p, start)); const va = this.insertb(p, locateInfo.loc, locateInfo.lt, locateInfo.li); this.flipAround(va); return va; } flipAround(v: Vertex): void { if (this.tds.dimension <= 1) return; let t = v.triangle!; let i: number; let next: Triangle; const start = t; do { i = t.indexV(v); next = t.neighbours[ccw(i)]!; this.propagatingFlip(t, i); t = next; } while (next !== start); } propagatingFlip(t: Triangle, i: number, depth = 0): void { if (!this.isFlipable(t, i)) return; const maxDepth = 100; if (depth === maxDepth) { throw new Error("maxde"); } const ni = t.neighbours[i]!; this.flip(t, i); this.propagatingFlip(t, i, depth + 1); i = ni.indexV(t.vertices[i]!); this.propagatingFlip(ni, i, depth + 1); } lessEdge(e1: Edge, e2: Edge): boolean { const ind1 = e1[1]; const ind2 = e2[1]; return e1[0].uid < e2[0].uid || (e1[0].uid === e2[0].uid && ind1 < ind2); } // Instead of only the affected triangles also send the indices around which the flip happened propagatingFlipE(edges: Edge[]): [Triangle, number, Triangle, number][] { const out: [Triangle, number, Triangle, number][] = []; let eI = 0; let t: Triangle; let i: number; let eni: Edge; const edgeSet: Edge[] = []; while (eI < edges.length) { t = edges[eI][0]; i = edges[eI][1]; if (this.isFlipable(t, i)) { eni = [t.neighbours[i]!, this.tds.mirrorIndex(t, i)]; if (this.lessEdge(edges[eI], eni)) edgeSet.push(edges[eI]); else edgeSet.push(eni); } ++eI; } let indf: number; let ni: Triangle; let indn: number; let ei: Edge; const e: (Edge | null)[] = [null, null, null, null]; while (edgeSet.length > 0) { t = edgeSet[0][0]; indf = edgeSet[0][1]; ni = t.neighbours[indf]!; indn = this.tds.mirrorIndex(t, indf); ei = [t, indf]; edgeSet.splice( edgeSet.findIndex((ed) => ed[0] === ei[0] && ed[1] === ei[1]), 1, ); e[0] = [t, cw(indf)]; e[1] = [t, ccw(indf)]; e[2] = [ni, cw(indn)]; e[3] = [ni, ccw(indn)]; for (const edge of e) { const tt = edge![0]; const ii = edge![1]; eni = [tt.neighbours[ii]!, this.tds.mirrorIndex(tt, ii)]; if (this.lessEdge(edge!, eni)) edgeSet.splice( edgeSet.findIndex((ed) => ed[0] === edge![0] && ed[1] === edge![1]), 1, ); else edgeSet.splice( edgeSet.findIndex((ed) => ed[0] === eni[0] && ed[1] === eni[1]), 1, ); } out.push([t, indf, t.neighbours[indf]!, this.tds.mirrorIndex(t, indf)]); this.flip(t, indf); e[0] = [t, indf]; e[1] = [t, cw(indf)]; e[2] = [ni, indn]; e[3] = [ni, cw(indn)]; for (const edge of e) { const tt = edge![0]; const ii = edge![1]; if (this.isFlipable(tt, ii)) { eni = [tt.neighbours[ii]!, this.tds.mirrorIndex(tt, ii)]; if (this.lessEdge(edge!, eni)) edgeSet.push(edge!); else edgeSet.push(eni); } } } return out; } flip(t: Triangle, i: number): void { const u = t.neighbours[i]!; const j = this.tds.mirrorIndex(t, i); const t1 = t.neighbours[cw(i)]!; const i1 = this.tds.mirrorIndex(t, cw(i)); const t2 = t.neighbours[ccw(i)]!; const i2 = this.tds.mirrorIndex(t, ccw(i)); const t3 = u.neighbours[cw(j)]!; const i3 = this.tds.mirrorIndex(u, cw(j)); const t4 = u.neighbours[ccw(j)]!; const i4 = this.tds.mirrorIndex(u, ccw(j)); this.tds.flip(t, i); t.constraints[t.indexT(u)] = false; u.constraints[u.indexT(t)] = false; t1.neighbours[i1]!.constraints[this.tds.mirrorIndex(t1, i1)] = t1.constraints[i1]; t2.neighbours[i2]!.constraints[this.tds.mirrorIndex(t2, i2)] = t2.constraints[i2]; t3.neighbours[i3]!.constraints[this.tds.mirrorIndex(t3, i3)] = t3.constraints[i3]; t4.neighbours[i4]!.constraints[this.tds.mirrorIndex(t4, i4)] = t4.constraints[i4]; } isFlipable(t: Triangle, i: number, perturb = true): boolean { const ni = t.neighbours[i]!; if (t.isInfinite() || ni.isInfinite()) return false; if (t.constraints[i]) return false; return sideOfOrientedCircle(ni, t.vertices[i]!.point!, perturb) === Sign.ON_POSITIVE_SIDE; } insertb(a: Point, loc: Triangle | null, lt: LocateType, li: number): Vertex { let insertInConstrainedEdge = false; let v1: Vertex; let v2: Vertex; if (lt === LocateType.EDGE && loc!.isConstrained(li)) { insertInConstrainedEdge = true; v1 = loc!.vertices[ccw(li)]!; v2 = loc!.vertices[cw(li)]!; } const va = this.insertc(a, loc, lt, li); if (insertInConstrainedEdge) this.updateConstraintsIncident(va, v1!, v2!); else if (lt !== LocateType.VERTEX) this.clearConstraintsIncident(va); if (this.tds.dimension === 2) this.updateConstraintsOpposite(va); return va; } updateConstraintsIncident(va: Vertex, c1: Vertex, c2: Vertex): void { if (this.tds.dimension === 0) return; if (this.tds.dimension === 1) { const ec = new EdgeCirculator(va, null); do { ec.t!.constraints[2] = true; } while (ec.next()); } else { const fc = new FaceCirculator(va, null); do { const indf = fc.t!.indexV(va); const cwi = cw(indf); const ccwi = ccw(indf); if (fc.t!.vertices[cwi] === c1 || fc.t!.vertices[cwi] === c2) { fc.t!.constraints[ccwi] = true; fc.t!.constraints[cwi] = false; } else { fc.t!.constraints[ccwi] = false; fc.t!.constraints[cwi] = true; } } while (fc.next()); } } clearConstraintsIncident(v: Vertex): void { const ec = new EdgeCirculator(v, null); if (ec.valid) { do { const t = ec.t!; const indf = ec.ri; t.constraints[indf] = false; if (this.tds.dimension === 2) t.neighbours[indf]!.constraints[this.tds.mirrorIndex(t, indf)] = false; } while (ec.next()); } } insertc(p: Point, loc: Triangle | null, lt: LocateType, li: number): Vertex { if (this.tds.vertices.length === 1) { return this.insertFirst(p); } else if (this.tds.vertices.length === 2) { if (lt === LocateType.VERTEX) return this.tds.finiteVertex; else return this.insertSecond(p); } switch (lt) { case LocateType.VERTEX: { return loc!.vertices[li]!; } case LocateType.OUTSIDE_AFFINE_HULL: { return this.insertOutsideAffineHull(p); } case LocateType.OUTSIDE_CONVEX_HULL: { return this.insertOutsideConvexHull(p, loc!); } case LocateType.EDGE: { return this.insertInEdge(p, loc!, li); } case LocateType.FACE: { return this.insertInFace(p, loc!); } } } insertInEdge(p: Point, loc: Triangle, li: number): Vertex { const v = this.tds.insertInEdge(loc, li); v.point = p; return v; } insertInFace(p: Point, loc: Triangle): Vertex { const v = this.tds.insertInFace(loc); v.point = p; return v; } insertFirst(p: Point): Vertex { const v = this.tds.insertDimUp(); v.point = p; return v; } insertSecond(p: Point): Vertex { const v = this.tds.insertDimUp(this.tds._infinite, true); v.point = p; return v; } insertOutsideAffineHull(p: Point): Vertex { let conform = false; if (this.tds.dimension === 1) { const t = this.tds.finiteEdge.first!; const orient = orientation(t.vertices[0]!.point!, t.vertices[1]!.point!, p); conform = orient === Sign.COUNTERCLOCKWISE; } const v = this.tds.insertDimUp(this.tds._infinite, conform); v.point = p; return v; } insertOutsideConvexHull(p: Point, t: Triangle): Vertex { let v: Vertex; if (this.tds.dimension === 1) { v = this.insertOutsideConvexHull1(p, t); } else { v = this.insertOutsideConvexHull2(p, t); } v.point = p; return v; } insertOutsideConvexHull1(p: Point, t: Triangle): Vertex { const v = this.tds.insertInEdge(t, 2); v.point = p; return v; } insertOutsideConvexHull2(p: Point, t: Triangle): Vertex { let li = t.indexV(this.tds._infinite); const ccwlist: Triangle[] = []; const cwlist: Triangle[] = []; let fc = new FaceCirculator(this.tds._infinite, t); let done = false; while (!done) { fc.prev(); li = fc.t!.indexV(this.tds._infinite); const q = fc.t!.vertices[ccw(li)]!.point!; const r = fc.t!.vertices[cw(li)]!.point!; if (orientation(p, q, r) === Sign.LEFT_TURN) ccwlist.push(fc.t!); else done = true; } fc = new FaceCirculator(this.tds._infinite, t); done = false; while (!done) { fc.next(); li = fc.t!.indexV(this.tds._infinite); const q = fc.t!.vertices[ccw(li)]!.point!; const r = fc.t!.vertices[cw(li)]!.point!; if (orientation(p, q, r) === Sign.LEFT_TURN) cwlist.push(fc.t!); else done = true; } const v = this.tds.insertInFace(t); v.point = p; let th; while (ccwlist.length > 0) { th = ccwlist[0]; li = ccw(th.indexV(this.tds._infinite)); this.tds.flip(th, li); ccwlist.shift(); } while (cwlist.length > 0) { th = cwlist[0]; li = cw(th.indexV(this.tds._infinite)); this.tds.flip(th, li); cwlist.shift(); } fc = new FaceCirculator(v, null); while (!fc.t!.isInfinite()) fc.next(); this.tds._infinite.triangle = fc.t!; return v; } locate( p: Point, start: Triangle | null, ): { loc: Triangle; lt: LocateType; li: number } | { loc: null; lt: number; li: number } { let lt = 0; let li = 0; if (this.tds.dimension < 0) { lt = LocateType.OUTSIDE_AFFINE_HULL; li = 4; return { loc: null, lt, li }; } else if (this.tds.dimension === 0) { if (xyEqual(p, this.tds.finiteVertex.triangle!.vertices[0]!.point!)) { lt = LocateType.VERTEX; } else { lt = LocateType.OUTSIDE_AFFINE_HULL; } li = 4; return { loc: null, lt, li }; } else if (this.tds.dimension === 1) { return this.marchLocate1D(p); } if (start === null) { const t = this.tds._infinite.triangle!; start = t.neighbours[t.indexV(this.tds._infinite)]!; } else if (start.isInfinite()) { start = start.neighbours[start.indexV(this.tds._infinite)]!; } return this.marchLocate2D(start, p); } marchLocate1D(p: Point): { loc: Triangle; lt: LocateType; li: number } { let ff = this.tds._infinite.triangle!; let iv = ff.indexV(this.tds._infinite); let t = ff.neighbours[iv]!; const pqt = orientation(t.vertices[0]!.point!, t.vertices[1]!.point!, p); if (pqt === Sign.RIGHT_TURN || pqt === Sign.LEFT_TURN) { return { loc: new Triangle(), lt: LocateType.OUTSIDE_AFFINE_HULL, li: 4 }; } let i = t.indexT(ff); if (collinearBetween(p, t.vertices[1 - i]!.point!, t.vertices[i]!.point!)) return { loc: ff, lt: LocateType.OUTSIDE_CONVEX_HULL, li: iv }; if (xyEqual(p, t.vertices[1 - i]!.point!)) return { loc: t, lt: LocateType.VERTEX, li: 1 - i }; ff = ff.neighbours[1 - iv]!; iv = ff.indexV(this.tds._infinite); t = ff.neighbours[iv]!; i = t.indexT(ff); if (collinearBetween(p, t.vertices[1 - i]!.point!, t.vertices[i]!.point!)) return { loc: ff, lt: LocateType.OUTSIDE_CONVEX_HULL, li: iv }; if (xyEqual(p, t.vertices[1 - i]!.point!)) return { loc: t, lt: LocateType.VERTEX, li: 1 - i }; throw new Error("Vision Error (marchLocate1D)"); } marchLocate2D(c: Triangle, p: Point): { loc: Triangle; lt: LocateType; li: number } { let prev = null; let first = true; let lt: LocateType | undefined; let li: number | undefined; while (true) { if (c.isInfinite()) { return { loc: c, lt: LocateType.OUTSIDE_CONVEX_HULL, li: c.indexV(this.tds._infinite) }; } const leftFirst = 0; // Math.round(Math.random()); const p0 = c.vertices[0]!.point!; const p1 = c.vertices[1]!.point!; const p2 = c.vertices[2]!.point!; let o0: Sign; let o1: Sign; let o2: Sign; if (first) { prev = c; first = false; o0 = orientation(p0, p1, p); if (o0 === Sign.NEGATIVE) { c = c.neighbours[2]!; continue; } o1 = orientation(p1, p2, p); if (o1 === Sign.NEGATIVE) { c = c.neighbours[0]!; continue; } o2 = orientation(p2, p0, p); if (o2 === Sign.NEGATIVE) { c = c.neighbours[1]!; continue; } } else if (leftFirst) { if (c.neighbours[0]! === prev) { prev = c; o0 = orientation(p0, p1, p); if (o0 === Sign.NEGATIVE) { c = c.neighbours[2]!; continue; } o2 = orientation(p2, p0, p); if (o2 === Sign.NEGATIVE) { c = c.neighbours[1]!; continue; } o1 = Sign.POSITIVE; } else if (c.neighbours[1]! === prev) { prev = c; o1 = orientation(p1, p2, p); if (o1 === Sign.NEGATIVE) { c = c.neighbours[0]!; continue; } o0 = orientation(p0, p1, p); if (o0 === Sign.NEGATIVE) { c = c.neighbours[2]!; continue; } o2 = Sign.POSITIVE; } else { prev = c; o2 = orientation(p2, p0, p); if (o2 === Sign.NEGATIVE) { c = c.neighbours[1]!; continue; } o1 = orientation(p1, p2, p); if (o1 === Sign.NEGATIVE) { c = c.neighbours[0]!; continue; } o0 = Sign.POSITIVE; } } else { if (c.neighbours[0] === prev) { prev = c; o2 = orientation(p2, p0, p); if (o2 === Sign.NEGATIVE) { c = c.neighbours[1]!; continue; } o0 = orientation(p0, p1, p); if (o0 === Sign.NEGATIVE) { c = c.neighbours[2]!; continue; } o1 = Sign.POSITIVE; } else if (c.neighbours[1] === prev) { prev = c; o0 = orientation(p0, p1, p); if (o0 === Sign.NEGATIVE) { c = c.neighbours[2]!; continue; } o1 = orientation(p1, p2, p); if (o1 === Sign.NEGATIVE) { c = c.neighbours[0]!; continue; } o2 = Sign.POSITIVE; } else { prev = c; o1 = orientation(p1, p2, p); if (o1 === Sign.NEGATIVE) { c = c.neighbours[0]!; continue; } o2 = orientation(p2, p0, p); if (o2 === Sign.NEGATIVE) { c = c.neighbours[1]!; continue; } o0 = Sign.POSITIVE; } } const sum = (o0 === Sign.COLLINEAR ? 1 : 0) + (o1 === Sign.COLLINEAR ? 1 : 0) + (o2 === Sign.COLLINEAR ? 1 : 0); switch (sum) { case 0: { lt = LocateType.FACE; li = 4; break; } case 1: { lt = LocateType.EDGE; li = o0 === Sign.COLLINEAR ? 2 : o1 === Sign.COLLINEAR ? 0 : 1; break; } case 2: { lt = LocateType.VERTEX; li = o0 !== Sign.COLLINEAR ? 2 : o1 !== Sign.COLLINEAR ? 0 : 1; break; } } if (lt === undefined || li === undefined) throw new Error("ert"); return { loc: c, lt, li }; } } iLocate(p: Point, start: Triangle | null): Triangle | null { if (this.tds.dimension < 2) return start; if (start === null) { const t = this.tds._infinite.triangle!; start = t.neighbours[t.indexV(this.tds._infinite)]; } else if (start.isInfinite()) { start = start.neighbours[start.indexV(this.tds._infinite)]; } let prev = null; let c = start!; let first = true; let nTurns = 2500; while (true) { if (!nTurns--) return c; if (c.isInfinite()) return c; const p0 = c.vertices[0]!.point!; const p1 = c.vertices[1]!.point!; const p2 = c.vertices[2]!.point!; if (first) { prev = c; first = false; if (hasInexactNegativeOrientation(p0, p1, p)) { c = c.neighbours[2]!; continue; } if (hasInexactNegativeOrientation(p1, p2, p)) { c = c.neighbours[0]!; continue; } if (hasInexactNegativeOrientation(p2, p0, p)) { c = c.neighbours[1]!; continue; } } else { if (c.neighbours[0] === prev) { prev = c; if (hasInexactNegativeOrientation(p0, p1, p)) { c = c.neighbours[2]!; continue; } if (hasInexactNegativeOrientation(p2, p0, p)) { c = c.neighbours[1]!; continue; } } else if (c.neighbours[1] === prev) { prev = c; if (hasInexactNegativeOrientation(p0, p1, p)) { c = c.neighbours[2]!; continue; } if (hasInexactNegativeOrientation(p1, p2, p)) { c = c.neighbours[0]!; continue; } } else { prev = c; if (hasInexactNegativeOrientation(p2, p0, p)) { c = c.neighbours[1]!; continue; } if (hasInexactNegativeOrientation(p1, p2, p)) { c = c.neighbours[0]!; continue; } } } break; } return c; } }
the_stack
import * as $protobuf from "protobufjs"; /** Namespace cosmos. */ export namespace cosmos { /** Namespace bank. */ namespace bank { /** Namespace v1beta1. */ namespace v1beta1 { /** Properties of a Params. */ interface IParams { /** Params sendEnabled */ sendEnabled?: (cosmos.bank.v1beta1.ISendEnabled[]|null); /** Params defaultSendEnabled */ defaultSendEnabled?: (boolean|null); } /** Represents a Params. */ class Params implements IParams { /** * Constructs a new Params. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IParams); /** Params sendEnabled. */ public sendEnabled: cosmos.bank.v1beta1.ISendEnabled[]; /** Params defaultSendEnabled. */ public defaultSendEnabled: boolean; /** * Creates a new Params instance using the specified properties. * @param [properties] Properties to set * @returns Params instance */ public static create(properties?: cosmos.bank.v1beta1.IParams): cosmos.bank.v1beta1.Params; /** * Encodes the specified Params message. Does not implicitly {@link cosmos.bank.v1beta1.Params.verify|verify} messages. * @param m Params message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IParams, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Params message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Params * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.Params; /** * Creates a Params message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Params */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Params; /** * Creates a plain object from a Params message. Also converts values to other types if specified. * @param m Params * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Params, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Params to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SendEnabled. */ interface ISendEnabled { /** SendEnabled denom */ denom?: (string|null); /** SendEnabled enabled */ enabled?: (boolean|null); } /** Represents a SendEnabled. */ class SendEnabled implements ISendEnabled { /** * Constructs a new SendEnabled. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.ISendEnabled); /** SendEnabled denom. */ public denom: string; /** SendEnabled enabled. */ public enabled: boolean; /** * Creates a new SendEnabled instance using the specified properties. * @param [properties] Properties to set * @returns SendEnabled instance */ public static create(properties?: cosmos.bank.v1beta1.ISendEnabled): cosmos.bank.v1beta1.SendEnabled; /** * Encodes the specified SendEnabled message. Does not implicitly {@link cosmos.bank.v1beta1.SendEnabled.verify|verify} messages. * @param m SendEnabled message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.ISendEnabled, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SendEnabled message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SendEnabled * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.SendEnabled; /** * Creates a SendEnabled message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SendEnabled */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.SendEnabled; /** * Creates a plain object from a SendEnabled message. Also converts values to other types if specified. * @param m SendEnabled * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.SendEnabled, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SendEnabled to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Input. */ interface IInput { /** Input address */ address?: (string|null); /** Input coins */ coins?: (cosmos.base.v1beta1.ICoin[]|null); } /** Represents an Input. */ class Input implements IInput { /** * Constructs a new Input. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IInput); /** Input address. */ public address: string; /** Input coins. */ public coins: cosmos.base.v1beta1.ICoin[]; /** * Creates a new Input instance using the specified properties. * @param [properties] Properties to set * @returns Input instance */ public static create(properties?: cosmos.bank.v1beta1.IInput): cosmos.bank.v1beta1.Input; /** * Encodes the specified Input message. Does not implicitly {@link cosmos.bank.v1beta1.Input.verify|verify} messages. * @param m Input message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IInput, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Input message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Input * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.Input; /** * Creates an Input message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Input */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Input; /** * Creates a plain object from an Input message. Also converts values to other types if specified. * @param m Input * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Input, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Input to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Output. */ interface IOutput { /** Output address */ address?: (string|null); /** Output coins */ coins?: (cosmos.base.v1beta1.ICoin[]|null); } /** Represents an Output. */ class Output implements IOutput { /** * Constructs a new Output. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IOutput); /** Output address. */ public address: string; /** Output coins. */ public coins: cosmos.base.v1beta1.ICoin[]; /** * Creates a new Output instance using the specified properties. * @param [properties] Properties to set * @returns Output instance */ public static create(properties?: cosmos.bank.v1beta1.IOutput): cosmos.bank.v1beta1.Output; /** * Encodes the specified Output message. Does not implicitly {@link cosmos.bank.v1beta1.Output.verify|verify} messages. * @param m Output message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IOutput, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Output message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Output * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.Output; /** * Creates an Output message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Output */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Output; /** * Creates a plain object from an Output message. Also converts values to other types if specified. * @param m Output * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Output, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Output to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Supply. */ interface ISupply { /** Supply total */ total?: (cosmos.base.v1beta1.ICoin[]|null); } /** Represents a Supply. */ class Supply implements ISupply { /** * Constructs a new Supply. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.ISupply); /** Supply total. */ public total: cosmos.base.v1beta1.ICoin[]; /** * Creates a new Supply instance using the specified properties. * @param [properties] Properties to set * @returns Supply instance */ public static create(properties?: cosmos.bank.v1beta1.ISupply): cosmos.bank.v1beta1.Supply; /** * Encodes the specified Supply message. Does not implicitly {@link cosmos.bank.v1beta1.Supply.verify|verify} messages. * @param m Supply message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.ISupply, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Supply message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Supply * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.Supply; /** * Creates a Supply message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Supply */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Supply; /** * Creates a plain object from a Supply message. Also converts values to other types if specified. * @param m Supply * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Supply, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Supply to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DenomUnit. */ interface IDenomUnit { /** DenomUnit denom */ denom?: (string|null); /** DenomUnit exponent */ exponent?: (number|null); /** DenomUnit aliases */ aliases?: (string[]|null); } /** Represents a DenomUnit. */ class DenomUnit implements IDenomUnit { /** * Constructs a new DenomUnit. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IDenomUnit); /** DenomUnit denom. */ public denom: string; /** DenomUnit exponent. */ public exponent: number; /** DenomUnit aliases. */ public aliases: string[]; /** * Creates a new DenomUnit instance using the specified properties. * @param [properties] Properties to set * @returns DenomUnit instance */ public static create(properties?: cosmos.bank.v1beta1.IDenomUnit): cosmos.bank.v1beta1.DenomUnit; /** * Encodes the specified DenomUnit message. Does not implicitly {@link cosmos.bank.v1beta1.DenomUnit.verify|verify} messages. * @param m DenomUnit message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IDenomUnit, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DenomUnit message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns DenomUnit * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.DenomUnit; /** * Creates a DenomUnit message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns DenomUnit */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.DenomUnit; /** * Creates a plain object from a DenomUnit message. Also converts values to other types if specified. * @param m DenomUnit * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.DenomUnit, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DenomUnit to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Metadata. */ interface IMetadata { /** Metadata description */ description?: (string|null); /** Metadata denomUnits */ denomUnits?: (cosmos.bank.v1beta1.IDenomUnit[]|null); /** Metadata base */ base?: (string|null); /** Metadata display */ display?: (string|null); /** Metadata name */ name?: (string|null); /** Metadata symbol */ symbol?: (string|null); } /** Represents a Metadata. */ class Metadata implements IMetadata { /** * Constructs a new Metadata. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IMetadata); /** Metadata description. */ public description: string; /** Metadata denomUnits. */ public denomUnits: cosmos.bank.v1beta1.IDenomUnit[]; /** Metadata base. */ public base: string; /** Metadata display. */ public display: string; /** Metadata name. */ public name: string; /** Metadata symbol. */ public symbol: string; /** * Creates a new Metadata instance using the specified properties. * @param [properties] Properties to set * @returns Metadata instance */ public static create(properties?: cosmos.bank.v1beta1.IMetadata): cosmos.bank.v1beta1.Metadata; /** * Encodes the specified Metadata message. Does not implicitly {@link cosmos.bank.v1beta1.Metadata.verify|verify} messages. * @param m Metadata message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IMetadata, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Metadata message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Metadata * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.Metadata; /** * Creates a Metadata message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Metadata */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.Metadata; /** * Creates a plain object from a Metadata message. Also converts values to other types if specified. * @param m Metadata * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.Metadata, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Metadata to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Represents a Msg */ class Msg extends $protobuf.rpc.Service { /** * Constructs a new Msg service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new Msg service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Msg; /** * Calls Send. * @param request MsgSend message or plain object * @param callback Node-style callback called with the error, if any, and MsgSendResponse */ public send(request: cosmos.bank.v1beta1.IMsgSend, callback: cosmos.bank.v1beta1.Msg.SendCallback): void; /** * Calls Send. * @param request MsgSend message or plain object * @returns Promise */ public send(request: cosmos.bank.v1beta1.IMsgSend): Promise<cosmos.bank.v1beta1.MsgSendResponse>; /** * Calls MultiSend. * @param request MsgMultiSend message or plain object * @param callback Node-style callback called with the error, if any, and MsgMultiSendResponse */ public multiSend(request: cosmos.bank.v1beta1.IMsgMultiSend, callback: cosmos.bank.v1beta1.Msg.MultiSendCallback): void; /** * Calls MultiSend. * @param request MsgMultiSend message or plain object * @returns Promise */ public multiSend(request: cosmos.bank.v1beta1.IMsgMultiSend): Promise<cosmos.bank.v1beta1.MsgMultiSendResponse>; } namespace Msg { /** * Callback as used by {@link cosmos.bank.v1beta1.Msg#send}. * @param error Error, if any * @param [response] MsgSendResponse */ type SendCallback = (error: (Error|null), response?: cosmos.bank.v1beta1.MsgSendResponse) => void; /** * Callback as used by {@link cosmos.bank.v1beta1.Msg#multiSend}. * @param error Error, if any * @param [response] MsgMultiSendResponse */ type MultiSendCallback = (error: (Error|null), response?: cosmos.bank.v1beta1.MsgMultiSendResponse) => void; } /** Properties of a MsgSend. */ interface IMsgSend { /** MsgSend fromAddress */ fromAddress?: (string|null); /** MsgSend toAddress */ toAddress?: (string|null); /** MsgSend amount */ amount?: (cosmos.base.v1beta1.ICoin[]|null); } /** Represents a MsgSend. */ class MsgSend implements IMsgSend { /** * Constructs a new MsgSend. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IMsgSend); /** MsgSend fromAddress. */ public fromAddress: string; /** MsgSend toAddress. */ public toAddress: string; /** MsgSend amount. */ public amount: cosmos.base.v1beta1.ICoin[]; /** * Creates a new MsgSend instance using the specified properties. * @param [properties] Properties to set * @returns MsgSend instance */ public static create(properties?: cosmos.bank.v1beta1.IMsgSend): cosmos.bank.v1beta1.MsgSend; /** * Encodes the specified MsgSend message. Does not implicitly {@link cosmos.bank.v1beta1.MsgSend.verify|verify} messages. * @param m MsgSend message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IMsgSend, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgSend message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgSend * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.MsgSend; /** * Creates a MsgSend message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgSend */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.MsgSend; /** * Creates a plain object from a MsgSend message. Also converts values to other types if specified. * @param m MsgSend * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.MsgSend, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgSend to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgSendResponse. */ interface IMsgSendResponse { } /** Represents a MsgSendResponse. */ class MsgSendResponse implements IMsgSendResponse { /** * Constructs a new MsgSendResponse. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IMsgSendResponse); /** * Creates a new MsgSendResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgSendResponse instance */ public static create(properties?: cosmos.bank.v1beta1.IMsgSendResponse): cosmos.bank.v1beta1.MsgSendResponse; /** * Encodes the specified MsgSendResponse message. Does not implicitly {@link cosmos.bank.v1beta1.MsgSendResponse.verify|verify} messages. * @param m MsgSendResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IMsgSendResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgSendResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgSendResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.MsgSendResponse; /** * Creates a MsgSendResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgSendResponse */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.MsgSendResponse; /** * Creates a plain object from a MsgSendResponse message. Also converts values to other types if specified. * @param m MsgSendResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.MsgSendResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgSendResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgMultiSend. */ interface IMsgMultiSend { /** MsgMultiSend inputs */ inputs?: (cosmos.bank.v1beta1.IInput[]|null); /** MsgMultiSend outputs */ outputs?: (cosmos.bank.v1beta1.IOutput[]|null); } /** Represents a MsgMultiSend. */ class MsgMultiSend implements IMsgMultiSend { /** * Constructs a new MsgMultiSend. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IMsgMultiSend); /** MsgMultiSend inputs. */ public inputs: cosmos.bank.v1beta1.IInput[]; /** MsgMultiSend outputs. */ public outputs: cosmos.bank.v1beta1.IOutput[]; /** * Creates a new MsgMultiSend instance using the specified properties. * @param [properties] Properties to set * @returns MsgMultiSend instance */ public static create(properties?: cosmos.bank.v1beta1.IMsgMultiSend): cosmos.bank.v1beta1.MsgMultiSend; /** * Encodes the specified MsgMultiSend message. Does not implicitly {@link cosmos.bank.v1beta1.MsgMultiSend.verify|verify} messages. * @param m MsgMultiSend message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IMsgMultiSend, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgMultiSend message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgMultiSend * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.MsgMultiSend; /** * Creates a MsgMultiSend message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgMultiSend */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.MsgMultiSend; /** * Creates a plain object from a MsgMultiSend message. Also converts values to other types if specified. * @param m MsgMultiSend * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.MsgMultiSend, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgMultiSend to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgMultiSendResponse. */ interface IMsgMultiSendResponse { } /** Represents a MsgMultiSendResponse. */ class MsgMultiSendResponse implements IMsgMultiSendResponse { /** * Constructs a new MsgMultiSendResponse. * @param [p] Properties to set */ constructor(p?: cosmos.bank.v1beta1.IMsgMultiSendResponse); /** * Creates a new MsgMultiSendResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgMultiSendResponse instance */ public static create(properties?: cosmos.bank.v1beta1.IMsgMultiSendResponse): cosmos.bank.v1beta1.MsgMultiSendResponse; /** * Encodes the specified MsgMultiSendResponse message. Does not implicitly {@link cosmos.bank.v1beta1.MsgMultiSendResponse.verify|verify} messages. * @param m MsgMultiSendResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.bank.v1beta1.IMsgMultiSendResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgMultiSendResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgMultiSendResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.bank.v1beta1.MsgMultiSendResponse; /** * Creates a MsgMultiSendResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgMultiSendResponse */ public static fromObject(d: { [k: string]: any }): cosmos.bank.v1beta1.MsgMultiSendResponse; /** * Creates a plain object from a MsgMultiSendResponse message. Also converts values to other types if specified. * @param m MsgMultiSendResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.bank.v1beta1.MsgMultiSendResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgMultiSendResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace staking. */ namespace staking { /** Namespace v1beta1. */ namespace v1beta1 { /** Represents a Msg */ class Msg extends $protobuf.rpc.Service { /** * Constructs a new Msg service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new Msg service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Msg; /** * Calls Delegate. * @param request MsgDelegate message or plain object * @param callback Node-style callback called with the error, if any, and MsgDelegateResponse */ public delegate(request: cosmos.staking.v1beta1.IMsgDelegate, callback: cosmos.staking.v1beta1.Msg.DelegateCallback): void; /** * Calls Delegate. * @param request MsgDelegate message or plain object * @returns Promise */ public delegate(request: cosmos.staking.v1beta1.IMsgDelegate): Promise<cosmos.staking.v1beta1.MsgDelegateResponse>; /** * Calls BeginRedelegate. * @param request MsgBeginRedelegate message or plain object * @param callback Node-style callback called with the error, if any, and MsgBeginRedelegateResponse */ public beginRedelegate(request: cosmos.staking.v1beta1.IMsgBeginRedelegate, callback: cosmos.staking.v1beta1.Msg.BeginRedelegateCallback): void; /** * Calls BeginRedelegate. * @param request MsgBeginRedelegate message or plain object * @returns Promise */ public beginRedelegate(request: cosmos.staking.v1beta1.IMsgBeginRedelegate): Promise<cosmos.staking.v1beta1.MsgBeginRedelegateResponse>; /** * Calls Undelegate. * @param request MsgUndelegate message or plain object * @param callback Node-style callback called with the error, if any, and MsgUndelegateResponse */ public undelegate(request: cosmos.staking.v1beta1.IMsgUndelegate, callback: cosmos.staking.v1beta1.Msg.UndelegateCallback): void; /** * Calls Undelegate. * @param request MsgUndelegate message or plain object * @returns Promise */ public undelegate(request: cosmos.staking.v1beta1.IMsgUndelegate): Promise<cosmos.staking.v1beta1.MsgUndelegateResponse>; } namespace Msg { /** * Callback as used by {@link cosmos.staking.v1beta1.Msg#delegate}. * @param error Error, if any * @param [response] MsgDelegateResponse */ type DelegateCallback = (error: (Error|null), response?: cosmos.staking.v1beta1.MsgDelegateResponse) => void; /** * Callback as used by {@link cosmos.staking.v1beta1.Msg#beginRedelegate}. * @param error Error, if any * @param [response] MsgBeginRedelegateResponse */ type BeginRedelegateCallback = (error: (Error|null), response?: cosmos.staking.v1beta1.MsgBeginRedelegateResponse) => void; /** * Callback as used by {@link cosmos.staking.v1beta1.Msg#undelegate}. * @param error Error, if any * @param [response] MsgUndelegateResponse */ type UndelegateCallback = (error: (Error|null), response?: cosmos.staking.v1beta1.MsgUndelegateResponse) => void; } /** Properties of a MsgDelegate. */ interface IMsgDelegate { /** MsgDelegate delegatorAddress */ delegatorAddress?: (string|null); /** MsgDelegate validatorAddress */ validatorAddress?: (string|null); /** MsgDelegate amount */ amount?: (cosmos.base.v1beta1.ICoin|null); } /** Represents a MsgDelegate. */ class MsgDelegate implements IMsgDelegate { /** * Constructs a new MsgDelegate. * @param [p] Properties to set */ constructor(p?: cosmos.staking.v1beta1.IMsgDelegate); /** MsgDelegate delegatorAddress. */ public delegatorAddress: string; /** MsgDelegate validatorAddress. */ public validatorAddress: string; /** MsgDelegate amount. */ public amount?: (cosmos.base.v1beta1.ICoin|null); /** * Creates a new MsgDelegate instance using the specified properties. * @param [properties] Properties to set * @returns MsgDelegate instance */ public static create(properties?: cosmos.staking.v1beta1.IMsgDelegate): cosmos.staking.v1beta1.MsgDelegate; /** * Encodes the specified MsgDelegate message. Does not implicitly {@link cosmos.staking.v1beta1.MsgDelegate.verify|verify} messages. * @param m MsgDelegate message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.staking.v1beta1.IMsgDelegate, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgDelegate message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgDelegate * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.staking.v1beta1.MsgDelegate; /** * Creates a MsgDelegate message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgDelegate */ public static fromObject(d: { [k: string]: any }): cosmos.staking.v1beta1.MsgDelegate; /** * Creates a plain object from a MsgDelegate message. Also converts values to other types if specified. * @param m MsgDelegate * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.staking.v1beta1.MsgDelegate, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgDelegate to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgDelegateResponse. */ interface IMsgDelegateResponse { } /** Represents a MsgDelegateResponse. */ class MsgDelegateResponse implements IMsgDelegateResponse { /** * Constructs a new MsgDelegateResponse. * @param [p] Properties to set */ constructor(p?: cosmos.staking.v1beta1.IMsgDelegateResponse); /** * Creates a new MsgDelegateResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgDelegateResponse instance */ public static create(properties?: cosmos.staking.v1beta1.IMsgDelegateResponse): cosmos.staking.v1beta1.MsgDelegateResponse; /** * Encodes the specified MsgDelegateResponse message. Does not implicitly {@link cosmos.staking.v1beta1.MsgDelegateResponse.verify|verify} messages. * @param m MsgDelegateResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.staking.v1beta1.IMsgDelegateResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgDelegateResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgDelegateResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.staking.v1beta1.MsgDelegateResponse; /** * Creates a MsgDelegateResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgDelegateResponse */ public static fromObject(d: { [k: string]: any }): cosmos.staking.v1beta1.MsgDelegateResponse; /** * Creates a plain object from a MsgDelegateResponse message. Also converts values to other types if specified. * @param m MsgDelegateResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.staking.v1beta1.MsgDelegateResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgDelegateResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgBeginRedelegate. */ interface IMsgBeginRedelegate { /** MsgBeginRedelegate delegatorAddress */ delegatorAddress?: (string|null); /** MsgBeginRedelegate validatorSrcAddress */ validatorSrcAddress?: (string|null); /** MsgBeginRedelegate validatorDstAddress */ validatorDstAddress?: (string|null); /** MsgBeginRedelegate amount */ amount?: (cosmos.base.v1beta1.ICoin|null); } /** Represents a MsgBeginRedelegate. */ class MsgBeginRedelegate implements IMsgBeginRedelegate { /** * Constructs a new MsgBeginRedelegate. * @param [p] Properties to set */ constructor(p?: cosmos.staking.v1beta1.IMsgBeginRedelegate); /** MsgBeginRedelegate delegatorAddress. */ public delegatorAddress: string; /** MsgBeginRedelegate validatorSrcAddress. */ public validatorSrcAddress: string; /** MsgBeginRedelegate validatorDstAddress. */ public validatorDstAddress: string; /** MsgBeginRedelegate amount. */ public amount?: (cosmos.base.v1beta1.ICoin|null); /** * Creates a new MsgBeginRedelegate instance using the specified properties. * @param [properties] Properties to set * @returns MsgBeginRedelegate instance */ public static create(properties?: cosmos.staking.v1beta1.IMsgBeginRedelegate): cosmos.staking.v1beta1.MsgBeginRedelegate; /** * Encodes the specified MsgBeginRedelegate message. Does not implicitly {@link cosmos.staking.v1beta1.MsgBeginRedelegate.verify|verify} messages. * @param m MsgBeginRedelegate message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.staking.v1beta1.IMsgBeginRedelegate, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgBeginRedelegate message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgBeginRedelegate * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.staking.v1beta1.MsgBeginRedelegate; /** * Creates a MsgBeginRedelegate message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgBeginRedelegate */ public static fromObject(d: { [k: string]: any }): cosmos.staking.v1beta1.MsgBeginRedelegate; /** * Creates a plain object from a MsgBeginRedelegate message. Also converts values to other types if specified. * @param m MsgBeginRedelegate * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.staking.v1beta1.MsgBeginRedelegate, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgBeginRedelegate to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgBeginRedelegateResponse. */ interface IMsgBeginRedelegateResponse { /** MsgBeginRedelegateResponse completionTime */ completionTime?: (google.protobuf.ITimestamp|null); } /** Represents a MsgBeginRedelegateResponse. */ class MsgBeginRedelegateResponse implements IMsgBeginRedelegateResponse { /** * Constructs a new MsgBeginRedelegateResponse. * @param [p] Properties to set */ constructor(p?: cosmos.staking.v1beta1.IMsgBeginRedelegateResponse); /** MsgBeginRedelegateResponse completionTime. */ public completionTime?: (google.protobuf.ITimestamp|null); /** * Creates a new MsgBeginRedelegateResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgBeginRedelegateResponse instance */ public static create(properties?: cosmos.staking.v1beta1.IMsgBeginRedelegateResponse): cosmos.staking.v1beta1.MsgBeginRedelegateResponse; /** * Encodes the specified MsgBeginRedelegateResponse message. Does not implicitly {@link cosmos.staking.v1beta1.MsgBeginRedelegateResponse.verify|verify} messages. * @param m MsgBeginRedelegateResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.staking.v1beta1.IMsgBeginRedelegateResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgBeginRedelegateResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgBeginRedelegateResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.staking.v1beta1.MsgBeginRedelegateResponse; /** * Creates a MsgBeginRedelegateResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgBeginRedelegateResponse */ public static fromObject(d: { [k: string]: any }): cosmos.staking.v1beta1.MsgBeginRedelegateResponse; /** * Creates a plain object from a MsgBeginRedelegateResponse message. Also converts values to other types if specified. * @param m MsgBeginRedelegateResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.staking.v1beta1.MsgBeginRedelegateResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgBeginRedelegateResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgUndelegate. */ interface IMsgUndelegate { /** MsgUndelegate delegatorAddress */ delegatorAddress?: (string|null); /** MsgUndelegate validatorAddress */ validatorAddress?: (string|null); /** MsgUndelegate amount */ amount?: (cosmos.base.v1beta1.ICoin|null); } /** Represents a MsgUndelegate. */ class MsgUndelegate implements IMsgUndelegate { /** * Constructs a new MsgUndelegate. * @param [p] Properties to set */ constructor(p?: cosmos.staking.v1beta1.IMsgUndelegate); /** MsgUndelegate delegatorAddress. */ public delegatorAddress: string; /** MsgUndelegate validatorAddress. */ public validatorAddress: string; /** MsgUndelegate amount. */ public amount?: (cosmos.base.v1beta1.ICoin|null); /** * Creates a new MsgUndelegate instance using the specified properties. * @param [properties] Properties to set * @returns MsgUndelegate instance */ public static create(properties?: cosmos.staking.v1beta1.IMsgUndelegate): cosmos.staking.v1beta1.MsgUndelegate; /** * Encodes the specified MsgUndelegate message. Does not implicitly {@link cosmos.staking.v1beta1.MsgUndelegate.verify|verify} messages. * @param m MsgUndelegate message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.staking.v1beta1.IMsgUndelegate, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgUndelegate message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgUndelegate * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.staking.v1beta1.MsgUndelegate; /** * Creates a MsgUndelegate message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgUndelegate */ public static fromObject(d: { [k: string]: any }): cosmos.staking.v1beta1.MsgUndelegate; /** * Creates a plain object from a MsgUndelegate message. Also converts values to other types if specified. * @param m MsgUndelegate * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.staking.v1beta1.MsgUndelegate, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgUndelegate to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgUndelegateResponse. */ interface IMsgUndelegateResponse { /** MsgUndelegateResponse completionTime */ completionTime?: (google.protobuf.ITimestamp|null); } /** Represents a MsgUndelegateResponse. */ class MsgUndelegateResponse implements IMsgUndelegateResponse { /** * Constructs a new MsgUndelegateResponse. * @param [p] Properties to set */ constructor(p?: cosmos.staking.v1beta1.IMsgUndelegateResponse); /** MsgUndelegateResponse completionTime. */ public completionTime?: (google.protobuf.ITimestamp|null); /** * Creates a new MsgUndelegateResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgUndelegateResponse instance */ public static create(properties?: cosmos.staking.v1beta1.IMsgUndelegateResponse): cosmos.staking.v1beta1.MsgUndelegateResponse; /** * Encodes the specified MsgUndelegateResponse message. Does not implicitly {@link cosmos.staking.v1beta1.MsgUndelegateResponse.verify|verify} messages. * @param m MsgUndelegateResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.staking.v1beta1.IMsgUndelegateResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgUndelegateResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgUndelegateResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.staking.v1beta1.MsgUndelegateResponse; /** * Creates a MsgUndelegateResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgUndelegateResponse */ public static fromObject(d: { [k: string]: any }): cosmos.staking.v1beta1.MsgUndelegateResponse; /** * Creates a plain object from a MsgUndelegateResponse message. Also converts values to other types if specified. * @param m MsgUndelegateResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.staking.v1beta1.MsgUndelegateResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgUndelegateResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace gov. */ namespace gov { /** Namespace v1beta1. */ namespace v1beta1 { /** VoteOption enum. */ enum VoteOption { VOTE_OPTION_UNSPECIFIED = 0, VOTE_OPTION_YES = 1, VOTE_OPTION_ABSTAIN = 2, VOTE_OPTION_NO = 3, VOTE_OPTION_NO_WITH_VETO = 4 } /** Represents a Msg */ class Msg extends $protobuf.rpc.Service { /** * Constructs a new Msg service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new Msg service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Msg; /** * Calls Vote. * @param request MsgVote message or plain object * @param callback Node-style callback called with the error, if any, and MsgVoteResponse */ public vote(request: cosmos.gov.v1beta1.IMsgVote, callback: cosmos.gov.v1beta1.Msg.VoteCallback): void; /** * Calls Vote. * @param request MsgVote message or plain object * @returns Promise */ public vote(request: cosmos.gov.v1beta1.IMsgVote): Promise<cosmos.gov.v1beta1.MsgVoteResponse>; /** * Calls Deposit. * @param request MsgDeposit message or plain object * @param callback Node-style callback called with the error, if any, and MsgDepositResponse */ public deposit(request: cosmos.gov.v1beta1.IMsgDeposit, callback: cosmos.gov.v1beta1.Msg.DepositCallback): void; /** * Calls Deposit. * @param request MsgDeposit message or plain object * @returns Promise */ public deposit(request: cosmos.gov.v1beta1.IMsgDeposit): Promise<cosmos.gov.v1beta1.MsgDepositResponse>; } namespace Msg { /** * Callback as used by {@link cosmos.gov.v1beta1.Msg#vote}. * @param error Error, if any * @param [response] MsgVoteResponse */ type VoteCallback = (error: (Error|null), response?: cosmos.gov.v1beta1.MsgVoteResponse) => void; /** * Callback as used by {@link cosmos.gov.v1beta1.Msg#deposit}. * @param error Error, if any * @param [response] MsgDepositResponse */ type DepositCallback = (error: (Error|null), response?: cosmos.gov.v1beta1.MsgDepositResponse) => void; } /** Properties of a MsgVote. */ interface IMsgVote { /** MsgVote proposalId */ proposalId?: (Long|null); /** MsgVote voter */ voter?: (string|null); /** MsgVote option */ option?: (cosmos.gov.v1beta1.VoteOption|null); } /** Represents a MsgVote. */ class MsgVote implements IMsgVote { /** * Constructs a new MsgVote. * @param [p] Properties to set */ constructor(p?: cosmos.gov.v1beta1.IMsgVote); /** MsgVote proposalId. */ public proposalId: Long; /** MsgVote voter. */ public voter: string; /** MsgVote option. */ public option: cosmos.gov.v1beta1.VoteOption; /** * Creates a new MsgVote instance using the specified properties. * @param [properties] Properties to set * @returns MsgVote instance */ public static create(properties?: cosmos.gov.v1beta1.IMsgVote): cosmos.gov.v1beta1.MsgVote; /** * Encodes the specified MsgVote message. Does not implicitly {@link cosmos.gov.v1beta1.MsgVote.verify|verify} messages. * @param m MsgVote message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.gov.v1beta1.IMsgVote, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgVote message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgVote * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.gov.v1beta1.MsgVote; /** * Creates a MsgVote message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgVote */ public static fromObject(d: { [k: string]: any }): cosmos.gov.v1beta1.MsgVote; /** * Creates a plain object from a MsgVote message. Also converts values to other types if specified. * @param m MsgVote * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.gov.v1beta1.MsgVote, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgVote to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgVoteResponse. */ interface IMsgVoteResponse { } /** Represents a MsgVoteResponse. */ class MsgVoteResponse implements IMsgVoteResponse { /** * Constructs a new MsgVoteResponse. * @param [p] Properties to set */ constructor(p?: cosmos.gov.v1beta1.IMsgVoteResponse); /** * Creates a new MsgVoteResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgVoteResponse instance */ public static create(properties?: cosmos.gov.v1beta1.IMsgVoteResponse): cosmos.gov.v1beta1.MsgVoteResponse; /** * Encodes the specified MsgVoteResponse message. Does not implicitly {@link cosmos.gov.v1beta1.MsgVoteResponse.verify|verify} messages. * @param m MsgVoteResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.gov.v1beta1.IMsgVoteResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgVoteResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgVoteResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.gov.v1beta1.MsgVoteResponse; /** * Creates a MsgVoteResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgVoteResponse */ public static fromObject(d: { [k: string]: any }): cosmos.gov.v1beta1.MsgVoteResponse; /** * Creates a plain object from a MsgVoteResponse message. Also converts values to other types if specified. * @param m MsgVoteResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.gov.v1beta1.MsgVoteResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgVoteResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgDeposit. */ interface IMsgDeposit { /** MsgDeposit proposalId */ proposalId?: (Long|null); /** MsgDeposit depositor */ depositor?: (string|null); /** MsgDeposit amount */ amount?: (cosmos.base.v1beta1.ICoin[]|null); } /** Represents a MsgDeposit. */ class MsgDeposit implements IMsgDeposit { /** * Constructs a new MsgDeposit. * @param [p] Properties to set */ constructor(p?: cosmos.gov.v1beta1.IMsgDeposit); /** MsgDeposit proposalId. */ public proposalId: Long; /** MsgDeposit depositor. */ public depositor: string; /** MsgDeposit amount. */ public amount: cosmos.base.v1beta1.ICoin[]; /** * Creates a new MsgDeposit instance using the specified properties. * @param [properties] Properties to set * @returns MsgDeposit instance */ public static create(properties?: cosmos.gov.v1beta1.IMsgDeposit): cosmos.gov.v1beta1.MsgDeposit; /** * Encodes the specified MsgDeposit message. Does not implicitly {@link cosmos.gov.v1beta1.MsgDeposit.verify|verify} messages. * @param m MsgDeposit message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.gov.v1beta1.IMsgDeposit, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgDeposit message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgDeposit * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.gov.v1beta1.MsgDeposit; /** * Creates a MsgDeposit message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgDeposit */ public static fromObject(d: { [k: string]: any }): cosmos.gov.v1beta1.MsgDeposit; /** * Creates a plain object from a MsgDeposit message. Also converts values to other types if specified. * @param m MsgDeposit * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.gov.v1beta1.MsgDeposit, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgDeposit to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgDepositResponse. */ interface IMsgDepositResponse { } /** Represents a MsgDepositResponse. */ class MsgDepositResponse implements IMsgDepositResponse { /** * Constructs a new MsgDepositResponse. * @param [p] Properties to set */ constructor(p?: cosmos.gov.v1beta1.IMsgDepositResponse); /** * Creates a new MsgDepositResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgDepositResponse instance */ public static create(properties?: cosmos.gov.v1beta1.IMsgDepositResponse): cosmos.gov.v1beta1.MsgDepositResponse; /** * Encodes the specified MsgDepositResponse message. Does not implicitly {@link cosmos.gov.v1beta1.MsgDepositResponse.verify|verify} messages. * @param m MsgDepositResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.gov.v1beta1.IMsgDepositResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgDepositResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgDepositResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.gov.v1beta1.MsgDepositResponse; /** * Creates a MsgDepositResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgDepositResponse */ public static fromObject(d: { [k: string]: any }): cosmos.gov.v1beta1.MsgDepositResponse; /** * Creates a plain object from a MsgDepositResponse message. Also converts values to other types if specified. * @param m MsgDepositResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.gov.v1beta1.MsgDepositResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgDepositResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace distribution. */ namespace distribution { /** Namespace v1beta1. */ namespace v1beta1 { /** Represents a Msg */ class Msg extends $protobuf.rpc.Service { /** * Constructs a new Msg service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new Msg service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Msg; /** * Calls WithdrawDelegatorReward. * @param request MsgWithdrawDelegatorReward message or plain object * @param callback Node-style callback called with the error, if any, and MsgWithdrawDelegatorRewardResponse */ public withdrawDelegatorReward(request: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorReward, callback: cosmos.distribution.v1beta1.Msg.WithdrawDelegatorRewardCallback): void; /** * Calls WithdrawDelegatorReward. * @param request MsgWithdrawDelegatorReward message or plain object * @returns Promise */ public withdrawDelegatorReward(request: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorReward): Promise<cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse>; } namespace Msg { /** * Callback as used by {@link cosmos.distribution.v1beta1.Msg#withdrawDelegatorReward}. * @param error Error, if any * @param [response] MsgWithdrawDelegatorRewardResponse */ type WithdrawDelegatorRewardCallback = (error: (Error|null), response?: cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse) => void; } /** Properties of a MsgWithdrawDelegatorReward. */ interface IMsgWithdrawDelegatorReward { /** MsgWithdrawDelegatorReward delegatorAddress */ delegatorAddress?: (string|null); /** MsgWithdrawDelegatorReward validatorAddress */ validatorAddress?: (string|null); } /** Represents a MsgWithdrawDelegatorReward. */ class MsgWithdrawDelegatorReward implements IMsgWithdrawDelegatorReward { /** * Constructs a new MsgWithdrawDelegatorReward. * @param [p] Properties to set */ constructor(p?: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorReward); /** MsgWithdrawDelegatorReward delegatorAddress. */ public delegatorAddress: string; /** MsgWithdrawDelegatorReward validatorAddress. */ public validatorAddress: string; /** * Creates a new MsgWithdrawDelegatorReward instance using the specified properties. * @param [properties] Properties to set * @returns MsgWithdrawDelegatorReward instance */ public static create(properties?: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorReward): cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward; /** * Encodes the specified MsgWithdrawDelegatorReward message. Does not implicitly {@link cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward.verify|verify} messages. * @param m MsgWithdrawDelegatorReward message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorReward, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgWithdrawDelegatorReward message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgWithdrawDelegatorReward * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward; /** * Creates a MsgWithdrawDelegatorReward message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgWithdrawDelegatorReward */ public static fromObject(d: { [k: string]: any }): cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward; /** * Creates a plain object from a MsgWithdrawDelegatorReward message. Also converts values to other types if specified. * @param m MsgWithdrawDelegatorReward * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.distribution.v1beta1.MsgWithdrawDelegatorReward, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgWithdrawDelegatorReward to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgWithdrawDelegatorRewardResponse. */ interface IMsgWithdrawDelegatorRewardResponse { } /** Represents a MsgWithdrawDelegatorRewardResponse. */ class MsgWithdrawDelegatorRewardResponse implements IMsgWithdrawDelegatorRewardResponse { /** * Constructs a new MsgWithdrawDelegatorRewardResponse. * @param [p] Properties to set */ constructor(p?: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorRewardResponse); /** * Creates a new MsgWithdrawDelegatorRewardResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgWithdrawDelegatorRewardResponse instance */ public static create(properties?: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorRewardResponse): cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse; /** * Encodes the specified MsgWithdrawDelegatorRewardResponse message. Does not implicitly {@link cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse.verify|verify} messages. * @param m MsgWithdrawDelegatorRewardResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.distribution.v1beta1.IMsgWithdrawDelegatorRewardResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgWithdrawDelegatorRewardResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgWithdrawDelegatorRewardResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse; /** * Creates a MsgWithdrawDelegatorRewardResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgWithdrawDelegatorRewardResponse */ public static fromObject(d: { [k: string]: any }): cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse; /** * Creates a plain object from a MsgWithdrawDelegatorRewardResponse message. Also converts values to other types if specified. * @param m MsgWithdrawDelegatorRewardResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.distribution.v1beta1.MsgWithdrawDelegatorRewardResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgWithdrawDelegatorRewardResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace base. */ namespace base { /** Namespace v1beta1. */ namespace v1beta1 { /** Properties of a Coin. */ interface ICoin { /** Coin denom */ denom?: (string|null); /** Coin amount */ amount?: (string|null); } /** Represents a Coin. */ class Coin implements ICoin { /** * Constructs a new Coin. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.ICoin); /** Coin denom. */ public denom: string; /** Coin amount. */ public amount: string; /** * Creates a new Coin instance using the specified properties. * @param [properties] Properties to set * @returns Coin instance */ public static create(properties?: cosmos.base.v1beta1.ICoin): cosmos.base.v1beta1.Coin; /** * Encodes the specified Coin message. Does not implicitly {@link cosmos.base.v1beta1.Coin.verify|verify} messages. * @param m Coin message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.ICoin, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Coin message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Coin * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.base.v1beta1.Coin; /** * Creates a Coin message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Coin */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.Coin; /** * Creates a plain object from a Coin message. Also converts values to other types if specified. * @param m Coin * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.Coin, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Coin to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DecCoin. */ interface IDecCoin { /** DecCoin denom */ denom?: (string|null); /** DecCoin amount */ amount?: (string|null); } /** Represents a DecCoin. */ class DecCoin implements IDecCoin { /** * Constructs a new DecCoin. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.IDecCoin); /** DecCoin denom. */ public denom: string; /** DecCoin amount. */ public amount: string; /** * Creates a new DecCoin instance using the specified properties. * @param [properties] Properties to set * @returns DecCoin instance */ public static create(properties?: cosmos.base.v1beta1.IDecCoin): cosmos.base.v1beta1.DecCoin; /** * Encodes the specified DecCoin message. Does not implicitly {@link cosmos.base.v1beta1.DecCoin.verify|verify} messages. * @param m DecCoin message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.IDecCoin, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DecCoin message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns DecCoin * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.base.v1beta1.DecCoin; /** * Creates a DecCoin message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns DecCoin */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.DecCoin; /** * Creates a plain object from a DecCoin message. Also converts values to other types if specified. * @param m DecCoin * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.DecCoin, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DecCoin to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an IntProto. */ interface IIntProto { /** IntProto int */ int?: (string|null); } /** Represents an IntProto. */ class IntProto implements IIntProto { /** * Constructs a new IntProto. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.IIntProto); /** IntProto int. */ public int: string; /** * Creates a new IntProto instance using the specified properties. * @param [properties] Properties to set * @returns IntProto instance */ public static create(properties?: cosmos.base.v1beta1.IIntProto): cosmos.base.v1beta1.IntProto; /** * Encodes the specified IntProto message. Does not implicitly {@link cosmos.base.v1beta1.IntProto.verify|verify} messages. * @param m IntProto message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.IIntProto, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an IntProto message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns IntProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.base.v1beta1.IntProto; /** * Creates an IntProto message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns IntProto */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.IntProto; /** * Creates a plain object from an IntProto message. Also converts values to other types if specified. * @param m IntProto * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.IntProto, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this IntProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a DecProto. */ interface IDecProto { /** DecProto dec */ dec?: (string|null); } /** Represents a DecProto. */ class DecProto implements IDecProto { /** * Constructs a new DecProto. * @param [p] Properties to set */ constructor(p?: cosmos.base.v1beta1.IDecProto); /** DecProto dec. */ public dec: string; /** * Creates a new DecProto instance using the specified properties. * @param [properties] Properties to set * @returns DecProto instance */ public static create(properties?: cosmos.base.v1beta1.IDecProto): cosmos.base.v1beta1.DecProto; /** * Encodes the specified DecProto message. Does not implicitly {@link cosmos.base.v1beta1.DecProto.verify|verify} messages. * @param m DecProto message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.base.v1beta1.IDecProto, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a DecProto message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns DecProto * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.base.v1beta1.DecProto; /** * Creates a DecProto message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns DecProto */ public static fromObject(d: { [k: string]: any }): cosmos.base.v1beta1.DecProto; /** * Creates a plain object from a DecProto message. Also converts values to other types if specified. * @param m DecProto * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.base.v1beta1.DecProto, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this DecProto to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace crypto. */ namespace crypto { /** Namespace multisig. */ namespace multisig { /** Namespace v1beta1. */ namespace v1beta1 { /** Properties of a MultiSignature. */ interface IMultiSignature { /** MultiSignature signatures */ signatures?: (Uint8Array[]|null); } /** Represents a MultiSignature. */ class MultiSignature implements IMultiSignature { /** * Constructs a new MultiSignature. * @param [p] Properties to set */ constructor(p?: cosmos.crypto.multisig.v1beta1.IMultiSignature); /** MultiSignature signatures. */ public signatures: Uint8Array[]; /** * Creates a new MultiSignature instance using the specified properties. * @param [properties] Properties to set * @returns MultiSignature instance */ public static create(properties?: cosmos.crypto.multisig.v1beta1.IMultiSignature): cosmos.crypto.multisig.v1beta1.MultiSignature; /** * Encodes the specified MultiSignature message. Does not implicitly {@link cosmos.crypto.multisig.v1beta1.MultiSignature.verify|verify} messages. * @param m MultiSignature message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.crypto.multisig.v1beta1.IMultiSignature, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MultiSignature message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MultiSignature * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.crypto.multisig.v1beta1.MultiSignature; /** * Creates a MultiSignature message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MultiSignature */ public static fromObject(d: { [k: string]: any }): cosmos.crypto.multisig.v1beta1.MultiSignature; /** * Creates a plain object from a MultiSignature message. Also converts values to other types if specified. * @param m MultiSignature * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.crypto.multisig.v1beta1.MultiSignature, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MultiSignature to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a CompactBitArray. */ interface ICompactBitArray { /** CompactBitArray extraBitsStored */ extraBitsStored?: (number|null); /** CompactBitArray elems */ elems?: (Uint8Array|null); } /** Represents a CompactBitArray. */ class CompactBitArray implements ICompactBitArray { /** * Constructs a new CompactBitArray. * @param [p] Properties to set */ constructor(p?: cosmos.crypto.multisig.v1beta1.ICompactBitArray); /** CompactBitArray extraBitsStored. */ public extraBitsStored: number; /** CompactBitArray elems. */ public elems: Uint8Array; /** * Creates a new CompactBitArray instance using the specified properties. * @param [properties] Properties to set * @returns CompactBitArray instance */ public static create(properties?: cosmos.crypto.multisig.v1beta1.ICompactBitArray): cosmos.crypto.multisig.v1beta1.CompactBitArray; /** * Encodes the specified CompactBitArray message. Does not implicitly {@link cosmos.crypto.multisig.v1beta1.CompactBitArray.verify|verify} messages. * @param m CompactBitArray message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.crypto.multisig.v1beta1.ICompactBitArray, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a CompactBitArray message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns CompactBitArray * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.crypto.multisig.v1beta1.CompactBitArray; /** * Creates a CompactBitArray message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns CompactBitArray */ public static fromObject(d: { [k: string]: any }): cosmos.crypto.multisig.v1beta1.CompactBitArray; /** * Creates a plain object from a CompactBitArray message. Also converts values to other types if specified. * @param m CompactBitArray * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.crypto.multisig.v1beta1.CompactBitArray, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this CompactBitArray to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace secp256k1. */ namespace secp256k1 { /** Properties of a PubKey. */ interface IPubKey { /** PubKey key */ key?: (Uint8Array|null); } /** Represents a PubKey. */ class PubKey implements IPubKey { /** * Constructs a new PubKey. * @param [p] Properties to set */ constructor(p?: cosmos.crypto.secp256k1.IPubKey); /** PubKey key. */ public key: Uint8Array; /** * Creates a new PubKey instance using the specified properties. * @param [properties] Properties to set * @returns PubKey instance */ public static create(properties?: cosmos.crypto.secp256k1.IPubKey): cosmos.crypto.secp256k1.PubKey; /** * Encodes the specified PubKey message. Does not implicitly {@link cosmos.crypto.secp256k1.PubKey.verify|verify} messages. * @param m PubKey message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.crypto.secp256k1.IPubKey, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PubKey message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns PubKey * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.crypto.secp256k1.PubKey; /** * Creates a PubKey message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns PubKey */ public static fromObject(d: { [k: string]: any }): cosmos.crypto.secp256k1.PubKey; /** * Creates a plain object from a PubKey message. Also converts values to other types if specified. * @param m PubKey * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.crypto.secp256k1.PubKey, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PubKey to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PrivKey. */ interface IPrivKey { /** PrivKey key */ key?: (Uint8Array|null); } /** Represents a PrivKey. */ class PrivKey implements IPrivKey { /** * Constructs a new PrivKey. * @param [p] Properties to set */ constructor(p?: cosmos.crypto.secp256k1.IPrivKey); /** PrivKey key. */ public key: Uint8Array; /** * Creates a new PrivKey instance using the specified properties. * @param [properties] Properties to set * @returns PrivKey instance */ public static create(properties?: cosmos.crypto.secp256k1.IPrivKey): cosmos.crypto.secp256k1.PrivKey; /** * Encodes the specified PrivKey message. Does not implicitly {@link cosmos.crypto.secp256k1.PrivKey.verify|verify} messages. * @param m PrivKey message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.crypto.secp256k1.IPrivKey, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PrivKey message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns PrivKey * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.crypto.secp256k1.PrivKey; /** * Creates a PrivKey message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns PrivKey */ public static fromObject(d: { [k: string]: any }): cosmos.crypto.secp256k1.PrivKey; /** * Creates a plain object from a PrivKey message. Also converts values to other types if specified. * @param m PrivKey * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.crypto.secp256k1.PrivKey, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PrivKey to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace tx. */ namespace tx { /** Namespace v1beta1. */ namespace v1beta1 { /** Properties of a Tx. */ interface ITx { /** Tx body */ body?: (cosmos.tx.v1beta1.ITxBody|null); /** Tx authInfo */ authInfo?: (cosmos.tx.v1beta1.IAuthInfo|null); /** Tx signatures */ signatures?: (Uint8Array[]|null); } /** Represents a Tx. */ class Tx implements ITx { /** * Constructs a new Tx. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.ITx); /** Tx body. */ public body?: (cosmos.tx.v1beta1.ITxBody|null); /** Tx authInfo. */ public authInfo?: (cosmos.tx.v1beta1.IAuthInfo|null); /** Tx signatures. */ public signatures: Uint8Array[]; /** * Creates a new Tx instance using the specified properties. * @param [properties] Properties to set * @returns Tx instance */ public static create(properties?: cosmos.tx.v1beta1.ITx): cosmos.tx.v1beta1.Tx; /** * Encodes the specified Tx message. Does not implicitly {@link cosmos.tx.v1beta1.Tx.verify|verify} messages. * @param m Tx message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.ITx, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Tx message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Tx * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.Tx; /** * Creates a Tx message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Tx */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.Tx; /** * Creates a plain object from a Tx message. Also converts values to other types if specified. * @param m Tx * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.Tx, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Tx to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a TxRaw. */ interface ITxRaw { /** TxRaw bodyBytes */ bodyBytes?: (Uint8Array|null); /** TxRaw authInfoBytes */ authInfoBytes?: (Uint8Array|null); /** TxRaw signatures */ signatures?: (Uint8Array[]|null); } /** Represents a TxRaw. */ class TxRaw implements ITxRaw { /** * Constructs a new TxRaw. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.ITxRaw); /** TxRaw bodyBytes. */ public bodyBytes: Uint8Array; /** TxRaw authInfoBytes. */ public authInfoBytes: Uint8Array; /** TxRaw signatures. */ public signatures: Uint8Array[]; /** * Creates a new TxRaw instance using the specified properties. * @param [properties] Properties to set * @returns TxRaw instance */ public static create(properties?: cosmos.tx.v1beta1.ITxRaw): cosmos.tx.v1beta1.TxRaw; /** * Encodes the specified TxRaw message. Does not implicitly {@link cosmos.tx.v1beta1.TxRaw.verify|verify} messages. * @param m TxRaw message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.ITxRaw, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TxRaw message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns TxRaw * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.TxRaw; /** * Creates a TxRaw message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns TxRaw */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.TxRaw; /** * Creates a plain object from a TxRaw message. Also converts values to other types if specified. * @param m TxRaw * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.TxRaw, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TxRaw to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SignDoc. */ interface ISignDoc { /** SignDoc bodyBytes */ bodyBytes?: (Uint8Array|null); /** SignDoc authInfoBytes */ authInfoBytes?: (Uint8Array|null); /** SignDoc chainId */ chainId?: (string|null); /** SignDoc accountNumber */ accountNumber?: (Long|null); } /** Represents a SignDoc. */ class SignDoc implements ISignDoc { /** * Constructs a new SignDoc. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.ISignDoc); /** SignDoc bodyBytes. */ public bodyBytes: Uint8Array; /** SignDoc authInfoBytes. */ public authInfoBytes: Uint8Array; /** SignDoc chainId. */ public chainId: string; /** SignDoc accountNumber. */ public accountNumber: Long; /** * Creates a new SignDoc instance using the specified properties. * @param [properties] Properties to set * @returns SignDoc instance */ public static create(properties?: cosmos.tx.v1beta1.ISignDoc): cosmos.tx.v1beta1.SignDoc; /** * Encodes the specified SignDoc message. Does not implicitly {@link cosmos.tx.v1beta1.SignDoc.verify|verify} messages. * @param m SignDoc message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.ISignDoc, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SignDoc message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SignDoc * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.SignDoc; /** * Creates a SignDoc message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SignDoc */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.SignDoc; /** * Creates a plain object from a SignDoc message. Also converts values to other types if specified. * @param m SignDoc * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.SignDoc, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SignDoc to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a TxBody. */ interface ITxBody { /** TxBody messages */ messages?: (google.protobuf.IAny[]|null); /** TxBody memo */ memo?: (string|null); /** TxBody timeoutHeight */ timeoutHeight?: (Long|null); /** TxBody extensionOptions */ extensionOptions?: (google.protobuf.IAny[]|null); /** TxBody nonCriticalExtensionOptions */ nonCriticalExtensionOptions?: (google.protobuf.IAny[]|null); } /** Represents a TxBody. */ class TxBody implements ITxBody { /** * Constructs a new TxBody. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.ITxBody); /** TxBody messages. */ public messages: google.protobuf.IAny[]; /** TxBody memo. */ public memo: string; /** TxBody timeoutHeight. */ public timeoutHeight: Long; /** TxBody extensionOptions. */ public extensionOptions: google.protobuf.IAny[]; /** TxBody nonCriticalExtensionOptions. */ public nonCriticalExtensionOptions: google.protobuf.IAny[]; /** * Creates a new TxBody instance using the specified properties. * @param [properties] Properties to set * @returns TxBody instance */ public static create(properties?: cosmos.tx.v1beta1.ITxBody): cosmos.tx.v1beta1.TxBody; /** * Encodes the specified TxBody message. Does not implicitly {@link cosmos.tx.v1beta1.TxBody.verify|verify} messages. * @param m TxBody message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.ITxBody, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a TxBody message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns TxBody * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.TxBody; /** * Creates a TxBody message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns TxBody */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.TxBody; /** * Creates a plain object from a TxBody message. Also converts values to other types if specified. * @param m TxBody * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.TxBody, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this TxBody to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an AuthInfo. */ interface IAuthInfo { /** AuthInfo signerInfos */ signerInfos?: (cosmos.tx.v1beta1.ISignerInfo[]|null); /** AuthInfo fee */ fee?: (cosmos.tx.v1beta1.IFee|null); } /** Represents an AuthInfo. */ class AuthInfo implements IAuthInfo { /** * Constructs a new AuthInfo. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.IAuthInfo); /** AuthInfo signerInfos. */ public signerInfos: cosmos.tx.v1beta1.ISignerInfo[]; /** AuthInfo fee. */ public fee?: (cosmos.tx.v1beta1.IFee|null); /** * Creates a new AuthInfo instance using the specified properties. * @param [properties] Properties to set * @returns AuthInfo instance */ public static create(properties?: cosmos.tx.v1beta1.IAuthInfo): cosmos.tx.v1beta1.AuthInfo; /** * Encodes the specified AuthInfo message. Does not implicitly {@link cosmos.tx.v1beta1.AuthInfo.verify|verify} messages. * @param m AuthInfo message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.IAuthInfo, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an AuthInfo message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns AuthInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.AuthInfo; /** * Creates an AuthInfo message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns AuthInfo */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.AuthInfo; /** * Creates a plain object from an AuthInfo message. Also converts values to other types if specified. * @param m AuthInfo * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.AuthInfo, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this AuthInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SignerInfo. */ interface ISignerInfo { /** SignerInfo publicKey */ publicKey?: (google.protobuf.IAny|null); /** SignerInfo modeInfo */ modeInfo?: (cosmos.tx.v1beta1.IModeInfo|null); /** SignerInfo sequence */ sequence?: (Long|null); } /** Represents a SignerInfo. */ class SignerInfo implements ISignerInfo { /** * Constructs a new SignerInfo. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.ISignerInfo); /** SignerInfo publicKey. */ public publicKey?: (google.protobuf.IAny|null); /** SignerInfo modeInfo. */ public modeInfo?: (cosmos.tx.v1beta1.IModeInfo|null); /** SignerInfo sequence. */ public sequence: Long; /** * Creates a new SignerInfo instance using the specified properties. * @param [properties] Properties to set * @returns SignerInfo instance */ public static create(properties?: cosmos.tx.v1beta1.ISignerInfo): cosmos.tx.v1beta1.SignerInfo; /** * Encodes the specified SignerInfo message. Does not implicitly {@link cosmos.tx.v1beta1.SignerInfo.verify|verify} messages. * @param m SignerInfo message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.ISignerInfo, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SignerInfo message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SignerInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.SignerInfo; /** * Creates a SignerInfo message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SignerInfo */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.SignerInfo; /** * Creates a plain object from a SignerInfo message. Also converts values to other types if specified. * @param m SignerInfo * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.SignerInfo, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SignerInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ModeInfo. */ interface IModeInfo { /** ModeInfo single */ single?: (cosmos.tx.v1beta1.ModeInfo.ISingle|null); /** ModeInfo multi */ multi?: (cosmos.tx.v1beta1.ModeInfo.IMulti|null); } /** Represents a ModeInfo. */ class ModeInfo implements IModeInfo { /** * Constructs a new ModeInfo. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.IModeInfo); /** ModeInfo single. */ public single?: (cosmos.tx.v1beta1.ModeInfo.ISingle|null); /** ModeInfo multi. */ public multi?: (cosmos.tx.v1beta1.ModeInfo.IMulti|null); /** ModeInfo sum. */ public sum?: ("single"|"multi"); /** * Creates a new ModeInfo instance using the specified properties. * @param [properties] Properties to set * @returns ModeInfo instance */ public static create(properties?: cosmos.tx.v1beta1.IModeInfo): cosmos.tx.v1beta1.ModeInfo; /** * Encodes the specified ModeInfo message. Does not implicitly {@link cosmos.tx.v1beta1.ModeInfo.verify|verify} messages. * @param m ModeInfo message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.IModeInfo, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ModeInfo message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns ModeInfo * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.ModeInfo; /** * Creates a ModeInfo message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns ModeInfo */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.ModeInfo; /** * Creates a plain object from a ModeInfo message. Also converts values to other types if specified. * @param m ModeInfo * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.ModeInfo, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ModeInfo to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace ModeInfo { /** Properties of a Single. */ interface ISingle { /** Single mode */ mode?: (cosmos.tx.signing.v1beta1.SignMode|null); } /** Represents a Single. */ class Single implements ISingle { /** * Constructs a new Single. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.ModeInfo.ISingle); /** Single mode. */ public mode: cosmos.tx.signing.v1beta1.SignMode; /** * Creates a new Single instance using the specified properties. * @param [properties] Properties to set * @returns Single instance */ public static create(properties?: cosmos.tx.v1beta1.ModeInfo.ISingle): cosmos.tx.v1beta1.ModeInfo.Single; /** * Encodes the specified Single message. Does not implicitly {@link cosmos.tx.v1beta1.ModeInfo.Single.verify|verify} messages. * @param m Single message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.ModeInfo.ISingle, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Single message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Single * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.ModeInfo.Single; /** * Creates a Single message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Single */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.ModeInfo.Single; /** * Creates a plain object from a Single message. Also converts values to other types if specified. * @param m Single * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.ModeInfo.Single, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Single to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Multi. */ interface IMulti { /** Multi bitarray */ bitarray?: (cosmos.crypto.multisig.v1beta1.ICompactBitArray|null); /** Multi modeInfos */ modeInfos?: (cosmos.tx.v1beta1.IModeInfo[]|null); } /** Represents a Multi. */ class Multi implements IMulti { /** * Constructs a new Multi. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.ModeInfo.IMulti); /** Multi bitarray. */ public bitarray?: (cosmos.crypto.multisig.v1beta1.ICompactBitArray|null); /** Multi modeInfos. */ public modeInfos: cosmos.tx.v1beta1.IModeInfo[]; /** * Creates a new Multi instance using the specified properties. * @param [properties] Properties to set * @returns Multi instance */ public static create(properties?: cosmos.tx.v1beta1.ModeInfo.IMulti): cosmos.tx.v1beta1.ModeInfo.Multi; /** * Encodes the specified Multi message. Does not implicitly {@link cosmos.tx.v1beta1.ModeInfo.Multi.verify|verify} messages. * @param m Multi message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.ModeInfo.IMulti, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Multi message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Multi * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.ModeInfo.Multi; /** * Creates a Multi message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Multi */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.ModeInfo.Multi; /** * Creates a plain object from a Multi message. Also converts values to other types if specified. * @param m Multi * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.ModeInfo.Multi, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Multi to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Properties of a Fee. */ interface IFee { /** Fee amount */ amount?: (cosmos.base.v1beta1.ICoin[]|null); /** Fee gasLimit */ gasLimit?: (Long|null); /** Fee payer */ payer?: (string|null); /** Fee granter */ granter?: (string|null); } /** Represents a Fee. */ class Fee implements IFee { /** * Constructs a new Fee. * @param [p] Properties to set */ constructor(p?: cosmos.tx.v1beta1.IFee); /** Fee amount. */ public amount: cosmos.base.v1beta1.ICoin[]; /** Fee gasLimit. */ public gasLimit: Long; /** Fee payer. */ public payer: string; /** Fee granter. */ public granter: string; /** * Creates a new Fee instance using the specified properties. * @param [properties] Properties to set * @returns Fee instance */ public static create(properties?: cosmos.tx.v1beta1.IFee): cosmos.tx.v1beta1.Fee; /** * Encodes the specified Fee message. Does not implicitly {@link cosmos.tx.v1beta1.Fee.verify|verify} messages. * @param m Fee message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.v1beta1.IFee, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Fee message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Fee * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.v1beta1.Fee; /** * Creates a Fee message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Fee */ public static fromObject(d: { [k: string]: any }): cosmos.tx.v1beta1.Fee; /** * Creates a plain object from a Fee message. Also converts values to other types if specified. * @param m Fee * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.v1beta1.Fee, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Fee to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } /** Namespace signing. */ namespace signing { /** Namespace v1beta1. */ namespace v1beta1 { /** SignMode enum. */ enum SignMode { SIGN_MODE_UNSPECIFIED = 0, SIGN_MODE_DIRECT = 1, SIGN_MODE_TEXTUAL = 2, SIGN_MODE_LEGACY_AMINO_JSON = 127 } /** Properties of a SignatureDescriptors. */ interface ISignatureDescriptors { /** SignatureDescriptors signatures */ signatures?: (cosmos.tx.signing.v1beta1.ISignatureDescriptor[]|null); } /** Represents a SignatureDescriptors. */ class SignatureDescriptors implements ISignatureDescriptors { /** * Constructs a new SignatureDescriptors. * @param [p] Properties to set */ constructor(p?: cosmos.tx.signing.v1beta1.ISignatureDescriptors); /** SignatureDescriptors signatures. */ public signatures: cosmos.tx.signing.v1beta1.ISignatureDescriptor[]; /** * Creates a new SignatureDescriptors instance using the specified properties. * @param [properties] Properties to set * @returns SignatureDescriptors instance */ public static create(properties?: cosmos.tx.signing.v1beta1.ISignatureDescriptors): cosmos.tx.signing.v1beta1.SignatureDescriptors; /** * Encodes the specified SignatureDescriptors message. Does not implicitly {@link cosmos.tx.signing.v1beta1.SignatureDescriptors.verify|verify} messages. * @param m SignatureDescriptors message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.signing.v1beta1.ISignatureDescriptors, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SignatureDescriptors message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SignatureDescriptors * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.signing.v1beta1.SignatureDescriptors; /** * Creates a SignatureDescriptors message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SignatureDescriptors */ public static fromObject(d: { [k: string]: any }): cosmos.tx.signing.v1beta1.SignatureDescriptors; /** * Creates a plain object from a SignatureDescriptors message. Also converts values to other types if specified. * @param m SignatureDescriptors * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.signing.v1beta1.SignatureDescriptors, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SignatureDescriptors to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a SignatureDescriptor. */ interface ISignatureDescriptor { /** SignatureDescriptor publicKey */ publicKey?: (google.protobuf.IAny|null); /** SignatureDescriptor data */ data?: (cosmos.tx.signing.v1beta1.SignatureDescriptor.IData|null); /** SignatureDescriptor sequence */ sequence?: (Long|null); } /** Represents a SignatureDescriptor. */ class SignatureDescriptor implements ISignatureDescriptor { /** * Constructs a new SignatureDescriptor. * @param [p] Properties to set */ constructor(p?: cosmos.tx.signing.v1beta1.ISignatureDescriptor); /** SignatureDescriptor publicKey. */ public publicKey?: (google.protobuf.IAny|null); /** SignatureDescriptor data. */ public data?: (cosmos.tx.signing.v1beta1.SignatureDescriptor.IData|null); /** SignatureDescriptor sequence. */ public sequence: Long; /** * Creates a new SignatureDescriptor instance using the specified properties. * @param [properties] Properties to set * @returns SignatureDescriptor instance */ public static create(properties?: cosmos.tx.signing.v1beta1.ISignatureDescriptor): cosmos.tx.signing.v1beta1.SignatureDescriptor; /** * Encodes the specified SignatureDescriptor message. Does not implicitly {@link cosmos.tx.signing.v1beta1.SignatureDescriptor.verify|verify} messages. * @param m SignatureDescriptor message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.signing.v1beta1.ISignatureDescriptor, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a SignatureDescriptor message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns SignatureDescriptor * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.signing.v1beta1.SignatureDescriptor; /** * Creates a SignatureDescriptor message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns SignatureDescriptor */ public static fromObject(d: { [k: string]: any }): cosmos.tx.signing.v1beta1.SignatureDescriptor; /** * Creates a plain object from a SignatureDescriptor message. Also converts values to other types if specified. * @param m SignatureDescriptor * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.signing.v1beta1.SignatureDescriptor, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this SignatureDescriptor to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace SignatureDescriptor { /** Properties of a Data. */ interface IData { /** Data single */ single?: (cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.ISingle|null); /** Data multi */ multi?: (cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.IMulti|null); } /** Represents a Data. */ class Data implements IData { /** * Constructs a new Data. * @param [p] Properties to set */ constructor(p?: cosmos.tx.signing.v1beta1.SignatureDescriptor.IData); /** Data single. */ public single?: (cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.ISingle|null); /** Data multi. */ public multi?: (cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.IMulti|null); /** Data sum. */ public sum?: ("single"|"multi"); /** * Creates a new Data instance using the specified properties. * @param [properties] Properties to set * @returns Data instance */ public static create(properties?: cosmos.tx.signing.v1beta1.SignatureDescriptor.IData): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data; /** * Encodes the specified Data message. Does not implicitly {@link cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.verify|verify} messages. * @param m Data message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.signing.v1beta1.SignatureDescriptor.IData, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Data message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Data * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data; /** * Creates a Data message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Data */ public static fromObject(d: { [k: string]: any }): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data; /** * Creates a plain object from a Data message. Also converts values to other types if specified. * @param m Data * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Data to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } namespace Data { /** Properties of a Single. */ interface ISingle { /** Single mode */ mode?: (cosmos.tx.signing.v1beta1.SignMode|null); /** Single signature */ signature?: (Uint8Array|null); } /** Represents a Single. */ class Single implements ISingle { /** * Constructs a new Single. * @param [p] Properties to set */ constructor(p?: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.ISingle); /** Single mode. */ public mode: cosmos.tx.signing.v1beta1.SignMode; /** Single signature. */ public signature: Uint8Array; /** * Creates a new Single instance using the specified properties. * @param [properties] Properties to set * @returns Single instance */ public static create(properties?: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.ISingle): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single; /** * Encodes the specified Single message. Does not implicitly {@link cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single.verify|verify} messages. * @param m Single message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.ISingle, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Single message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Single * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single; /** * Creates a Single message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Single */ public static fromObject(d: { [k: string]: any }): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single; /** * Creates a plain object from a Single message. Also converts values to other types if specified. * @param m Single * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Single, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Single to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Multi. */ interface IMulti { /** Multi bitarray */ bitarray?: (cosmos.crypto.multisig.v1beta1.ICompactBitArray|null); /** Multi signatures */ signatures?: (cosmos.tx.signing.v1beta1.SignatureDescriptor.IData[]|null); } /** Represents a Multi. */ class Multi implements IMulti { /** * Constructs a new Multi. * @param [p] Properties to set */ constructor(p?: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.IMulti); /** Multi bitarray. */ public bitarray?: (cosmos.crypto.multisig.v1beta1.ICompactBitArray|null); /** Multi signatures. */ public signatures: cosmos.tx.signing.v1beta1.SignatureDescriptor.IData[]; /** * Creates a new Multi instance using the specified properties. * @param [properties] Properties to set * @returns Multi instance */ public static create(properties?: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.IMulti): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi; /** * Encodes the specified Multi message. Does not implicitly {@link cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi.verify|verify} messages. * @param m Multi message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.IMulti, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Multi message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Multi * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi; /** * Creates a Multi message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Multi */ public static fromObject(d: { [k: string]: any }): cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi; /** * Creates a plain object from a Multi message. Also converts values to other types if specified. * @param m Multi * @param [o] Conversion options * @returns Plain object */ public static toObject(m: cosmos.tx.signing.v1beta1.SignatureDescriptor.Data.Multi, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Multi to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } } } } } /** Namespace google. */ export namespace google { /** Namespace protobuf. */ namespace protobuf { /** Properties of an Any. */ interface IAny { /** Any type_url */ type_url?: (string|null); /** Any value */ value?: (Uint8Array|null); } /** Represents an Any. */ class Any implements IAny { /** * Constructs a new Any. * @param [p] Properties to set */ constructor(p?: google.protobuf.IAny); /** Any type_url. */ public type_url: string; /** Any value. */ public value: Uint8Array; /** * Creates a new Any instance using the specified properties. * @param [properties] Properties to set * @returns Any instance */ public static create(properties?: google.protobuf.IAny): google.protobuf.Any; /** * Encodes the specified Any message. Does not implicitly {@link google.protobuf.Any.verify|verify} messages. * @param m Any message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: google.protobuf.IAny, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Any message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Any * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): google.protobuf.Any; /** * Creates an Any message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Any */ public static fromObject(d: { [k: string]: any }): google.protobuf.Any; /** * Creates a plain object from an Any message. Also converts values to other types if specified. * @param m Any * @param [o] Conversion options * @returns Plain object */ public static toObject(m: google.protobuf.Any, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Any to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Timestamp. */ interface ITimestamp { /** Timestamp seconds */ seconds?: (Long|null); /** Timestamp nanos */ nanos?: (number|null); } /** Represents a Timestamp. */ class Timestamp implements ITimestamp { /** * Constructs a new Timestamp. * @param [p] Properties to set */ constructor(p?: google.protobuf.ITimestamp); /** Timestamp seconds. */ public seconds: Long; /** Timestamp nanos. */ public nanos: number; /** * Creates a new Timestamp instance using the specified properties. * @param [properties] Properties to set * @returns Timestamp instance */ public static create(properties?: google.protobuf.ITimestamp): google.protobuf.Timestamp; /** * Encodes the specified Timestamp message. Does not implicitly {@link google.protobuf.Timestamp.verify|verify} messages. * @param m Timestamp message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: google.protobuf.ITimestamp, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Timestamp message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Timestamp * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): google.protobuf.Timestamp; /** * Creates a Timestamp message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Timestamp */ public static fromObject(d: { [k: string]: any }): google.protobuf.Timestamp; /** * Creates a plain object from a Timestamp message. Also converts values to other types if specified. * @param m Timestamp * @param [o] Conversion options * @returns Plain object */ public static toObject(m: google.protobuf.Timestamp, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Timestamp to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } /** Namespace ibc. */ export namespace ibc { /** Namespace applications. */ namespace applications { /** Namespace transfer. */ namespace transfer { /** Namespace v1. */ namespace v1 { /** Represents a Msg */ class Msg extends $protobuf.rpc.Service { /** * Constructs a new Msg service. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited */ constructor(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); /** * Creates new Msg service using the specified rpc implementation. * @param rpcImpl RPC implementation * @param [requestDelimited=false] Whether requests are length-delimited * @param [responseDelimited=false] Whether responses are length-delimited * @returns RPC service. Useful where requests and/or responses are streamed. */ public static create(rpcImpl: $protobuf.RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): Msg; /** * Calls Transfer. * @param request MsgTransfer message or plain object * @param callback Node-style callback called with the error, if any, and MsgTransferResponse */ public transfer(request: ibc.applications.transfer.v1.IMsgTransfer, callback: ibc.applications.transfer.v1.Msg.TransferCallback): void; /** * Calls Transfer. * @param request MsgTransfer message or plain object * @returns Promise */ public transfer(request: ibc.applications.transfer.v1.IMsgTransfer): Promise<ibc.applications.transfer.v1.MsgTransferResponse>; } namespace Msg { /** * Callback as used by {@link ibc.applications.transfer.v1.Msg#transfer}. * @param error Error, if any * @param [response] MsgTransferResponse */ type TransferCallback = (error: (Error|null), response?: ibc.applications.transfer.v1.MsgTransferResponse) => void; } /** Properties of a MsgTransfer. */ interface IMsgTransfer { /** MsgTransfer sourcePort */ sourcePort?: (string|null); /** MsgTransfer sourceChannel */ sourceChannel?: (string|null); /** MsgTransfer token */ token?: (cosmos.base.v1beta1.ICoin|null); /** MsgTransfer sender */ sender?: (string|null); /** MsgTransfer receiver */ receiver?: (string|null); /** MsgTransfer timeoutHeight */ timeoutHeight?: (ibc.core.client.v1.IHeight|null); /** MsgTransfer timeoutTimestamp */ timeoutTimestamp?: (Long|null); } /** Represents a MsgTransfer. */ class MsgTransfer implements IMsgTransfer { /** * Constructs a new MsgTransfer. * @param [p] Properties to set */ constructor(p?: ibc.applications.transfer.v1.IMsgTransfer); /** MsgTransfer sourcePort. */ public sourcePort: string; /** MsgTransfer sourceChannel. */ public sourceChannel: string; /** MsgTransfer token. */ public token?: (cosmos.base.v1beta1.ICoin|null); /** MsgTransfer sender. */ public sender: string; /** MsgTransfer receiver. */ public receiver: string; /** MsgTransfer timeoutHeight. */ public timeoutHeight?: (ibc.core.client.v1.IHeight|null); /** MsgTransfer timeoutTimestamp. */ public timeoutTimestamp: Long; /** * Creates a new MsgTransfer instance using the specified properties. * @param [properties] Properties to set * @returns MsgTransfer instance */ public static create(properties?: ibc.applications.transfer.v1.IMsgTransfer): ibc.applications.transfer.v1.MsgTransfer; /** * Encodes the specified MsgTransfer message. Does not implicitly {@link ibc.applications.transfer.v1.MsgTransfer.verify|verify} messages. * @param m MsgTransfer message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: ibc.applications.transfer.v1.IMsgTransfer, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgTransfer message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgTransfer * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): ibc.applications.transfer.v1.MsgTransfer; /** * Creates a MsgTransfer message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgTransfer */ public static fromObject(d: { [k: string]: any }): ibc.applications.transfer.v1.MsgTransfer; /** * Creates a plain object from a MsgTransfer message. Also converts values to other types if specified. * @param m MsgTransfer * @param [o] Conversion options * @returns Plain object */ public static toObject(m: ibc.applications.transfer.v1.MsgTransfer, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgTransfer to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MsgTransferResponse. */ interface IMsgTransferResponse { } /** Represents a MsgTransferResponse. */ class MsgTransferResponse implements IMsgTransferResponse { /** * Constructs a new MsgTransferResponse. * @param [p] Properties to set */ constructor(p?: ibc.applications.transfer.v1.IMsgTransferResponse); /** * Creates a new MsgTransferResponse instance using the specified properties. * @param [properties] Properties to set * @returns MsgTransferResponse instance */ public static create(properties?: ibc.applications.transfer.v1.IMsgTransferResponse): ibc.applications.transfer.v1.MsgTransferResponse; /** * Encodes the specified MsgTransferResponse message. Does not implicitly {@link ibc.applications.transfer.v1.MsgTransferResponse.verify|verify} messages. * @param m MsgTransferResponse message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: ibc.applications.transfer.v1.IMsgTransferResponse, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MsgTransferResponse message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns MsgTransferResponse * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): ibc.applications.transfer.v1.MsgTransferResponse; /** * Creates a MsgTransferResponse message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns MsgTransferResponse */ public static fromObject(d: { [k: string]: any }): ibc.applications.transfer.v1.MsgTransferResponse; /** * Creates a plain object from a MsgTransferResponse message. Also converts values to other types if specified. * @param m MsgTransferResponse * @param [o] Conversion options * @returns Plain object */ public static toObject(m: ibc.applications.transfer.v1.MsgTransferResponse, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MsgTransferResponse to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } } /** Namespace core. */ namespace core { /** Namespace client. */ namespace client { /** Namespace v1. */ namespace v1 { /** Properties of an Height. */ interface IHeight { /** Height revisionNumber */ revisionNumber?: (Long|null); /** Height revisionHeight */ revisionHeight?: (Long|null); } /** Represents an Height. */ class Height implements IHeight { /** * Constructs a new Height. * @param [p] Properties to set */ constructor(p?: ibc.core.client.v1.IHeight); /** Height revisionNumber. */ public revisionNumber: Long; /** Height revisionHeight. */ public revisionHeight: Long; /** * Creates a new Height instance using the specified properties. * @param [properties] Properties to set * @returns Height instance */ public static create(properties?: ibc.core.client.v1.IHeight): ibc.core.client.v1.Height; /** * Encodes the specified Height message. Does not implicitly {@link ibc.core.client.v1.Height.verify|verify} messages. * @param m Height message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: ibc.core.client.v1.IHeight, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Height message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns Height * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): ibc.core.client.v1.Height; /** * Creates an Height message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns Height */ public static fromObject(d: { [k: string]: any }): ibc.core.client.v1.Height; /** * Creates a plain object from an Height message. Also converts values to other types if specified. * @param m Height * @param [o] Conversion options * @returns Plain object */ public static toObject(m: ibc.core.client.v1.Height, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Height to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } } } } /** Namespace tendermint. */ export namespace tendermint { /** Namespace crypto. */ namespace crypto { /** Properties of a PublicKey. */ interface IPublicKey { /** PublicKey ed25519 */ ed25519?: (Uint8Array|null); /** PublicKey secp256k1 */ secp256k1?: (Uint8Array|null); } /** Represents a PublicKey. */ class PublicKey implements IPublicKey { /** * Constructs a new PublicKey. * @param [p] Properties to set */ constructor(p?: tendermint.crypto.IPublicKey); /** PublicKey ed25519. */ public ed25519: Uint8Array; /** PublicKey secp256k1. */ public secp256k1: Uint8Array; /** PublicKey sum. */ public sum?: ("ed25519"|"secp256k1"); /** * Creates a new PublicKey instance using the specified properties. * @param [properties] Properties to set * @returns PublicKey instance */ public static create(properties?: tendermint.crypto.IPublicKey): tendermint.crypto.PublicKey; /** * Encodes the specified PublicKey message. Does not implicitly {@link tendermint.crypto.PublicKey.verify|verify} messages. * @param m PublicKey message or plain object to encode * @param [w] Writer to encode to * @returns Writer */ public static encode(m: tendermint.crypto.IPublicKey, w?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PublicKey message from the specified reader or buffer. * @param r Reader or buffer to decode from * @param [l] Message length if known beforehand * @returns PublicKey * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(r: ($protobuf.Reader|Uint8Array), l?: number): tendermint.crypto.PublicKey; /** * Creates a PublicKey message from a plain object. Also converts values to their respective internal types. * @param d Plain object * @returns PublicKey */ public static fromObject(d: { [k: string]: any }): tendermint.crypto.PublicKey; /** * Creates a plain object from a PublicKey message. Also converts values to other types if specified. * @param m PublicKey * @param [o] Conversion options * @returns Plain object */ public static toObject(m: tendermint.crypto.PublicKey, o?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PublicKey to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } } }
the_stack
import { field, Logger, logger } from "@coder/logger" import * as cp from "child_process" import * as path from "path" import * as rfs from "rotating-file-stream" import { Emitter } from "../common/emitter" import { DefaultedArgs } from "./cli" import { paths } from "./util" const timeoutInterval = 10000 // 10s, matches VS Code's timeouts. /** * Listen to a single message from a process. Reject if the process errors, * exits, or times out. * * `fn` is a function that determines whether the message is the one we're * waiting for. */ export function onMessage<M, T extends M>( proc: cp.ChildProcess | NodeJS.Process, fn: (message: M) => message is T, customLogger?: Logger, ): Promise<T> { return new Promise((resolve, reject) => { const cleanup = () => { proc.off("error", onError) proc.off("exit", onExit) proc.off("message", onMessage) clearTimeout(timeout) } const timeout = setTimeout(() => { cleanup() reject(new Error("timed out")) }, timeoutInterval) const onError = (error: Error) => { cleanup() reject(error) } const onExit = (code: number) => { cleanup() reject(new Error(`exited unexpectedly with code ${code}`)) } const onMessage = (message: M) => { ;(customLogger || logger).trace("got message", field("message", message)) if (fn(message)) { cleanup() resolve(message) } } proc.on("message", onMessage) // NodeJS.Process doesn't have `error` but binding anyway shouldn't break // anything. It does have `exit` but the types aren't working. ;(proc as cp.ChildProcess).on("error", onError) ;(proc as cp.ChildProcess).on("exit", onExit) }) } interface ParentHandshakeMessage { type: "handshake" args: DefaultedArgs } interface ChildHandshakeMessage { type: "handshake" } interface RelaunchMessage { type: "relaunch" version: string } type ChildMessage = RelaunchMessage | ChildHandshakeMessage type ParentMessage = ParentHandshakeMessage class ProcessError extends Error { public constructor(message: string, public readonly code: number | undefined) { super(message) this.name = this.constructor.name Error.captureStackTrace(this, this.constructor) } } /** * Wrapper around a process that tries to gracefully exit when a process exits * and provides a way to prevent `process.exit`. */ abstract class Process { /** * Emit this to trigger a graceful exit. */ protected readonly _onDispose = new Emitter<NodeJS.Signals | undefined>() /** * Emitted when the process is about to be disposed. */ public readonly onDispose = this._onDispose.event /** * Uniquely named logger for the process. */ public abstract logger: Logger public constructor() { process.on("SIGINT", () => this._onDispose.emit("SIGINT")) process.on("SIGTERM", () => this._onDispose.emit("SIGTERM")) process.on("exit", () => this._onDispose.emit(undefined)) this.onDispose((signal, wait) => { // Remove listeners to avoid possibly triggering disposal again. process.removeAllListeners() // Try waiting for other handlers to run first then exit. this.logger.debug("disposing", field("code", signal)) wait.then(() => this.exit(0)) setTimeout(() => this.exit(0), 5000) }) } /** * Ensure control over when the process exits. */ public preventExit(): void { ;(process.exit as any) = (code?: number) => { this.logger.warn(`process.exit() was prevented: ${code || "unknown code"}.`) } } private readonly processExit: (code?: number) => never = process.exit /** * Will always exit even if normal exit is being prevented. */ public exit(error?: number | ProcessError): never { if (error && typeof error !== "number") { this.processExit(typeof error.code === "number" ? error.code : 1) } else { this.processExit(error) } } } /** * Child process that will clean up after itself if the parent goes away and can * perform a handshake with the parent and ask it to relaunch. */ class ChildProcess extends Process { public logger = logger.named(`child:${process.pid}`) public constructor(private readonly parentPid: number) { super() // Kill the inner process if the parent dies. This is for the case where the // parent process is forcefully terminated and cannot clean up. setInterval(() => { try { // process.kill throws an exception if the process doesn't exist. process.kill(this.parentPid, 0) } catch (_) { // Consider this an error since it should have been able to clean up // the child process unless it was forcefully killed. this.logger.error(`parent process ${parentPid} died`) this._onDispose.emit(undefined) } }, 5000) } /** * Initiate the handshake and wait for a response from the parent. */ public async handshake(): Promise<DefaultedArgs> { this.send({ type: "handshake" }) const message = await onMessage<ParentMessage, ParentHandshakeMessage>( process, (message): message is ParentHandshakeMessage => { return message.type === "handshake" }, this.logger, ) return message.args } /** * Notify the parent process that it should relaunch the child. */ public relaunch(version: string): void { this.send({ type: "relaunch", version }) } /** * Send a message to the parent. */ private send(message: ChildMessage): void { if (!process.send) { throw new Error("not spawned with IPC") } process.send(message) } } /** * Parent process wrapper that spawns the child process and performs a handshake * with it. Will relaunch the child if it receives a SIGUSR1 or SIGUSR2 or is * asked to by the child. If the child otherwise exits the parent will also * exit. */ export class ParentProcess extends Process { public logger = logger.named(`parent:${process.pid}`) private child?: cp.ChildProcess private started?: Promise<void> private readonly logStdoutStream: rfs.RotatingFileStream private readonly logStderrStream: rfs.RotatingFileStream protected readonly _onChildMessage = new Emitter<ChildMessage>() protected readonly onChildMessage = this._onChildMessage.event private args?: DefaultedArgs public constructor(private currentVersion: string) { super() process.on("SIGUSR1", async () => { this.logger.info("Received SIGUSR1; hotswapping") this.relaunch() }) process.on("SIGUSR2", async () => { this.logger.info("Received SIGUSR2; hotswapping") this.relaunch() }) const opts = { size: "10M", maxFiles: 10, } this.logStdoutStream = rfs.createStream(path.join(paths.data, "coder-logs", "code-server-stdout.log"), opts) this.logStderrStream = rfs.createStream(path.join(paths.data, "coder-logs", "code-server-stderr.log"), opts) this.onDispose(() => this.disposeChild()) this.onChildMessage((message) => { switch (message.type) { case "relaunch": this.logger.info(`Relaunching: ${this.currentVersion} -> ${message.version}`) this.currentVersion = message.version this.relaunch() break default: this.logger.error(`Unrecognized message ${message}`) break } }) } private async disposeChild(): Promise<void> { this.started = undefined if (this.child) { const child = this.child child.removeAllListeners() child.kill() // Wait for the child to exit otherwise its output will be lost which can // be especially problematic if you're trying to debug why cleanup failed. await new Promise((r) => child!.on("exit", r)) } } private async relaunch(): Promise<void> { this.disposeChild() try { this.started = this._start() await this.started } catch (error: any) { this.logger.error(error.message) this.exit(typeof error.code === "number" ? error.code : 1) } } public start(args: DefaultedArgs): Promise<void> { // Store for relaunches. this.args = args if (!this.started) { this.started = this._start() } return this.started } private async _start(): Promise<void> { const child = this.spawn() this.child = child // Log both to stdout and to the log directory. if (child.stdout) { child.stdout.pipe(this.logStdoutStream) child.stdout.pipe(process.stdout) } if (child.stderr) { child.stderr.pipe(this.logStderrStream) child.stderr.pipe(process.stderr) } this.logger.debug(`spawned inner process ${child.pid}`) await this.handshake(child) child.once("exit", (code) => { this.logger.debug(`inner process ${child.pid} exited unexpectedly`) this.exit(code || 0) }) } private spawn(): cp.ChildProcess { // Use spawn (instead of fork) to use the new binary in case it was updated. return cp.spawn(process.argv[0], process.argv.slice(1), { env: { ...process.env, CODE_SERVER_PARENT_PID: process.pid.toString(), NODE_OPTIONS: `--max-old-space-size=2048 ${process.env.NODE_OPTIONS || ""}`, }, stdio: ["pipe", "pipe", "pipe", "ipc"], }) } /** * Wait for a handshake from the child then reply. */ private async handshake(child: cp.ChildProcess): Promise<void> { if (!this.args) { throw new Error("started without args") } await onMessage<ChildMessage, ChildHandshakeMessage>( child, (message): message is ChildHandshakeMessage => { return message.type === "handshake" }, this.logger, ) this.send(child, { type: "handshake", args: this.args }) } /** * Send a message to the child. */ private send(child: cp.ChildProcess, message: ParentMessage): void { child.send(message) } } /** * Process wrapper. */ export const wrapper = typeof process.env.CODE_SERVER_PARENT_PID !== "undefined" ? new ChildProcess(parseInt(process.env.CODE_SERVER_PARENT_PID)) : new ParentProcess(require("../../package.json").version) export function isChild(proc: ChildProcess | ParentProcess): proc is ChildProcess { return proc instanceof ChildProcess } // It's possible that the pipe has closed (for example if you run code-server // --version | head -1). Assume that means we're done. if (!process.stdout.isTTY) { process.stdout.on("error", () => wrapper.exit()) } // Don't let uncaught exceptions crash the process. process.on("uncaughtException", (error) => { wrapper.logger.error(`Uncaught exception: ${error.message}`) if (typeof error.stack !== "undefined") { wrapper.logger.error(error.stack) } })
the_stack
import * as coreClient from "@azure/core-client"; export type MethodRequestUnion = | MethodRequest | MediaGraphTopologySetRequest | MediaGraphTopologySetRequestBody | MediaGraphInstanceSetRequest | MediaGraphInstanceSetRequestBody | ItemNonSetRequestBaseUnion | MediaGraphTopologyListRequest | MediaGraphInstanceListRequest; export type MediaGraphSourceUnion = | MediaGraphSource | MediaGraphRtspSource | MediaGraphIoTHubMessageSource; export type MediaGraphProcessorUnion = | MediaGraphProcessor | MediaGraphMotionDetectionProcessor | MediaGraphExtensionProcessorBaseUnion | MediaGraphSignalGateProcessor; export type MediaGraphSinkUnion = | MediaGraphSink | MediaGraphIoTHubMessageSink | MediaGraphFileSink | MediaGraphAssetSink; export type MediaGraphEndpointUnion = | MediaGraphEndpoint | MediaGraphUnsecuredEndpoint | MediaGraphTlsEndpoint; export type MediaGraphCredentialsUnion = | MediaGraphCredentials | MediaGraphUsernamePasswordCredentials | MediaGraphHttpHeaderCredentials; export type MediaGraphCertificateSourceUnion = | MediaGraphCertificateSource | MediaGraphPemCertificateList; export type MediaGraphImageFormatUnion = | MediaGraphImageFormat | MediaGraphImageFormatRaw | MediaGraphImageFormatJpeg | MediaGraphImageFormatBmp | MediaGraphImageFormatPng; export type ItemNonSetRequestBaseUnion = | ItemNonSetRequestBase | MediaGraphTopologyGetRequest | MediaGraphTopologyDeleteRequest | MediaGraphInstanceGetRequest | MediaGraphInstanceActivateRequest | MediaGraphInstanceDeActivateRequest | MediaGraphInstanceDeleteRequest; export type MediaGraphExtensionProcessorBaseUnion = | MediaGraphExtensionProcessorBase | MediaGraphCognitiveServicesVisionExtension | MediaGraphGrpcExtension | MediaGraphHttpExtension; /** Base Class for Method Requests. */ export interface MethodRequest { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: | "GraphTopologySet" | "MediaGraphTopologySetRequestBody" | "GraphInstanceSet" | "MediaGraphInstanceSetRequestBody" | "ItemNonSetRequestBase" | "GraphTopologyList" | "GraphTopologyGet" | "GraphTopologyDelete" | "GraphInstanceList" | "GraphInstanceGet" | "GraphInstanceActivate" | "GraphInstanceDeactivate" | "GraphInstanceDelete"; /** api version */ apiVersion?: "2.0"; } /** The definition of a media graph topology. */ export interface MediaGraphTopology { /** The identifier for the media graph topology. */ name: string; /** The system data for a resource. This is used by both topologies and instances. */ systemData?: MediaGraphSystemData; /** A description of the properties of a media graph topology. */ properties?: MediaGraphTopologyProperties; } /** The system data for a resource. This is used by both topologies and instances. */ export interface MediaGraphSystemData { /** The timestamp of resource creation (UTC). */ createdAt?: Date; /** The timestamp of resource last modification (UTC). */ lastModifiedAt?: Date; } /** A description of the properties of a media graph topology. */ export interface MediaGraphTopologyProperties { /** A description of a media graph topology. It is recommended to use this to describe the expected use of the topology. */ description?: string; /** The list of parameters defined in the topology. The value for these parameters are supplied by instances of this topology. */ parameters?: MediaGraphParameterDeclaration[]; /** The list of source nodes in this topology. */ sources?: MediaGraphSourceUnion[]; /** The list of processor nodes in this topology. */ processors?: MediaGraphProcessorUnion[]; /** The list of sink nodes in this topology. */ sinks?: MediaGraphSinkUnion[]; } /** The declaration of a parameter in the media graph topology. A media graph topology can be authored with parameters. Then, during graph instance creation, the value for those parameters can be specified. This allows the same graph topology to be used as a blueprint for multiple graph instances with different values for the parameters. */ export interface MediaGraphParameterDeclaration { /** The name of the parameter. */ name: string; /** The type of the parameter. */ type: MediaGraphParameterType; /** Description of the parameter. */ description?: string; /** The default value for the parameter to be used if the media graph instance does not specify a value. */ default?: string; } /** A source node in a media graph. */ export interface MediaGraphSource { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": | "#Microsoft.Media.MediaGraphRtspSource" | "#Microsoft.Media.MediaGraphIoTHubMessageSource"; /** The name to be used for this source node. */ name: string; } /** A node that represents the desired processing of media in a graph. Takes media and/or events as inputs, and emits media and/or event as output. */ export interface MediaGraphProcessor { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": | "#Microsoft.Media.MediaGraphMotionDetectionProcessor" | "#Microsoft.Media.MediaGraphExtensionProcessorBase" | "#Microsoft.Media.MediaGraphCognitiveServicesVisionExtension" | "#Microsoft.Media.MediaGraphGrpcExtension" | "#Microsoft.Media.MediaGraphHttpExtension" | "#Microsoft.Media.MediaGraphSignalGateProcessor"; /** The name for this processor node. */ name: string; /** An array of the names of the other nodes in the media graph, the outputs of which are used as input for this processor node. */ inputs: MediaGraphNodeInput[]; } /** Represents the input to any node in a media graph. */ export interface MediaGraphNodeInput { /** The name of another node in the media graph, the output of which is used as input to this node. */ nodeName: string; /** Allows for the selection of particular streams from another node. */ outputSelectors?: MediaGraphOutputSelector[]; } /** Allows for the selection of particular streams from another node. */ export interface MediaGraphOutputSelector { /** The stream property to compare with. */ property?: MediaGraphOutputSelectorProperty; /** The operator to compare streams by. */ operator?: MediaGraphOutputSelectorOperator; /** Value to compare against. */ value?: string; } /** Enables a media graph to write media data to a destination outside of the Live Video Analytics IoT Edge module. */ export interface MediaGraphSink { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": | "#Microsoft.Media.MediaGraphIoTHubMessageSink" | "#Microsoft.Media.MediaGraphFileSink" | "#Microsoft.Media.MediaGraphAssetSink"; /** The name to be used for the media graph sink. */ name: string; /** An array of the names of the other nodes in the media graph, the outputs of which are used as input for this sink node. */ inputs: MediaGraphNodeInput[]; } /** Represents an instance of a media graph. */ export interface MediaGraphInstance { /** The identifier for the media graph instance. */ name: string; /** The system data for a resource. This is used by both topologies and instances. */ systemData?: MediaGraphSystemData; /** Properties of a media graph instance. */ properties?: MediaGraphInstanceProperties; } /** Properties of a media graph instance. */ export interface MediaGraphInstanceProperties { /** An optional description for the instance. */ description?: string; /** The name of the media graph topology that this instance will run. A topology with this name should already have been set in the Edge module. */ topologyName?: string; /** List of one or more graph instance parameters. */ parameters?: MediaGraphParameterDefinition[]; /** Allowed states for a graph instance. */ state?: MediaGraphInstanceState; } /** A key-value pair. A media graph topology allows certain values to be parameterized. When an instance is created, the parameters are supplied with arguments specific to that instance. This allows the same graph topology to be used as a blueprint for multiple graph instances with different values for the parameters. */ export interface MediaGraphParameterDefinition { /** The name of the parameter defined in the media graph topology. */ name: string; /** The value to supply for the named parameter defined in the media graph topology. */ value: string; } /** Base class for endpoints. */ export interface MediaGraphEndpoint { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": | "#Microsoft.Media.MediaGraphUnsecuredEndpoint" | "#Microsoft.Media.MediaGraphTlsEndpoint"; /** Polymorphic credentials to be presented to the endpoint. */ credentials?: MediaGraphCredentialsUnion; /** Url for the endpoint. */ url: string; } /** Credentials to present during authentication. */ export interface MediaGraphCredentials { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": | "#Microsoft.Media.MediaGraphUsernamePasswordCredentials" | "#Microsoft.Media.MediaGraphHttpHeaderCredentials"; } /** Base class for certificate sources. */ export interface MediaGraphCertificateSource { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphPemCertificateList"; } /** Options for controlling the authentication of TLS endpoints. */ export interface MediaGraphTlsValidationOptions { /** Boolean value ignoring the host name (common name) during validation. */ ignoreHostname?: string; /** Boolean value ignoring the integrity of the certificate chain at the current time. */ ignoreSignature?: string; } /** Describes the properties of an image frame. */ export interface MediaGraphImage { /** The scaling mode for the image. */ scale?: MediaGraphImageScale; /** Encoding settings for an image. */ format?: MediaGraphImageFormatUnion; } /** The scaling mode for the image. */ export interface MediaGraphImageScale { /** Describes the modes for scaling an input video frame into an image, before it is sent to an inference engine. */ mode?: MediaGraphImageScaleMode; /** The desired output width of the image. */ width?: string; /** The desired output height of the image. */ height?: string; } /** Encoding settings for an image. */ export interface MediaGraphImageFormat { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": | "#Microsoft.Media.MediaGraphImageFormatRaw" | "#Microsoft.Media.MediaGraphImageFormatJpeg" | "#Microsoft.Media.MediaGraphImageFormatBmp" | "#Microsoft.Media.MediaGraphImageFormatPng"; } /** Describes the properties of a sample. */ export interface MediaGraphSamplingOptions { /** If true, limits the samples submitted to the extension to only samples which have associated inference(s) */ skipSamplesWithoutAnnotation?: string; /** Maximum rate of samples submitted to the extension */ maximumSamplesPerSecond?: string; } /** Describes how media should be transferred to the inference engine. */ export interface MediaGraphGrpcExtensionDataTransfer { /** The size of the buffer for all in-flight frames in mebibytes if mode is SharedMemory. Should not be specified otherwise. */ sharedMemorySizeMiB?: string; /** How frame data should be transmitted to the inference engine. */ mode: MediaGraphGrpcExtensionDataTransferMode; } /** Represents the MediaGraphTopologySetRequest. */ export type MediaGraphTopologySetRequest = MethodRequest & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphTopologySet"; /** The definition of a media graph topology. */ graph: MediaGraphTopology; }; /** Represents the MediaGraphTopologySetRequest body. */ export type MediaGraphTopologySetRequestBody = MethodRequest & MediaGraphTopology & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "MediaGraphTopologySetRequestBody"; }; /** Represents the MediaGraphInstanceSetRequest. */ export type MediaGraphInstanceSetRequest = MethodRequest & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphInstanceSet"; /** Represents an instance of a media graph. */ instance: MediaGraphInstance; }; /** Represents the MediaGraphInstanceSetRequest body. */ export type MediaGraphInstanceSetRequestBody = MethodRequest & MediaGraphInstance & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "MediaGraphInstanceSetRequestBody"; }; export type ItemNonSetRequestBase = MethodRequest & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: | "ItemNonSetRequestBase" | "GraphTopologyGet" | "GraphTopologyDelete" | "GraphInstanceGet" | "GraphInstanceActivate" | "GraphInstanceDeactivate" | "GraphInstanceDelete"; /** method name */ name: string; }; /** Represents the MediaGraphTopologyListRequest. */ export type MediaGraphTopologyListRequest = MethodRequest & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphTopologyList"; }; /** Represents the MediaGraphInstanceListRequest. */ export type MediaGraphInstanceListRequest = MethodRequest & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphInstanceList"; }; /** Enables a media graph to capture media from a RTSP server. */ export type MediaGraphRtspSource = MediaGraphSource & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphRtspSource"; /** Underlying RTSP transport. This is used to enable or disable HTTP tunneling. */ transport?: MediaGraphRtspTransport; /** RTSP endpoint of the stream that is being connected to. */ endpoint: MediaGraphEndpointUnion; }; /** Enables a media graph to receive messages via routes declared in the IoT Edge deployment manifest. */ export type MediaGraphIoTHubMessageSource = MediaGraphSource & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphIoTHubMessageSource"; /** Name of the input path where messages can be routed to (via routes declared in the IoT Edge deployment manifest). */ hubInputName?: string; }; /** A node that accepts raw video as input, and detects if there are moving objects present. If so, then it emits an event, and allows frames where motion was detected to pass through. Other frames are blocked/dropped. */ export type MediaGraphMotionDetectionProcessor = MediaGraphProcessor & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphMotionDetectionProcessor"; /** Enumeration that specifies the sensitivity of the motion detection processor. */ sensitivity?: MediaGraphMotionDetectionSensitivity; /** Indicates whether the processor should detect and output the regions, within the video frame, where motion was detected. Default is true. */ outputMotionRegion?: boolean; /** Event aggregation window duration, or 0 for no aggregation. */ eventAggregationWindow?: string; }; /** Processor that allows for extensions outside of the Live Video Analytics Edge module to be integrated into the graph. It is the base class for various different kinds of extension processor types. */ export type MediaGraphExtensionProcessorBase = MediaGraphProcessor & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": | "#Microsoft.Media.MediaGraphExtensionProcessorBase" | "#Microsoft.Media.MediaGraphCognitiveServicesVisionExtension" | "#Microsoft.Media.MediaGraphGrpcExtension" | "#Microsoft.Media.MediaGraphHttpExtension"; /** Endpoint to which this processor should connect. */ endpoint: MediaGraphEndpointUnion; /** Describes the parameters of the image that is sent as input to the endpoint. */ image: MediaGraphImage; /** Describes the sampling options to be applied when forwarding samples to the extension. */ samplingOptions?: MediaGraphSamplingOptions; }; /** A signal gate determines when to block (gate) incoming media, and when to allow it through. It gathers input events over the activationEvaluationWindow, and determines whether to open or close the gate. */ export type MediaGraphSignalGateProcessor = MediaGraphProcessor & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphSignalGateProcessor"; /** The period of time over which the gate gathers input events before evaluating them. */ activationEvaluationWindow?: string; /** Signal offset once the gate is activated (can be negative). It is an offset between the time the event is received, and the timestamp of the first media sample (eg. video frame) that is allowed through by the gate. */ activationSignalOffset?: string; /** The minimum period for which the gate remains open in the absence of subsequent triggers (events). */ minimumActivationTime?: string; /** The maximum period for which the gate remains open in the presence of subsequent events. */ maximumActivationTime?: string; }; /** Enables a media graph to publish messages that can be delivered via routes declared in the IoT Edge deployment manifest. */ export type MediaGraphIoTHubMessageSink = MediaGraphSink & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphIoTHubMessageSink"; /** Name of the output path to which the media graph will publish message. These messages can then be delivered to desired destinations by declaring routes referencing the output path in the IoT Edge deployment manifest. */ hubOutputName: string; }; /** Enables a media graph to write/store media (video and audio) to a file on the Edge device. */ export type MediaGraphFileSink = MediaGraphSink & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphFileSink"; /** Absolute directory for all outputs to the Edge device from this sink. */ baseDirectoryPath: string; /** File name pattern for creating new files on the Edge device. The pattern must include at least one system variable. See the documentation for available variables and additional examples. */ fileNamePattern: string; /** Maximum amount of disk space that can be used for storing files from this sink. */ maximumSizeMiB: string; }; /** Enables a media graph to record media to an Azure Media Services asset for subsequent playback. */ export type MediaGraphAssetSink = MediaGraphSink & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphAssetSink"; /** A name pattern when creating new assets. The pattern must include at least one system variable. See the documentation for available variables and additional examples. */ assetNamePattern: string; /** When writing media to an asset, wait until at least this duration of media has been accumulated on the Edge. Expressed in increments of 30 seconds, with a minimum of 30 seconds and a recommended maximum of 5 minutes. */ segmentLength?: string; /** Path to a local file system directory for temporary caching of media before writing to an Asset. Used when the Edge device is temporarily disconnected from Azure. */ localMediaCachePath: string; /** Maximum amount of disk space that can be used for temporary caching of media. */ localMediaCacheMaximumSizeMiB: string; }; /** An endpoint that the media graph can connect to, with no encryption in transit. */ export type MediaGraphUnsecuredEndpoint = MediaGraphEndpoint & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphUnsecuredEndpoint"; }; /** A TLS endpoint for media graph external connections. */ export type MediaGraphTlsEndpoint = MediaGraphEndpoint & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphTlsEndpoint"; /** Trusted certificates when authenticating a TLS connection. Null designates that Azure Media Service's source of trust should be used. */ trustedCertificates?: MediaGraphCertificateSourceUnion; /** Validation options to use when authenticating a TLS connection. By default, strict validation is used. */ validationOptions?: MediaGraphTlsValidationOptions; }; /** Username/password credential pair. */ export type MediaGraphUsernamePasswordCredentials = MediaGraphCredentials & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphUsernamePasswordCredentials"; /** Username for a username/password pair. */ username: string; /** Password for a username/password pair. Please use a parameter so that the actual value is not returned on PUT or GET requests. */ password: string; }; /** Http header service credentials. */ export type MediaGraphHttpHeaderCredentials = MediaGraphCredentials & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphHttpHeaderCredentials"; /** HTTP header name. */ headerName: string; /** HTTP header value. Please use a parameter so that the actual value is not returned on PUT or GET requests. */ headerValue: string; }; /** A list of PEM formatted certificates. */ export type MediaGraphPemCertificateList = MediaGraphCertificateSource & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphPemCertificateList"; /** PEM formatted public certificates one per entry. */ certificates: string[]; }; /** Encoding settings for raw images. */ export type MediaGraphImageFormatRaw = MediaGraphImageFormat & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphImageFormatRaw"; /** The pixel format that will be used to encode images. */ pixelFormat: MediaGraphImageFormatRawPixelFormat; }; /** Encoding settings for Jpeg images. */ export type MediaGraphImageFormatJpeg = MediaGraphImageFormat & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphImageFormatJpeg"; /** The image quality. Value must be between 0 to 100 (best quality). */ quality?: string; }; /** Encoding settings for Bmp images. */ export type MediaGraphImageFormatBmp = MediaGraphImageFormat & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphImageFormatBmp"; }; /** Encoding settings for Png images. */ export type MediaGraphImageFormatPng = MediaGraphImageFormat & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphImageFormatPng"; }; /** Represents the MediaGraphTopologyGetRequest. */ export type MediaGraphTopologyGetRequest = ItemNonSetRequestBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphTopologyGet"; }; /** Represents the MediaGraphTopologyDeleteRequest. */ export type MediaGraphTopologyDeleteRequest = ItemNonSetRequestBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphTopologyDelete"; }; /** Represents the MediaGraphInstanceGetRequest. */ export type MediaGraphInstanceGetRequest = ItemNonSetRequestBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphInstanceGet"; }; /** Represents the MediaGraphInstanceActivateRequest. */ export type MediaGraphInstanceActivateRequest = ItemNonSetRequestBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphInstanceActivate"; }; /** Represents the MediaGraphInstanceDeactivateRequest. */ export type MediaGraphInstanceDeActivateRequest = ItemNonSetRequestBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphInstanceDeactivate"; }; /** Represents the MediaGraphInstanceDeleteRequest. */ export type MediaGraphInstanceDeleteRequest = ItemNonSetRequestBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ methodName: "GraphInstanceDelete"; }; /** A processor that allows the media graph to send video frames to a Cognitive Services Vision extension. Inference results are relayed to downstream nodes. */ export type MediaGraphCognitiveServicesVisionExtension = MediaGraphExtensionProcessorBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphCognitiveServicesVisionExtension"; }; /** A processor that allows the media graph to send video frames to an external inference container over a gRPC connection. This can be done using shared memory (for high frame rates), or over the network. Inference results are relayed to downstream nodes. */ export type MediaGraphGrpcExtension = MediaGraphExtensionProcessorBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphGrpcExtension"; /** How media should be transferred to the inference engine. */ dataTransfer: MediaGraphGrpcExtensionDataTransfer; /** Optional configuration to pass to the gRPC extension. */ extensionConfiguration?: string; }; /** A processor that allows the media graph to send video frames (mostly at low frame rates e.g. <5 fps) to an external inference container over an HTTP-based RESTful API. Inference results are relayed to downstream nodes. */ export type MediaGraphHttpExtension = MediaGraphExtensionProcessorBase & { /** Polymorphic discriminator, which specifies the different types this object can be */ "@type": "#Microsoft.Media.MediaGraphHttpExtension"; }; /** Known values of {@link MediaGraphParameterType} that the service accepts. */ export enum KnownMediaGraphParameterType { /** A string parameter value. */ String = "String", /** A string to hold sensitive information as parameter value. */ SecretString = "SecretString", /** A 32-bit signed integer as parameter value. */ Int = "Int", /** A 64-bit double-precision floating point type as parameter value. */ Double = "Double", /** A boolean value that is either true or false. */ Bool = "Bool" } /** * Defines values for MediaGraphParameterType. \ * {@link KnownMediaGraphParameterType} can be used interchangeably with MediaGraphParameterType, * this enum contains the known values that the service supports. * ### Known values supported by the service * **String**: A string parameter value. \ * **SecretString**: A string to hold sensitive information as parameter value. \ * **Int**: A 32-bit signed integer as parameter value. \ * **Double**: A 64-bit double-precision floating point type as parameter value. \ * **Bool**: A boolean value that is either true or false. */ export type MediaGraphParameterType = string; /** Known values of {@link MediaGraphOutputSelectorProperty} that the service accepts. */ export enum KnownMediaGraphOutputSelectorProperty { /** The stream's MIME type or subtype. */ MediaType = "mediaType" } /** * Defines values for MediaGraphOutputSelectorProperty. \ * {@link KnownMediaGraphOutputSelectorProperty} can be used interchangeably with MediaGraphOutputSelectorProperty, * this enum contains the known values that the service supports. * ### Known values supported by the service * **mediaType**: The stream's MIME type or subtype. */ export type MediaGraphOutputSelectorProperty = string; /** Known values of {@link MediaGraphOutputSelectorOperator} that the service accepts. */ export enum KnownMediaGraphOutputSelectorOperator { /** A media type is the same type or a subtype. */ Is = "is", /** A media type is not the same type or a subtype. */ IsNot = "isNot" } /** * Defines values for MediaGraphOutputSelectorOperator. \ * {@link KnownMediaGraphOutputSelectorOperator} can be used interchangeably with MediaGraphOutputSelectorOperator, * this enum contains the known values that the service supports. * ### Known values supported by the service * **is**: A media type is the same type or a subtype. \ * **isNot**: A media type is not the same type or a subtype. */ export type MediaGraphOutputSelectorOperator = string; /** Known values of {@link MediaGraphInstanceState} that the service accepts. */ export enum KnownMediaGraphInstanceState { /** The media graph instance is idle and not processing media. */ Inactive = "Inactive", /** The media graph instance is transitioning into the active state. */ Activating = "Activating", /** The media graph instance is active and processing media. */ Active = "Active", /** The media graph instance is transitioning into the inactive state. */ Deactivating = "Deactivating" } /** * Defines values for MediaGraphInstanceState. \ * {@link KnownMediaGraphInstanceState} can be used interchangeably with MediaGraphInstanceState, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Inactive**: The media graph instance is idle and not processing media. \ * **Activating**: The media graph instance is transitioning into the active state. \ * **Active**: The media graph instance is active and processing media. \ * **Deactivating**: The media graph instance is transitioning into the inactive state. */ export type MediaGraphInstanceState = string; /** Known values of {@link MediaGraphRtspTransport} that the service accepts. */ export enum KnownMediaGraphRtspTransport { /** HTTP/HTTPS transport. This should be used when HTTP tunneling is desired. */ Http = "Http", /** TCP transport. This should be used when HTTP tunneling is NOT desired. */ Tcp = "Tcp" } /** * Defines values for MediaGraphRtspTransport. \ * {@link KnownMediaGraphRtspTransport} can be used interchangeably with MediaGraphRtspTransport, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Http**: HTTP\/HTTPS transport. This should be used when HTTP tunneling is desired. \ * **Tcp**: TCP transport. This should be used when HTTP tunneling is NOT desired. */ export type MediaGraphRtspTransport = string; /** Known values of {@link MediaGraphMotionDetectionSensitivity} that the service accepts. */ export enum KnownMediaGraphMotionDetectionSensitivity { /** Low Sensitivity. */ Low = "Low", /** Medium Sensitivity. */ Medium = "Medium", /** High Sensitivity. */ High = "High" } /** * Defines values for MediaGraphMotionDetectionSensitivity. \ * {@link KnownMediaGraphMotionDetectionSensitivity} can be used interchangeably with MediaGraphMotionDetectionSensitivity, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Low**: Low Sensitivity. \ * **Medium**: Medium Sensitivity. \ * **High**: High Sensitivity. */ export type MediaGraphMotionDetectionSensitivity = string; /** Known values of {@link MediaGraphImageScaleMode} that the service accepts. */ export enum KnownMediaGraphImageScaleMode { /** Use the same aspect ratio as the input frame. */ PreserveAspectRatio = "PreserveAspectRatio", /** Center pad the input frame to match the given dimensions. */ Pad = "Pad", /** Stretch input frame to match given dimensions. */ Stretch = "Stretch" } /** * Defines values for MediaGraphImageScaleMode. \ * {@link KnownMediaGraphImageScaleMode} can be used interchangeably with MediaGraphImageScaleMode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **PreserveAspectRatio**: Use the same aspect ratio as the input frame. \ * **Pad**: Center pad the input frame to match the given dimensions. \ * **Stretch**: Stretch input frame to match given dimensions. */ export type MediaGraphImageScaleMode = string; /** Known values of {@link MediaGraphGrpcExtensionDataTransferMode} that the service accepts. */ export enum KnownMediaGraphGrpcExtensionDataTransferMode { /** Frames are transferred embedded into the gRPC messages. */ Embedded = "Embedded", /** Frames are transferred through shared memory. */ SharedMemory = "SharedMemory" } /** * Defines values for MediaGraphGrpcExtensionDataTransferMode. \ * {@link KnownMediaGraphGrpcExtensionDataTransferMode} can be used interchangeably with MediaGraphGrpcExtensionDataTransferMode, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Embedded**: Frames are transferred embedded into the gRPC messages. \ * **SharedMemory**: Frames are transferred through shared memory. */ export type MediaGraphGrpcExtensionDataTransferMode = string; /** Known values of {@link MediaGraphImageFormatRawPixelFormat} that the service accepts. */ export enum KnownMediaGraphImageFormatRawPixelFormat { /** Planar YUV 4:2:0, 12bpp, (1 Cr and Cb sample per 2x2 Y samples). */ Yuv420P = "Yuv420p", /** Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian. */ Rgb565Be = "Rgb565be", /** Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian. */ Rgb565Le = "Rgb565le", /** Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused/undefined. */ Rgb555Be = "Rgb555be", /** Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused/undefined. */ Rgb555Le = "Rgb555le", /** Packed RGB 8:8:8, 24bpp, RGBRGB. */ Rgb24 = "Rgb24", /** Packed RGB 8:8:8, 24bpp, BGRBGR. */ Bgr24 = "Bgr24", /** Packed ARGB 8:8:8:8, 32bpp, ARGBARGB. */ Argb = "Argb", /** Packed RGBA 8:8:8:8, 32bpp, RGBARGBA. */ Rgba = "Rgba", /** Packed ABGR 8:8:8:8, 32bpp, ABGRABGR. */ Abgr = "Abgr", /** Packed BGRA 8:8:8:8, 32bpp, BGRABGRA. */ Bgra = "Bgra" } /** * Defines values for MediaGraphImageFormatRawPixelFormat. \ * {@link KnownMediaGraphImageFormatRawPixelFormat} can be used interchangeably with MediaGraphImageFormatRawPixelFormat, * this enum contains the known values that the service supports. * ### Known values supported by the service * **Yuv420p**: Planar YUV 4:2:0, 12bpp, (1 Cr and Cb sample per 2x2 Y samples). \ * **Rgb565be**: Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), big-endian. \ * **Rgb565le**: Packed RGB 5:6:5, 16bpp, (msb) 5R 6G 5B(lsb), little-endian. \ * **Rgb555be**: Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), big-endian , X=unused\/undefined. \ * **Rgb555le**: Packed RGB 5:5:5, 16bpp, (msb)1X 5R 5G 5B(lsb), little-endian, X=unused\/undefined. \ * **Rgb24**: Packed RGB 8:8:8, 24bpp, RGBRGB. \ * **Bgr24**: Packed RGB 8:8:8, 24bpp, BGRBGR. \ * **Argb**: Packed ARGB 8:8:8:8, 32bpp, ARGBARGB. \ * **Rgba**: Packed RGBA 8:8:8:8, 32bpp, RGBARGBA. \ * **Abgr**: Packed ABGR 8:8:8:8, 32bpp, ABGRABGR. \ * **Bgra**: Packed BGRA 8:8:8:8, 32bpp, BGRABGRA. */ export type MediaGraphImageFormatRawPixelFormat = string; /** Optional parameters. */ export interface MediaServicesClientOptionalParams extends coreClient.ServiceClientOptions { /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import React from 'react' import { Events, i18n, isAbortableResponse, isCodedError, isCommentaryResponse, isTabLayoutModificationResponse, isRadioTable, isReactResponse, isMarkdownResponse, isMixedResponse, isMultiModalResponse, isNavResponse, isXtermResponse, isTable, Tab as KuiTab, Stream, Streamable, Util } from '@kui-shell/core' import { BlockViewTraits, BlockOperationTraits } from './' import { BlockModel, ProcessingBlock, FinishedBlock, hasUUID, hasCommand, hasBeenRerun, isBeingRerun, isFinished, isProcessingOrBeingRerun as isProcessing, isOk, isCancelled, isEmpty, isOutputOnly, isOutputRedirected, isOops, isReplay, isWithCompleteEvent } from './BlockModel' import Actions from './Actions' import SplitPosition from '../SplitPosition' import Scalar from '../../../Content/Scalar/' // !! DO NOT MAKE LAZY. See https://github.com/IBM/kui/issues/6758 import KuiContext from '../../../Client/context' import { Maximizable } from '../../Sidecar/width' const Ansi = React.lazy(() => import('../../../Content/Scalar/Ansi')) const ExpandableSection = React.lazy(() => import('../../../spi/ExpandableSection')) const strings = i18n('plugin-client-common') type Props = { /** tab UUID */ uuid: string /** for key handlers, which may go away soon */ tab: KuiTab /** Block ordinal */ idx: number /** Block ordinal to be displayed to user */ displayedIdx?: number /** Position of the enclosing split. Default: SplitPosition.default */ splitPosition?: SplitPosition model: ProcessingBlock | FinishedBlock onRender: () => void willUpdateCommand?: (idx: number, command: string) => void } & Maximizable & BlockViewTraits & BlockOperationTraits interface State { alreadyListen: boolean assertHasContent?: boolean isResultRendered: boolean nStreamingOutputs: number streamingConsumer: Stream } export default class Output extends React.PureComponent<Props, State> { private readonly _willRemove = () => this.props.willRemove(undefined, this.props.idx) private readonly _willUpdateCommand = (command: string) => this.props.willUpdateCommand(this.props.idx, command) private streamingOutput: Streamable[] = [] public constructor(props: Props) { super(props) const streamingConsumer = this.streamingConsumer.bind(this) this.state = { alreadyListen: false, isResultRendered: false, nStreamingOutputs: 0, streamingConsumer } } // eslint-disable-next-line @typescript-eslint/no-unused-vars private async streamingConsumer(part: Streamable) { if (hasUUID(this.props.model)) { const tabUUID = this.props.uuid const execUUID = this.props.model.execUUID // done with this part... not done with all parts const done = () => { this.props.onRender() Events.eventChannelUnsafe.emit(`/command/stdout/done/${tabUUID}/${execUUID}`) } // part === null: the controller wants to clear prior output if (part === null) { // remove last output this.streamingOutput.pop() this.setState(curState => ({ nStreamingOutputs: curState.nStreamingOutputs - 1 })) done() } else { if (isOutputRedirected(this.props.model)) { // if we were asked to redirect to a file, then we can // immediately indicate that we are done with this part done() } else { this.streamingOutput.push(Buffer.isBuffer(part) ? part.toString() : part) // use setTimeout to introduce hysteresis, so we aren't // forcing a react re-render for a bunch of tiny streaming // updates setTimeout(() => { this.setState({ nStreamingOutputs: this.streamingOutput.length }) setTimeout(done, 10) }, 10) } } } } public static getDerivedStateFromProps(props: Props, state: State) { if (isProcessing(props.model) && !state.alreadyListen) { // listen for streaming output (unless the output has been redirected to a file) const tabUUID = props.uuid Events.eventChannelUnsafe.on(`/command/stdout/${tabUUID}/${props.model.execUUID}`, state.streamingConsumer) return { alreadyListen: true, isResultRendered: false, streamingOutput: [] } } else if (isFinished(props.model) && !state.isResultRendered) { const tabUUID = props.uuid if (!isEmpty(props.model)) { Events.eventChannelUnsafe.off(`/command/stdout/${tabUUID}/${props.model.execUUID}`, state.streamingConsumer) } return { alreadyListen: false, isResultRendered: true } } else { return state } } private unmounted = false public componentWillUnmount() { this.unmounted = true } private onRender(assertHasContent: boolean): void { if (this.unmounted) return else if (this.props.onRender && !isBeingRerun(this.props.model) && !hasBeenRerun(this.props.model)) { // we don't want reruns to trigger any scrolling behavior this.props.onRender() } this.setState({ assertHasContent }) } private readonly _onRender = this.onRender.bind(this) private hasStreamingOutput() { return this.state.nStreamingOutputs > 0 } private outputWillOverflow() { // RadioTable currently uses the Dropdown component that will overflow return isWithCompleteEvent(this.props.model) && isRadioTable(this.props.model.response) } private stream() { if (this.hasStreamingOutput()) { // we may have duplicates in streamingOutput and response // see https://github.com/kubernetes-sigs/kui/pull/8354 const response = isWithCompleteEvent(this.props.model) ? this.props.model.response : undefined const streamingOutput = !response ? this.streamingOutput : this.streamingOutput.filter(_ => { if (isMixedResponse(response)) { return !response.find(_2 => _ === _2) } else { return _ !== response } }) if (streamingOutput.length < this.streamingOutput.length) { this.streamingOutput = streamingOutput } if (streamingOutput.every(_ => typeof _ === 'string')) { const combined = streamingOutput.join('') return ( <div className="repl-result-like result-vertical" data-stream> <React.Suspense fallback={<div />}> <Ansi>{combined}</Ansi> </React.Suspense> </div> ) } return ( <div className="repl-result-like result-vertical" data-stream> {streamingOutput.map((part, idx) => ( <React.Suspense fallback={<div />} key={idx}> <Scalar tab={this.props.tab} execUUID={hasUUID(this.props.model) && this.props.model.execUUID} response={part} isWidthConstrained={this.props.isWidthConstrained} willChangeSize={this.props.willChangeSize} willUpdateCommand={this._willUpdateCommand} onRender={this._onRender} /> </React.Suspense> ))} </div> ) } } private result() { if (isProcessing(this.props.model)) { return <div className="repl-result" /> } else if (isEmpty(this.props.model)) { // no result to display for these cases return <React.Fragment /> } else { const statusCode = isOops(this.props.model) ? isCodedError(this.props.model.response) ? this.props.model.response.code || this.props.model.response.statusCode : 500 : isFinished(this.props.model) ? 0 : undefined return ( <div className={ 'repl-result' + (isOops(this.props.model) ? ' oops' : '') + (isWithCompleteEvent(this.props.model) && isMixedResponse(this.props.model.response) ? ' flex-column' : '') + (this.outputWillOverflow() ? ' overflow-visible' : '') } data-status-code={statusCode} > {isCancelled(this.props.model) ? ( <React.Fragment /> ) : ( <React.Suspense fallback={<div />}> <Scalar tab={this.props.tab} execUUID={hasUUID(this.props.model) && this.props.model.execUUID} response={this.props.model.response} completeEvent={this.props.model.completeEvent} isWidthConstrained={this.props.isWidthConstrained} willChangeSize={this.props.willChangeSize} willFocusBlock={this.props.willFocusBlock} willRemove={this._willRemove} willUpdateCommand={this._willUpdateCommand} onRender={this._onRender} /> </React.Suspense> )} </div> ) } } private cursor() { /* if (isProcessing(this.props.model)) { return ( <div className="repl-result-spinner"> <div className="repl-result-spinner-inner"></div> </div> ) } */ } private isShowingSomethingInTerminal(block: BlockModel): block is FinishedBlock { if (isProcessing(this.props.model)) { return this.hasStreamingOutput() } else if (isFinished(block) && !isCancelled(block) && !isEmpty(block)) { const { response } = block return ( isOops(block) || isAbortableResponse(response) || isMultiModalResponse(response) || isNavResponse(response) || isCommentaryResponse(response) || isTabLayoutModificationResponse(response) || isReactResponse(response) || Util.isHTML(response) || isMarkdownResponse(response) || (Array.isArray(response) && response.length > 0) || (typeof response === 'string' && response.length > 0) || typeof response === 'number' || isTable(response) || isMixedResponse(response) || (isXtermResponse(response) && response.rows && response.rows.length !== 0) || this.hasStreamingOutput() ) } else { return false } } private ok(hasContent: boolean) { if (isOk(this.props.model)) { if (hasContent) { return <div className="ok" /> } else { return <div className="ok">{strings('ok')}</div> } } } private ctx(/* insideBrackets: React.ReactNode = this.props.displayedIdx || this.props.idx + 1 */) { return ( <KuiContext.Consumer> {config => !config.noPromptContext && ( <span className="repl-context" onClick={this.props.willFocusBlock} data-input-count={this.props.idx} data-custom-prompt={!!config.prompt || undefined} /> ) } </KuiContext.Consumer> ) } /** For output-only blocks, render the Block Actions */ private actions() { if (isOutputOnly(this.props.model)) { return <Actions {...this.props} command={hasCommand(this.props.model) && this.props.model.command} /> } } /** @return the UI for the main/content part of the Output */ private content(hasContent: boolean) { return ( <div className="result-vertical"> {this.stream()} {this.result()} {this.cursor()} {this.ok(hasContent)} </div> ) } public render() { const hasContent = this.state.assertHasContent !== undefined ? this.state.assertHasContent : this.isShowingSomethingInTerminal(this.props.model) // when displaying blocks in a loaded Snapshot (isReplay) that // have not yet been rerun (hasBeenRerun), then wrap an expando // around them (except don't wrap expandos around output-only // blocks, such as for Commentary) const noExpando = !isReplay(this.props.model) || hasBeenRerun(this.props.model) || isOutputOnly(this.props.model) const content = noExpando ? ( this.content(hasContent) ) : ( <ExpandableSection className="flex-fill" expanded={this.props.splitPosition === 'bottom-strip' /* Default expanded for bottom strip positioning */} showMore={strings('Show Sample Output')} showLess={strings('Hide Sample Output')} > {this.content(hasContent)} </ExpandableSection> ) return ( <div className={'repl-output ' + (hasContent ? ' repl-result-has-content' : '')}> {hasContent && this.ctx()} {content} {this.actions()} </div> ) } }
the_stack
import { parse, ParseResult } from "@babel/parser"; import traverse from "@babel/traverse"; import generate from '@babel/generator'; import * as t from '@babel/types'; import { IDocsAPI } from "../../types"; import { Resource } from "../../resource"; import { getContentByPath } from "../../utils"; const path_ = require("path") export function getDocsRes(filePath: string, resource: Resource) { const content = getContentByPath(`${filePath}/props.d.ts`) if (!content) return const ast = parse(content, { sourceType: 'module', plugins: ['typescript'] }) const target = getDefaultPropsTypeName(ast) getExtends(`${filePath}/props.d.ts`, target, resource) } function getDefaultPropsTypeName(ast: ParseResult<t.File>) { let target = "" traverse(ast, { ExportDeclaration(path) { if (path.node.type === "ExportNamedDeclaration") { if (path.node.declaration?.type === "VariableDeclaration") { if (path.node.declaration.declarations[0].id.type === "Identifier") { if (path.node.declaration.declarations[0].id.typeAnnotation?.type === "TSTypeAnnotation") { if (path.node.declaration.declarations[0].id.typeAnnotation?.typeAnnotation.type === "TSTypeReference") { if (path.node.declaration.declarations[0].id.typeAnnotation?.typeAnnotation.typeParameters?.params[0].type === "TSTypeReference") { if (path.node.declaration.declarations[0].id.typeAnnotation?.typeAnnotation.typeParameters?.params[0].typeName.type === "Identifier") { target = path.node.declaration.declarations[0].id.typeAnnotation?.typeAnnotation.typeParameters?.params[0].typeName.name } } } } } } } } }) return target } function getExtends(filePath: string, target: string, resource: Resource, genTypes?: string[]) { const content = getContentByPath(filePath) as string // TODO 类型精确一点 // @ts-ignore let genParams: any const ast = parse(content, { sourceType: 'module', plugins: ['typescript'] }) traverse(ast, { TSInterfaceDeclaration(path) { if (path.node.id.type === "Identifier") { if (path.node.id.name === target) { // 组件的描述 const potentialDes = path.parentPath.node.leadingComments?.[0].value if (potentialDes && !resource.desc) { const { description } = processComment(potentialDes) resource.addDesc(description) } // 获取泛型参数 genParams = path.node.typeParameters?.params.map((item, idx) => { if (genTypes) { return { name: item.name, value: genTypes[idx] } } return { name: item.name, value: item.default } }) // 将泛型变量替换成真正的泛型的值 path.node.body.body.map(item => { if (item.typeAnnotation?.start && item.typeAnnotation.end) { // 泛型变量 if (item.typeAnnotation.typeAnnotation.type === "TSFunctionType") { item.typeAnnotation.typeAnnotation.parameters.forEach(genItem => { // console.log(JSON.stringify(genItem)) if (genItem.typeAnnotation?.type === "TSTypeAnnotation") { if (genItem.typeAnnotation.typeAnnotation.type === "TSTypeReference") { if (genItem.typeAnnotation.typeAnnotation.typeName.type === "Identifier") { const genName = genItem.typeAnnotation.typeAnnotation.typeName.name // @ts-ignore const node = genParams?.find(li => li.name === genName) if (node) { let type if (typeof node.value !== "string") { type = content.slice(node.value.start, node.value.end) || content.slice(node.default.start, node.default.end) } else { type = node.value || content.slice(node.default.start, node.default.end) } // 设置泛型的变量名称 genItem.typeAnnotation.typeAnnotation.typeName.name = type } } } } }) // 统一解析处理,生成解析后的信息 processTSProperty(item, resource) } else { // 属性 processTSProperty(item, resource) } } }) // 获取继承的类型信息,antd-mini 中继承多个的情况一般不会出现 // dfs 一下 if (path.node.extends) { path.node.extends.forEach(item => { if (item.expression.type === "Identifier") { const res = getExtendsPath(ast, item.expression.name, filePath) if (!res) return const genArray = item.typeParameters?.params.map(n => { if (n.type !== "TSTypeReference") { if (n.start && n.end) { return content.slice(n.start, n.end) } } return 'any' }) getExtends(res, item.expression.name, resource, genArray) } }) } } } } }) } /** * * @param ast 解析的 ast 树 * @param target 继承的类名 * @param filePath 当前解析文件的名称 * @returns 继承的类名所在的文件位置 */ function getExtendsPath(ast: ParseResult<t.File>, target: string, filePath: string) { let res = '' traverse(ast, { Identifier(path) { if (path.node.name === target) { const binding = path.scope.getBinding(target) if (binding?.path.parentPath?.node.type === "ImportDeclaration") { // 继承的类型是 import 进来的 const source = binding?.path.parentPath?.node.source.value res = path_.join(filePath, '../', path_.join(source, '/index.d.ts')) } else if (path.node.type = "Identifier") { // 继承的类型在同一个文件内 res = filePath } } } }) return res } /** * * 读取 API 的描述与默认值 * @param node 需要处理的节点 */ function processAPI(ast: ParseResult<t.File>, content: string): ['method' | 'prop', IDocsAPI] | void { const interfaceNode = ast.program.body[0] if (interfaceNode.type === "TSInterfaceDeclaration") { const api: IDocsAPI = { description: "", default: "", name: "", types: "" } let nodeType: 'method' | 'prop' = 'prop' const node = interfaceNode.body.body[0] if (node.leadingComments) { const comment = node.leadingComments[0].value; const { description, defaultValue } = processComment(comment) api.description = description api.default = defaultValue } if (node.type === 'TSPropertySignature') { if (node.key.type === "Identifier") { api.name = node.key.name } if (node.typeAnnotation?.typeAnnotation.type === "TSTypeLiteral") { const res = node.typeAnnotation.typeAnnotation.members.reduce((prev, cur) => { if (cur.start && cur.end) { prev += `${content.slice(cur.start, cur.end)} ` } return prev }, " ") api.types = `{${res}}` } else if (node.typeAnnotation?.typeAnnotation.start && node.typeAnnotation?.typeAnnotation.end) { // markdown 文件中 | 要转义一下,否则渲染会有问题 api.types = content.slice(node.typeAnnotation?.typeAnnotation.start, node.typeAnnotation?.typeAnnotation.end).replace(/\|/g, "&verbar;") } // TODO 考虑两种写法,可以通过 eslint 规定 只能 写 后一种类型 // a: () => void // a() : void if (node.typeAnnotation?.typeAnnotation.type === "TSFunctionType") { nodeType = 'method' } } // console.log(JSON.stringify(node)) return [nodeType, api] } } function processComment(comment: string) { let currentKey: 'description' | 'default'; const res = comment.split("*").reduce((prev, cur) => { const lineContent = cur.trim() if (lineContent) { if (lineContent.startsWith('@description')) { currentKey = 'description' } if (lineContent.startsWith('@default')) { currentKey = 'default' } prev[currentKey] += lineContent return prev } return prev }, { description: "", default: "" } as { description: string, default: string }) return { description: res.description.replace('@description', '').trim(), defaultValue: res.default.replace('@default', '').trim() } } function processTSProperty(ast: t.TSTypeElement, resource: Resource) { ast.trailingComments = null // 随便拼的,为了让 babel 解析 // TODO 优化 const newCode = `interface ITES { ${generate(ast).code} }` const res = processAPI(parse(newCode, { sourceType: 'module', plugins: ['typescript'] }), newCode) if (res) { if (res[0] === "prop") resource.addApiProp(res[1]) if (res[0] === "method") resource.addApiMethod(res[1]) } }
the_stack
import { RuleTester, Failure, Position, dedent } from './ruleTester'; // ESLint Tests: https://github.com/eslint/eslint/blob/master/tests/lib/rules/max-len.js const ruleTester = new RuleTester('ter-max-len'); function expecting(errors: Array<[number, number] | [number, number, boolean]>): Failure[] { return errors.map((err) => { let message = `Line ${err[0] + 1} exceeds the maximum line length of ${err[1]}.`; if (err[2]) { message = `Line ${err[0] + 1} exceeds the maximum comment line length of ${err[1]}.`; } return { failure: message, startPosition: new Position(err[0]), endPosition: new Position() }; }); } ruleTester.addTestGroup('no-options', 'should warn when the line exceeds the limit', [ { code: '' }, { code: 'var x = 5;\nvar x = 2;' }, { code: 'var x = 5;\nvar x = 2;', options: [80] }, { code: 'var one\t\t= 1;\nvar three\t= 3;', options: [16, 4] }, { code: '\tvar one\t\t= 1;\n\tvar three\t= 3;', options: [20, 4] }, { code: 'var i = 1;\r\nvar i = 1;\n', options: [10, 4] }, { code: '\n// Blank line on top\nvar foo = module.exports = {};\n', options: [80, 4] }, { code: '\n// Blank line on top\nvar foo = module.exports = {};\n' }, { code: '\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tvar i = 1;', errors: expecting([[0, 80]]) }, { code: 'var x = 5, y = 2, z = 5;', options: [10], errors: expecting([[0, 10]]) }, { code: '\t\t\tvar i = 1;', options: [15], errors: expecting([[0, 15]]) }, { code: '\t\t\tvar i = 1;\n\t\t\tvar j = 1;', options: [15, { tabWidth: 4 }], errors: expecting([[0, 15], [1, 15]]) } ]); ruleTester.addTestGroup('patterns', 'should ignore specified patterns', [ { code: dedent` var dep = require('really/really/really/really/really/really/really/long/module'); const dep = require('another/really/really/really/really/really/really/long/module'); foobar = 'this line will be ignored because it starts with foobar ...'; `, options: [50, { ignorePattern: '^\\s*(var|const)\\s.+=\\s*require\\s*\\(|^\\s*foobar' }] }, { code: `foo(bar(bazz('this is a long'), 'line of'), 'stuff');`, options: [40, 4, { ignorePattern: 'foo.+bazz\\(' }] }, { code: `foo(bar(bazz('this is a long'), 'line of'), 'stuff');`, options: [40, 4], // ignorePattern is disabled errors: expecting([[0, 40]]) }, { code: dedent` var foobar = 'this line isn\\'t matched by the regexp'; var fizzbuzz = 'but this one is matched by the regexp'; `, options: [20, 4, { ignorePattern: 'fizzbuzz' }], errors: expecting([[1, 20]]) } ]); ruleTester.addTestGroup('imports', 'should ignore long module specifiers', [ { code: dedent` import { obj1, obj2, obj3, obj4 } from 'my-favorite-module/with/lots/of/deep/nested/modules'; import { obj1, obj2, obj3, obj4, } from 'my-favorite-module/with/lots/of/deep/nested/modules'; `, options: [50, { ignoreImports: true }] }, { code: dedent` import { obj1, obj2, obj3, obj4, just, trying, to, be, a, rebel, here } from 'my-favorite-module/with/lots/of/deep/nested/modules'; `, options: [50, { ignoreImports: true }], errors: expecting([[2, 50]]) } ]); ruleTester.addTestGroup('urls', 'should ignore lines that contain urls', [ { code: `foo('http://example.com/this/is/?a=longish&url=in#here');`, options: [40, 4, { ignoreUrls: true }] }, { code: `foo('http://example.com/this/is/?a=longish&url=in#here');`, options: [40, 4], // ignoreUrls is disabled errors: expecting([[0, 40]]) } ]); ruleTester.addTestGroup('comments', 'should handle comments', [ { code: 'var foo = module.exports = {}; // really long trailing comment', options: [40, 4, { ignoreComments: true }] }, { code: 'foo(); \t// strips entire comment *and* trailing whitespace', options: [6, 4, { ignoreComments: true }] }, { code: '// really long comment on its own line sitting here', options: [40, 4, { ignoreComments: true }] }, { code: 'var /*inline-comment*/ i = 1;' }, { code: 'var /*inline-comment*/ i = 1; // with really long trailing comment', options: [40, 4, { ignoreComments: true }] }, { code: dedent` /* hey there! this is a multiline comment with longish lines in various places but with a short line-length */`, options: [10, 4, { ignoreComments: true }] }, { code: dedent` // I like short comments function butLongSourceLines() { weird(eh()) }`, options: [80, { tabWidth: 4, comments: 30 }] }, { code: dedent` // Full line comment someCode(); // With a long trailing comment.`, options: [{ code: 30, tabWidth: 4, comments: 20, ignoreTrailingComments: true }] }, { code: 'var foo = module.exports = {}; // really long trailing comment', options: [40, 4, { ignoreTrailingComments: true }] }, { code: 'var foo = module.exports = {}; // really long trailing comment', options: [40, 4, { ignoreComments: true, ignoreTrailingComments: false }] }, { code: dedent` function foo() { //this line has 29 characters }`, options: [40, 4, { comments: 29 }] }, { code: dedent` function foo() { //this line has 33 characters }`, options: [40, 4, { comments: 33 }] }, { code: dedent` function foo() { /*this line has 29 characters and this one has 21*/ }`, options: [40, 4, { comments: 29 }] }, { code: dedent` function foo() { /*this line has 33 characters and this one has 25*/ }`, options: [40, 4, { comments: 33 }] }, { code: dedent` function foo() { var a; /*this line has 40 characters and this one has 36 characters*/ }`, options: [40, 4, { comments: 36 }] }, { code: dedent` function foo() { /*this line has 33 characters and this one has 43 characters*/ var a; }`, options: [43, 4, { comments: 33 }] }, { code: dedent` function foo() { //this line has 29 characters }`, options: [40, 4, { comments: 28 }], errors: expecting([[2, 28, true]]) }, { code: dedent` function foo() { //this line has 33 characters }`, options: [40, 4, { comments: 32 }], errors: expecting([[2, 32, true]]) }, { code: dedent` function foo() { /*this line has 29 characters and this one has 32 characters*/ }`, options: [40, 4, { comments: 28 }], errors: expecting([ [2, 28, true], [3, 28, true] ]) }, { code: dedent` function foo() { /*this line has 33 characters and this one has 36 characters*/ }`, options: [40, 4, { comments: 32 }], errors: expecting([ [2, 32, true], [3, 32, true] ]) }, { code: dedent` function foo() { var a; /*this line has 40 characters and this one has 36 characters*/ }`, options: [39, 4, { comments: 35 }], errors: expecting([ [2, 39], [3, 35, true] ]) }, { code: dedent` function foo() { /*this line has 33 characters and this one has 43 characters*/ var a; }`, options: [42, 4, { comments: 32 }], errors: expecting([ [2, 32, true], [3, 42] ]) }, // check comments with the same length as non-comments - https://github.com/eslint/eslint/issues/6564 { code: dedent` // This commented line has precisely 51 characters. var x = 'This line also has exactly 51 characters';`, options: [20, { ignoreComments: true }], errors: expecting([[2, 20]]) }, { code: 'var /*this is a long non-removed inline comment*/ i = 1;', options: [20, { tabWidth: 4, ignoreComments: true }], errors: expecting([[0, 20]]) }, { code: `var longLine = 'will trigger'; // even with a comment`, options: [10, 4, { ignoreComments: true }], errors: expecting([[0, 10]]) }, { code: `var foo = module.exports = {}; // really long trailing comment`, options: [40, 4], // ignoreComments is disabled errors: expecting([[0, 40]]) }, { code: '// A comment that exceeds the max comment length.', options: [80, 4, { comments: 20 }], errors: expecting([[0, 20, true]]) }, { code: '// A comment that exceeds the max comment length.', options: [{ code: 20 }], errors: expecting([[0, 20]]) }, { code: '//This is very long comment with more than 40 characters which is invalid', options: [40, 4, { ignoreTrailingComments: true }], errors: expecting([[0, 40]]) } ]); ruleTester.addTestGroup('regex', 'should ignore long regular expression literals', [ { code: 'var foo = /this is a very long pattern/;', options: [29, 4, { ignoreRegExpLiterals: true }] } ]); ruleTester.addTestGroup('template-literals', 'should ignore template literals', [ { code: 'var foo = veryLongIdentifier;\nvar bar = `this is a very long string`;', options: [29, 4, { ignoreTemplateLiterals: true }] }, { code: 'var foo = veryLongIdentifier;\nvar bar = `this is a very long string\nand this is another line that is very long`;', options: [29, 4, { ignoreTemplateLiterals: true }] }, { code: dedent` var foo = veryLongIdentifier; var bar = \`this is a very long string and this is another line that is very long and here is another and another!\`;`, options: [29, 4, { ignoreTemplateLiterals: true }] }, { code: dedent` var foo = veryLongIdentifier; var bar = \`this is a very long string and this is another line that is very long and here is another with replacement \${x} and another!\`;`, options: [29, 4, { ignoreTemplateLiterals: true }] } ]); ruleTester.addTestGroup('strings', 'should ignore strings', [ { code: `var foo = veryLongIdentifier;\nvar bar = 'this is a very long string';`, options: [29, 4, { ignoreStrings: true }] }, { code: `var foo = veryLongIdentifier;\nvar bar = "this is a very long string";`, options: [29, 4, { ignoreStrings: true }] }, { code: dedent` var str = "this is a very long string\ with continuation";`, options: [29, 4, { ignoreStrings: true }] }, { code: 'var str = \"this is a very long string\\\nwith continuation\\\nand with another very very long continuation\\\nand ending\";', options: [29, 4, { ignoreStrings: true }] } ]); ruleTester.addTestGroup('strings-regex', 'should handle ignoreStrings and ignoreRegExpLiterals options', [ { code: `var foo = veryLongIdentifier;\nvar bar = /this is a very very long pattern/;`, options: [29, { ignoreStrings: false, ignoreRegExpLiterals: false }], errors: expecting([[1, 29]]) }, { code: `var foo = veryLongIdentifier;\nvar bar = new RegExp('this is a very very long pattern');`, options: [29, { ignoreStrings: false, ignoreRegExpLiterals: true }], errors: expecting([[1, 29]]) } ]); ruleTester.addTestGroup('strings-templates', 'should handle the ignoreStrings and ignoreTemplateLiterals options', [ { code: `var foo = veryLongIdentifier;\nvar bar = 'this is a very long string';`, options: [29, { ignoreStrings: false, ignoreTemplateLiterals: true }], errors: expecting([[1, 29]]) }, { code: `var foo = veryLongIdentifier;\nvar bar = \"this is a very long string\";`, options: [29, { ignoreStrings: false, ignoreTemplateLiterals: true }], errors: expecting([[1, 29]]) }, { code: 'var foo = veryLongIdentifier;\nvar bar = `this is a very long string`;', options: [29, { ignoreStrings: false, ignoreTemplateLiterals: false }], errors: expecting([[1, 29]]) }, { code: dedent` var foo = veryLongIdentifier; var bar = \`this is a very long string and this is another line that is very long\`;`, options: [29, { ignoreStrings: false, ignoreTemplateLiterals: false }], errors: expecting([ [2, 29], [3, 29] ]) } ]); ruleTester.runTests();
the_stack
'use strict'; import * as React from 'react'; import client from 'js/slycat-web-client'; import SlycatSelector, {Option} from 'components/SlycatSelector.tsx'; /** * @member hostname name of the host we are connecting * (assumes we have a connection already to the host) * @member persistenceId uuid for local storage * @member onSelectFileCallBack called every time a file is selected * returns the files info (path, file.type, file:FileMetaData) * @member onSelectParserCallBack called every time a parser is selected * returns the parser type (dakota or csv) * @member onReauthCallBack called every time we lose connection to the host * @export * @interface RemoteFileBrowserProps */ export interface RemoteFileBrowserProps { hostname: string persistenceId?: string onSelectFileCallBack: Function onSelectParserCallBack: Function onReauthCallBack: Function selectedOption: string } /** * @member path path shown in box * @member pathInput path to current file when selected * @member persistenceId uuid add to get local storage say if there were * two of these classes being used * @member rawFiles list of the current files meta data we are looking at * @member pathError do we have a path error * @member browseError do we have a browsing error * @member browserUpdating are we in the middle of getting data * @member selected id of selected file * @export * @interface RemoteFileBrowserState */ export interface RemoteFileBrowserState { path:string pathInput:string persistenceId:string rawFiles: FileMetaData[] pathError: boolean browseError: boolean browserUpdating: boolean selected:number } /** * @member type file type * @member name filename * @member size size of file * @member mtime last accessed time * @member mimeType type of file * @interface FileMetaData */ interface FileMetaData { type: string name: string size: string mtime: string mimeType: string } /** * used to create a file browsing window like using 'ls' and 'cd' in a linux terminal * * @export * @class RemoteFileBrowser * @extends {React.Component<RemoteFileBrowserProps, RemoteFileBrowserState>} */ export default class RemoteFileBrowser extends React.Component<RemoteFileBrowserProps, RemoteFileBrowserState> { public constructor(props:RemoteFileBrowserProps) { super(props) this.state = { path:"/", pathInput: "/", rawFiles: [], pathError: false, browseError: false, persistenceId: props.persistenceId === undefined ? '' : props.persistenceId, browserUpdating: false, selected:-1 } } /** * given a path return all the items in said path (like ls) * * @param pathInput path to return all ls properties from * @private * @memberof RemoteFileBrowser */ private browse = (pathInput:string) => { // First check if we have a remote connection... client.get_remotes_fetch(this.props.hostname) .then((json) => { // If we have a session, go on. if(json.status) { pathInput = (pathInput === ""?"/":pathInput); this.setState({ rawFiles:[], browserUpdating:true, selected:-1, path:pathInput, pathInput }); client.post_remote_browse( { hostname : this.props.hostname, path : pathInput, success : (results:any) => { localStorage.setItem("slycat-remote-browser-path-" + this.state.persistenceId + this.props.hostname, pathInput); this.setState({ browseError:false, pathError:false, }); let files: FileMetaData[] = [] if(pathInput != "/") files.push({type: "", name: "..", size: "", mtime: "", mimeType:"application/x-directory"}); for(let i = 0; i != results.names.length; ++i) files.push({name:results.names[i], size:results.sizes[i], type:results.types[i], mtime:results.mtimes[i], mimeType:results["mime-types"][i]}); this.setState({ rawFiles:files, browserUpdating:false }); }, error : (results:any) => { if(this.state.path != this.state.pathInput) { this.setState({pathError:true, browserUpdating:false}); } if(results.status == 400){ alert("bad file path") } this.setState({browseError:true, browserUpdating:false}); } }); } // Otherwise...we don't have a session anymore, so // run the reauth callback if one was passed. else { if(this.props.onReauthCallBack) { this.props.onReauthCallBack(); } } }); } /** * takes a path and returns the directory above it * * @param path string path * @private * @returns new string path one level up * @memberof RemoteFileBrowser */ private pathDirname = (path:string):string => { var new_path = path.replace(/\/\.?(\w|\-|\.)*\/?$/, ""); if(new_path == "") new_path = "/"; return new_path; } /** * takes left path and right path and joins them * @param right string path * @param left string path * @private * @requires joined paths * @memberof RemoteFileBrowser */ private pathJoin = (left:string, right:string):string => { var new_path = left; if(new_path.slice(-1) != "/") new_path += "/"; new_path += right; return new_path; } /** * given a file(which includes its full path), browse to the path above it * * @param file meta data for the file selected to browse up * one level from said path * @private * @memberof RemoteFileBrowser */ private browseUpByFile = (file:FileMetaData) => { this.setState({selected:-1}); // If the file is our parent directory, move up the hierarchy. if(file.name === "..") { this.browse(this.pathDirname(this.state.path)); } // If the file is a directory, move down the hierarchy. else if(file.type === "d") { this.browse(this.pathJoin(this.state.path, file.name)); } } keyPress = (event:any, pathInput:string) => { if (event.key == 'Enter'){ // How would I trigger the button that is in the render? I have this so far. this.browse(pathInput); } } /** * Given a row id and file info set the selected file and * callBack to tell caller Path, file.type, file:FileMetaData * * @param file an object of FileMetaData * @param i index of selected row in the table * @private * @memberof RemoteFileBrowser */ private selectRow = (file:FileMetaData, i:number) => { let newPath:string = this.state.path; const path_split:string[] = this.state.path.split("/"); /** * If the user types out the full path, including file name, * we don't want to join the file name with the path * (resulting in duplicate file names). */ if(path_split[path_split.length - 1] !== file.name) { newPath = this.pathJoin(this.state.path, file.name); } this.setState({selected:i},() => { // tell our create what we selected this.props.onSelectFileCallBack(newPath, file.type, file); }) } /** * takes a list of file info from the state and converts it * to an html * * @private * @memberof RemoteFileBrowser * @returns JSX.Element[] with the styled file list */ private getFilesAsJsx = ():JSX.Element[] => { const rawFilesJSX = this.state.rawFiles.map((rawFile, i) => { return ( <tr className={this.state.selected==i?'selected':''} key={i} onClick={()=>this.selectRow(rawFile,i)} onDoubleClick={()=> this.browseUpByFile(rawFile)}> <td data-bind-fail="html:icon"> {rawFile.mimeType === "application/x-directory"? <span className='fa fa-folder'></span>: <span className='fa fa-file-o'></span>} </td> <td data-bind-fail="text:name">{rawFile.name}</td> <td data-bind-fail="text:size">{rawFile.size}</td> <td data-bind-fail="text:mtime">{rawFile.mtime}</td> </tr> ) }) return rawFilesJSX; // if(file.mime_type() in component.icon_map) // { // icon = component.icon_map[file.mime_type()]; // } // else if(_.startsWith(file.mime_type(), "text/")) // { // icon = "<span class='fa fa-file-text-o'></span>"; // } // else if(_.startsWith(file.mime_type(), "image/")) // { // icon = "<span class='fa fa-file-image-o'></span>"; // } // else if(_.startsWith(file.mime_type(), "video/")) // { // icon = "<span class='fa fa-file-video-o'></span>"; // } } public async componentDidMount() { const path = localStorage.getItem("slycat-remote-browser-path-" + this.state.persistenceId + this.props.hostname); if(path != null){ this.setState({path,pathInput:path}); await this.browse(this.pathDirname(path)); } } public render() { let options: Option[] = []; if(this.props.selectedOption == "csv" || this.props.selectedOption == "hdf5") { options = [{ text:'Comma separated values (CSV)', value:'slycat-csv-parser' }, { text:'Dakota tabular', value:'slycat-dakota-parser' }]; } else { options = [{ text:'Dakota tabular', value:'slycat-dakota-parser' }]; } const pathStyle:any = { width: 'calc(100% - 44px)', float: 'left', marginRight: '5px' } const styleTable:any = { position: "relative", height: (window.innerHeight*0.4)+"px", overflow: "auto", display: "block", border: "1px solid rgb(222, 226, 230)", } return ( <div className="slycat-remote-browser"> <label className='font-weight-bold justify-content-start mb-2' htmlFor='slycat-remote-browser-path'> {this.props.hostname}: </label> <div className="form-group row path mb-3"> <div className="col-sm-12"> <div className="input-group" style={pathStyle}> <input type="text" className="form-control" id="slycat-remote-browser-path" value={this.state.pathInput} onKeyPress={() => this.keyPress(event, this.state.pathInput)} onChange={(e:React.ChangeEvent<HTMLInputElement>) => { this.setState({pathInput:e.target.value}) } } /> <div className="input-group-append"> <button className="btn btn-secondary" onClick={() => this.browse(this.state.pathInput)}>Go</button> </div> </div> <div className="btn-group" role="group" style={{float: 'right'}}> <button className="btn btn-secondary" type="button" title="Navigate to parent directory" onClick={() => { this.browse(this.pathDirname(this.state.path))} } > <i className="fa fa-level-up" aria-hidden="true"></i> </button> </div> </div> {/* <div className="path alert alert-danger" role="alert"> Oops, that path is not accessible. Please try again. </div> */} </div> {!this.state.browserUpdating? <div style={styleTable} className='mb-3'> <table className="table table-hover table-sm" style={{borderBottom: '1px solid rgb(222, 226, 230)'}}> <thead className="thead-light"> <tr> <th></th> <th>Name</th> <th>Size</th> <th>Date Modified</th> </tr> </thead> <tbody> {this.getFilesAsJsx()} </tbody> </table> </div>: <button className="btn btn-primary" type="button" disabled> <span className="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading... </button>} <SlycatSelector onSelectCallBack={this.props.onSelectParserCallBack} label={'Filetype'} options={options} /> </div> ); } }
the_stack
import type {$FixMe, $IntentionalAny} from '@theatre/shared/utils/types' import userReadableTypeOfValue from '@theatre/shared/utils/userReadableTypeOfValue' import type {Rgba} from '@theatre/shared/utils/color' import { decorateRgba, linearSrgbToOklab, oklabToLinearSrgb, srgbToLinearSrgb, linearSrgbToSrgb, } from '@theatre/shared/utils/color' import {clamp, mapValues} from 'lodash-es' import type { IShorthandCompoundProps, IValidCompoundProps, ShorthandCompoundPropsToLonghandCompoundProps, } from './internals' import {propTypeSymbol, sanitizeCompoundProps} from './internals' // eslint-disable-next-line unused-imports/no-unused-imports import type SheetObject from '@theatre/core/sheetObjects/SheetObject' // Notes on naming: // As of now, prop types are either `simple` or `composite`. // The compound type is a composite type. So is the upcoming enum type. // Composite types are not directly sequenceable yet. Their simple sub/ancestor props are. // We’ll provide a nice UX to manage keyframing of multiple sub-props. /** * Validates the common options given to all prop types, such as `opts.label` * * @param fnCallSignature - See references for examples * @param opts - The common options of all prop types * @returns void - will throw if options are invalid */ const validateCommonOpts = (fnCallSignature: string, opts?: CommonOpts) => { if (process.env.NODE_ENV !== 'production') { if (opts === undefined) return if (typeof opts !== 'object' || opts === null) { throw new Error( `opts in ${fnCallSignature} must either be undefined or an object.`, ) } if (Object.prototype.hasOwnProperty.call(opts, 'label')) { const {label} = opts if (typeof label !== 'string') { throw new Error( `opts.label in ${fnCallSignature} should be a string. ${userReadableTypeOfValue( label, )} given.`, ) } if (label.trim().length !== label.length) { throw new Error( `opts.label in ${fnCallSignature} should not start/end with whitespace. "${label}" given.`, ) } if (label.length === 0) { throw new Error( `opts.label in ${fnCallSignature} should not be an empty string. If you wish to have no label, remove opts.label from opts.`, ) } } } } /** * A compound prop type (basically a JS object). * * @example * Usage: * ```ts * // shorthand * const position = { * x: 0, * y: 0 * } * assert(sheet.object('some object', position).value.x === 0) * * // nesting * const foo = {bar: {baz: {quo: 0}}} * assert(sheet.object('some object', foo).value.bar.baz.quo === 0) * * // With additional options: * const position = t.compound( * {x: 0, y: 0}, * // a custom label for the prop: * {label: "Position"} * ) * ``` * */ export const compound = <Props extends IShorthandCompoundProps>( props: Props, opts: CommonOpts = {}, ): PropTypeConfig_Compound< ShorthandCompoundPropsToLonghandCompoundProps<Props> > => { validateCommonOpts('t.compound(props, opts)', opts) const sanitizedProps = sanitizeCompoundProps(props) const deserializationCache = new WeakMap<{}, unknown>() const config: PropTypeConfig_Compound< ShorthandCompoundPropsToLonghandCompoundProps<Props> > = { type: 'compound', props: sanitizedProps, valueType: null as $IntentionalAny, [propTypeSymbol]: 'TheatrePropType', label: opts.label, default: mapValues(sanitizedProps, (p) => p.default) as $IntentionalAny, deserializeAndSanitize: (json: unknown) => { if (typeof json !== 'object' || !json) return undefined if (deserializationCache.has(json)) { return deserializationCache.get(json) } // TODO we should probably also check here whether `json` is a pure object rather // than an instance of a class, just to avoid the possible edge cases of handling // class instances. const deserialized: $FixMe = {} let atLeastOnePropWasDeserialized = false for (const [key, propConfig] of Object.entries(sanitizedProps)) { if (Object.prototype.hasOwnProperty.call(json, key)) { const deserializedSub = propConfig.deserializeAndSanitize( (json as $IntentionalAny)[key] as unknown, ) if (deserializedSub != null) { atLeastOnePropWasDeserialized = true deserialized[key] = deserializedSub } } } deserializationCache.set(json, deserialized) if (atLeastOnePropWasDeserialized) { return deserialized } }, } return config } /** * A number prop type. * * @example * Usage * ```ts * // shorthand: * const obj = sheet.object('key', {x: 0}) * * // With options (equal to above) * const obj = sheet.object('key', { * x: t.number(0) * }) * * // With a range (note that opts.range is just a visual guide, not a validation rule) * const x = t.number(0, {range: [0, 10]}) // limited to 0 and 10 * * // With custom nudging * const x = t.number(0, {nudgeMultiplier: 0.1}) // nudging will happen in 0.1 increments * * // With custom nudging function * const x = t.number({ * nudgeFn: ( * // the mouse movement (in pixels) * deltaX: number, * // the movement as a fraction of the width of the number editor's input * deltaFraction: number, * // A multiplier that's usually 1, but might be another number if user wants to nudge slower/faster * magnitude: number, * // the configuration of the number * config: {nudgeMultiplier?: number; range?: [number, number]}, * ): number => { * return deltaX * magnitude * }, * }) * ``` * * @param defaultValue - The default value (Must be a finite number) * @param opts - The options (See usage examples) * @returns A number prop config */ export const number = ( defaultValue: number, opts: { nudgeFn?: PropTypeConfig_Number['nudgeFn'] range?: PropTypeConfig_Number['range'] nudgeMultiplier?: number label?: string } = {}, ): PropTypeConfig_Number => { if (process.env.NODE_ENV !== 'production') { validateCommonOpts('t.number(defaultValue, opts)', opts) if (typeof defaultValue !== 'number' || !isFinite(defaultValue)) { throw new Error( `Argument defaultValue in t.number(defaultValue) must be a number. ${userReadableTypeOfValue( defaultValue, )} given.`, ) } if (typeof opts === 'object' && opts !== null) { if (Object.prototype.hasOwnProperty.call(opts, 'range')) { if (!Array.isArray(opts.range)) { throw new Error( `opts.range in t.number(defaultValue, opts) must be a tuple of two numbers. ${userReadableTypeOfValue( opts.range, )} given.`, ) } if (opts.range.length !== 2) { throw new Error( `opts.range in t.number(defaultValue, opts) must have two elements. ${opts.range.length} given.`, ) } if (!opts.range.every((n) => typeof n === 'number' && !isNaN(n))) { throw new Error( `opts.range in t.number(defaultValue, opts) must be a tuple of two numbers.`, ) } if (opts.range[0] >= opts.range[1]) { throw new Error( `opts.range[0] in t.number(defaultValue, opts) must be smaller than opts.range[1]. Given: ${JSON.stringify( opts.range, )}`, ) } } if (Object.prototype.hasOwnProperty.call(opts, 'nudgeMultiplier')) { if ( typeof opts.nudgeMultiplier !== 'number' || !isFinite(opts.nudgeMultiplier) ) { throw new Error( `opts.nudgeMultiplier in t.number(defaultValue, opts) must be a finite number. ${userReadableTypeOfValue( opts.nudgeMultiplier, )} given.`, ) } } if (Object.prototype.hasOwnProperty.call(opts, 'nudgeFn')) { if (typeof opts.nudgeFn !== 'function') { throw new Error( `opts.nudgeFn in t.number(defaultValue, opts) must be a function. ${userReadableTypeOfValue( opts.nudgeFn, )} given.`, ) } } } } return { type: 'number', valueType: 0, default: defaultValue, [propTypeSymbol]: 'TheatrePropType', ...(opts ? opts : {}), label: opts.label, nudgeFn: opts.nudgeFn ?? defaultNumberNudgeFn, nudgeMultiplier: typeof opts.nudgeMultiplier === 'number' ? opts.nudgeMultiplier : 1, interpolate: _interpolateNumber, deserializeAndSanitize: numberDeserializer(opts.range), } } const numberDeserializer = (range?: PropTypeConfig_Number['range']) => range ? (json: unknown): undefined | number => { if (!(typeof json === 'number' && isFinite(json))) return undefined return clamp(json, range[0], range[1]) } : _ensureNumber const _ensureNumber = (value: unknown): undefined | number => typeof value === 'number' && isFinite(value) ? value : undefined const _interpolateNumber = ( left: number, right: number, progression: number, ): number => { return left + progression * (right - left) } export const rgba = ( defaultValue: Rgba = {r: 0, g: 0, b: 0, a: 1}, opts: CommonOpts = {}, ): PropTypeConfig_Rgba => { if (process.env.NODE_ENV !== 'production') { validateCommonOpts('t.rgba(defaultValue, opts)', opts) // Lots of duplicated code and stuff that probably shouldn't be here, mostly // because we are still figuring out how we are doing validation, sanitization, // decoding, decorating. // Validate default value let valid = true for (const p of ['r', 'g', 'b', 'a']) { if ( !Object.prototype.hasOwnProperty.call(defaultValue, p) || typeof (defaultValue as $IntentionalAny)[p] !== 'number' ) { valid = false } } if (!valid) { throw new Error( `Argument defaultValue in t.rgba(defaultValue) must be of the shape { r: number; g: number, b: number, a: number; }.`, ) } } // Clamp defaultValue components between 0 and 1 const sanitized = {} for (const component of ['r', 'g', 'b', 'a']) { ;(sanitized as $IntentionalAny)[component] = Math.min( Math.max((defaultValue as $IntentionalAny)[component], 0), 1, ) } return { type: 'rgba', valueType: null as $IntentionalAny, default: decorateRgba(sanitized as Rgba), [propTypeSymbol]: 'TheatrePropType', label: opts.label, interpolate: _interpolateRgba, deserializeAndSanitize: _sanitizeRgba, } } const _sanitizeRgba = (val: unknown): Rgba | undefined => { if (!val) return undefined let valid = true for (const c of ['r', 'g', 'b', 'a']) { if ( !Object.prototype.hasOwnProperty.call(val, c) || typeof (val as $IntentionalAny)[c] !== 'number' ) { valid = false } } if (!valid) return undefined // Clamp defaultValue components between 0 and 1 const sanitized = {} for (const c of ['r', 'g', 'b', 'a']) { ;(sanitized as $IntentionalAny)[c] = Math.min( Math.max((val as $IntentionalAny)[c], 0), 1, ) } return decorateRgba(sanitized as Rgba) } const _interpolateRgba = ( left: Rgba, right: Rgba, progression: number, ): Rgba => { const leftLab = linearSrgbToOklab(srgbToLinearSrgb(left)) const rightLab = linearSrgbToOklab(srgbToLinearSrgb(right)) const interpolatedLab = { L: (1 - progression) * leftLab.L + progression * rightLab.L, a: (1 - progression) * leftLab.a + progression * rightLab.a, b: (1 - progression) * leftLab.b + progression * rightLab.b, alpha: (1 - progression) * leftLab.alpha + progression * rightLab.alpha, } const interpolatedRgba = linearSrgbToSrgb(oklabToLinearSrgb(interpolatedLab)) return decorateRgba(interpolatedRgba) } /** * A boolean prop type * * @example * Usage: * ```ts * // shorthand: * const obj = sheet.object('key', {isOn: true}) * * // with a label: * const obj = sheet.object('key', { * isOn: t.boolean(true, { * label: 'Enabled' * }) * }) * ``` * * @param defaultValue - The default value (must be a boolean) * @param opts - Options (See usage examples) */ export const boolean = ( defaultValue: boolean, opts: { label?: string interpolate?: Interpolator<boolean> } = {}, ): PropTypeConfig_Boolean => { if (process.env.NODE_ENV !== 'production') { validateCommonOpts('t.boolean(defaultValue, opts)', opts) if (typeof defaultValue !== 'boolean') { throw new Error( `defaultValue in t.boolean(defaultValue) must be a boolean. ${userReadableTypeOfValue( defaultValue, )} given.`, ) } } return { type: 'boolean', default: defaultValue, valueType: null as $IntentionalAny, [propTypeSymbol]: 'TheatrePropType', label: opts.label, interpolate: opts.interpolate ?? leftInterpolate, deserializeAndSanitize: _ensureBoolean, } } const _ensureBoolean = (val: unknown): boolean | undefined => { return typeof val === 'boolean' ? val : undefined } function leftInterpolate<T>(left: T): T { return left } /** * A string prop type * * @example * Usage: * ```ts * // shorthand: * const obj = sheet.object('key', {message: "Animation loading"}) * * // with a label: * const obj = sheet.object('key', { * message: t.string("Animation Loading", { * label: 'The Message' * }) * }) * ``` * * @param defaultValue - The default value (must be a string) * @param opts - The options (See usage examples) * @returns A string prop type */ export const string = ( defaultValue: string, opts: { label?: string interpolate?: Interpolator<string> } = {}, ): PropTypeConfig_String => { if (process.env.NODE_ENV !== 'production') { validateCommonOpts('t.string(defaultValue, opts)', opts) if (typeof defaultValue !== 'string') { throw new Error( `defaultValue in t.string(defaultValue) must be a string. ${userReadableTypeOfValue( defaultValue, )} given.`, ) } } return { type: 'string', default: defaultValue, valueType: null as $IntentionalAny, [propTypeSymbol]: 'TheatrePropType', label: opts.label, interpolate: opts.interpolate ?? leftInterpolate, deserializeAndSanitize: _ensureString, } } function _ensureString(s: unknown): string | undefined { return typeof s === 'string' ? s : undefined } /** * A stringLiteral prop type, useful for building menus or radio buttons. * * @example * Usage: * ```ts * // Basic usage * const obj = sheet.object('key', { * light: t.stringLiteral("r", {r: "Red", "g": "Green"}) * }) * * // Shown as a radio switch with a custom label * const obj = sheet.object('key', { * light: t.stringLiteral("r", {r: "Red", "g": "Green"}) * }, {as: "switch", label: "Street Light"}) * ``` * * @returns A stringLiteral prop type * */ export function stringLiteral< ValuesAndLabels extends {[key in string]: string}, >( /** * Default value (a string that equals one of the options) */ defaultValue: Extract<keyof ValuesAndLabels, string>, /** * The options. Use the `"value": "Label"` format. * * An object like `{[value]: Label}`. Example: `{r: "Red", "g": "Green"}` */ valuesAndLabels: ValuesAndLabels, /** * opts.as Determines if editor is shown as a menu or a switch. Either 'menu' or 'switch'. Default: 'menu' */ opts: { as?: 'menu' | 'switch' label?: string interpolate?: Interpolator<Extract<keyof ValuesAndLabels, string>> } = {}, ): PropTypeConfig_StringLiteral<Extract<keyof ValuesAndLabels, string>> { return { type: 'stringLiteral', default: defaultValue, valuesAndLabels: {...valuesAndLabels}, [propTypeSymbol]: 'TheatrePropType', valueType: null as $IntentionalAny, as: opts.as ?? 'menu', label: opts.label, interpolate: opts.interpolate ?? leftInterpolate, deserializeAndSanitize( json: unknown, ): undefined | Extract<keyof ValuesAndLabels, string> { if (typeof json !== 'string') return undefined if (Object.prototype.hasOwnProperty.call(valuesAndLabels, json)) { return json as $IntentionalAny } else { return undefined } }, } } /** * A linear interpolator for a certain value type. * * @param left - the value to interpolate from (beginning) * @param right - the value to interpolate to (end) * @param progression - the amount of progression. Starts at 0 and ends at 1. But could overshoot in either direction * * @example * ```ts * const numberInterpolator: Interpolator<number> = (left, right, progression) => left + progression * (right - left) * * numberInterpolator(-50, 50, 0.5) === 0 * numberInterpolator(-50, 50, 0) === -50 * numberInterpolator(-50, 50, 1) === 50 * numberInterpolator(-50, 50, 2) === 150 // overshoot * ``` */ export type Interpolator<T> = (left: T, right: T, progression: number) => T export interface IBasePropType< LiteralIdentifier extends string, ValueType, DeserializeType = ValueType, > { /** * Each prop config has a string literal identifying it. For example, * `assert.equal(t.number(10).type, 'number')` */ type: LiteralIdentifier /** * the `valueType` is only used by typescript. It won't be present in runtime. */ valueType: ValueType [propTypeSymbol]: 'TheatrePropType' /** * Each prop type may be given a custom label instead of the name of the sub-prop * it is in. * * @example * ```ts * const position = { * x: t.number(0), // label would be 'x' * y: t.number(0, {label: 'top'}) // label would be 'top' * } * ``` */ label: string | undefined default: ValueType /** * Each prop config has a `deserializeAndSanitize()` function that deserializes and sanitizes * any js value into one that is acceptable by this prop config, or `undefined`. * * As a rule, the value returned by this function should not hold any reference to `json` or any * other value referenced by the descendent props of `json`. This is to ensure that json values * controlled by the user can never change the values in the store. See `deserializeAndSanitize()` in * `t.compound()` or `t.rgba()` as examples. * * The `DeserializeType` is usually equal to `ValueType`. That is the case with * all simple prop configs, such as `number`, `string`, or `rgba`. However, composite * configs such as `compound` or `enum` may deserialize+sanitize into a partial value. For example, * a prop config of `t.compound({x: t.number(0), y: t.number(0)})` may deserialize+sanitize into `{x: 10}`. * This behavior is used by {@link SheetObject.getValues} to replace the missing sub-props * with their default value. * * Admittedly, this partial deserialization behavior is not what the word "deserialize" * typically implies in most codebases, so feel free to change this name into a more * appropriate one. * * Additionally, returning an `undefined` allows {@link SheetObject.getValues} to * replace the `undefined` with the default value of that prop. */ deserializeAndSanitize: (json: unknown) => undefined | DeserializeType } interface ISimplePropType<LiteralIdentifier extends string, ValueType> extends IBasePropType<LiteralIdentifier, ValueType, ValueType> { interpolate: Interpolator<ValueType> } export interface PropTypeConfig_Number extends ISimplePropType<'number', number> { range?: [min: number, max: number] nudgeFn: NumberNudgeFn nudgeMultiplier: number } export type NumberNudgeFn = (p: { deltaX: number deltaFraction: number magnitude: number config: PropTypeConfig_Number }) => number const defaultNumberNudgeFn: NumberNudgeFn = ({ config, deltaX, deltaFraction, magnitude, }) => { const {range} = config if (range) { return ( deltaFraction * (range[1] - range[0]) * magnitude * config.nudgeMultiplier ) } return deltaX * magnitude * config.nudgeMultiplier } export interface PropTypeConfig_Boolean extends ISimplePropType<'boolean', boolean> {} type CommonOpts = { /** * Each prop type may be given a custom label instead of the name of the sub-prop * it is in. * * @example * ```ts * const position = { * x: t.number(0), // label would be 'x' * y: t.number(0, {label: 'top'}) // label would be 'top' * } * ``` */ label?: string } export interface PropTypeConfig_String extends ISimplePropType<'string', string> {} export interface PropTypeConfig_StringLiteral<T extends string> extends ISimplePropType<'stringLiteral', T> { valuesAndLabels: Record<T, string> as: 'menu' | 'switch' } export interface PropTypeConfig_Rgba extends ISimplePropType<'rgba', Rgba> {} type DeepPartialCompound<Props extends IValidCompoundProps> = { [K in keyof Props]?: DeepPartial<Props[K]> } type DeepPartial<Conf extends PropTypeConfig> = Conf extends PropTypeConfig_AllSimples ? Conf['valueType'] : Conf extends PropTypeConfig_Compound<infer T> ? DeepPartialCompound<T> : never export interface PropTypeConfig_Compound<Props extends IValidCompoundProps> extends IBasePropType< 'compound', {[K in keyof Props]: Props[K]['valueType']}, DeepPartialCompound<Props> > { props: Record<string, PropTypeConfig> } export interface PropTypeConfig_Enum extends IBasePropType<'enum', {}> { cases: Record<string, PropTypeConfig> defaultCase: string } export type PropTypeConfig_AllSimples = | PropTypeConfig_Number | PropTypeConfig_Boolean | PropTypeConfig_String | PropTypeConfig_StringLiteral<$IntentionalAny> | PropTypeConfig_Rgba export type PropTypeConfig = | PropTypeConfig_AllSimples | PropTypeConfig_Compound<$IntentionalAny> | PropTypeConfig_Enum export type {IShorthandCompoundProps}
the_stack
import * as assert from 'assert' import { Schemas } from 'aws-sdk' import * as sinon from 'sinon' import { CommandMessage, createMessageReceivedFunc, getPageHeader, getRegistryNames, getSearchListForSingleRegistry, getSearchResults, } from '../../../eventSchemas/commands/searchSchemas' import { RegistryItemNode } from '../../../eventSchemas/explorer/registryItemNode' import { SchemasNode } from '../../../eventSchemas/explorer/schemasNode' import { TelemetryService } from '../../../shared/telemetry/telemetryService' import { getTabSizeSetting } from '../../../shared/utilities/editorUtilities' import { MockOutputChannel } from '../../../test/mockOutputChannel' import { MockSchemaClient } from '../../shared/clients/mockClients' import { asyncGenerator } from '../../utilities/collectionUtils' import * as vscode from 'vscode' describe('Search Schemas', function () { let sandbox: sinon.SinonSandbox beforeEach(function () { sandbox = sinon.createSandbox() }) afterEach(function () { sandbox.restore() }) const schemaClient = new MockSchemaClient() const TEST_REGISTRY = 'testRegistry' const TEST_REGISTRY2 = 'testRegistry2' const FAIL_REGISTRY = 'failRegistry' const FAIL_REGISTRY2 = 'failRegistry2' const fakeRegion = 'testRegion' const versionSummary1: Schemas.SearchSchemaVersionSummary = { SchemaVersion: '1', } const versionSummary2: Schemas.SearchSchemaVersionSummary = { SchemaVersion: '2', } const searchSummary1: Schemas.SearchSchemaSummary = { RegistryName: TEST_REGISTRY, SchemaName: 'testSchema1', SchemaVersions: [versionSummary1, versionSummary2], } const searchSummary2: Schemas.SearchSchemaSummary = { RegistryName: TEST_REGISTRY, SchemaName: 'testSchema2', SchemaVersions: [versionSummary1], } const searchSummary3: Schemas.SearchSchemaSummary = { RegistryName: TEST_REGISTRY2, SchemaName: 'testSchema3', SchemaVersions: [versionSummary1], } describe('getSearchListForSingleRegistry', function () { it('should return summaries', async function () { const searchSummaryList = [searchSummary1, searchSummary2] sandbox .stub(schemaClient, 'searchSchemas') .withArgs('searchText', TEST_REGISTRY) .returns(asyncGenerator(searchSummaryList)) const results = await getSearchListForSingleRegistry(schemaClient, TEST_REGISTRY, 'searchText') assert.strictEqual(results.length, 2, 'search should return 2 summaries') assert.strictEqual(results[0].VersionList.length, 2, 'first summary has two verions') assert.strictEqual(results[0].VersionList[0], '2', 'first version should be 2 - descending order') assert.strictEqual(results[0].VersionList[1], '1', 'second version should be 1') assert.strictEqual(results[1].VersionList.length, 1, 'second summary has 1 version') assert.strictEqual(results[1].VersionList[0], '1', 'version should be 1') assert.strictEqual( results[0].Title, searchSummary1.SchemaName!, 'title should be same as schemaName, no prefix appended' ) assert.strictEqual( results[1].Title, searchSummary2.SchemaName!, 'title should be same as schemaName, no prefix appended' ) assert.strictEqual(results[0].RegistryName, TEST_REGISTRY, 'summary should belong to requested registry') assert.strictEqual(results[1].RegistryName, TEST_REGISTRY, 'summary should belong to requested registry') }) it('should display an error message when search api call fails', async function () { const searchSummaryList = [searchSummary1, searchSummary2] const vscodeSpy = sandbox.spy(vscode.window, 'showErrorMessage') const displayMessage = `Unable to search registry ${FAIL_REGISTRY}` sandbox .stub(schemaClient, 'searchSchemas') .withArgs('randomText', TEST_REGISTRY) .returns(asyncGenerator(searchSummaryList)) //make an api call with non existent registryName - should return empty results const results = await getSearchListForSingleRegistry(schemaClient, FAIL_REGISTRY, 'randomText') assert.strictEqual(results.length, 0, 'should return 0 summaries') assert.strictEqual(vscodeSpy.callCount, 1, ' error message should be shown exactly once') assert.strictEqual(vscodeSpy.firstCall.lastArg, displayMessage, 'should display correct error message') }) }) describe('getSearchResults', function () { it('should display error message for failed registries and return summaries for successful ones', async function () { const vscodeSpy = sandbox.spy(vscode.window, 'showErrorMessage') const displayMessage = `Unable to search registry ${FAIL_REGISTRY}` const displayMessage2 = `Unable to search registry ${FAIL_REGISTRY2}` const searchSummaryList1 = [searchSummary1, searchSummary2] const searchSummaryList2 = [searchSummary3] const searchSchemaStub = sandbox.stub(schemaClient, 'searchSchemas') searchSchemaStub.withArgs('randomText', TEST_REGISTRY).returns(asyncGenerator(searchSummaryList1)).onCall(0) searchSchemaStub .withArgs('randomText', TEST_REGISTRY2) .returns(asyncGenerator(searchSummaryList2)) .onCall(1) const results = await getSearchResults( schemaClient, [TEST_REGISTRY, TEST_REGISTRY2, FAIL_REGISTRY, FAIL_REGISTRY2], 'randomText' ) assert.strictEqual(results.length, 3, 'should return 3 summaries') //results are unordered, sort for testing purposes results.sort(function (a, b) { return a.RegistryName > b.RegistryName ? 1 : b.RegistryName > a.RegistryName ? -1 : 0 }) const expectedTitle1 = TEST_REGISTRY.concat('/', searchSummary1.SchemaName!) const expectedTitle2 = TEST_REGISTRY.concat('/', searchSummary2.SchemaName!) const expectedTitle3 = TEST_REGISTRY2.concat('/', searchSummary3.SchemaName!) assert.strictEqual(results[0].RegistryName, TEST_REGISTRY, 'sumnmary should belong to requested registry') assert.strictEqual(results[1].RegistryName, TEST_REGISTRY, 'sumnmary should belong to requested registry') assert.strictEqual(results[2].RegistryName, TEST_REGISTRY2, 'sumnmary should belong to requested registry') assert.strictEqual(results[0].Title, expectedTitle1, 'title should be prefixed with registryName') assert.strictEqual(results[1].Title, expectedTitle2, 'title should be prefixed with registryName') assert.strictEqual(results[2].Title, expectedTitle3, 'title should be prefixed with registryName') assert.strictEqual(results[0].VersionList.length, 2, 'first summary has 2 versions') assert.strictEqual(results[1].VersionList.length, 1, 'second summary has 1 version') assert.strictEqual(results[2].VersionList.length, 1, 'third summary has 1 version') //failed registries assert.strictEqual(vscodeSpy.callCount, 2, 'should display 2 error message, 1 per each failed registry') assert.strictEqual(vscodeSpy.firstCall.lastArg, displayMessage, 'should display correct error message') assert.strictEqual(vscodeSpy.secondCall.lastArg, displayMessage2, 'should display correct error message') }) }) describe('createMessageReceivedFunc', function () { let postMessageSpy: sinon.SinonSpy<[any], Thenable<boolean>> beforeEach(function () { postMessageSpy = sandbox.spy(onPostMessage) }) const mockTelemetryService = ({ record: () => {}, } as any) as TelemetryService const outputChannel = new MockOutputChannel() const singleRegistryName = [TEST_REGISTRY] const multipleRegistryNames = [TEST_REGISTRY, TEST_REGISTRY2] const AWS_EVENT_SCHEMA_RAW = '{"openapi":"3.0.0","info":{"version":"1.0.0","title":"Event"},"paths":{},"components":{"schemas":{"Event":{"type":"object"}}}}' const schemaResponse: Schemas.DescribeSchemaResponse = { Content: AWS_EVENT_SCHEMA_RAW, } it('shows schema content for latest matching schema version by default', async function () { const versionedSummary = { RegistryName: TEST_REGISTRY, Title: getPageHeader(singleRegistryName), VersionList: ['3', '2', '1'], } const fakeMessage: CommandMessage = { command: 'fetchSchemaContent', version: undefined, schemaSummary: versionedSummary, } sandbox.stub(schemaClient, 'describeSchema').returns(Promise.resolve(schemaResponse)) const expectedArgument1 = { command: 'showSchemaContent', results: JSON.stringify(JSON.parse(schemaResponse.Content!), undefined, getTabSizeSetting()), version: '3', } const expectedArgument2 = { command: 'setVersionsDropdown', results: fakeMessage.schemaSummary!.VersionList, } const returnedFunc = createMessageReceivedFunc({ registryNames: singleRegistryName, schemaClient: schemaClient, telemetryService: mockTelemetryService, onPostMessage: postMessageSpy, outputChannel: outputChannel, }) await returnedFunc(fakeMessage) assert.strictEqual( postMessageSpy.callCount, 2, 'post message should be called twice, for showingSchemaContent and setVersionsDropdown' ) assert.deepStrictEqual( postMessageSpy.firstCall.lastArg, expectedArgument1, 'should call showSchemaContent command with pretty schema and latest version 3' ) assert.deepStrictEqual( postMessageSpy.secondCall.lastArg, expectedArgument2, 'should call setVersionDropdown command with correct list of versions' ) }) it('shows schema content for user selected version', async function () { const versionedSummary = { RegistryName: TEST_REGISTRY, Title: getPageHeader(multipleRegistryNames), VersionList: ['1'], } const fakeMessage: CommandMessage = { command: 'fetchSchemaContent', version: '1', schemaSummary: versionedSummary, } sandbox.stub(schemaClient, 'describeSchema').returns(Promise.resolve(schemaResponse)) const expectedArgument = { command: 'showSchemaContent', results: JSON.stringify(JSON.parse(schemaResponse.Content!), undefined, getTabSizeSetting()), version: '1', } const returnedFunc = createMessageReceivedFunc({ registryNames: multipleRegistryNames, schemaClient: schemaClient, telemetryService: mockTelemetryService, onPostMessage: postMessageSpy, outputChannel: outputChannel, }) await returnedFunc(fakeMessage) assert.strictEqual( postMessageSpy.callCount, 1, 'post message should be called once since the user has selected version' ) assert.deepStrictEqual( postMessageSpy.firstCall.lastArg, expectedArgument, 'should call showSchemaContent command with pretty schema and latest version 1' ) }) it('shows schema list when user makes a search', async function () { const fakeMessage: CommandMessage = { command: 'searchSchemas', keyword: 'searchText' } const expectResults1 = { RegistryName: TEST_REGISTRY, Title: TEST_REGISTRY + '/testSchema1', VersionList: ['2', '1'], } const expectResults2 = { RegistryName: TEST_REGISTRY, Title: TEST_REGISTRY + '/testSchema2', VersionList: ['1'], } const expectedArgument = { command: 'showSearchSchemaList', results: [expectResults1, expectResults2], resultsNotFound: false, } const searchSummaryList = [searchSummary1, searchSummary2] sandbox .stub(schemaClient, 'searchSchemas') .withArgs('searchText', TEST_REGISTRY) .returns(asyncGenerator(searchSummaryList)) const returnedFunc = createMessageReceivedFunc({ registryNames: multipleRegistryNames, schemaClient: schemaClient, telemetryService: mockTelemetryService, onPostMessage: postMessageSpy, outputChannel: outputChannel, }) await returnedFunc(fakeMessage) assert.strictEqual(postMessageSpy.callCount, 1, 'postMessage should call showSearchSchemaList command') assert.deepStrictEqual( postMessageSpy.firstCall.lastArg, expectedArgument, 'postMessage should have correct results' ) }) it('throws an error for an invalid command message', async function () { const fakeMessage: CommandMessage = { command: 'invalidCommand' } const errorMessage = `Search webview command ${fakeMessage.command} is invalid` const returnedFunc = createMessageReceivedFunc({ registryNames: multipleRegistryNames, schemaClient: schemaClient, telemetryService: mockTelemetryService, onPostMessage: postMessageSpy, outputChannel: outputChannel, }) await assert.rejects(returnedFunc(fakeMessage), new Error(errorMessage), 'Should fail for invalidCommand') }) function onPostMessage(message: any): Thenable<boolean> { if (message) { return Promise.resolve(true) } return Promise.resolve(false) } }) describe('getRegistryNameList', function () { it('should return list with single registry name for registryItemNode', async function () { const fakeRegistryNew = { RegistryName: TEST_REGISTRY, RegistryArn: 'arn:aws:schemas:us-west-2:19930409:registry/testRegistry', } const registryItemNode = new RegistryItemNode(fakeRegion, fakeRegistryNew) const result = await getRegistryNames(registryItemNode, schemaClient) assert.deepStrictEqual(result, [TEST_REGISTRY], 'should have a single registry name in it') }) it('should return list with multiple registry names for schemasNode', async function () { const schemasNode = new SchemasNode(fakeRegion) const registrySummary1 = { RegistryArn: 'arn:aws:registry/' + TEST_REGISTRY, RegistryName: TEST_REGISTRY } const registrySummary2 = { RegistryArn: 'arn:aws:registry/' + TEST_REGISTRY2, RegistryName: TEST_REGISTRY2 } sandbox.stub(schemaClient, 'listRegistries').returns(asyncGenerator([registrySummary1, registrySummary2])) const result = await getRegistryNames(schemasNode, schemaClient) assert.deepStrictEqual(result, [TEST_REGISTRY, TEST_REGISTRY2], 'should have two registry names in it') }) it('should return an empty list and display error message if schemas service not available in the region', async function () { const vscodeSpy = sandbox.spy(vscode.window, 'showErrorMessage') const displayMessage = 'Error loading Schemas resources' const schemasNode = new SchemasNode(fakeRegion) sandbox.stub(schemaClient, 'listRegistries') const results = await getRegistryNames(schemasNode, schemaClient) assert.ok(results.length === 0, 'Should return an empty array') assert.strictEqual(vscodeSpy.callCount, 1, ' error message should be shown exactly once') assert.strictEqual(vscodeSpy.firstCall.lastArg, displayMessage, 'should display correct error message') }) }) })
the_stack
import * as React from 'react'; import { IPropertyFieldGroupOrPerson, PrincipalType } from './IPropertyFieldPeoplePicker'; import { NormalPeoplePicker, IBasePickerSuggestionsProps } from 'office-ui-fabric-react/lib/Pickers'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { IPersonaProps, PersonaPresence, PersonaInitialsColor } from 'office-ui-fabric-react/lib/Persona'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import * as strings from 'PropertyControlStrings'; import { IPropertyFieldPeoplePickerHostProps, IPeoplePickerState } from './IPropertyFieldPeoplePickerHost'; import SPPeopleSearchService from '../../services/SPPeopleSearchService'; import FieldErrorMessage from '../errorMessage/FieldErrorMessage'; import * as telemetry from '../../common/telemetry'; import { setPropertyValue } from '../../helpers/GeneralHelper'; /** * Renders the controls for PropertyFieldPeoplePicker component */ export default class PropertyFieldPeoplePickerHost extends React.Component<IPropertyFieldPeoplePickerHostProps, IPeoplePickerState> { private searchService: SPPeopleSearchService; private intialPersonas: Array<IPersonaProps> = new Array<IPersonaProps>(); private resultsPeople: Array<IPropertyFieldGroupOrPerson> = new Array<IPropertyFieldGroupOrPerson>(); private resultsPersonas: Array<IPersonaProps> = new Array<IPersonaProps>(); private selectedPeople: Array<IPropertyFieldGroupOrPerson> = new Array<IPropertyFieldGroupOrPerson>(); private selectedPersonas: Array<IPersonaProps> = new Array<IPersonaProps>(); private async: Async; private delayedValidate: (value: IPropertyFieldGroupOrPerson[]) => void; /** * Constructor method */ constructor(props: IPropertyFieldPeoplePickerHostProps) { super(props); telemetry.track('PropertyFieldPeoplePicker', { allowDuplicate: props.allowDuplicate, principalType: props.principalType ? props.principalType.toString() : '', disabled: props.disabled }); this.searchService = new SPPeopleSearchService(); this.onSearchFieldChanged = this.onSearchFieldChanged.bind(this); this.onItemChanged = this.onItemChanged.bind(this); this.createInitialPersonas(); this.state = { resultsPeople: this.resultsPeople, resultsPersonas: this.resultsPersonas, errorMessage: '' }; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } /** * A search field change occured */ private onSearchFieldChanged(searchText: string, currentSelected: IPersonaProps[]): Promise<IPersonaProps[]> | IPersonaProps[] { if (searchText.length > 2) { // Clear the suggestions list this.setState({ resultsPeople: this.resultsPeople, resultsPersonas: this.resultsPersonas }); // Request the search service const result = this.searchService.searchPeople(this.props.context, searchText, this.props.principalType, this.props.targetSiteUrl).then((response: IPropertyFieldGroupOrPerson[]) => { this.resultsPeople = []; this.resultsPersonas = []; // If allowDuplicate == false, so remove duplicates from results if (this.props.allowDuplicate === false) { response = this.removeDuplicates(response); } response.forEach((element: IPropertyFieldGroupOrPerson, index: number) => { // Fill the results Array this.resultsPeople.push(element); // Transform the response in IPersonaProps object this.resultsPersonas.push(this.getPersonaFromPeople(element, index)); }); // Refresh the component's state this.setState({ resultsPeople: this.resultsPeople, resultsPersonas: this.resultsPersonas }); return this.resultsPersonas; }); return result; } else { return []; } } /** * Remove the duplicates if property allowDuplicate equals false */ private removeDuplicates(responsePeople: IPropertyFieldGroupOrPerson[]): IPropertyFieldGroupOrPerson[] { if (this.selectedPeople === null || this.selectedPeople.length === 0) { return responsePeople; } const res: IPropertyFieldGroupOrPerson[] = []; for (const element of responsePeople) { let found: boolean = false; for (let i: number = 0; i < this.selectedPeople.length; i++) { const responseItem: IPropertyFieldGroupOrPerson = this.selectedPeople[i]; if (responseItem.login === element.login && responseItem.id === element.id) { found = true; break; } } if (found === false) { res.push(element); } } return res; } /** * Creates the collection of initial personas from initial IPropertyFieldGroupOrPerson collection */ private createInitialPersonas(): void { if (this.props.initialData === null || typeof (this.props.initialData) !== typeof Array<IPropertyFieldGroupOrPerson>()) { return; } this.props.initialData.forEach((element: IPropertyFieldGroupOrPerson, index: number) => { const persona: IPersonaProps = this.getPersonaFromPeople(element, index); this.intialPersonas.push(persona); this.selectedPersonas.push(persona); this.selectedPeople.push(element); }); } /** * Generates a IPersonaProps object from a IPropertyFieldGroupOrPerson object */ private getPersonaFromPeople(element: IPropertyFieldGroupOrPerson, index: number): IPersonaProps { return { primaryText: element.fullName, secondaryText: element.jobTitle, imageUrl: element.imageUrl, imageInitials: element.initials, presence: PersonaPresence.none, initialsColor: this.getRandomInitialsColor(index) }; } /** * Refreshes the web part properties */ private refreshWebPartProperties(): void { this.delayedValidate(this.selectedPeople); } /** * Validates the new custom field value */ private validate(value: IPropertyFieldGroupOrPerson[]): void { if (this.props.onGetErrorMessage === null || this.props.onGetErrorMessage === undefined) { this.notifyAfterValidate(this.props.initialData, value); return; } const errResult: string | PromiseLike<string> = this.props.onGetErrorMessage(value || []); if (errResult) { if (typeof errResult === 'string') { if (errResult === '') { this.notifyAfterValidate(this.props.initialData, value); } this.setState({ errorMessage: errResult }); } else { errResult.then((errorMessage: string) => { if (!errorMessage) { this.notifyAfterValidate(this.props.initialData, value); } this.setState({ errorMessage: errorMessage }); }); } } else { this.notifyAfterValidate(this.props.initialData, value); this.setState({ errorMessage: null }); } } /** * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: IPropertyFieldGroupOrPerson[], newValue: IPropertyFieldGroupOrPerson[]) { if (this.props.onPropertyChange && newValue) { setPropertyValue(this.props.properties, this.props.targetProperty, newValue); this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); // Trigger the apply button if (typeof this.props.onChange !== 'undefined' && this.props.onChange !== null) { this.props.onChange(this.props.targetProperty, newValue); } } } /** * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } /** * Find the index of the selected person * @param selectedItem */ private _findIndex(selectedItem: IPersonaProps): number { for (let i = 0; i < this.resultsPersonas.length; i++) { const crntPersona = this.resultsPersonas[i]; // Check if the imageUrl, primaryText, secondaryText are equal if (crntPersona.imageUrl === selectedItem.imageUrl && crntPersona.primaryText === selectedItem.primaryText && crntPersona.secondaryText === selectedItem.secondaryText) { return i; } } return -1; } /** * Event raises when the user changed people from the PeoplePicker component */ private onItemChanged(selectedItems: IPersonaProps[]): void { if (selectedItems.length > 0) { if (selectedItems.length > this.selectedPersonas.length) { const index: number = this._findIndex(selectedItems[selectedItems.length - 1]); if (index > -1) { const people: IPropertyFieldGroupOrPerson = this.resultsPeople[index]; this.selectedPeople.push(people); this.selectedPersonas.push(this.resultsPersonas[index]); } } else { this.selectedPersonas.forEach((person, index2) => { const selectedItemIndex: number = selectedItems.indexOf(person); if (selectedItemIndex === -1) { this.selectedPersonas.splice(index2, 1); this.selectedPeople.splice(index2, 1); } }); } } else { this.selectedPersonas.splice(0, this.selectedPersonas.length); this.selectedPeople.splice(0, this.selectedPeople.length); } this.refreshWebPartProperties(); } /** * Generate a PersonaInitialsColor from the item position in the collection */ private getRandomInitialsColor(index: number): PersonaInitialsColor { const num: number = index % 13; switch (num) { case 0: return PersonaInitialsColor.blue; case 1: return PersonaInitialsColor.darkBlue; case 2: return PersonaInitialsColor.teal; case 3: return PersonaInitialsColor.lightGreen; case 4: return PersonaInitialsColor.green; case 5: return PersonaInitialsColor.darkGreen; case 6: return PersonaInitialsColor.lightPink; case 7: return PersonaInitialsColor.pink; case 8: return PersonaInitialsColor.magenta; case 9: return PersonaInitialsColor.purple; case 10: return PersonaInitialsColor.black; case 11: return PersonaInitialsColor.orange; case 12: return PersonaInitialsColor.red; case 13: return PersonaInitialsColor.darkRed; default: return PersonaInitialsColor.blue; } } /** * Renders the PeoplePicker controls with Office UI Fabric */ public render(): JSX.Element { const suggestionProps: IBasePickerSuggestionsProps = { suggestionsHeaderText: strings.PeoplePickerSuggestedContacts, noResultsFoundText: strings.PeoplePickerNoResults, loadingText: strings.PeoplePickerLoading, }; // Check which text have to be shown if (this.props.principalType && this.props.principalType.length > 0) { let userType = this.props.principalType.indexOf(PrincipalType.Users) !== -1; let groupType = this.props.principalType.indexOf(PrincipalType.SharePoint) !== -1 || this.props.principalType.indexOf(PrincipalType.Security) !== -1; // Check if both user and group are present if (userType && groupType) { suggestionProps.suggestionsHeaderText = strings.PeoplePickerSuggestedCombined; } // If only group is active if (!userType && groupType) { suggestionProps.suggestionsHeaderText = strings.PeoplePickerSuggestedGroups; } } // Renders content return ( <div> {this.props.label && <Label>{this.props.label}</Label>} <NormalPeoplePicker disabled={this.props.disabled} pickerSuggestionsProps={suggestionProps} onResolveSuggestions={this.onSearchFieldChanged} onChange={this.onItemChanged} defaultSelectedItems={this.intialPersonas} itemLimit={this.props.multiSelect ? undefined : 1} /> <FieldErrorMessage errorMessage={this.state.errorMessage} /> </div> ); } }
the_stack
import '../elements/interpreter_controls'; import '@material/mwc-icon'; import {MobxLitElement} from '@adobe/lit-mobx'; // tslint:disable:no-new-decorators import {customElement} from 'lit/decorators'; import {css, html, TemplateResult} from 'lit'; import {computed, observable} from 'mobx'; import {app} from '../core/app'; import {LitModule} from '../core/lit_module'; import {TableData, TableEntry} from '../elements/table'; import {CallConfig, formatForDisplay, IndexedInput, Input, LitName, ModelInfoMap, Spec} from '../lib/types'; import {flatten, isLitSubtype} from '../lib/utils'; import {GroupService} from '../services/group_service'; import {SelectionService, SliceService} from '../services/services'; import {styles} from './generator_module.css'; import {styles as sharedStyles} from '../lib/shared_styles.css'; /** * Custom element for in-table add/remove controls. * We use a custom element here so we can encapsulate styles. */ @customElement('generated-row-controls') export class GeneratedRowControls extends MobxLitElement { static override get styles() { return [ sharedStyles, styles, css` :host { display: flex; flex-direction: row; color: #1a73e8; } :host > * { margin-right: 4px; } ` ]; } override render() { const addPoint = () => { const event = new CustomEvent('add-point'); this.dispatchEvent(event); }; const removePoint = () => { const event = new CustomEvent('remove-point'); this.dispatchEvent(event); }; // clang-format off return html` <mwc-icon class="icon-button outlined" @click=${addPoint}> add_box </mwc-icon> <mwc-icon class="icon-button outlined" @click=${removePoint}> delete </mwc-icon> `; // clang-format on } } /** * A LIT module that allows the user to generate new examples. */ @customElement('generator-module') export class GeneratorModule extends LitModule { static override title = 'Datapoint Generator'; static override numCols = 10; static override template = () => { return html`<generator-module></generator-module>`; }; static override duplicateForModelComparison = false; private readonly groupService = app.getService(GroupService); private readonly sliceService = app.getService(SliceService); static override get styles() { return [sharedStyles, styles]; } @observable editedData: Input = {}; @observable isGenerating = false; @observable generated: IndexedInput[][] = []; @observable appliedGenerator: string|null = null; @observable sliceName: string = ''; @computed get datasetName() { return this.appState.currentDataset; } // TODO(lit-team): make model configurable. @computed get modelName() { return this.appState.currentModels[0]; } @computed get globalParams() { return { 'model_name': this.modelName, 'dataset_name': this.datasetName, }; } @computed get totalNumGenerated() { return this.generated.reduce((a, b) => a + b.length, 0); } override firstUpdated() { const getSelectedData = () => this.selectionService.primarySelectedInputData; this.reactImmediately(getSelectedData, selectedData => { if (this.selectionService.lastUser !== this) { this.resetEditedData(); } }); // If all staged examples are removed one-by-one, make sure we reset // to a clean state. this.react(() => this.totalNumGenerated, numAvailable => { if (numAvailable <= 0) { this.resetEditedData(); } }); } override updated() { super.updated(); // Update the header items to be the width of the rows of the table. const header = this.shadowRoot!.getElementById('header') as ParentNode; const firstRow = this.shadowRoot!.querySelector('.row') as ParentNode; if (header) { for (let i = 0; i < header.children.length; i++) { const width = (firstRow.children[i] as HTMLElement).offsetWidth; const child = header.children[i]; (child as HTMLElement).style.minWidth = `${width}px`; } } } private resetEditedData() { this.generated = []; this.appliedGenerator = null; this.sliceName = ''; } private handleGeneratorClick(generator: string, config?: CallConfig) { if (!this.isGenerating) { this.resetEditedData(); this.generate(generator, this.modelName, config); } } private makeAutoSliceName(generator: string, config?: CallConfig) { const segments: string[] = [generator]; if (config != null) { for (const key of Object.keys(config)) { // Skip these since they don't come from the actual controls form. if (this.globalParams.hasOwnProperty(key)) continue; segments.push(`${key}=${config[key]}`); } } return segments.join(':'); } private async generate( generator: string, modelName: string, config?: CallConfig) { this.isGenerating = true; this.appliedGenerator = generator; const sourceExamples = this.selectionService.selectedInputData; try { const generated = await this.apiService.getGenerated( sourceExamples, modelName, this.appState.currentDataset, generator, config); // Populate additional metadata fields. // parentId and source should already be set from the backend. for (const examples of generated) { for (const ex of examples) { Object.assign(ex['meta'], {added: 1}); } } this.generated = generated; this.isGenerating = false; this.sliceName = this.makeAutoSliceName(generator, config); } catch (err) { this.isGenerating = false; } } private async createNewDatapoints(data: IndexedInput[][]) { const newExamples = flatten(data); this.appState.commitNewDatapoints(newExamples); const newIds = newExamples.map(d => d.id); if (newIds.length === 0) return; if (this.sliceName !== '') { this.sliceService.addOrAppendToSlice(this.sliceName, newIds); } const parentIds = new Set<string>(newExamples.map(ex => ex.meta['parentId']!)); // Select parents and children, and set primary to the first child. this.selectionService.selectIds([...parentIds, ...newIds], this); this.selectionService.setPrimarySelection(newIds[0], this); // If in comparison mode, set reference selection to the parent point // for direct comparison. if (this.appState.compareExamplesEnabled) { const referenceSelectionService = app.getServiceArray(SelectionService)[1]; referenceSelectionService.selectIds([...parentIds, ...newIds], this); // parentIds[0] is not necessarily the parent of newIds[0], if // generated[0] is []. const parentId = newExamples[0].meta['parentId']!; referenceSelectionService.setPrimarySelection(parentId, this); } } override render() { return html` <div class="module-container"> <div class="module-content generator-module-content"> ${this.renderGeneratorButtons()} ${this.renderGenerated()} </div> <div class="module-footer"> <p class="module-status">${this.getStatus()}</p> <p class="module-status">${this.getSliceStatus()}</p> ${this.renderOverallControls()} </div> </div> `; } getSliceStatus(): TemplateResult|null { const sliceExists = this.sliceService.namedSlices.has(this.sliceName); if (!sliceExists) return null; const existingSliceSize = this.sliceService.getSliceByName(this.sliceName)!.length; const s = existingSliceSize === 1 ? '' : 's'; // clang-format off return html` Slice exists (${existingSliceSize} point${s}); will append ${this.totalNumGenerated} more. `; // clang-format on } /** * Determine module's status as a string to display in the footer. */ getStatus(): string|TemplateResult { if (this.isGenerating) { return 'Generating...'; } if (this.appliedGenerator) { const s = this.totalNumGenerated === 1 ? '' : 's'; return ` ${this.appliedGenerator}: generated ${this.totalNumGenerated} counterfactual${s} from ${this.generated.length} inputs. `; } const generatorsInfo = this.appState.metadata.generators; const generators = Object.keys(generatorsInfo); if (!generators.length) { return 'No generator components available.'; } const data = this.selectionService.selectedInputData; const selectAll = () => { this.selectionService.selectAll(); }; if (data.length <= 0) { return html` No examples selected. <span class='select-all' @click=${selectAll}> Select entire dataset? </span>`; } const s = data.length === 1 ? '' : 's'; return ` Generate counterfactuals from current selection (${data.length} datapoint${s}). `; } renderInterstitial() { // clang-format off return html` <div class="interstitial"> <img src="static/interstitial-select.png" /> <p> <strong>Counterfactual Generators</strong> Create new datapoints derived from the current selection. </p> </div>`; // clang-format on } renderEmptyNotice() { // clang-format off return html` <div class="interstitial"> <p>No examples generated.</p> </div>`; // clang-format on } renderGenerated() { const rows: TableData[] = this.createEntries(); if (!this.appliedGenerator) { return this.renderInterstitial(); } if (rows.length <= 0) { if (this.isGenerating) { return null; } else { return this.renderEmptyNotice(); } } // clang-format off return html` <div class="results-holder"> <lit-data-table class="table" .columnNames=${Object.keys(rows[0])} .data=${rows} ></lit-data-table> </div> `; // clang-format on } /** * Render the generated counterfactuals themselves. */ createEntries() { const rows: TableData[] = []; for (let parentIndex = 0; parentIndex < this.generated.length; parentIndex++) { const generatedList = this.generated[parentIndex]; for (let generatedIndex = 0; generatedIndex < generatedList.length; generatedIndex++) { const generated = generatedList[generatedIndex]; const addPoint = async () => { this.generated[parentIndex].splice(generatedIndex, 1); await this.createNewDatapoints([[generated]]); }; const removePoint = () => { this.generated[parentIndex].splice(generatedIndex, 1); }; const fieldNames = Object.keys(generated.data); // render values for each datapoint. const row: {[key: string]: TableEntry} = {}; for (const key of fieldNames) { const editable = !this.appState.currentModelRequiredInputSpecKeys.includes(key); row[key] = editable ? this.renderEntry(generated.data, key) : generated.data[key]; } row['Add/Remove'] = html`<generated-row-controls @add-point=${addPoint} @remove-point=${removePoint} />`; rows.push(row); } } return rows; } renderOverallControls() { const onAddAll = async () => { await this.createNewDatapoints(this.generated); this.resetEditedData(); }; const onClickCompare = async () => { this.appState.compareExamplesEnabled = true; // this.createNewDatapoints() will set reference selection if // comparison mode is enabled. await onAddAll(); }; const setSliceName = (e: Event) => { // tslint:disable-next-line:no-any this.sliceName = (e as any).target.value; }; const controlsDisabled = this.totalNumGenerated <= 0; // clang-format off return html` <div class="overall-controls"> <label for="slice-name">Slice name:</label> <input type="text" class="slice-name-input" name="slice-name" .value=${this.sliceName} @input=${setSliceName} placeholder="Name for generated set"> <button class="hairline-button" ?disabled=${controlsDisabled} @click=${onAddAll}> Add all </button> <button class='hairline-button' @click=${onClickCompare} ?disabled=${controlsDisabled}> Add and compare </button> <button class="hairline-button" ?disabled=${controlsDisabled} @click=${this.resetEditedData}> Clear </button> </div>`; // clang-format on } renderGeneratorButtons() { const generatorsInfo = this.appState.metadata.generators; const generators = Object.keys(generatorsInfo); // Add event listener for generation events. const onGenClick = (event: CustomEvent) => { // tslint:disable-next-line:no-any const generatorParams: {[setting: string]: string} = event.detail.settings; // tslint:disable-next-line:no-any const generatorName = event.detail.name; // Add user-specified parameters from the applied generator. const allParams = Object.assign({}, this.globalParams, generatorParams); this.handleGeneratorClick(generatorName, allParams); }; // clang-format off return html` <div class="generators-panel"> ${generators.map(genName => { const spec = generatorsInfo[genName].configSpec; const clonedSpec = JSON.parse(JSON.stringify(spec)) as Spec; const description = generatorsInfo[genName].description; for (const fieldName of Object.keys(clonedSpec)) { // If the generator uses a field matcher, then get the matching // field names from the specified spec and use them as the vocab. if (isLitSubtype(clonedSpec[fieldName], ['FieldMatcher','MultiFieldMatcher'])) { clonedSpec[fieldName].vocab = this.appState.getSpecKeysFromFieldMatcher( clonedSpec[fieldName], this.modelName); } } return html` <lit-interpreter-controls .spec=${clonedSpec} .name=${genName} .description=${description||''} @interpreter-click=${onGenClick} ?bordered=${true}> </lit-interpreter-controls>`; })} </div> `; // clang-format on } renderEntry(mutableInput: Input, key: string) { const value = mutableInput[key]; const isCategorical = this.groupService.categoricalFeatureNames.includes(key); const handleInputChange = (e: Event) => { // tslint:disable-next-line:no-any mutableInput[key] = (e as any).target.value; }; // For categorical outputs, render a dropdown. const renderCategoricalInput = () => { const catVals = this.groupService.categoricalFeatures[key]; // clang-format off return { template: html` <select class="dropdown" @change=${handleInputChange}> ${catVals.map(val => { return html` <option value="${val}" ?selected=${val === value}> ${val} </option>`; })} </select>`, value }; // clang-format on }; // For non-categorical outputs, render an editable textfield. // TODO(lit-dev): Consolidate this logic with the datapoint editor, // ideally as part of b/172597999. const renderFreeformInput = () => { const fieldSpec = this.appState.currentDatasetSpec[key]; const nonEditableSpecs: LitName[] = ['EdgeLabels', 'SpanLabels']; const formattedVal = formatForDisplay(value, fieldSpec); if (isLitSubtype(fieldSpec, nonEditableSpecs)) { return formattedVal; } return { template: html`<input type="text" class="input-box" @input=${handleInputChange} .value="${formattedVal}" />`, value: formattedVal, }; }; return isCategorical ? renderCategoricalInput() : renderFreeformInput(); } static override shouldDisplayModule(modelSpecs: ModelInfoMap, datasetSpec: Spec) { return true; } } declare global { interface HTMLElementTagNameMap { 'generator-module': GeneratorModule; } }
the_stack
import { AttributeTypeModel, BinaryReader, common, ConfirmedTransactionJSON, crypto, getSignData, InvalidFormatError, IOHelper, JSONHelper, MAX_TRANSACTION_SIZE, multiSignatureContractCost, Script, scriptHashToAddress, signatureContractCost, TransactionDataJSON, TransactionJSON, TransactionModel, TransactionModelAdd, UInt160, VerifyResultModel, VerifyResultModelExtended, } from '@neo-one/client-common'; import { BN } from 'bn.js'; import _ from 'lodash'; import { DeserializeWireBaseOptions, DeserializeWireOptions, SerializableContainer, SerializableContainerType, SerializeJSONContext, } from '../Serializable'; import { Signer } from '../Signer'; import { TransactionVerificationContext } from '../TransactionVerificationContext'; import { utils } from '../utils'; import { maxVerificationGas, Verifiable, VerifyOptions } from '../Verifiable'; import { Witness } from '../Witness'; import { Attribute, deserializeAttribute } from './attributes'; export type TransactionAdd = TransactionModelAdd<Attribute, Witness, Signer>; export type TransactionAddUnsigned = Omit<TransactionModelAdd<Attribute, Witness, Signer>, 'witnesses'>; export interface TransactionDataAddOn { readonly blockHash: string; readonly blockIndex: number; readonly transactionIndex: number; } export class Transaction extends TransactionModel<Attribute, Witness, Signer> implements SerializableContainer, Verifiable { public static deserializeWireBase(options: DeserializeWireBaseOptions): Transaction { const { version, nonce, systemFee, networkFee, validUntilBlock, signers, attributes, script } = this.deserializeWireBaseUnsigned(options); const { reader } = options; const witnesses = reader.readArray(() => Witness.deserializeWireBase(options), signers?.length); if (witnesses.length !== signers?.length) { throw new InvalidFormatError( `Expected witnesses length to equal signers length. Got ${witnesses.length} witnesses and ${signers?.length} signers`, ); } return new Transaction({ version, nonce, systemFee, networkFee, validUntilBlock, signers, attributes, script, witnesses, network: options.context.network, maxValidUntilBlockIncrement: options.context.maxValidUntilBlockIncrement, }); } public static deserializeWireBaseUnsigned(options: DeserializeWireBaseOptions): TransactionAddUnsigned { const { reader } = options; const version = reader.readUInt8(); if (version > 0) { throw new InvalidFormatError(`Expected version to equal 0, found: ${version}`); } const nonce = reader.readUInt32LE(); const systemFee = reader.readInt64LE(); if (systemFee.ltn(0)) { throw new InvalidFormatError(`Expected systemFee to be greater than 0, found: ${systemFee.toString()}`); } const networkFee = reader.readInt64LE(); if (networkFee.ltn(0)) { throw new InvalidFormatError(`Expected networkFee to be greater than 0, found: ${networkFee.toString()}`); } if (systemFee.add(networkFee).lt(systemFee)) { throw new InvalidFormatError(); } const validUntilBlock = reader.readUInt32LE(); const signers = this.deserializeSigners(options, this.maxTransactionAttributes); const attributes = this.deserializeAttributes(options, this.maxTransactionAttributes - signers.length); const script = reader.readVarBytesLE(utils.USHORT_MAX.toNumber()); if (script.length === 0) { throw new InvalidFormatError(`Expected script length to be greater than 0, found: ${script.length}`); } return { version, nonce, systemFee, networkFee, validUntilBlock, signers, attributes, script, network: options.context.network, maxValidUntilBlockIncrement: options.context.maxValidUntilBlockIncrement, }; } public static deserializeWire(options: DeserializeWireOptions): Transaction { return this.deserializeWireBase({ context: options.context, reader: new BinaryReader(options.buffer), }); } private static deserializeSigners(options: DeserializeWireBaseOptions, maxCount: number) { const { reader } = options; const count = reader.readVarUIntLE(new BN(maxCount)).toNumber(); if (count === 0) { throw new InvalidFormatError(`Expected signer count > 0, found: ${count}`); } const signerSet = new Set<UInt160>(); return _.range(count).map(() => { const signer = Signer.deserializeWireBase(options); if (signerSet.has(signer.account)) { throw new InvalidFormatError(`Expected signers to be unique, found repeat: ${signer}`); } signerSet.add(signer.account); return signer; }); } private static deserializeAttributes(options: DeserializeWireBaseOptions, maxCount: number) { const { reader } = options; const count = reader.readVarUIntLE(new BN(maxCount)).toNumber(); const attributeSet = new Set<AttributeTypeModel>(); return _.range(count).map(() => { const attribute = deserializeAttribute(options); if (!attribute.allowMultiple && attributeSet.has(attribute.type)) { throw new InvalidFormatError(`Only 1 ${attribute.type} attribute allowed, found at least 2`); } attributeSet.add(attribute.type); return attribute; }); } public get size() { return this.sizeInternal(); } public readonly type: SerializableContainerType = 'Transaction'; private readonly sizeInternal = utils.lazy( () => Transaction.headerSize + IOHelper.sizeOfArray(this.signers, (signer) => signer.size) + IOHelper.sizeOfArray(this.attributes, (attr) => attr.size) + IOHelper.sizeOfVarBytesLE(this.script) + IOHelper.sizeOfArray(this.witnesses, (witness) => witness.size), ); public async verifyStateDependent( verifyOptions: VerifyOptions, transactionContext?: TransactionVerificationContext, ): Promise<VerifyResultModelExtended> { const { storage, native, verifyWitness, vm, headerCache } = verifyOptions; const index = await native.Ledger.currentIndex(storage); if (this.validUntilBlock <= index) { return { verifyResult: VerifyResultModel.Expired, failureReason: `Transaction is expired. Current index ${index} is greater than validUntilBlock ${this.validUntilBlock}`, }; } if (this.validUntilBlock > index + this.maxValidUntilBlockIncrement) { return { verifyResult: VerifyResultModel.Expired, failureReason: `Transaction is expired. Current index ${index} plus maxValidUntilBlockIncrement ${this.maxValidUntilBlockIncrement} is less than validUntilBlock ${this.validUntilBlock}`, }; } const hashes = this.getScriptHashesForVerifying(); const blockedHashes: UInt160[] = []; const blocked = await Promise.all( hashes.map(async (hash) => { const isBlocked = await native.Policy.isBlocked(storage, hash); if (isBlocked) { // tslint:disable-next-line: no-array-mutation blockedHashes.push(hash); } return isBlocked; }), ); if (blocked.some((bool) => bool)) { return { verifyResult: VerifyResultModel.PolicyFail, failureReason: `The following signers are blocked: ${blockedHashes .map((hash) => common.uInt160ToString(hash)) .join(', ')}`, }; } const checkTxPromise = transactionContext?.checkTransaction(this, storage) ?? Promise.resolve({ result: true }); const checkTx = await checkTxPromise; if (!checkTx.result) { return { verifyResult: VerifyResultModel.InsufficientFunds, failureReason: checkTx.failureReason }; } const failedAttributes: Attribute[] = []; const attrVerifications = await Promise.all( this.attributes.map(async (attr) => { const verification = await attr.verify(verifyOptions, this); if (!verification) { // tslint:disable-next-line: no-array-mutation failedAttributes.push(attr); } return verification; }), ); if (attrVerifications.some((verification) => !verification)) { return { verifyResult: VerifyResultModel.Invalid, failureReason: `The following attributes failed verification: ${failedAttributes .map((attr) => JSON.stringify(attr.serializeJSON())) .join(', ')}`, }; } const [feePerByte, execFeeFactor] = await Promise.all([ native.Policy.getFeePerByte(storage), native.Policy.getExecFeeFactor(storage), ]); const feeNeeded = feePerByte.muln(this.size); let netFee = this.networkFee.sub(feeNeeded); if (netFee.ltn(0)) { return { verifyResult: VerifyResultModel.InsufficientFunds, failureReason: `Insufficient network fee. Transaction size ${ this.size } times fee per byte of ${feePerByte.toString()} = ${feeNeeded.toString()} is greater than attached network fee ${this.networkFee.toString()}`, }; } if (netFee.gt(maxVerificationGas)) { netFee = maxVerificationGas; } // tslint:disable-next-line: no-loop-statement for (let i = 0; i < hashes.length; i += 1) { const witness = this.witnesses[i]; const multiSigResult = crypto.isMultiSigContractWithResult(witness.verification); if (multiSigResult.result) { const { m, n } = multiSigResult; netFee = netFee.sub(new BN(multiSignatureContractCost(m, n).toString(), 10).muln(execFeeFactor)); } else if (crypto.isSignatureContract(witness.verification)) { netFee = netFee.sub(new BN(signatureContractCost.toString(), 10).muln(execFeeFactor)); } else { const { result, gas, failureReason } = await verifyWitness({ vm, verifiable: this, storage, native, hash: hashes[i], witness, gas: netFee, headerCache, settings: verifyOptions.settings, }); if (!result) { return { verifyResult: VerifyResultModel.InsufficientFunds, failureReason: `Witness verification failed for witness ${common.uInt160ToString( witness.scriptHash, )}. Reason: ${failureReason}.`, }; } netFee = netFee.sub(gas); } if (netFee.ltn(0)) { return { verifyResult: VerifyResultModel.InsufficientFunds, failureReason: `Insufficient network fee while verifying witnesses. Try adding ${netFee .neg() .toString()} to network fee`, }; } } return { verifyResult: VerifyResultModel.Succeed }; } public async verifyStateIndependent(verifyOptions: VerifyOptions): Promise<VerifyResultModelExtended> { const network = verifyOptions.settings?.network ?? this.network; if (this.size > MAX_TRANSACTION_SIZE) { return { verifyResult: VerifyResultModel.Invalid, failureReason: '' }; } try { // tslint:disable-next-line: no-unused-expression new Script(this.script, true); } catch (error) { return { verifyResult: VerifyResultModel.Invalid, failureReason: `Transaction script is invalid: ${error.message}`, }; } const hashes = this.getScriptHashesForVerifying(); if (hashes.length !== this.witnesses.length) { return { verifyResult: VerifyResultModel.Invalid, failureReason: `Expected hashes length ${hashes.length} to equal witnesses length ${this.witnesses.length}`, }; } // tslint:disable-next-line: no-loop-statement for (let i = 0; i < hashes.length; i += 1) { const multiSigResult = crypto.isMultiSigContractWithResult(this.witnesses[i].verification); if (crypto.isSignatureContract(this.witnesses[i].verification)) { const pubkey = common.bufferToECPoint(this.witnesses[i].verification.slice(2, 35)); try { const signature = this.witnesses[i].invocation.slice(2); const signData = getSignData(this.hash, network); if (!crypto.verify({ publicKey: pubkey, message: signData, signature })) { return { verifyResult: VerifyResultModel.Invalid, failureReason: 'Signature verification failed' }; } } catch (error) { return { verifyResult: VerifyResultModel.Invalid, failureReason: `Signature verification failed: ${error.message}`, }; } } else if (multiSigResult.result) { const { points, m } = multiSigResult; const signatures = crypto.getMultiSignatures(this.witnesses[i].invocation); if (!hashes[i].equals(this.witnesses[i].scriptHash)) { return { verifyResult: VerifyResultModel.Invalid, failureReason: `Expected witness scripthash ${common.uInt160ToString( this.witnesses[i].scriptHash, )} to equal ${common.uInt160ToString(hashes[i])}`, }; } if (signatures === undefined) { // This check is not in there code but it's possible that their code // could throw a null reference exception without this sort of check return { verifyResult: VerifyResultModel.Invalid, failureReason: 'Expected witness invocation signature to be defined', }; } if (signatures.length !== m) { return { verifyResult: VerifyResultModel.Invalid, failureReason: `Expected signatures length ${signatures.length} to equal witness verification script result length ${m}`, }; } const n = points.length; const message = getSignData(this.hash, network); try { // tslint:disable-next-line: no-loop-statement for (let x = 0, y = 0; x < m && y < n; ) { if (crypto.verify({ message, signature: signatures[x], publicKey: points[y] })) { x += 1; } y += 1; if (m - x > n - y) { return { verifyResult: VerifyResultModel.Invalid, failureReason: 'Error while verifying invocation signature', }; } } } catch (error) { return { verifyResult: VerifyResultModel.Invalid, failureReason: `Error while verifying invocation signatures: ${error.message}`, }; } } } return { verifyResult: VerifyResultModel.Succeed }; } public async verify( verifyOptions: VerifyOptions, verifyContext?: TransactionVerificationContext, ): Promise<VerifyResultModelExtended> { const independentResult = await this.verifyStateIndependent(verifyOptions); if (independentResult.verifyResult !== VerifyResultModel.Succeed) { return independentResult; } return this.verifyStateDependent(verifyOptions, verifyContext); } public serializeJSON(): TransactionJSON { return { hash: JSONHelper.writeUInt256(this.hash), size: this.size, version: this.version, nonce: this.nonce, sender: this.sender ? scriptHashToAddress(common.uInt160ToString(this.sender)) : undefined, sysfee: JSONHelper.writeFixed8(this.systemFee), netfee: JSONHelper.writeFixed8(this.networkFee), validuntilblock: this.validUntilBlock, signers: this.signers.map((signer) => signer.serializeJSON()), attributes: this.attributes.map((attr) => attr.serializeJSON()), script: JSONHelper.writeBase64Buffer(this.script), witnesses: this.witnesses.map((witness) => witness.serializeJSON()), }; } public async serializeJSONWithData(context: SerializeJSONContext): Promise<ConfirmedTransactionJSON> { const base = this.serializeJSON(); const data = await context.tryGetTransactionData(this.hash); let transactionData: TransactionDataJSON | undefined; if (data !== undefined) { transactionData = { blockIndex: data.blockIndex, blockHash: JSONHelper.writeUInt256(data.blockHash), globalIndex: JSONHelper.writeUInt64(data.globalIndex), transactionIndex: data.transactionIndex, votes: data.votes.map((v) => v.serializeJSON()), policyChanges: data.policyChanges.map((change) => change.serializeJSON()), deletedContractHashes: data.deletedContractHashes.map((hash) => JSONHelper.writeUInt160(hash)), deployedContracts: data.deployedContracts.map((c) => c.serializeJSON()), updatedContracts: data.updatedContracts.map((c) => c.serializeJSON()), executionResult: data.executionResult.serializeJSON(), actions: data.actions.map((action) => action.serializeJSON()), }; } return { ...base, transactionData, }; } }
the_stack
import { FSHTank } from '../import/FSHTank'; import { StructureDefinition, InstanceDefinition, ElementDefinition, PathPart } from '../fhirtypes'; import { Instance, SourceInfo } from '../fshtypes'; import { logger, Fishable, Type, Metadata, resolveSoftIndexing } from '../utils'; import { setPropertyOnInstance, replaceReferences, cleanResource, splitOnPathPeriods, setImpliedPropertiesOnInstance, applyInsertRules, isExtension, getSliceName, isModifierExtension } from '../fhirtypes/common'; import { InstanceOfNotDefinedError } from '../errors/InstanceOfNotDefinedError'; import { InstanceOfLogicalProfileError } from '../errors/InstanceOfLogicalProfileError'; import { Package } from '.'; import { cloneDeep, merge, uniq } from 'lodash'; import { AssignmentRule } from '../fshtypes/rules'; export class InstanceExporter implements Fishable { constructor( private readonly tank: FSHTank, private readonly pkg: Package, private readonly fisher: Fishable ) {} private setAssignedValues( fshInstanceDef: Instance, instanceDef: InstanceDefinition, instanceOfStructureDefinition: StructureDefinition ): InstanceDefinition { // The fshInstanceDef.rules list may contain insert rules, which will be expanded to AssignmentRules applyInsertRules(fshInstanceDef, this.tank); resolveSoftIndexing(fshInstanceDef.rules); let rules = fshInstanceDef.rules.map(r => cloneDeep(r)) as AssignmentRule[]; // Normalize all rules to not use the optional [0] index rules.forEach(r => { r.path = r.path.replace(/\[0+\]/g, ''); }); rules = rules.map(r => replaceReferences(r, this.tank, this.fisher)); // Convert strings in AssignmentRules to instances rules = rules.filter(r => { if (r.isInstance) { const instance: InstanceDefinition = this.fishForFHIR(r.value as string); if (instance != null) { r.value = instance; return true; } else { logger.error( `Cannot find definition for Instance: ${r.value}. Skipping rule.`, r.sourceInfo ); return false; } } return true; }); // Collect all paths that indicate the sub-paths of that path should be of a given resourceType // for example, if a.b = SomePatientInstance, then any subpath (a.b.x) must ensure that when validating // Patient is used for the type of a.b const inlineResourcePaths: { path: string; instanceOf: string }[] = []; rules.forEach(r => { if (r.isInstance && r.value instanceof InstanceDefinition) { inlineResourcePaths.push({ path: r.path, // We only use the first element of the meta.profile array, if a need arises for a more // comprehensive approach, we can come back to this later instanceOf: r.value.meta?.profile?.[0] ?? r.value.resourceType }); } if (r.path.endsWith('.resourceType') && typeof r.value === 'string') { inlineResourcePaths.push({ // Only get the part of the path before resourceType, aka if path is a.b.resourceType // the relevant element is a.b, since it is the actual Resource element path: splitOnPathPeriods(r.path).slice(0, -1).join('.'), instanceOf: r.value }); } }); // When assigning values, things happen in the order: // 1 - Validate values for rules that are on the instance // 2 - Determine all rules implied by the Structure Definition // 3 - Set values from rules implied by the Structure Definition // 4 - Set values from rules directly on the instance // This order is required due to the fact that validateValueAtPath changes instanceOfStructureDefinition // in certain cases that must happen before setting rules from the Structure Definition. In the future // we may want to refactor validateValueAtPath, but for now things should happen in this order const ruleMap: Map< string, { pathParts: PathPart[]; assignedValue: any; sourceInfo: SourceInfo } > = new Map(); rules.forEach(rule => { try { const matchingInlineResourcePaths = inlineResourcePaths.filter( i => rule.path.startsWith(`${i.path}.`) && rule.path !== `${i.path}.resourceType` ); // Generate an array of resourceTypes that matches the path, so if path is // a.b.c.d.e, and b is a Bundle and D is a Patient, // inlineResourceTypes = [undefined, "Bundle", undefined, "Patient", undefined] const inlineResourceTypes: string[] = []; matchingInlineResourcePaths.forEach(match => { inlineResourceTypes[splitOnPathPeriods(match.path).length - 1] = match.instanceOf; }); const validatedRule = instanceOfStructureDefinition.validateValueAtPath( rule.path, rule.value, this.fisher, inlineResourceTypes ); // Record each valid rule in a map ruleMap.set(rule.path, { pathParts: validatedRule.pathParts, assignedValue: validatedRule.assignedValue, sourceInfo: rule.sourceInfo }); } catch (e) { logger.error(e.message, rule.sourceInfo); } }); const paths = ['', ...rules.map(rule => rule.path)]; // To correctly assign properties, we need to: // 1 - Assign implied properties on the original instance // 2 - Assign rule properties on a copy of the result of 1, so that rule assignment can build on implied assignment // 3 - Merge the result of 2 with the result of 1, so that any implied properties which may have been overwrtiten // in step 2 are maintained...don't worry I'm confused too setImpliedPropertiesOnInstance(instanceDef, instanceOfStructureDefinition, paths, this.fisher); const ruleInstance = cloneDeep(instanceDef); ruleMap.forEach(rule => { setPropertyOnInstance(ruleInstance, rule.pathParts, rule.assignedValue, this.fisher); // was an instance of an extension used correctly with respect to modifiers? if ( isExtension(rule.pathParts[rule.pathParts.length - 1].base) && typeof rule.assignedValue === 'object' ) { const extension = this.fisher.fishForFHIR(rule.assignedValue.url, Type.Extension); if (extension) { const pathBase = rule.pathParts[rule.pathParts.length - 1].base; const isModifier = isModifierExtension(extension); if (isModifier && pathBase === 'extension') { logger.error( `Instance of modifier extension ${ extension.name ?? extension.id } assigned to extension path. Modifier extensions should only be assigned to modifierExtension paths.`, rule.sourceInfo ); } else if (!isModifier && pathBase === 'modifierExtension') { logger.error( `Instance of non-modifier extension ${ extension.name ?? extension.id } assigned to modifierExtension path. Non-modifier extensions should only be assigned to extension paths.`, rule.sourceInfo ); } } } // were extensions used correctly along the path? rule.pathParts.forEach(pathPart => { if (isExtension(pathPart.base)) { const sliceName = getSliceName(pathPart); if (sliceName) { const extension = this.fisher.fishForFHIR(sliceName, Type.Extension); if (extension) { const isModifier = isModifierExtension(extension); if (isModifier && pathPart.base === 'extension') { logger.error( `Modifier extension ${ extension.name ?? extension.id } used on extension element. Modifier extensions should only be used with modifierExtension elements.`, rule.sourceInfo ); } else if (!isModifier && pathPart.base === 'modifierExtension') { logger.error( `Non-modifier extension ${ extension.name ?? extension.id } used on modifierExtension element. Non-modifier extensions should only be used with extension elements.`, rule.sourceInfo ); } } } } }); }); instanceDef = merge(instanceDef, ruleInstance); return instanceDef; } /** * Check that all required elements are present on an InstanceDefinition or * a sub-part of an InstanceDefinition for all children of an element. * An element is required if it has minimum cardinality greater than 1. * @param {{[key: string]: any}} instance - The InstanceDefinition or subsection of an InstanceDefinition we are validating * @param {ElementDefinition} element - The element we are trying to validate all children of * @param {Instance} fshDefinition - The FSH definition that we built the original InstanceDefinition from */ private validateRequiredChildElements( instance: { [key: string]: any }, element: ElementDefinition, fshDefinition: Instance ): void { // Get only direct children of the element const children = element.children(true); children.forEach(c => { let child = c; // Get the last part of the path, A.B.C => C const childPathEnd = child.path.split('.').slice(-1)[0]; // Note that in most cases the _ prefixed element will not exist. But if it does exist, we validate // using the _ prefixed element, since it will contain any children of the primitive let instanceChild = instance[`_${childPathEnd}`] ?? instance[childPathEnd]; // If the element is a choice, we will fail to find it, we need to use the choice name if (instanceChild == null && childPathEnd.endsWith('[x]')) { const possibleChoiceSlices = [...children]; element .findConnectedElements() .forEach(ce => possibleChoiceSlices.push(...ce.children(true))); const choiceSlices = possibleChoiceSlices.filter(c => c.path === child.path && c.sliceName); for (const choiceSlice of choiceSlices) { instanceChild = instance[choiceSlice.sliceName]; if (instanceChild != null) { // Once we find the the choiceSlice that matches, use it as the child child = choiceSlice; break; } } } // Recursively validate children of the current element if (Array.isArray(instanceChild)) { // If the child is a slice, and there are no array elements with matching slice names // but there are array elements that could match (since they use numerical indices) // we can go no further in validation, since we can't know which slice is represented if ( child.sliceName && !instanceChild.find((arrayEl: any) => arrayEl?._sliceName === child.sliceName) && instanceChild.find((arrayEl: any) => !arrayEl?._sliceName) ) { return; } // Filter so that if the child is a slice, we only count relevant slices // A slice is relevant if it is the child slice or is a reslice of child. // Typically, a sliceName that starts with child.sliceName + '/' is a reslice. instanceChild = instanceChild.filter( (arrayEl: any) => !child.sliceName || arrayEl?._sliceName === child.sliceName || arrayEl?._sliceName?.toString().startsWith(`${child.sliceName}/`) ); instanceChild.forEach((arrayEl: any) => { if (arrayEl != null) this.validateRequiredChildElements(arrayEl, child, fshDefinition); }); } else if (instanceChild != null) { this.validateRequiredChildElements(instanceChild, child, fshDefinition); } // Log an error if: // 1 - The child element is 1.., but not on the instance // 2 - The child element is n..m, but it has k < n elements if ( (child.min > 0 && instanceChild == null) || (Array.isArray(instanceChild) && instanceChild.length < child.min) ) { // Can't point to any specific rule, so give sourceInfo of entire instance logger.error( `Element ${child.id} has minimum cardinality ${child.min} but occurs ${ instanceChild ? instanceChild.length : 0 } time(s).`, fshDefinition.sourceInfo ); } }); } /** * Check that all required elements are present on an instance * @param {InstanceDefinition} instanceDef - The InstanceDefinition we are validating * @param {ElementDefinition[]} elements - The elements of the StructDef that instanceDef is an instance of * @param {Instance} fshDefinition - The FSH definition that we built instanceDef from */ private validateRequiredElements( instanceDef: InstanceDefinition, elements: ElementDefinition[], fshDefinition: Instance ): void { this.validateRequiredChildElements(instanceDef, elements[0], fshDefinition); } private shouldSetMetaProfile(instanceDef: InstanceDefinition): boolean { switch (this.tank.config.instanceOptions?.setMetaProfile) { case 'never': return false; case 'inline-only': return instanceDef._instanceMeta.usage === 'Inline'; case 'standalone-only': return instanceDef._instanceMeta.usage !== 'Inline'; case 'always': default: return true; } } private shouldSetId(instanceDef: InstanceDefinition): boolean { switch (this.tank.config.instanceOptions?.setId) { case 'standalone-only': return instanceDef._instanceMeta.usage !== 'Inline'; case 'always': default: return true; } } fishForFHIR(item: string): InstanceDefinition { let result = this.pkg.fish(item, Type.Instance) as InstanceDefinition; if (result == null) { // If we find a FSH definition, then we can export and fish for it again const fshDefinition = this.tank.fish(item, Type.Instance) as Instance; if (fshDefinition) { this.exportInstance(fshDefinition); result = this.pkg.fish(item, Type.Instance) as InstanceDefinition; } } return result; } fishForMetadata(item: string): Metadata { // If it's in the tank, it can get the metadata from there (no need to export like in fishForFHIR) return this.fisher.fishForMetadata(item, Type.Instance); } exportInstance(fshDefinition: Instance): InstanceDefinition { if (this.pkg.instances.some(i => i._instanceMeta.name === fshDefinition.id)) { return; } let isResource = true; const json = this.fisher.fishForFHIR( fshDefinition.instanceOf, Type.Resource, Type.Profile, Type.Extension, Type.Type ); if (!json) { throw new InstanceOfNotDefinedError( fshDefinition.name, fshDefinition.instanceOf, fshDefinition.sourceInfo ); } // Since creating an instance of a Logical is not allowed, // creating an instance of a Profile of a logical model is also not allowed if (json.kind === 'logical' && json.derivation === 'constraint') { throw new InstanceOfLogicalProfileError( fshDefinition.name, fshDefinition.instanceOf, fshDefinition.sourceInfo ); } if (json.kind !== 'resource') { // If the instance is not a resource, it should be inline, since it cannot exist as a standalone instance isResource = false; if (fshDefinition.usage !== 'Inline') { logger.warn( `Instance ${fshDefinition.name} is not an instance of a resource, so it should only be used inline on other instances, and it will not be exported to a standalone file. Specify "Usage: #inline" to remove this warning.`, fshDefinition.sourceInfo ); fshDefinition.usage = 'Inline'; } } const instanceOfStructureDefinition = StructureDefinition.fromJSON(json); let instanceDef = new InstanceDefinition(); instanceDef._instanceMeta.name = fshDefinition.id; // This is name of the instance in the FSH if (fshDefinition.title) { instanceDef._instanceMeta.title = fshDefinition.title; } if (fshDefinition.description) { instanceDef._instanceMeta.description = fshDefinition.description; } if (fshDefinition.usage) { instanceDef._instanceMeta.usage = fshDefinition.usage; if ( fshDefinition.usage === 'Definition' && instanceOfStructureDefinition.elements.some( element => element.id === `${instanceOfStructureDefinition.type}.url` ) ) { instanceDef.url = `${this.tank.config.canonical}/${instanceOfStructureDefinition.type}/${fshDefinition.id}`; } } if (isResource) { instanceDef.resourceType = instanceOfStructureDefinition.type; // ResourceType is determined by the StructureDefinition of the type if (this.shouldSetId(instanceDef)) { instanceDef.id = fshDefinition.id; } } else { instanceDef._instanceMeta.sdType = instanceOfStructureDefinition.type; } // Set Assigned values based on the FSH rules and the Structure Definition instanceDef = this.setAssignedValues(fshDefinition, instanceDef, instanceOfStructureDefinition); // should we add the instanceOf to meta.profile? // if the exact url is not in there, and a versioned url is also not in there, add it to the front. // otherwise, add it at the front. if ( this.shouldSetMetaProfile(instanceDef) && isResource && instanceOfStructureDefinition.derivation === 'constraint' ) { // elements of instanceDef.meta.profile may be objects if they are provided by slices, // since they have to keep track of the _sliceName property. // this is technically not a match for the defined type of instanceDef.meta.profile, // so give the parameter a union type to handle both cases. if ( !instanceDef.meta?.profile?.some((profile: string | { assignedValue: string }) => { const profileUrl = typeof profile === 'object' ? profile.assignedValue : profile; return ( profileUrl === instanceOfStructureDefinition.url || profileUrl.startsWith(`${instanceOfStructureDefinition.url}|`) ); }) ) { // we might have to create meta or meta.profile first, if no rules already created those if (instanceDef.meta == null) { instanceDef.meta = { profile: [instanceOfStructureDefinition.url] }; } else if (instanceDef.meta.profile == null) { instanceDef.meta.profile = [instanceOfStructureDefinition.url]; } else { instanceDef.meta.profile.unshift(instanceOfStructureDefinition.url); } } } instanceDef.validateId(fshDefinition.sourceInfo); this.validateRequiredElements( instanceDef, instanceOfStructureDefinition.elements, fshDefinition ); cleanResource(instanceDef); this.pkg.instances.push(instanceDef); // Once all rules are set, we should ensure that we did not add a duplicate profile URL anywhere if (instanceDef.meta?.profile) instanceDef.meta.profile = uniq(instanceDef.meta.profile); // check for another instance of the same type with the same id // see https://www.hl7.org/fhir/resource.html#id // instanceDef has already been added to the package, so it's fine if it matches itself // inline instances are not written to their own files, so those can be skipped in this if ( instanceDef._instanceMeta.usage !== 'Inline' && this.pkg.instances.some( instance => instance._instanceMeta.usage !== 'Inline' && instanceDef.resourceType === instance.resourceType && instanceDef.id === instance.id && instanceDef !== instance ) ) { logger.error( `Multiple instances of type ${instanceDef.resourceType} with id ${instanceDef.id}. Each non-inline instance of a given type must have a unique id.`, fshDefinition.sourceInfo ); } return instanceDef; } /** * Exports Instances * @param {FSHTank} tank - The FSH tank we are exporting * @returns {Package} */ export(): Package { const instances = this.tank.getAllInstances(); for (const instance of instances) { try { this.exportInstance(instance); } catch (e) { logger.error(e.message, e.sourceInfo); } } if (instances.length > 0) { logger.info(`Converted ${instances.length} FHIR instances.`); } return this.pkg; } }
the_stack
import { LitElement, html, TemplateResult, css, PropertyValues, CSSResultGroup } from 'lit'; import { render } from 'lit'; import { property, customElement, state } from 'lit/decorators'; import { HomeAssistant, hasConfigOrEntityChanged, hasAction, ActionHandlerEvent, handleAction, LovelaceCardEditor, getLovelace, fireEvent, } from 'custom-card-helpers'; // This is a community maintained npm module with common helper functions/types import './editor'; import { mergeDeep, hasConfigOrEntitiesChanged, createConfigArray, createObjectGroupConfigArray } from './helpers'; import type { Floor3dCardConfig, EntityFloor3dCardConfig } from './types'; import { CARD_VERSION } from './const'; import { localize } from './localize/localize'; //import three.js libraries for 3D rendering import * as THREE from 'three'; import { Projector } from 'three/examples/jsm/renderers/Projector'; import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'; import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader'; import { MTLLoader } from 'three/examples/jsm/loaders/MTLLoader'; import { BooleanKeyframeTrack, Box3, DirectionalLightHelper, Group, LessEqualStencilFunc, Material, Mesh, Vector3 } from 'three'; import { TrackballControls } from 'three/examples/jsm/controls/TrackballControls'; import { Sky } from 'three/examples/jsm/objects/Sky'; import { NotEqualStencilFunc, Object3D } from 'three'; /* eslint no-console: 0 */ console.info( `%c FLOOR3D-CARD \n%c ${localize('common.version')} ${CARD_VERSION} `, 'color: orange; font-weight: bold; background: black', 'color: white; font-weight: bold; background: dimgray', ); // This puts your card into the UI card picker dialog (window as any).customCards = (window as any).customCards || []; (window as any).customCards.push({ type: 'floor3d-card', name: 'Floor3d Card', description: 'A custom card to visualize and activate entities in a live 3D model', }); // TODO Name your custom element @customElement('floor3d-card') export class Floor3dCard extends LitElement { private _scene?: THREE.Scene; private _camera?: THREE.PerspectiveCamera; private _renderer?: THREE.WebGLRenderer; private _controls?: OrbitControls; private _hemiLight?: THREE.HemisphereLight; private _modelX?: number; private _modelY?: number; private _modelZ?: number; private _to_animate: boolean; private _bboxmodel: THREE.Object3D; private _states?: string[]; private _color?: number[][]; private _initialmaterial?: THREE.Material[][]; private _clonedmaterial?: THREE.Material[][]; private _brightness?: number[]; private _lights?: string[]; private _canvas?: HTMLCanvasElement[]; private _unit_of_measurement?: string[]; private _text?: string[]; private _objposition: number[][]; private _slidingdoorposition: THREE.Vector3[][]; private _objects_to_rotate: THREE.Group[]; private _pivot: THREE.Vector3[]; private _degrees: number[]; private _axis_for_door: THREE.Vector3[]; private _axis_to_rotate: string[]; private _round_per_seconds: number[]; private _rotation_state: number[]; private _rotation_index: number[]; private _clock?: THREE.Clock; private _slidingdoor: THREE.Group[]; private _eval: Function; private _firstcall?: boolean; private _resizeTimeout?: number; private _resizeObserver: ResizeObserver; private _zIndexInterval: number; private _performActionListener: EventListener; private _fireventListener: EventListener; private _changeListener: EventListener; private _cardObscured: boolean; private _card?: HTMLElement; private _content?: HTMLElement; private _progress?: HTMLElement; private _config!: Floor3dCardConfig; private _configArray: Floor3dCardConfig[] = []; private _object_ids?: Floor3dCardConfig[] = []; private _overlay: HTMLDivElement; private _hass?: HomeAssistant; private _haShadowRoot: any; private _card_id: string; private _ambient_light: THREE.AmbientLight; private _direction_light: THREE.DirectionalLight; private _point_light: THREE.PointLight; _helper: THREE.DirectionalLightHelper; _modelready: boolean; private _maxtextureimage: number; constructor() { super(); this._cardObscured = false; this._resizeObserver = new ResizeObserver(() => { this._resizeCanvasDebounce() }); this._performActionListener = (evt) => this._performAction(evt); this._fireventListener = (evt) => this._firevent(evt); this._changeListener = () => this._render(); this._haShadowRoot = document.querySelector('home-assistant').shadowRoot; this._eval = eval; this._card_id = 'ha-card-1'; console.log('New Card'); } public connectedCallback(): void { super.connectedCallback(); if (this._modelready) { if (this._ispanel() || this._issidebar()) { this._resizeObserver.observe(this._card); } this._zIndexInterval = window.setInterval(() => { this._zIndexChecker(); }, 250); if (this._to_animate) { this._clock = new THREE.Clock(); this._renderer.setAnimationLoop(() => this._rotateobjects()); } if (this._ispanel() || this._issidebar()) { this._resizeCanvas(); } } } public disconnectedCallback(): void { super.disconnectedCallback(); this._resizeObserver.disconnect(); window.clearInterval(this._zIndexInterval); if (this._modelready) { if (this._to_animate) { this._clock = null; this._renderer.setAnimationLoop(null); } } } public static async getConfigElement(): Promise<LovelaceCardEditor> { return document.createElement('floor3d-card-editor'); } public static getStubConfig(): object { return {}; } // TODO Add any properities that should cause your element to re-render here // https://lit-element.polymer-project.org/guide/properties //@property({ attribute: false }) public hass!: HomeAssistant; @state() private config!: Floor3dCardConfig; // https://lit-element.polymer-project.org/guide/properties#accessors-custom public setConfig(config: Floor3dCardConfig): void { // TODO Check for required fields and that they are of the proper format console.log('Set Config'); if (!config) { throw new Error(localize('common.invalid_configuration')); } this._config = config; this._configArray = createConfigArray(this._config); this._object_ids = createObjectGroupConfigArray(this._config); this._initialmaterial = []; this._clonedmaterial = []; let i = 0; this._object_ids.forEach((entity) => { this._initialmaterial.push([]); this._clonedmaterial.push([]); entity.objects.forEach(() => { this._initialmaterial[i].push(null); this._clonedmaterial[i].push(null); }); i += 1; }); if (this._config.show_warning) { render(this._showWarning(localize('common.show_warning')), this._card); return; } if (this._config.show_error) { render(this._showError(localize('common.show_error')), this._card); return; } } public rerender(): void { this._content.removeEventListener('dblclick', this._performActionListener); this._content.removeEventListener('touchstart', this._performActionListener); this._controls.removeEventListener('change', this._changeListener); this._renderer.setAnimationLoop(null); this._resizeObserver.disconnect(); window.clearInterval(this._zIndexInterval); this._renderer.domElement.remove(); this._renderer = null; this._states = null; this.hass = this._hass; this.display3dmodel(); } private _ispanel(): boolean { let root: any = document.querySelector('home-assistant'); root = root && root.shadowRoot; root = root && root.querySelector('home-assistant-main'); root = root && root.shadowRoot; root = root && root.querySelector('app-drawer-layout partial-panel-resolver'); root = (root && root.shadowRoot) || root; root = root && root.querySelector('ha-panel-lovelace'); root = root && root.shadowRoot; root = root && root.querySelector('hui-root'); root = root && root.shadowRoot; root = root && root.querySelector('ha-app-layout'); const panel: [] = root.getElementsByTagName('HUI-PANEL-VIEW'); if (panel.length == 0) { return false; } else { return true; } } private _issidebar(): boolean { let root: any = document.querySelector('home-assistant'); root = root && root.shadowRoot; root = root && root.querySelector('home-assistant-main'); root = root && root.shadowRoot; root = root && root.querySelector('app-drawer-layout partial-panel-resolver'); root = (root && root.shadowRoot) || root; root = root && root.querySelector('ha-panel-lovelace'); root = root && root.shadowRoot; root = root && root.querySelector('hui-root'); root = root && root.shadowRoot; root = root && root.querySelector('ha-app-layout'); const sidebar: [] = root.getElementsByTagName('HUI-SIDEBAR-VIEW'); if (sidebar.length == 0) { return false; } else { return true; } } getCardSize(): number { console.log('Get Card Size Called'); if (this._renderer) { //return this._renderer.domElement.height / 50; return 10; } else { return 10; } } firstUpdated(): void { //called after the model has been loaded into the Renderer and first render console.log('First updated start'); this._card = this.shadowRoot.getElementById(this._card_id); if (this._card) { if (!this._content) { this._content = document.createElement('div'); this._content.style.width = '100%'; this._content.style.height = '100%'; this._content.style.alignContent = 'center'; this._card.appendChild(this._content); } if (!this._ispanel()) { (this._card as any).header = this._config.name ? this._config.name : 'Floor 3d'; } if (this._content && !this._renderer) { this.display3dmodel(); } console.log('First updated end'); } } private _render(): void { //render the model this._direction_light.position.set(this._camera.position.x, this._camera.position.y, this._camera.position.z); this._direction_light.rotation.set(this._camera.rotation.x, this._camera.rotation.y, this._camera.rotation.z); this._renderer.render(this._scene, this._camera); } private _getintersect(e: any): THREE.Intersection[] { const mouse: THREE.Vector2 = new THREE.Vector2(); mouse.x = (e.offsetX / this._content.clientWidth) * 2 - 1; mouse.y = -(e.offsetY / this._content.clientHeight) * 2 + 1; const raycaster: THREE.Raycaster = new THREE.Raycaster(); raycaster.setFromCamera(mouse, this._camera); const intersects: THREE.Intersection[] = raycaster.intersectObjects(this._scene.children, true); return intersects; } private _firevent(e: any): void { //double click on object to show the name const intersects = this._getintersect(e); if (intersects.length > 0 && intersects[0].object.name != '') { this._config.entities.forEach((entity, i) => { for (let j = 0; j < this._object_ids[i].objects.length; j++) { if (this._object_ids[i].objects[j].object_id == intersects[0].object.name) { if (this._config.entities[i].action) { switch (this._config.entities[i].action) { case "more-info": fireEvent(this, "hass-more-info", { entityId: entity.entity }); break; case "overlay": if (this._overlay) { this._overlay.textContent = entity.entity + ": " + this._hass.states[entity.entity].state } break; case "default": default: this._defaultaction(intersects); } return; } else { this._defaultaction(intersects); return; } } break; } }); } } private _defaultaction(intersects: THREE.Intersection[]): void { if (intersects.length > 0 && intersects[0].object.name != '') { if (getLovelace().editMode) { window.prompt('Object:', intersects[0].object.name); } else { this._config.entities.forEach((entity, i) => { if (entity.type3d == 'light' || entity.type3d == 'gesture' || entity.type3d == 'camera') { for (let j = 0; j < this._object_ids[i].objects.length; j++) { if (this._object_ids[i].objects[j].object_id == intersects[0].object.name) { if (entity.type3d == 'light') { this._hass.callService(entity.entity.split('.')[0], 'toggle', { entity_id: entity.entity, }); } else if (entity.type3d == 'gesture') { this._hass.callService(entity.gesture.domain, entity.gesture.service, { entity_id: entity.entity, }); } else if (entity.type3d == 'camera') { fireEvent(this, "hass-more-info", { entityId: entity.entity }); //this._hass.states[entity.entity].attributes["entity_picture"] } break; } } } }); } } else if (getLovelace().editMode) { window.prompt( 'YAML:', 'camera_position: { x: ' + this._camera.position.x + ', y: ' + this._camera.position.y + ', z: ' + this._camera.position.z + ' }\n' + 'camera_rotate: { x: ' + this._camera.rotation.x + ', y: ' + this._camera.rotation.y + ', z: ' + this._camera.rotation.z + ' }', ); } } private _performAction(e: any): void { //double click on object to show the name const mouse: THREE.Vector2 = new THREE.Vector2(); mouse.x = (e.offsetX / this._content.clientWidth) * 2 - 1; mouse.y = -(e.offsetY / this._content.clientHeight) * 2 + 1; const raycaster: THREE.Raycaster = new THREE.Raycaster(); raycaster.setFromCamera(mouse, this._camera); const intersects = this._getintersect(e); this._defaultaction(intersects); } private _zIndexChecker(): void { let centerX = (this._card.getBoundingClientRect().left + this._card.getBoundingClientRect().right) / 2; let centerY = (this._card.getBoundingClientRect().top + this._card.getBoundingClientRect().bottom) / 2; let topElement = this._haShadowRoot.elementFromPoint(centerX, centerY); if (topElement != null) { let topZIndex = this._getZIndex(topElement.shadowRoot.firstElementChild); let myZIndex = this._getZIndex(this._card); if (myZIndex != topZIndex) { if (!this._cardObscured) { this._cardObscured = true; if (this._to_animate) { console.log("Canvas Obscured; stopping animation"); this._clock = null; this._renderer.setAnimationLoop(null); } } } else { if (this._cardObscured) { this._cardObscured = false; if (this._to_animate) { console.log("Canvas visible again; starting animation"); this._clock = new THREE.Clock(); this._renderer.setAnimationLoop(() => this._rotateobjects()); } } } } } private _getZIndex(toCheck: any): string { let returnVal: string; returnVal = getComputedStyle(toCheck).getPropertyValue('--dialog-z-index'); if (returnVal == '') { returnVal = getComputedStyle(toCheck).getPropertyValue('z-index'); } if (returnVal == '' || returnVal == 'auto') { if (toCheck.parentNode.constructor.name == 'ShadowRoot') { return this._getZIndex(toCheck.parentNode.host); } else if (toCheck.parentNode.constructor.name == 'HTMLDocument') { return '0'; } else { return this._getZIndex(toCheck.parentNode); } } return returnVal; } private _resizeCanvasDebounce(): void { window.clearTimeout(this._resizeTimeout); this._resizeTimeout = window.setTimeout(() => { this._resizeCanvas(); }, 50); } private _resizeCanvas(): void { console.log('Resize canvas start'); if ( this._renderer.domElement.parentElement.clientWidth !== this._renderer.domElement.width || this._renderer.domElement.parentElement.clientHeight !== this._renderer.domElement.height ) { this._camera.aspect = this._renderer.domElement.parentElement.clientWidth / this._renderer.domElement.parentElement.clientHeight; this._camera.updateProjectionMatrix(); this._renderer.setSize( this._renderer.domElement.parentElement.clientWidth, this._renderer.domElement.parentElement.clientHeight, !this._issidebar(), ); this._renderer.render(this._scene, this._camera); } console.log('Resize canvas end'); } private _statewithtemplate(entity: Floor3dCardConfig): string { if (this._hass.states[entity.entity]) { let state = this._hass.states[entity.entity].state; if (entity.entity_template) { const trimmed = entity.entity_template.trim(); if (trimmed.substring(0, 3) === '[[[' && trimmed.slice(-3) === ']]]' && trimmed.includes('$entity')) { const normal = trimmed.slice(3, -3).replace(/\$entity/g, state); state = this._eval(normal); } } return state; } else { return ''; } } public set hass(hass: HomeAssistant) { //called by Home Assistant Lovelace when a change of state is detected in entities this._hass = hass; if (this._config.entities) { if (!this._states) { //prepares to save the state this._states = []; this._unit_of_measurement = []; this._color = []; this._brightness = []; this._lights = []; this._canvas = []; this._text = []; this._config.entities.forEach((entity) => { if (entity.entity !== '') { this._states.push(this._statewithtemplate(entity)); this._canvas.push(null); if (entity.type3d == 'text') { if (entity.text.attribute) { if (hass.states[entity.entity].attributes[entity.text.attribute]) { this._text.push(hass.states[entity.entity].attributes[entity.text.attribute]); } else { this._text.push(this._statewithtemplate(entity)); } } else { this._text.push(this._statewithtemplate(entity)); } } else { this._text.push(''); } if (entity.type3d == 'light') { this._lights.push(entity.object_id + '_light'); } else { this._lights.push(''); } let i = this._color.push([255, 255, 255]) - 1; if (hass.states[entity.entity].attributes['color_mode']) { if ((hass.states[entity.entity].attributes['color_mode'] = 'color_temp')) { this._color[i] = this._TemperatureToRGB(parseInt(hass.states[entity.entity].attributes['color_temp'])); } } if ((hass.states[entity.entity].attributes['color_mode'] = 'rgb')) { if (hass.states[entity.entity].attributes['rgb_color'] !== this._color[i]) { this._color[i] = hass.states[entity.entity].attributes['rgb_color']; } } let j = this._brightness.push(-1) - 1; if (hass.states[entity.entity].attributes['brightness']) { this._brightness[j] = hass.states[entity.entity].attributes['brightness']; } if (hass.states[entity.entity].attributes['unit_of_measurement']) { this._unit_of_measurement.push(hass.states[entity.entity].attributes['unit_of_measurement']); } else { this._unit_of_measurement.push(''); } } }); this._firstcall = false; } if (this._renderer && this._modelready) { let torerender = false; this._config.entities.forEach((entity, i) => { if (entity.entity !== '') { let state = this._statewithtemplate(entity); if (entity.type3d == 'light') { let toupdate = false; if (this._states[i] !== state) { this._states[i] = state; toupdate = true; } if (hass.states[entity.entity].attributes['color_mode']) { if ((hass.states[entity.entity].attributes['color_mode'] = 'color_temp')) { if ( this._TemperatureToRGB(parseInt(hass.states[entity.entity].attributes['color_temp'])) !== this._color[i] ) { toupdate = true; this._color[i] = this._TemperatureToRGB( parseInt(hass.states[entity.entity].attributes['color_temp']), ); } } if ((hass.states[entity.entity].attributes['color_mode'] = 'rgb')) { if (hass.states[entity.entity].attributes['rgb_color'] !== this._color[i]) { toupdate = true; this._color[i] = hass.states[entity.entity].attributes['rgb_color']; } } } if (hass.states[entity.entity].attributes['brightness']) { if (hass.states[entity.entity].attributes['brightness'] !== this._brightness[i]) { toupdate = true; this._brightness[i] = hass.states[entity.entity].attributes['brightness']; } } if (toupdate) { this._updatelight(entity, i); torerender = true; } } else if (entity.type3d == 'text') { let toupdate = false; if (entity.text.attribute) { if (hass.states[entity.entity].attributes[entity.text.attribute]) { if (this._text[i] != hass.states[entity.entity].attributes[entity.text.attribute]) { this._text[i] = hass.states[entity.entity].attributes[entity.text.attribute]; toupdate = true; } } else { this._text[i] = ''; toupdate = true; } } else { if (this._text[i] != this._statewithtemplate(entity)) { this._text[i] = this._statewithtemplate(entity); toupdate = true; } } if (this._canvas[i] && toupdate) { this._updatetext(entity, this._text[i], this._canvas[i], this._unit_of_measurement[i]); torerender = true; } } else if (entity.type3d == 'rotate') { this._states[i] = state; this._rotatecalc(entity, i); } else if (this._states[i] !== state) { this._states[i] = state; if (entity.type3d == 'color') { this._updatecolor(entity, i); torerender = true; } else if (entity.type3d == 'hide') { this._updatehide(entity, i); torerender = true; } else if (entity.type3d == 'show') { this._updateshow(entity, i); torerender = true; } else if (entity.type3d == 'door') { this._updatedoor(entity, i); torerender = true; } } } }); if (torerender) { this._render(); } } } } protected display3dmodel(): void { //load the model into the GL Renderer console.log('Start Build Renderer'); this._modelready = false; this._scene = new THREE.Scene(); if (this._config.backgroundColor && this._config.backgroundColor != '#000000') { this._scene.background = new THREE.Color(this._config.backgroundColor); } else { this._scene.background = new THREE.Color('#aaaaaa'); } this._camera = new THREE.PerspectiveCamera(45, 1, 0.1, 10000); this._ambient_light = new THREE.AmbientLight(0xffffff, 0.5); this._direction_light = new THREE.DirectionalLight(0xffffff, 0.5); this._direction_light.matrixAutoUpdate = true; this._direction_light.castShadow = false; this._scene.add(this._direction_light); this._scene.add(this._ambient_light); this._renderer = new THREE.WebGLRenderer({ antialias: true, logarithmicDepthBuffer: true }); this._maxtextureimage = this._renderer.context.getParameter( this._renderer.context.MAX_TEXTURE_IMAGE_UNITS ); console.log("Max Texture Image Units: " + this._maxtextureimage); console.log( "Max Texture Image Units: number of lights casting shadow should be less than the above number" ); this._renderer.domElement.style.width = '100%'; this._renderer.domElement.style.height = '100%'; this._renderer.domElement.style.display = 'block'; if (this._config.path && this._config.path != '') { let path = this._config.path; const lastChar = path.substr(-1); if (lastChar != '/') { path = path + '/'; } console.log('Path: ' + path); if (this._config.mtlfile && this._config.mtlfile != '') { const mtlLoader: MTLLoader = new MTLLoader(); mtlLoader.setPath(path); mtlLoader.load( this._config.mtlfile, this._onLoaded3DMaterials.bind(this), this._onLoadMaterialProgress.bind(this), function (error: ErrorEvent): void { throw new Error(error.error); }, ); } else { const objLoader: OBJLoader = new OBJLoader(); objLoader.load( path + this._config.objfile, this._onLoaded3DModel.bind(this), this._onLoadObjectProgress.bind(this), function (error: ErrorEvent): void { throw new Error(error.error); }, ); } } else { throw new Error('Path is empty'); } console.log('End Build Renderer'); } private _onLoadError(event: ErrorEvent): void { this._showError(event.error); } private _onLoadMaterialProgress(_progress: ProgressEvent): void { //progress function called at regular intervals during material loading process this._content.innerText = '1/2: ' + Math.round((_progress.loaded / _progress.total) * 100) + '%'; } private _onLoadObjectProgress(_progress: ProgressEvent): void { //progress function called at regular intervals during object loading process this._content.innerText = '2/2: ' + Math.round((_progress.loaded / _progress.total) * 100) + '%'; } private _onLoaded3DModel(object: THREE.Object3D): void { // Object Loaded Event: last root object passed to the function console.log('Object loaded start'); let model_array = []; this._bboxmodel = object; this._scene.add(this._bboxmodel); this._content.innerText = '2/2: 100%'; //this._scene.add(new THREE.AxesHelper(300)); if (this._config.shadow) { if (this._config.shadow == 'yes') { console.log('Shadow On'); this._renderer.shadowMap.enabled = true; this._bboxmodel.traverse(this._setShadow.bind(this)); } else { console.log('Shadow Off'); this._renderer.shadowMap.enabled = false; } } this._add3dObjects(); console.log('Object loaded end'); if (this._content && this._renderer) { this._modelready = true; console.log('Show canvas'); this._content.innerText = ''; this._content.appendChild(this._renderer.domElement); if (this._config.click == 'yes') { this._content.addEventListener('click', this._fireventListener); } this._content.addEventListener('dblclick', this._performActionListener); this._content.addEventListener('touchstart', this._performActionListener); this._setCamera(); this._controls = new OrbitControls(this._camera, this._renderer.domElement); this._controls.maxPolarAngle = (0.9 * Math.PI) / 2; this._controls.addEventListener('change', this._changeListener); this._renderer.setPixelRatio(window.devicePixelRatio); if (this._config.lock_camera == 'yes') { /* this._controls.enableRotate = false; this._controls.enableZoom = false; this._controls.enablePan = false; */ this._controls.enabled = false } if (this._config.overlay == 'yes') { console.log("Start config Overlay"); const overlay = document.createElement('div'); overlay.id = 'overlay'; overlay.className = 'overlay'; overlay.style.setProperty("position", "absolute"); if (this._config.overlay_alignment) { switch (this._config.overlay_alignment) { case 'top-left': overlay.style.setProperty("top", "0px"); overlay.style.setProperty("left", "0px"); break; case 'top-right': overlay.style.setProperty("top", "0px"); overlay.style.setProperty("right", "0px"); break; case 'bottom-left': overlay.style.setProperty("bottom", "0px"); overlay.style.setProperty("left", "0px"); break; case 'bottom-right': overlay.style.setProperty("bottom", "0px"); overlay.style.setProperty("right", "0px"); break; default: overlay.style.setProperty("top", "0px"); overlay.style.setProperty("left", "0px"); } } if (this._config.overlay_width) { overlay.style.setProperty("width", this._config.overlay_width + '%'); } else { overlay.style.setProperty("width", "33%"); } if (this._config.overlay_height) { overlay.style.setProperty("height", this._config.overlay_height + '%'); } else { overlay.style.setProperty("height", "20%"); } if (this._config.overlay_bgcolor) { overlay.style.setProperty("background-color", this._config.overlay_bgcolor); } else { overlay.style.setProperty("background-color", "transparent"); } if (this._config.overlay_fgcolor) { overlay.style.setProperty("color", this._config.overlay_fgcolor); } else { overlay.style.setProperty("color", "black"); } if (this._config.overlay_font) { overlay.style.fontFamily = this._config.overlay_font; } if (this._config.overlay_fontsize) { overlay.style.fontSize = this._config.overlay_fontsize; } overlay.style.setProperty("overflow", "hidden"); overlay.style.setProperty("white-space", "nowrap"); if (this._getZIndex(this._renderer.domElement.parentNode)) { overlay.style.setProperty("z-index", (Number(this._getZIndex(this._renderer.domElement.parentNode)) + 1).toString(10)); } else { overlay.style.setProperty("z-index", "999"); } (this._renderer.domElement.parentNode as HTMLElement).style.setProperty("position", "relative"); this._renderer.domElement.parentNode.appendChild(overlay); this._overlay = overlay; console.log("End config Overlay"); } // ambient and directional light if (this._hass.states[this._config.globalLightPower]) { if (!Number.isNaN(this._hass.states[this._config.globalLightPower].state)) { this._ambient_light.intensity = this._direction_light.intensity = Number( this._hass.states[this._config.globalLightPower].state, ); } } else { if (this._config.globalLightPower) { this._ambient_light.intensity = this._direction_light.intensity = Number(this._config.globalLightPower); } else { this._ambient_light.intensity = this._direction_light.intensity = 0.5; } } //first render this._render(); this._resizeCanvas(); this._zIndexInterval = window.setInterval(() => { this._zIndexChecker(); }, 250); if (this._ispanel() || this._issidebar()) { this._resizeObserver.observe(this._card); } } } private _setCamera(): void { const box: THREE.Box3 = new THREE.Box3().setFromObject(this._bboxmodel); this._modelX = this._bboxmodel.position.x = -(box.max.x - box.min.x) / 2; this._modelY = this._bboxmodel.position.y = -box.min.y; this._modelZ = this._bboxmodel.position.z = -(box.max.z - box.min.z) / 2; if (this._config.camera_position) { this._camera.position.set( this._config.camera_position.x, this._config.camera_position.y, this._config.camera_position.z, ); this._direction_light.position.set( this._config.camera_position.x, this._config.camera_position.y, this._config.camera_position.z, ); } else { this._camera.position.set(box.max.x * 1.3, box.max.y * 5, box.max.z * 1.3); this._direction_light.position.set(box.max.x * 1.3, box.max.y * 5, box.max.z * 1.3); } if (this._config.camera_rotate) { this._camera.rotation.set( this._config.camera_rotate.x, this._config.camera_rotate.y, this._config.camera_rotate.z, ); this._direction_light.rotation.set( this._config.camera_rotate.x, this._config.camera_rotate.y, this._config.camera_rotate.z, ); } else { this._camera.lookAt(box.max.multiplyScalar(0.5)); this._direction_light.lookAt(box.max.multiplyScalar(0.5)); } this._camera.updateProjectionMatrix() } private _setNoShadowLight(object: THREE.Object3D): void { object.receiveShadow = true; object.castShadow = false; return; } private _setShadow(object: THREE.Object3D): void { object.receiveShadow = true; object.castShadow = true; return; } private _onLoaded3DMaterials(materials: MTLLoader.MaterialCreator): void { // Materials Loaded Event: last root material passed to the function console.log('Material loaded start'); materials.preload(); let path = this._config.path; const lastChar = path.substr(-1); if (lastChar != '/') { path = path + '/'; } const objLoader: OBJLoader = new OBJLoader(); objLoader.setMaterials(materials); objLoader.load( path + this._config.objfile, this._onLoaded3DModel.bind(this), this._onLoadObjectProgress.bind(this), function (error: ErrorEvent): void { throw new Error(error.error); }, ); console.log('Material loaded end'); } private _add3dObjects(): void { // Add-Modify the objects bound to the entities in the card config console.log('Add Objects Start'); if (this._states && this._config.entities) { this._round_per_seconds = []; this._axis_to_rotate = []; this._rotation_state = []; this._rotation_index = []; this._pivot = []; this._axis_for_door = []; this._degrees = []; this._slidingdoor = []; this._objposition = []; this._slidingdoorposition = []; this._to_animate = false; this._config.entities.forEach((entity, i) => { this._objposition.push([0, 0, 0]); this._pivot.push(null); this._axis_for_door.push(null); this._degrees.push(0); this._slidingdoor.push(null); this._slidingdoorposition.push([]); if (entity.entity !== '') { if (entity.type3d == 'rotate') { //console.log("Start Add Rotate Object"); this._round_per_seconds.push(entity.rotate.round_per_second); this._axis_to_rotate.push(entity.rotate.axis); this._rotation_state.push(0); this._rotation_index.push(i); let bbox: THREE.Box3; let hinge: any; if (entity.rotate.hinge) { hinge = this._scene.getObjectByName(entity.rotate.hinge); } else { hinge = this._scene.getObjectByName(this._object_ids[i].objects[0].object_id); } bbox = new THREE.Box3().setFromObject(hinge); this._pivot[i] = new THREE.Vector3; this._pivot[i].subVectors(bbox.max, bbox.min).multiplyScalar(0.5); this._pivot[i].add(bbox.min); this._object_ids[i].objects.forEach(element => { let _obj: any = this._scene.getObjectByName(element.object_id); this._centerobjecttopivot(_obj, this._pivot[i]); _obj.geometry.applyMatrix4( new THREE.Matrix4().makeTranslation( -(this._pivot[i].x), -(this._pivot[i].y), -(this._pivot[i].z) ) ); }); //console.log("End Add Rotate Object"); } if (entity.type3d == 'door') { if (entity.door.doortype == "swing") { //console.log("Start Add Door Swing"); let position = new THREE.Vector3(); if (entity.door.hinge) { let hinge: THREE.Mesh = this._scene.getObjectByName(entity.door.hinge) as THREE.Mesh; hinge.geometry.computeBoundingBox(); let boundingBox = hinge.geometry.boundingBox; position.subVectors(boundingBox.max, boundingBox.min); switch (Math.max(position.x, position.y, position.z)) { case position.x: this._axis_for_door[i] = new THREE.Vector3(1, 0, 0); break; case position.z: this._axis_for_door[i] = new THREE.Vector3(0, 0, 1); break; case position.y: default: this._axis_for_door[i] = new THREE.Vector3(0, 1, 0); } position.multiplyScalar(0.5); position.add(boundingBox.min); position.applyMatrix4(hinge.matrixWorld); } else { let pane: THREE.Mesh; if (entity.door.pane) { pane = this._scene.getObjectByName(entity.door.pane) as THREE.Mesh; } else { pane = this._scene.getObjectByName(this._object_ids[i].objects[0].object_id) as THREE.Mesh; } pane.geometry.computeBoundingBox(); let boundingBox = pane.geometry.boundingBox; position.subVectors(boundingBox.max, boundingBox.min); if (entity.door.side) { switch (entity.door.side) { case "up": position.x = position.x / 2; position.z = position.z / 2; position.y = position.y; if (position.x > position.z) { this._axis_for_door[i] = new THREE.Vector3(1, 0, 0); } else { this._axis_for_door[i] = new THREE.Vector3(0, 0, 1); } break; case "down": position.x = position.x / 2; position.z = position.z / 2; position.y = 0; if (position.x > position.z) { this._axis_for_door[i] = new THREE.Vector3(1, 0, 0); } else { this._axis_for_door[i] = new THREE.Vector3(0, 0, 1); } break; case "left": if (position.x > position.z) { position.x = 0; position.z = position.z / 2; } else { position.z = 0; position.x = position.x / 2; } this._axis_for_door[i] = new THREE.Vector3(0, 1, 0); position.y = 0; break; case "right": if (position.x > position.z) { position.z = position.z / 2; } else { position.x = position.x / 2; } this._axis_for_door[i] = new THREE.Vector3(0, 1, 0); position.y = 0; break; } } position.add(boundingBox.min); position.applyMatrix4(pane.matrixWorld); } this._pivot[i] = position; this._degrees[i] = (entity.door.degrees) ? (entity.door.degrees) : 90; this._object_ids[i].objects.forEach(element => { let _obj: any = this._scene.getObjectByName(element.object_id); this._centerobjecttopivot(_obj, this._pivot[i]); _obj.geometry.applyMatrix4( new THREE.Matrix4().makeTranslation( -(this._pivot[i].x), -(this._pivot[i].y), -(this._pivot[i].z) ) ); }); //console.log("End Add Door Swing"); } else if (entity.door.doortype == "slide") { //console.log("Start Add Door Slide"); this._object_ids[i].objects.forEach((element) => { let _obj: any = this._scene.getObjectByName(element.object_id); let objbbox = new THREE.Box3().setFromObject(_obj); this._slidingdoorposition[i].push(objbbox.min); this._centerobjecttopivot(_obj, objbbox.min); _obj.geometry.applyMatrix4( new THREE.Matrix4().makeTranslation( -(objbbox.min.x), -(objbbox.min.y), -(objbbox.min.z) ) ); }); //console.log("End Add Door Slide"); } } if (entity.type3d == 'light') { // Add Virtual Light Objects this._object_ids[i].objects.forEach((element) => { const _foundobject: any = this._scene.getObjectByName(element.object_id); if (_foundobject) { const box: THREE.Box3 = new THREE.Box3(); box.setFromObject(_foundobject); const light: THREE.PointLight = new THREE.PointLight(new THREE.Color('#ffffff'), 0, 700, 2); let x: number, y: number, z: number; x = (box.max.x - box.min.x) / 2 + box.min.x; z = (box.max.z - box.min.z) / 2 + box.min.z; y = (box.max.y - box.min.y) / 2 + box.min.y; if (entity.light.vertical_alignment) { switch (entity.light.vertical_alignment) { case 'top': y = box.max.y; break; case 'middle': y = (box.max.y - box.min.y) / 2 + box.min.y; break; case 'bottom': y = box.min.y; break; } } this._bboxmodel.add(light); light.position.set(x, y, z); this._setNoShadowLight(_foundobject); _foundobject.traverseAncestors(this._setNoShadowLight.bind(this)); if (entity.light.shadow == "no") { light.castShadow = false; } else { light.castShadow = true; } light.name = element.object_id + '_light'; //this._updatelight(entity, this._states[i], this._lights[i], this._color[i], this._brightness[i]); } }); } if (entity.type3d == 'color') { // Clone Material to allow object color changes based on Color Conditions Objects let j = 0; this._object_ids[i].objects.forEach((element) => { let _foundobject: any = this._scene.getObjectByName(element.object_id); this._initialmaterial[i][j] = _foundobject.material; if (!Array.isArray(_foundobject.material)) { this._clonedmaterial[i][j] = _foundobject.material.clone(); } j = j + 1; }); } if (entity.type3d == 'text') { // Clone object to print the text this._object_ids[i].objects.forEach((element) => { let _foundobject: any = this._scene.getObjectByName(element.object_id); let box: THREE.Box3 = new THREE.Box3(); box.setFromObject(_foundobject); let _newobject = _foundobject.clone(); //(_newobject as Mesh).scale.set(1.005, 1.005, 1.005); _newobject.name = "f3dobj_" + _foundobject.name; this._bboxmodel.add(_newobject); }); } } }); this._config.entities.forEach((entity, i) => { if (entity.entity !== '') { if (entity.type3d == 'light') { this._updatelight(entity, i); } else if (entity.type3d == 'color') { this._updatecolor(entity, i); } else if (entity.type3d == 'hide') { this._updatehide(entity, i); } else if (entity.type3d == 'show') { this._updateshow(entity, i); } else if (entity.type3d == 'door') { this._updatedoor(entity, i); } else if (entity.type3d == 'text') { this._canvas[i] = this._createTextCanvas(entity, this._text[i], this._unit_of_measurement[i]); } else if (entity.type3d == 'rotate') { this._rotatecalc(entity, i); } } }); } console.log('Add 3D Object End'); } // manage all entity types private _createTextCanvas(entity, text: string, uom: string): HTMLCanvasElement { const canvas = document.createElement('canvas'); this._updateTextCanvas(entity, canvas, text + uom); return canvas; } private _updateTextCanvas(entity: Floor3dCardConfig, canvas: HTMLCanvasElement, text: string): void { const _foundobject: any = this._scene.getObjectByName("f3dobj_" + entity.object_id); const ctx = canvas.getContext('2d'); // Prepare the font to be able to measure let fontSize = 56; ctx.font = `${fontSize}px ${entity.text.font ? entity.text.font : 'monospace'}`; const textMetrics = ctx.measureText(text); let width = textMetrics.width; let height = fontSize; let perct = 1.0; if (entity.text.span) { perct = parseFloat(entity.text.span) / 100.0; } // Resize canvas to match text size width = width / perct; height = height / perct; canvas.width = width; canvas.height = height; canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; // Re-apply font since canvas is resized. ctx.font = `${fontSize}px ${entity.text.font ? entity.text.font : 'monospace'}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = entity.text.textbgcolor ? entity.text.textbgcolor : 'transparent'; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = entity.text.textfgcolor ? entity.text.textfgcolor : 'white'; ctx.fillText(text, width / 2, height / 2); const texture = new THREE.CanvasTexture(canvas); texture.repeat.set(1, 1); if (_foundobject instanceof Mesh) { if (((_foundobject as Mesh).material as THREE.MeshBasicMaterial).name.startsWith("f3dmat")) { ((_foundobject as Mesh).material as THREE.MeshBasicMaterial).map = texture; } else { const material = new THREE.MeshBasicMaterial({ map: texture, transparent: true }); material.name = "f3dmat" + _foundobject.name; (_foundobject as Mesh).material = material; } } } private _TemperatureToRGB(t: number): number[] { let temp = 10000 / t; //kelvins = 1,000,000/mired (and that /100) let r: number, g: number, b: number; let rgb: number[] = [0, 0, 0]; if (temp <= 66) { r = 255; g = temp; g = 99.470802 * Math.log(g) - 161.119568; if (temp <= 19) { b = 0; } else { b = temp - 10; b = 138.517731 * Math.log(b) - 305.044793; } } else { r = temp - 60; r = 329.698727 * Math.pow(r, -0.13320476); g = temp - 60; g = 288.12217 * Math.pow(g, -0.07551485); b = 255; } rgb = [Math.floor(r), Math.floor(g), Math.floor(b)]; return rgb; } private _RGBToHex(r: number, g: number, b: number): string { // RGB Color array to hex string converter let rs: string = r.toString(16); let gs: string = g.toString(16); let bs: string = b.toString(16); if (rs.length == 1) rs = '0' + rs; if (gs.length == 1) gs = '0' + gs; if (bs.length == 1) bs = '0' + bs; return '#' + rs + gs + bs; } private _updatetext(_item: Floor3dCardConfig, state: string, canvas: HTMLCanvasElement, uom: string): void { this._updateTextCanvas(_item, canvas, state + uom); } private _updatelight(item: Floor3dCardConfig, i: number): void { // Illuminate the light object when, for the bound device, one of its attribute gets modified in HA. See set hass property this._object_ids[i].objects.forEach((element) => { const light: any = this._scene.getObjectByName(element.object_id + '_light'); if (!light) { return; } let max: number; if (item.light.lumens) { max = item.light.lumens; } else { max = 800; } if (this._states[i] == 'on') { if (this._brightness[i] != -1) { light.intensity = 0.003 * max * (this._brightness[i] / 255); } else { light.intensity = 0.003 * max; } if (!this._color[i]) { light.color = new THREE.Color('#ffffff'); } else { light.color = new THREE.Color(this._RGBToHex(this._color[i][0], this._color[i][1], this._color[i][2])); } } else { light.intensity = 0; //light.color = new THREE.Color('#000000'); } }); } private _updatedoor(item: Floor3dCardConfig, i: number): void { // perform action of door objects const _obj: any = this._scene.getObjectByName(this._object_ids[i].objects[0].object_id); let door: THREE.Mesh; door = _obj; if (door) { if (item.door.doortype) { if (item.door.doortype == 'swing') { this._rotatedoorpivot(item, i); return; } else if (item.door.doortype == 'slide') { this._translatedoor(item, i, this._states[i]); return; } } } } private _centerobjecttopivot(object: THREE.Mesh, pivot: THREE.Vector3) { object.applyMatrix4( new THREE.Matrix4().makeTranslation( -(pivot.x), -(pivot.y), -(pivot.z) ) ); object.position.copy(pivot); } private _rotatedoorpivot(entity: Floor3dCardConfig, index: number) { this._object_ids[index].objects.forEach(element => { let _obj: any = this._scene.getObjectByName(element.object_id); //this._centerobjecttopivot(_obj, this._pivot[index]); if (this._states[index] == "on") { if (entity.door.direction == "inner") { //_obj.rotateOnAxis(this._axis_for_door[index], -Math.PI * this._degrees[index] / 180); if (this._axis_for_door[index].y == 1) { _obj.rotation.y = -Math.PI * this._degrees[index] / 180; } else if (this._axis_for_door[index].x == 1) { _obj.rotation.x = -Math.PI * this._degrees[index] / 180; } else if (this._axis_for_door[index].z == 1) { _obj.rotation.z = -Math.PI * this._degrees[index] / 180; } } else if (entity.door.direction == "outer") { //_obj.rotateOnAxis(this._axis_for_door[index], Math.PI * this._degrees[index] / 180); if (this._axis_for_door[index].y == 1) { _obj.rotation.y = Math.PI * this._degrees[index] / 180; } else if (this._axis_for_door[index].x == 1) { _obj.rotation.x = Math.PI * this._degrees[index] / 180; } else if (this._axis_for_door[index].z == 1) { _obj.rotation.z = Math.PI * this._degrees[index] / 180; } } } else { _obj.rotation.x = 0; _obj.rotation.y = 0; _obj.rotation.z = 0; } }); } private _rotatecalc(entity: Floor3dCardConfig, i: number) { let j = this._rotation_index.indexOf(i); //1 if the entity is on, 0 if the entity is off this._rotation_state[j] = (this._states[i] == 'on' ? 1 : 0); //If the entity is on and it has the 'percentage' attribute, convert the percentage integer //into a decimal and store it as the rotation state if (this._rotation_state[j] != 0 && this._hass.states[entity.entity].attributes['percentage']) { this._rotation_state[j] = this._hass.states[entity.entity].attributes['percentage'] / 100; } //If the entity is on and it is reversed, set the rotation state to the negative value of itself if ( this._rotation_state[j] != 0 && this._hass.states[entity.entity].attributes['direction'] && this._hass.states[entity.entity].attributes['direction'] == 'reverse' ) { this._rotation_state[j] = 0 - this._rotation_state[j]; } //If every rotating entity is stopped, disable animation if (this._rotation_state.every(item => item === 0)) { if (this._to_animate) { this._to_animate = false; this._clock = null; this._renderer.setAnimationLoop(null); } } //Otherwise, start an animation loop else if (!this._to_animate) { this._to_animate = true; this._clock = new THREE.Clock(); this._renderer.setAnimationLoop(() => this._rotateobjects()); } } private _rotateobjects() { let moveBy = this._clock.getDelta() * Math.PI * 2; this._rotation_state.forEach((state, index) => { if (state != 0) { this._object_ids[this._rotation_index[index]].objects.forEach(element => { let _obj = this._scene.getObjectByName(element.object_id); if (_obj) { switch (this._axis_to_rotate[index]) { case "x": _obj.rotation.x += this._round_per_seconds[index] * this._rotation_state[index] * moveBy; break; case "y": _obj.rotation.y += this._round_per_seconds[index] * this._rotation_state[index] * moveBy; break; case "z": _obj.rotation.z += this._round_per_seconds[index] * this._rotation_state[index] * moveBy; break; } } }); } }); this._renderer.render(this._scene, this._camera); } private _translatedoor(item: Floor3dCardConfig, index: number, doorstate: string) { //console.log("Translate Door Start"); let translate: THREE.Vector3 = new THREE.Vector3(0, 0, 0); let size: Vector3 = new THREE.Vector3(); let center: Vector3 = new THREE.Vector3(); let pane = this._scene.getObjectByName(item.door.pane); if (!pane) { pane = this._scene.getObjectByName(this._object_ids[index].objects[0].object_id); } let bbox = new THREE.Box3().setFromObject(pane); size.subVectors(bbox.max, bbox.min); let percentage: number; if (item.door.percentage) { percentage = item.door.percentage; } else { percentage = 100; } if (doorstate == 'off') { this._object_ids[index].objects.forEach((element, j) => { let _obj: any = this._scene.getObjectByName(element.object_id); _obj.position.set(this._slidingdoorposition[index][j].x, this._slidingdoorposition[index][j].y, this._slidingdoorposition[index][j].z); }); } else if (doorstate == 'on') { if (item.door.side == 'left') { if (size.x > size.z) { translate.z += 0; translate.x += -size.x * percentage / 100; translate.y = 0 } else { translate.z += -size.z * percentage / 100; translate.x += 0; translate.y += 0; } } else if (item.door.side == 'right') { if (size.x > size.z) { translate.z += 0; translate.x += +size.x * percentage / 100; translate.y += 0; } else { translate.z += +size.z * percentage / 100; translate.x += 0; translate.y += 0 } } else if (item.door.side == 'down') { translate.y += -size.y * percentage / 100; translate.x += 0; translate.z += 0; } else if (item.door.side == 'up') { translate.y += +size.y * percentage / 100; translate.x += 0; translate.z += 0; } this._object_ids[index].objects.forEach((element) => { let _obj: any = this._scene.getObjectByName(element.object_id); _obj.applyMatrix4( new THREE.Matrix4().makeTranslation( (translate.x), (translate.y), (translate.z) ) ); }); } } private _updatecolor(item: any, index: number): void { // Change the color of the object when, for the bound device, the state matches the condition let j = 0; this._object_ids[index].objects.forEach((element) => { let _object: any = this._scene.getObjectByName(element.object_id); if (_object) { let i: any; let defaultcolor = true; for (i in item.colorcondition) { if (this._states[index] == item.colorcondition[i].state) { const colorarray = item.colorcondition[i].color.split(','); let color = ''; if (colorarray.length == 3) { color = this._RGBToHex(Number(colorarray[0]), Number(colorarray[1]), Number(colorarray[2])); } else { color = item.colorcondition[i].color; } if (!Array.isArray(_object.material)) { _object.material = this._clonedmaterial[index][j]; _object.material.color.set(color); } defaultcolor = false; break; } } if (defaultcolor) { if (this._initialmaterial[index][j]) { _object.material = this._initialmaterial[index][j]; } } } j += 1; }); } private _updatehide(item: Floor3dCardConfig, index: number): void { // hide the object when the state is equal to the configured value this._object_ids[index].objects.forEach((element) => { const _object: any = this._scene.getObjectByName(element.object_id); if (_object) { if (this._states[index] == item.hide.state) { _object.visible = false; } else { _object.visible = true; } } }); } private _updateshow(item: Floor3dCardConfig, index: number): void { // hide the object when the state is equal to the configured value this._object_ids[index].objects.forEach((element) => { const _object: any = this._scene.getObjectByName(element.object_id); if (_object) { if (this._states[index] == item.show.state) { _object.visible = true; } else { _object.visible = false; } } }); } // end of manage entity types // https://lit-element.polymer-project.org/guide/lifecycle#shouldupdate protected shouldUpdate(_changedProps: PropertyValues): boolean { return true; //return hasConfigOrEntityChanged(this, _changedProps, false); } // https://lit-element.polymer-project.org/guide/templates protected render(): TemplateResult | void { if (this._config.show_error) { return this._showError(localize('common.show_error')); } let htmlHeight: string; if (this._ispanel()) htmlHeight = 'calc(100vh - var(--header-height))'; else htmlHeight = 'auto'; return html` <ha-card tabindex="0" .style=${`${this._config.style || 'overflow: hidden; width: auto; height: ' + htmlHeight + '; position: relative;'}`} id="${this._card_id}"> </ha-card> `; } private _handleAction(ev: ActionHandlerEvent): void { //not implemented to not interfere with the Action handler of the Three.js canvas object if (this.hass && this._config && ev.detail.action) { handleAction(this, this.hass, this._config, ev.detail.action); } } private _showWarning(warning: string): TemplateResult { return html`<hui-warning>${warning}</hui-warning>`; } private _showError(error: string): TemplateResult { const errorCard = document.createElement('hui-error-card'); errorCard.setConfig({ type: 'error', error, origConfig: this._config, }); return html`${errorCard}`; } // https://lit-element.polymer-project.org/guide/styles static get styles(): CSSResultGroup { return css``; } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { StaticSites } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { WebSiteManagementClient } from "../webSiteManagementClient"; import { StaticSiteARMResource, StaticSitesListNextOptionalParams, StaticSitesListOptionalParams, StaticSitesGetStaticSitesByResourceGroupNextOptionalParams, StaticSitesGetStaticSitesByResourceGroupOptionalParams, StaticSiteUserARMResource, StaticSitesListStaticSiteUsersNextOptionalParams, StaticSitesListStaticSiteUsersOptionalParams, StaticSiteBuildARMResource, StaticSitesGetStaticSiteBuildsNextOptionalParams, StaticSitesGetStaticSiteBuildsOptionalParams, StaticSiteFunctionOverviewARMResource, StaticSitesListStaticSiteBuildFunctionsNextOptionalParams, StaticSitesListStaticSiteBuildFunctionsOptionalParams, StaticSiteCustomDomainOverviewARMResource, StaticSitesListStaticSiteCustomDomainsNextOptionalParams, StaticSitesListStaticSiteCustomDomainsOptionalParams, StaticSitesListStaticSiteFunctionsNextOptionalParams, StaticSitesListStaticSiteFunctionsOptionalParams, StaticSitesListResponse, StaticSitesGetStaticSitesByResourceGroupResponse, StaticSitesGetStaticSiteOptionalParams, StaticSitesGetStaticSiteResponse, StaticSitesCreateOrUpdateStaticSiteOptionalParams, StaticSitesCreateOrUpdateStaticSiteResponse, StaticSitesDeleteStaticSiteOptionalParams, StaticSitePatchResource, StaticSitesUpdateStaticSiteOptionalParams, StaticSitesUpdateStaticSiteResponse, StaticSitesListStaticSiteUsersResponse, StaticSitesDeleteStaticSiteUserOptionalParams, StaticSitesUpdateStaticSiteUserOptionalParams, StaticSitesUpdateStaticSiteUserResponse, StaticSitesGetStaticSiteBuildsResponse, StaticSitesGetStaticSiteBuildOptionalParams, StaticSitesGetStaticSiteBuildResponse, StaticSitesDeleteStaticSiteBuildOptionalParams, StringDictionary, StaticSitesCreateOrUpdateStaticSiteBuildFunctionAppSettingsOptionalParams, StaticSitesCreateOrUpdateStaticSiteBuildFunctionAppSettingsResponse, StaticSitesListStaticSiteBuildFunctionsResponse, StaticSitesListStaticSiteBuildFunctionAppSettingsOptionalParams, StaticSitesListStaticSiteBuildFunctionAppSettingsResponse, StaticSitesCreateOrUpdateStaticSiteFunctionAppSettingsOptionalParams, StaticSitesCreateOrUpdateStaticSiteFunctionAppSettingsResponse, StaticSiteUserInvitationRequestResource, StaticSitesCreateUserRolesInvitationLinkOptionalParams, StaticSitesCreateUserRolesInvitationLinkResponse, StaticSitesListStaticSiteCustomDomainsResponse, StaticSitesCreateOrUpdateStaticSiteCustomDomainOptionalParams, StaticSitesCreateOrUpdateStaticSiteCustomDomainResponse, StaticSitesDeleteStaticSiteCustomDomainOptionalParams, StaticSitesValidateCustomDomainCanBeAddedToStaticSiteOptionalParams, StaticSitesDetachStaticSiteOptionalParams, StaticSitesListStaticSiteFunctionsResponse, StaticSitesListStaticSiteFunctionAppSettingsOptionalParams, StaticSitesListStaticSiteFunctionAppSettingsResponse, StaticSitesListStaticSiteSecretsOptionalParams, StaticSitesListStaticSiteSecretsResponse, StaticSiteResetPropertiesARMResource, StaticSitesResetStaticSiteApiKeyOptionalParams, StaticSitesListNextResponse, StaticSitesGetStaticSitesByResourceGroupNextResponse, StaticSitesListStaticSiteUsersNextResponse, StaticSitesGetStaticSiteBuildsNextResponse, StaticSitesListStaticSiteBuildFunctionsNextResponse, StaticSitesListStaticSiteCustomDomainsNextResponse, StaticSitesListStaticSiteFunctionsNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing StaticSites operations. */ export class StaticSitesImpl implements StaticSites { private readonly client: WebSiteManagementClient; /** * Initialize a new instance of the class StaticSites class. * @param client Reference to the service client */ constructor(client: WebSiteManagementClient) { this.client = client; } /** * Description for Get all Static Sites for a subscription. * @param options The options parameters. */ public list( options?: StaticSitesListOptionalParams ): PagedAsyncIterableIterator<StaticSiteARMResource> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: StaticSitesListOptionalParams ): AsyncIterableIterator<StaticSiteARMResource[]> { let result = await this._list(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( options?: StaticSitesListOptionalParams ): AsyncIterableIterator<StaticSiteARMResource> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * Description for Gets all static sites in the specified resource group. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param options The options parameters. */ public listStaticSitesByResourceGroup( resourceGroupName: string, options?: StaticSitesGetStaticSitesByResourceGroupOptionalParams ): PagedAsyncIterableIterator<StaticSiteARMResource> { const iter = this.getStaticSitesByResourceGroupPagingAll( resourceGroupName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getStaticSitesByResourceGroupPagingPage( resourceGroupName, options ); } }; } private async *getStaticSitesByResourceGroupPagingPage( resourceGroupName: string, options?: StaticSitesGetStaticSitesByResourceGroupOptionalParams ): AsyncIterableIterator<StaticSiteARMResource[]> { let result = await this._getStaticSitesByResourceGroup( resourceGroupName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getStaticSitesByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *getStaticSitesByResourceGroupPagingAll( resourceGroupName: string, options?: StaticSitesGetStaticSitesByResourceGroupOptionalParams ): AsyncIterableIterator<StaticSiteARMResource> { for await (const page of this.getStaticSitesByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Description for Gets the list of users of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param authprovider The auth provider for the users. * @param options The options parameters. */ public listStaticSiteUsers( resourceGroupName: string, name: string, authprovider: string, options?: StaticSitesListStaticSiteUsersOptionalParams ): PagedAsyncIterableIterator<StaticSiteUserARMResource> { const iter = this.listStaticSiteUsersPagingAll( resourceGroupName, name, authprovider, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listStaticSiteUsersPagingPage( resourceGroupName, name, authprovider, options ); } }; } private async *listStaticSiteUsersPagingPage( resourceGroupName: string, name: string, authprovider: string, options?: StaticSitesListStaticSiteUsersOptionalParams ): AsyncIterableIterator<StaticSiteUserARMResource[]> { let result = await this._listStaticSiteUsers( resourceGroupName, name, authprovider, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listStaticSiteUsersNext( resourceGroupName, name, authprovider, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listStaticSiteUsersPagingAll( resourceGroupName: string, name: string, authprovider: string, options?: StaticSitesListStaticSiteUsersOptionalParams ): AsyncIterableIterator<StaticSiteUserARMResource> { for await (const page of this.listStaticSiteUsersPagingPage( resourceGroupName, name, authprovider, options )) { yield* page; } } /** * Description for Gets all static site builds for a particular static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param options The options parameters. */ public listStaticSiteBuilds( resourceGroupName: string, name: string, options?: StaticSitesGetStaticSiteBuildsOptionalParams ): PagedAsyncIterableIterator<StaticSiteBuildARMResource> { const iter = this.getStaticSiteBuildsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.getStaticSiteBuildsPagingPage( resourceGroupName, name, options ); } }; } private async *getStaticSiteBuildsPagingPage( resourceGroupName: string, name: string, options?: StaticSitesGetStaticSiteBuildsOptionalParams ): AsyncIterableIterator<StaticSiteBuildARMResource[]> { let result = await this._getStaticSiteBuilds( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._getStaticSiteBuildsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *getStaticSiteBuildsPagingAll( resourceGroupName: string, name: string, options?: StaticSitesGetStaticSiteBuildsOptionalParams ): AsyncIterableIterator<StaticSiteBuildARMResource> { for await (const page of this.getStaticSiteBuildsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Gets the functions of a particular static site build. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param prId The stage site identifier. * @param options The options parameters. */ public listStaticSiteBuildFunctions( resourceGroupName: string, name: string, prId: string, options?: StaticSitesListStaticSiteBuildFunctionsOptionalParams ): PagedAsyncIterableIterator<StaticSiteFunctionOverviewARMResource> { const iter = this.listStaticSiteBuildFunctionsPagingAll( resourceGroupName, name, prId, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listStaticSiteBuildFunctionsPagingPage( resourceGroupName, name, prId, options ); } }; } private async *listStaticSiteBuildFunctionsPagingPage( resourceGroupName: string, name: string, prId: string, options?: StaticSitesListStaticSiteBuildFunctionsOptionalParams ): AsyncIterableIterator<StaticSiteFunctionOverviewARMResource[]> { let result = await this._listStaticSiteBuildFunctions( resourceGroupName, name, prId, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listStaticSiteBuildFunctionsNext( resourceGroupName, name, prId, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listStaticSiteBuildFunctionsPagingAll( resourceGroupName: string, name: string, prId: string, options?: StaticSitesListStaticSiteBuildFunctionsOptionalParams ): AsyncIterableIterator<StaticSiteFunctionOverviewARMResource> { for await (const page of this.listStaticSiteBuildFunctionsPagingPage( resourceGroupName, name, prId, options )) { yield* page; } } /** * Description for Gets all static site custom domains for a particular static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site resource to search in. * @param options The options parameters. */ public listStaticSiteCustomDomains( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteCustomDomainsOptionalParams ): PagedAsyncIterableIterator<StaticSiteCustomDomainOverviewARMResource> { const iter = this.listStaticSiteCustomDomainsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listStaticSiteCustomDomainsPagingPage( resourceGroupName, name, options ); } }; } private async *listStaticSiteCustomDomainsPagingPage( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteCustomDomainsOptionalParams ): AsyncIterableIterator<StaticSiteCustomDomainOverviewARMResource[]> { let result = await this._listStaticSiteCustomDomains( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listStaticSiteCustomDomainsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listStaticSiteCustomDomainsPagingAll( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteCustomDomainsOptionalParams ): AsyncIterableIterator<StaticSiteCustomDomainOverviewARMResource> { for await (const page of this.listStaticSiteCustomDomainsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Gets the functions of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param options The options parameters. */ public listStaticSiteFunctions( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteFunctionsOptionalParams ): PagedAsyncIterableIterator<StaticSiteFunctionOverviewARMResource> { const iter = this.listStaticSiteFunctionsPagingAll( resourceGroupName, name, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listStaticSiteFunctionsPagingPage( resourceGroupName, name, options ); } }; } private async *listStaticSiteFunctionsPagingPage( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteFunctionsOptionalParams ): AsyncIterableIterator<StaticSiteFunctionOverviewARMResource[]> { let result = await this._listStaticSiteFunctions( resourceGroupName, name, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listStaticSiteFunctionsNext( resourceGroupName, name, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listStaticSiteFunctionsPagingAll( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteFunctionsOptionalParams ): AsyncIterableIterator<StaticSiteFunctionOverviewARMResource> { for await (const page of this.listStaticSiteFunctionsPagingPage( resourceGroupName, name, options )) { yield* page; } } /** * Description for Get all Static Sites for a subscription. * @param options The options parameters. */ private _list( options?: StaticSitesListOptionalParams ): Promise<StaticSitesListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * Description for Gets all static sites in the specified resource group. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param options The options parameters. */ private _getStaticSitesByResourceGroup( resourceGroupName: string, options?: StaticSitesGetStaticSitesByResourceGroupOptionalParams ): Promise<StaticSitesGetStaticSitesByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, getStaticSitesByResourceGroupOperationSpec ); } /** * Description for Gets the details of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param options The options parameters. */ getStaticSite( resourceGroupName: string, name: string, options?: StaticSitesGetStaticSiteOptionalParams ): Promise<StaticSitesGetStaticSiteResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, getStaticSiteOperationSpec ); } /** * Description for Creates a new static site in an existing resource group, or updates an existing * static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site to create or update. * @param staticSiteEnvelope A JSON representation of the staticsite properties. See example. * @param options The options parameters. */ createOrUpdateStaticSite( resourceGroupName: string, name: string, staticSiteEnvelope: StaticSiteARMResource, options?: StaticSitesCreateOrUpdateStaticSiteOptionalParams ): Promise<StaticSitesCreateOrUpdateStaticSiteResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, staticSiteEnvelope, options }, createOrUpdateStaticSiteOperationSpec ); } /** * Description for Deletes a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site to delete. * @param options The options parameters. */ deleteStaticSite( resourceGroupName: string, name: string, options?: StaticSitesDeleteStaticSiteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, deleteStaticSiteOperationSpec ); } /** * Description for Creates a new static site in an existing resource group, or updates an existing * static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site to create or update. * @param staticSiteEnvelope A JSON representation of the staticsite properties. See example. * @param options The options parameters. */ updateStaticSite( resourceGroupName: string, name: string, staticSiteEnvelope: StaticSitePatchResource, options?: StaticSitesUpdateStaticSiteOptionalParams ): Promise<StaticSitesUpdateStaticSiteResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, staticSiteEnvelope, options }, updateStaticSiteOperationSpec ); } /** * Description for Gets the list of users of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param authprovider The auth provider for the users. * @param options The options parameters. */ private _listStaticSiteUsers( resourceGroupName: string, name: string, authprovider: string, options?: StaticSitesListStaticSiteUsersOptionalParams ): Promise<StaticSitesListStaticSiteUsersResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, authprovider, options }, listStaticSiteUsersOperationSpec ); } /** * Description for Deletes the user entry from the static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the staticsite. * @param authprovider The auth provider for this user. * @param userid The user id of the user. * @param options The options parameters. */ deleteStaticSiteUser( resourceGroupName: string, name: string, authprovider: string, userid: string, options?: StaticSitesDeleteStaticSiteUserOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, authprovider, userid, options }, deleteStaticSiteUserOperationSpec ); } /** * Description for Updates a user entry with the listed roles * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param authprovider The auth provider for this user. * @param userid The user id of the user. * @param staticSiteUserEnvelope A JSON representation of the StaticSiteUser properties. See example. * @param options The options parameters. */ updateStaticSiteUser( resourceGroupName: string, name: string, authprovider: string, userid: string, staticSiteUserEnvelope: StaticSiteUserARMResource, options?: StaticSitesUpdateStaticSiteUserOptionalParams ): Promise<StaticSitesUpdateStaticSiteUserResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, authprovider, userid, staticSiteUserEnvelope, options }, updateStaticSiteUserOperationSpec ); } /** * Description for Gets all static site builds for a particular static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param options The options parameters. */ private _getStaticSiteBuilds( resourceGroupName: string, name: string, options?: StaticSitesGetStaticSiteBuildsOptionalParams ): Promise<StaticSitesGetStaticSiteBuildsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, getStaticSiteBuildsOperationSpec ); } /** * Description for Gets the details of a static site build. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param prId The stage site identifier. * @param options The options parameters. */ getStaticSiteBuild( resourceGroupName: string, name: string, prId: string, options?: StaticSitesGetStaticSiteBuildOptionalParams ): Promise<StaticSitesGetStaticSiteBuildResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, prId, options }, getStaticSiteBuildOperationSpec ); } /** * Description for Deletes a static site build. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param prId The stage site identifier. * @param options The options parameters. */ deleteStaticSiteBuild( resourceGroupName: string, name: string, prId: string, options?: StaticSitesDeleteStaticSiteBuildOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, prId, options }, deleteStaticSiteBuildOperationSpec ); } /** * Description for Creates or updates the function app settings of a static site build. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param prId The stage site identifier. * @param appSettings String dictionary resource. * @param options The options parameters. */ createOrUpdateStaticSiteBuildFunctionAppSettings( resourceGroupName: string, name: string, prId: string, appSettings: StringDictionary, options?: StaticSitesCreateOrUpdateStaticSiteBuildFunctionAppSettingsOptionalParams ): Promise< StaticSitesCreateOrUpdateStaticSiteBuildFunctionAppSettingsResponse > { return this.client.sendOperationRequest( { resourceGroupName, name, prId, appSettings, options }, createOrUpdateStaticSiteBuildFunctionAppSettingsOperationSpec ); } /** * Description for Gets the functions of a particular static site build. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param prId The stage site identifier. * @param options The options parameters. */ private _listStaticSiteBuildFunctions( resourceGroupName: string, name: string, prId: string, options?: StaticSitesListStaticSiteBuildFunctionsOptionalParams ): Promise<StaticSitesListStaticSiteBuildFunctionsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, prId, options }, listStaticSiteBuildFunctionsOperationSpec ); } /** * Description for Gets the application settings of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param prId The stage site identifier. * @param options The options parameters. */ listStaticSiteBuildFunctionAppSettings( resourceGroupName: string, name: string, prId: string, options?: StaticSitesListStaticSiteBuildFunctionAppSettingsOptionalParams ): Promise<StaticSitesListStaticSiteBuildFunctionAppSettingsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, prId, options }, listStaticSiteBuildFunctionAppSettingsOperationSpec ); } /** * Description for Creates or updates the function app settings of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param appSettings String dictionary resource. * @param options The options parameters. */ createOrUpdateStaticSiteFunctionAppSettings( resourceGroupName: string, name: string, appSettings: StringDictionary, options?: StaticSitesCreateOrUpdateStaticSiteFunctionAppSettingsOptionalParams ): Promise<StaticSitesCreateOrUpdateStaticSiteFunctionAppSettingsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, appSettings, options }, createOrUpdateStaticSiteFunctionAppSettingsOperationSpec ); } /** * Description for Creates an invitation link for a user with the role * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param staticSiteUserRolesInvitationEnvelope Static sites user roles invitation resource. * @param options The options parameters. */ createUserRolesInvitationLink( resourceGroupName: string, name: string, staticSiteUserRolesInvitationEnvelope: StaticSiteUserInvitationRequestResource, options?: StaticSitesCreateUserRolesInvitationLinkOptionalParams ): Promise<StaticSitesCreateUserRolesInvitationLinkResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, staticSiteUserRolesInvitationEnvelope, options }, createUserRolesInvitationLinkOperationSpec ); } /** * Description for Gets all static site custom domains for a particular static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site resource to search in. * @param options The options parameters. */ private _listStaticSiteCustomDomains( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteCustomDomainsOptionalParams ): Promise<StaticSitesListStaticSiteCustomDomainsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listStaticSiteCustomDomainsOperationSpec ); } /** * Description for Creates a new static site custom domain in an existing resource group and static * site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param domainName The custom domain to create. * @param options The options parameters. */ createOrUpdateStaticSiteCustomDomain( resourceGroupName: string, name: string, domainName: string, options?: StaticSitesCreateOrUpdateStaticSiteCustomDomainOptionalParams ): Promise<StaticSitesCreateOrUpdateStaticSiteCustomDomainResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, domainName, options }, createOrUpdateStaticSiteCustomDomainOperationSpec ); } /** * Description for Deletes a custom domain. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param domainName The custom domain to delete. * @param options The options parameters. */ deleteStaticSiteCustomDomain( resourceGroupName: string, name: string, domainName: string, options?: StaticSitesDeleteStaticSiteCustomDomainOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, domainName, options }, deleteStaticSiteCustomDomainOperationSpec ); } /** * Description for Validates a particular custom domain can be added to a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param domainName The custom domain to validate. * @param options The options parameters. */ validateCustomDomainCanBeAddedToStaticSite( resourceGroupName: string, name: string, domainName: string, options?: StaticSitesValidateCustomDomainCanBeAddedToStaticSiteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, domainName, options }, validateCustomDomainCanBeAddedToStaticSiteOperationSpec ); } /** * Description for Detaches a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site to detach. * @param options The options parameters. */ detachStaticSite( resourceGroupName: string, name: string, options?: StaticSitesDetachStaticSiteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, detachStaticSiteOperationSpec ); } /** * Description for Gets the functions of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param options The options parameters. */ private _listStaticSiteFunctions( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteFunctionsOptionalParams ): Promise<StaticSitesListStaticSiteFunctionsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listStaticSiteFunctionsOperationSpec ); } /** * Description for Gets the application settings of a static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param options The options parameters. */ listStaticSiteFunctionAppSettings( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteFunctionAppSettingsOptionalParams ): Promise<StaticSitesListStaticSiteFunctionAppSettingsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listStaticSiteFunctionAppSettingsOperationSpec ); } /** * Description for Lists the secrets for an existing static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param options The options parameters. */ listStaticSiteSecrets( resourceGroupName: string, name: string, options?: StaticSitesListStaticSiteSecretsOptionalParams ): Promise<StaticSitesListStaticSiteSecretsResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, options }, listStaticSiteSecretsOperationSpec ); } /** * Description for Resets the api key for an existing static site. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param resetPropertiesEnvelope Static Site Reset Properties ARM resource. * @param options The options parameters. */ resetStaticSiteApiKey( resourceGroupName: string, name: string, resetPropertiesEnvelope: StaticSiteResetPropertiesARMResource, options?: StaticSitesResetStaticSiteApiKeyOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, name, resetPropertiesEnvelope, options }, resetStaticSiteApiKeyOperationSpec ); } /** * ListNext * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( nextLink: string, options?: StaticSitesListNextOptionalParams ): Promise<StaticSitesListNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listNextOperationSpec ); } /** * GetStaticSitesByResourceGroupNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param nextLink The nextLink from the previous successful call to the GetStaticSitesByResourceGroup * method. * @param options The options parameters. */ private _getStaticSitesByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: StaticSitesGetStaticSitesByResourceGroupNextOptionalParams ): Promise<StaticSitesGetStaticSitesByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, getStaticSitesByResourceGroupNextOperationSpec ); } /** * ListStaticSiteUsersNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param authprovider The auth provider for the users. * @param nextLink The nextLink from the previous successful call to the ListStaticSiteUsers method. * @param options The options parameters. */ private _listStaticSiteUsersNext( resourceGroupName: string, name: string, authprovider: string, nextLink: string, options?: StaticSitesListStaticSiteUsersNextOptionalParams ): Promise<StaticSitesListStaticSiteUsersNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, authprovider, nextLink, options }, listStaticSiteUsersNextOperationSpec ); } /** * GetStaticSiteBuildsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param nextLink The nextLink from the previous successful call to the GetStaticSiteBuilds method. * @param options The options parameters. */ private _getStaticSiteBuildsNext( resourceGroupName: string, name: string, nextLink: string, options?: StaticSitesGetStaticSiteBuildsNextOptionalParams ): Promise<StaticSitesGetStaticSiteBuildsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, getStaticSiteBuildsNextOperationSpec ); } /** * ListStaticSiteBuildFunctionsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param prId The stage site identifier. * @param nextLink The nextLink from the previous successful call to the ListStaticSiteBuildFunctions * method. * @param options The options parameters. */ private _listStaticSiteBuildFunctionsNext( resourceGroupName: string, name: string, prId: string, nextLink: string, options?: StaticSitesListStaticSiteBuildFunctionsNextOptionalParams ): Promise<StaticSitesListStaticSiteBuildFunctionsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, prId, nextLink, options }, listStaticSiteBuildFunctionsNextOperationSpec ); } /** * ListStaticSiteCustomDomainsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site resource to search in. * @param nextLink The nextLink from the previous successful call to the ListStaticSiteCustomDomains * method. * @param options The options parameters. */ private _listStaticSiteCustomDomainsNext( resourceGroupName: string, name: string, nextLink: string, options?: StaticSitesListStaticSiteCustomDomainsNextOptionalParams ): Promise<StaticSitesListStaticSiteCustomDomainsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listStaticSiteCustomDomainsNextOperationSpec ); } /** * ListStaticSiteFunctionsNext * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the static site. * @param nextLink The nextLink from the previous successful call to the ListStaticSiteFunctions * method. * @param options The options parameters. */ private _listStaticSiteFunctionsNext( resourceGroupName: string, name: string, nextLink: string, options?: StaticSitesListStaticSiteFunctionsNextOptionalParams ): Promise<StaticSitesListStaticSiteFunctionsNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, name, nextLink, options }, listStaticSiteFunctionsNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Web/staticSites", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const getStaticSitesByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const getStaticSiteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteARMResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateStaticSiteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.StaticSiteARMResource }, 202: { bodyMapper: Mappers.StaticSiteARMResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.staticSiteEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteStaticSiteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}", httpMethod: "DELETE", responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const updateStaticSiteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.StaticSiteARMResource }, 202: { bodyMapper: Mappers.StaticSiteARMResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.staticSiteEnvelope1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listStaticSiteUsersOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/authproviders/{authprovider}/listUsers", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.StaticSiteUserCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.authprovider ], headerParameters: [Parameters.accept], serializer }; const deleteStaticSiteUserOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/authproviders/{authprovider}/users/{userid}", httpMethod: "DELETE", responses: { 200: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.authprovider, Parameters.userid ], headerParameters: [Parameters.accept], serializer }; const updateStaticSiteUserOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/authproviders/{authprovider}/users/{userid}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.StaticSiteUserARMResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.staticSiteUserEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.authprovider, Parameters.userid ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getStaticSiteBuildsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/builds", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteBuildCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const getStaticSiteBuildOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/builds/{prId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteBuildARMResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.prId ], headerParameters: [Parameters.accept], serializer }; const deleteStaticSiteBuildOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/builds/{prId}", httpMethod: "DELETE", responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.prId ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateStaticSiteBuildFunctionAppSettingsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/builds/{prId}/config/functionappsettings", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.StringDictionary }, 202: { bodyMapper: Mappers.StringDictionary }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.appSettings, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.prId ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listStaticSiteBuildFunctionsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/builds/{prId}/functions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteFunctionOverviewCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.prId ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteBuildFunctionAppSettingsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/builds/{prId}/listFunctionAppSettings", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.StringDictionary }, 202: { bodyMapper: Mappers.StringDictionary }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.prId ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateStaticSiteFunctionAppSettingsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/config/functionappsettings", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.StringDictionary }, 202: { bodyMapper: Mappers.StringDictionary }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.appSettings, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const createUserRolesInvitationLinkOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/createUserInvitation", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.StaticSiteUserInvitationResponseResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.staticSiteUserRolesInvitationEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listStaticSiteCustomDomainsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/customDomains", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteCustomDomainOverviewCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateStaticSiteCustomDomainOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/customDomains/{domainName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.StaticSiteCustomDomainOverviewARMResource }, 202: { bodyMapper: Mappers.StaticSiteCustomDomainOverviewARMResource }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.domainName ], headerParameters: [Parameters.accept], serializer }; const deleteStaticSiteCustomDomainOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/customDomains/{domainName}", httpMethod: "DELETE", responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.domainName ], headerParameters: [Parameters.accept], serializer }; const validateCustomDomainCanBeAddedToStaticSiteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/customDomains/{domainName}/validate", httpMethod: "POST", responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.domainName ], headerParameters: [Parameters.accept], serializer }; const detachStaticSiteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/detach", httpMethod: "POST", responses: { 200: {}, 202: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteFunctionsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/functions", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteFunctionOverviewCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteFunctionAppSettingsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/listFunctionAppSettings", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.StringDictionary }, 202: { bodyMapper: Mappers.StringDictionary }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteSecretsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/listSecrets", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.StringDictionary }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept], serializer }; const resetStaticSiteApiKeyOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/staticSites/{name}/resetapikey", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.DefaultErrorResponse } }, requestBody: Parameters.resetPropertiesEnvelope, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const getStaticSitesByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteUsersNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteUserCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink, Parameters.authprovider ], headerParameters: [Parameters.accept], serializer }; const getStaticSiteBuildsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteBuildCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteBuildFunctionsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteFunctionOverviewCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink, Parameters.prId ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteCustomDomainsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteCustomDomainOverviewCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listStaticSiteFunctionsNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.StaticSiteFunctionOverviewCollection }, default: { bodyMapper: Mappers.DefaultErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.name, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import { Literal, NamedNode, Quad_Object } from "@rdfjs/types"; import { Thing, Url, UrlString } from "../interfaces"; import { internal_isValidUrl, Time } from "../datatypes"; import { internal_throwIfNotThing } from "./thing.internal"; import { removeAll } from "./remove"; import { isThing, ValidPropertyUrlExpectedError, ValidValueUrlExpectedError, } from "./thing"; import { addBoolean, addDatetime, addDate, addDecimal, addInteger, addLiteral, addNamedNode, addStringNoLocale, addStringWithLocale, addTerm, addTime, addUrl, } from "./add"; /** * Create a new Thing with existing values replaced by the given URL for the given Property. * * To preserve existing values, see [[addUrl]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set a URL value on. * @param property Property for which to set the given URL value. * @param url URL to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export const setUrl: SetOfType<Url | UrlString | Thing> = ( thing, property, url ) => { internal_throwIfNotThing(thing); if (!internal_isValidUrl(property)) { throw new ValidPropertyUrlExpectedError(property); } if (!isThing(url) && !internal_isValidUrl(url)) { throw new ValidValueUrlExpectedError(url); } return addUrl(removeAll(thing, property), property, url); }; /** @hidden Alias of [[setUrl]] for those who prefer IRI terminology. */ export const setIri = setUrl; /** * Create a new Thing with existing values replaced by the given boolean for the given Property. * * To preserve existing values, see [[addBoolean]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set a boolean value on. * @param property Property for which to set the given boolean value. * @param value Boolean to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export const setBoolean: SetOfType<boolean> = (thing, property, value) => { internal_throwIfNotThing(thing); return addBoolean(removeAll(thing, property), property, value); }; /** * Create a new Thing with existing values replaced by the given datetime for the given Property. * * To preserve existing values, see [[addDatetime]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set an datetime value on. * @param property Property for which to set the given datetime value. * @param value Datetime to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export const setDatetime: SetOfType<Date> = (thing, property, value) => { internal_throwIfNotThing(thing); return addDatetime(removeAll(thing, property), property, value); }; /** * Create a new Thing with existing values replaced by the given date for the given Property. * * To preserve existing values, see [[addDate]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set an date value on. * @param property Property for which to set the given date value. * @param value Date to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. * @since 1.10.0 */ export const setDate: SetOfType<Date> = (thing, property, value) => { internal_throwIfNotThing(thing); return addDate(removeAll(thing, property), property, value); }; /** * Create a new Thing with existing values replaced by the given time for the given Property. * * To preserve existing values, see [[addTime]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set an time value on. * @param property Property for which to set the given time value. * @param value time to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. * @since 1.10.0 */ export const setTime: SetOfType<Time> = (thing, property, value) => { internal_throwIfNotThing(thing); return addTime(removeAll(thing, property), property, value); }; /** * Create a new Thing with existing values replaced by the given decimal for the given Property. * * To preserve existing values, see [[addDecimal]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set a decimal value on. * @param property Property for which to set the given decimal value. * @param value Decimal to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export const setDecimal: SetOfType<number> = (thing, property, value) => { internal_throwIfNotThing(thing); return addDecimal(removeAll(thing, property), property, value); }; /** * Create a new Thing with existing values replaced by the given integer for the given Property. * * To preserve existing values, see [[addInteger]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set an integer value on. * @param property Property for which to set the given integer value. * @param value Integer to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export const setInteger: SetOfType<number> = (thing, property, value) => { internal_throwIfNotThing(thing); return addInteger(removeAll(thing, property), property, value); }; /** * Create a new Thing with existing values replaced by the given English string for the given * Property. * * To preserve existing values, see [[addStringEnglish]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set a localised string value on. * @param property Property for which to set the given localised string value. * @param value Localised string to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. * @since 1.13.0 */ export function setStringEnglish<T extends Thing>( thing: T, property: Url | UrlString, value: string ): T { return setStringWithLocale(thing, property, value, "en"); } /** * Create a new Thing with existing values replaced by the given localised string for the given Property. * * To preserve existing values, see [[addStringWithLocale]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set a localised string value on. * @param property Property for which to set the given localised string value. * @param value Localised string to set on `thing` for the given `property`. * @param locale Locale of the added string. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export function setStringWithLocale<T extends Thing>( thing: T, property: Url | UrlString, value: string, locale: string ): T { internal_throwIfNotThing(thing); return addStringWithLocale( removeAll(thing, property), property, value, locale ); } /** * Create a new Thing with existing values replaced by the given unlocalised string for the given Property. * * To preserve existing values, see [[addStringNoLocale]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set an unlocalised string value on. * @param property Property for which to set the given unlocalised string value. * @param value Unlocalised string to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export const setStringNoLocale: SetOfType<string> = ( thing, property, value ) => { internal_throwIfNotThing(thing); return addStringNoLocale(removeAll(thing, property), property, value); }; /** * Create a new Thing with existing values replaced by the given Named Node for the given Property. * * This replaces existing values for the given Property. To preserve them, see [[addNamedNode]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @ignore This should not be needed due to the other set*() functions. If you do find yourself needing it, please file a feature request for your use case. * @param thing The [[Thing]] to set a NamedNode on. * @param property Property for which to set the value. * @param value The NamedNode to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export function setNamedNode<T extends Thing>( thing: T, property: Url | UrlString, value: NamedNode ): T { internal_throwIfNotThing(thing); return addNamedNode(removeAll(thing, property), property, value); } /** * Create a new Thing with existing values replaced by the given Literal for the given Property. * * This replaces existing values for the given Property. To preserve them, see [[addLiteral]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @ignore This should not be needed due to the other set*() functions. If you do find yourself needing it, please file a feature request for your use case. * @param thing The [[Thing]] to set a Literal on. * @param property Property for which to set the value. * @param value The Literal to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export function setLiteral<T extends Thing>( thing: T, property: Url | UrlString, value: Literal ): T { internal_throwIfNotThing(thing); return addLiteral(removeAll(thing, property), property, value); } /** * Creates a new Thing with existing values replaced by the given Term for the given Property. * * This replaces existing values for the given Property. To preserve them, see [[addTerm]]. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @ignore This should not be needed due to the other set*() functions. If you do find yourself needing it, please file a feature request for your use case. * @param thing The [[Thing]] to set a Term on. * @param property Property for which to set the value. * @param value The raw RDF/JS value to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. * @since 0.3.0 */ export function setTerm<T extends Thing>( thing: T, property: Url | UrlString, value: Quad_Object ): T { internal_throwIfNotThing(thing); if (!internal_isValidUrl(property)) { throw new ValidPropertyUrlExpectedError(property); } return addTerm(removeAll(thing, property), property, value); } /** * Create a new Thing with existing values replaced by the given value for the given Property. * * The original `thing` is not modified; this function returns a cloned Thing with updated values. * * @param thing Thing to set a value on. * @param property Property for which to set the given value. * @param value Value to set on `thing` for the given `property`. * @returns A new Thing equal to the input Thing with existing values replaced by the given value for the given Property. */ export type SetOfType<Type> = <T extends Thing>( thing: T, property: Url | UrlString, value: Type ) => T;
the_stack
import {ResourceBase} from '../resource' import {Value, List} from '../dataTypes' export class InforNexusConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: InforNexusConnectorProfileProperties) { Object.assign(this, properties) } } export class DynatraceConnectorProfileCredentials { ApiToken!: Value<string> constructor(properties: DynatraceConnectorProfileCredentials) { Object.assign(this, properties) } } export class MarketoConnectorProfileCredentials { ClientId!: Value<string> ClientSecret!: Value<string> AccessToken?: Value<string> ConnectorOAuthRequest?: ConnectorOAuthRequest constructor(properties: MarketoConnectorProfileCredentials) { Object.assign(this, properties) } } export class RedshiftConnectorProfileCredentials { Username!: Value<string> Password!: Value<string> constructor(properties: RedshiftConnectorProfileCredentials) { Object.assign(this, properties) } } export class ZendeskConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: ZendeskConnectorProfileProperties) { Object.assign(this, properties) } } export class GoogleAnalyticsConnectorProfileCredentials { ClientId!: Value<string> ClientSecret!: Value<string> AccessToken?: Value<string> RefreshToken?: Value<string> ConnectorOAuthRequest?: ConnectorOAuthRequest constructor(properties: GoogleAnalyticsConnectorProfileCredentials) { Object.assign(this, properties) } } export class DynatraceConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: DynatraceConnectorProfileProperties) { Object.assign(this, properties) } } export class SalesforceConnectorProfileCredentials { AccessToken?: Value<string> RefreshToken?: Value<string> ConnectorOAuthRequest?: ConnectorOAuthRequest ClientCredentialsArn?: Value<string> constructor(properties: SalesforceConnectorProfileCredentials) { Object.assign(this, properties) } } export class RedshiftConnectorProfileProperties { DatabaseUrl!: Value<string> BucketName!: Value<string> BucketPrefix?: Value<string> RoleArn!: Value<string> constructor(properties: RedshiftConnectorProfileProperties) { Object.assign(this, properties) } } export class ConnectorProfileCredentials { Amplitude?: AmplitudeConnectorProfileCredentials Datadog?: DatadogConnectorProfileCredentials Dynatrace?: DynatraceConnectorProfileCredentials GoogleAnalytics?: GoogleAnalyticsConnectorProfileCredentials InforNexus?: InforNexusConnectorProfileCredentials Marketo?: MarketoConnectorProfileCredentials Redshift?: RedshiftConnectorProfileCredentials Salesforce?: SalesforceConnectorProfileCredentials ServiceNow?: ServiceNowConnectorProfileCredentials Singular?: SingularConnectorProfileCredentials Slack?: SlackConnectorProfileCredentials Snowflake?: SnowflakeConnectorProfileCredentials Trendmicro?: TrendmicroConnectorProfileCredentials Veeva?: VeevaConnectorProfileCredentials Zendesk?: ZendeskConnectorProfileCredentials constructor(properties: ConnectorProfileCredentials) { Object.assign(this, properties) } } export class SingularConnectorProfileCredentials { ApiKey!: Value<string> constructor(properties: SingularConnectorProfileCredentials) { Object.assign(this, properties) } } export class ServiceNowConnectorProfileCredentials { Username!: Value<string> Password!: Value<string> constructor(properties: ServiceNowConnectorProfileCredentials) { Object.assign(this, properties) } } export class SnowflakeConnectorProfileCredentials { Username!: Value<string> Password!: Value<string> constructor(properties: SnowflakeConnectorProfileCredentials) { Object.assign(this, properties) } } export class ZendeskConnectorProfileCredentials { ClientId!: Value<string> ClientSecret!: Value<string> AccessToken?: Value<string> ConnectorOAuthRequest?: ConnectorOAuthRequest constructor(properties: ZendeskConnectorProfileCredentials) { Object.assign(this, properties) } } export class SnowflakeConnectorProfileProperties { Warehouse!: Value<string> Stage!: Value<string> BucketName!: Value<string> BucketPrefix?: Value<string> PrivateLinkServiceName?: Value<string> AccountName?: Value<string> Region?: Value<string> constructor(properties: SnowflakeConnectorProfileProperties) { Object.assign(this, properties) } } export class SalesforceConnectorProfileProperties { InstanceUrl?: Value<string> isSandboxEnvironment?: Value<boolean> constructor(properties: SalesforceConnectorProfileProperties) { Object.assign(this, properties) } } export class ConnectorProfileConfig { ConnectorProfileProperties?: ConnectorProfileProperties ConnectorProfileCredentials!: ConnectorProfileCredentials constructor(properties: ConnectorProfileConfig) { Object.assign(this, properties) } } export class AmplitudeConnectorProfileCredentials { ApiKey!: Value<string> SecretKey!: Value<string> constructor(properties: AmplitudeConnectorProfileCredentials) { Object.assign(this, properties) } } export class ConnectorOAuthRequest { AuthCode?: Value<string> RedirectUri?: Value<string> constructor(properties: ConnectorOAuthRequest) { Object.assign(this, properties) } } export class DatadogConnectorProfileCredentials { ApiKey!: Value<string> ApplicationKey!: Value<string> constructor(properties: DatadogConnectorProfileCredentials) { Object.assign(this, properties) } } export class SlackConnectorProfileCredentials { ClientId!: Value<string> ClientSecret!: Value<string> AccessToken?: Value<string> ConnectorOAuthRequest?: ConnectorOAuthRequest constructor(properties: SlackConnectorProfileCredentials) { Object.assign(this, properties) } } export class TrendmicroConnectorProfileCredentials { ApiSecretKey!: Value<string> constructor(properties: TrendmicroConnectorProfileCredentials) { Object.assign(this, properties) } } export class VeevaConnectorProfileCredentials { Username!: Value<string> Password!: Value<string> constructor(properties: VeevaConnectorProfileCredentials) { Object.assign(this, properties) } } export class VeevaConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: VeevaConnectorProfileProperties) { Object.assign(this, properties) } } export class SlackConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: SlackConnectorProfileProperties) { Object.assign(this, properties) } } export class MarketoConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: MarketoConnectorProfileProperties) { Object.assign(this, properties) } } export class InforNexusConnectorProfileCredentials { AccessKeyId!: Value<string> UserId!: Value<string> SecretAccessKey!: Value<string> Datakey!: Value<string> constructor(properties: InforNexusConnectorProfileCredentials) { Object.assign(this, properties) } } export class DatadogConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: DatadogConnectorProfileProperties) { Object.assign(this, properties) } } export class ServiceNowConnectorProfileProperties { InstanceUrl!: Value<string> constructor(properties: ServiceNowConnectorProfileProperties) { Object.assign(this, properties) } } export class ConnectorProfileProperties { Datadog?: DatadogConnectorProfileProperties Dynatrace?: DynatraceConnectorProfileProperties InforNexus?: InforNexusConnectorProfileProperties Marketo?: MarketoConnectorProfileProperties Redshift?: RedshiftConnectorProfileProperties Salesforce?: SalesforceConnectorProfileProperties ServiceNow?: ServiceNowConnectorProfileProperties Slack?: SlackConnectorProfileProperties Snowflake?: SnowflakeConnectorProfileProperties Veeva?: VeevaConnectorProfileProperties Zendesk?: ZendeskConnectorProfileProperties constructor(properties: ConnectorProfileProperties) { Object.assign(this, properties) } } export interface ConnectorProfileProperties { ConnectorProfileName: Value<string> KMSArn?: Value<string> ConnectorType: Value<string> ConnectionMode: Value<string> ConnectorProfileConfig?: ConnectorProfileConfig } export default class ConnectorProfile extends ResourceBase<ConnectorProfileProperties> { static InforNexusConnectorProfileProperties = InforNexusConnectorProfileProperties static DynatraceConnectorProfileCredentials = DynatraceConnectorProfileCredentials static MarketoConnectorProfileCredentials = MarketoConnectorProfileCredentials static RedshiftConnectorProfileCredentials = RedshiftConnectorProfileCredentials static ZendeskConnectorProfileProperties = ZendeskConnectorProfileProperties static GoogleAnalyticsConnectorProfileCredentials = GoogleAnalyticsConnectorProfileCredentials static DynatraceConnectorProfileProperties = DynatraceConnectorProfileProperties static SalesforceConnectorProfileCredentials = SalesforceConnectorProfileCredentials static RedshiftConnectorProfileProperties = RedshiftConnectorProfileProperties static ConnectorProfileCredentials = ConnectorProfileCredentials static SingularConnectorProfileCredentials = SingularConnectorProfileCredentials static ServiceNowConnectorProfileCredentials = ServiceNowConnectorProfileCredentials static SnowflakeConnectorProfileCredentials = SnowflakeConnectorProfileCredentials static ZendeskConnectorProfileCredentials = ZendeskConnectorProfileCredentials static SnowflakeConnectorProfileProperties = SnowflakeConnectorProfileProperties static SalesforceConnectorProfileProperties = SalesforceConnectorProfileProperties static ConnectorProfileConfig = ConnectorProfileConfig static AmplitudeConnectorProfileCredentials = AmplitudeConnectorProfileCredentials static ConnectorOAuthRequest = ConnectorOAuthRequest static DatadogConnectorProfileCredentials = DatadogConnectorProfileCredentials static SlackConnectorProfileCredentials = SlackConnectorProfileCredentials static TrendmicroConnectorProfileCredentials = TrendmicroConnectorProfileCredentials static VeevaConnectorProfileCredentials = VeevaConnectorProfileCredentials static VeevaConnectorProfileProperties = VeevaConnectorProfileProperties static SlackConnectorProfileProperties = SlackConnectorProfileProperties static MarketoConnectorProfileProperties = MarketoConnectorProfileProperties static InforNexusConnectorProfileCredentials = InforNexusConnectorProfileCredentials static DatadogConnectorProfileProperties = DatadogConnectorProfileProperties static ServiceNowConnectorProfileProperties = ServiceNowConnectorProfileProperties static ConnectorProfileProperties = ConnectorProfileProperties constructor(properties: ConnectorProfileProperties) { super('AWS::AppFlow::ConnectorProfile', properties) } }
the_stack
import * as DomUtil from '../common/dom_util'; import {Attribute} from '../enrich_mathml/enrich_mathml'; import {SemanticAttr, SemanticFont, SemanticRole, SemanticType} from '../semantic_tree/semantic_attr'; import {SemanticNode} from '../semantic_tree/semantic_node'; import {SemanticNodeFactory} from '../semantic_tree/semantic_node_factory'; import SemanticProcessor from '../semantic_tree/semantic_processor'; import {SemanticSkeleton, Sexp} from '../semantic_tree/semantic_skeleton'; import {SemanticTree} from '../semantic_tree/semantic_tree'; import * as SemanticUtil from '../semantic_tree/semantic_util'; import * as WalkerUtil from './walker_util'; // Note that reassemble tree will not give you exactly the original tree, as the // mathml nodes and mathml tree components can not be reconstructed. export class RebuildStree { /** * The node factory. */ public factory: SemanticNodeFactory = new SemanticNodeFactory(); /** * A dictionary to keep track of produced nodes. */ public nodeDict: {[key: string]: SemanticNode} = {}; /** * The semantic root node in the mml structure. */ public mmlRoot: Element; /** * The semantic root node in the mml structure. */ public streeRoot: SemanticNode; /** * The semantic tree to be computed. */ public stree: SemanticTree; /** * The xml representation of semantic tree. */ public xml: Element; /** * Adds external attributes if they exists. Recurses one level if we have a * leaf element with a none-text child. * @param snode The semantic node. * @param node The mml node. * @param leaf True if it is a leaf node. */ public static addAttributes(snode: SemanticNode, node: Element, leaf: boolean) { if (leaf && node.childNodes.length === 1 && node.childNodes[0].nodeType !== DomUtil.NodeType.TEXT_NODE) { SemanticUtil.addAttributes(snode, node.childNodes[0] as Element); } SemanticUtil.addAttributes(snode, node); } /** * Sets the text content of the semantic node. If no text content is available * or it is ignored, but an operator is given, it uses that. * @param snode The semantic node. * @param node The mml node. * @param ignore Ignores using text content. */ public static textContent(snode: SemanticNode, node: Element, ignore?: boolean) { if (!ignore && node.textContent) { snode.textContent = node.textContent; return; } let operator = WalkerUtil.splitAttribute( WalkerUtil.getAttribute(node, Attribute.OPERATOR)); if (operator.length > 1) { snode.textContent = operator[1]; } } /** * Tests if a collapsed attribute belongs to a punctuated index. * @param collapsed A skeleton structure. * @return True if the skeleton indicates a collapsed punctuated * element. */ public static isPunctuated(collapsed: Sexp): boolean { return !SemanticSkeleton.simpleCollapseStructure(collapsed) && (collapsed as any)[1] && SemanticSkeleton.contentCollapseStructure((collapsed as any)[1]); } /** * @param mathml The enriched MathML node. */ constructor(public mathml: Element) { this.mmlRoot = WalkerUtil.getSemanticRoot(mathml); this.streeRoot = this.assembleTree(this.mmlRoot); this.stree = SemanticTree.fromNode(this.streeRoot, this.mathml); this.xml = this.stree.xml(); SemanticProcessor.getInstance().setNodeFactory(this.factory); } /** * @return The rebuilt semantic tree. */ public getTree(): SemanticTree { return this.stree; } /** * Assembles the semantic tree from the data attributes of the MathML node. * @param node The MathML node. * @return The corresponding semantic tree node. */ public assembleTree(node: Element): SemanticNode { let snode = this.makeNode(node); let children = WalkerUtil.splitAttribute( WalkerUtil.getAttribute(node, Attribute.CHILDREN)); let content = WalkerUtil.splitAttribute( WalkerUtil.getAttribute(node, Attribute.CONTENT)); RebuildStree.addAttributes( snode, node, !(children.length || content.length)); if (content.length === 0 && children.length === 0) { RebuildStree.textContent(snode, node); return snode; } if (content.length > 0) { let fcontent = WalkerUtil.getBySemanticId(this.mathml, content[0]); if (fcontent) { RebuildStree.textContent(snode, fcontent, true); } } snode.contentNodes = content.map(id => this.setParent(id, snode)); snode.childNodes = children.map(id => this.setParent(id, snode)); let collapsed = WalkerUtil.getAttribute(node, Attribute.COLLAPSED); return collapsed ? this.postProcess(snode, collapsed) : snode; } /** * Creates a new semantic node from the data in the MathML node. * @param node The enriched MathML node. * @return The reconstructed semantic tree node. */ public makeNode(node: Element): SemanticNode { let type = WalkerUtil.getAttribute(node, Attribute.TYPE); let role = WalkerUtil.getAttribute(node, Attribute.ROLE); let font = WalkerUtil.getAttribute(node, Attribute.FONT); let annotation = WalkerUtil.getAttribute(node, Attribute.ANNOTATION) || ''; let id = WalkerUtil.getAttribute(node, Attribute.ID); let embellished = WalkerUtil.getAttribute(node, Attribute.EMBELLISHED); let fencepointer = WalkerUtil.getAttribute(node, Attribute.FENCEPOINTER); let snode = this.createNode(parseInt(id, 10)); snode.type = (type as SemanticType); snode.role = (role as SemanticRole); snode.font = font ? (font as SemanticFont) : SemanticFont.UNKNOWN; snode.parseAnnotation(annotation); if (fencepointer) { snode.fencePointer = fencepointer; } if (embellished) { snode.embellished = (embellished as SemanticType); } return snode; } /** * Creates a punctuation node containing an invisible comma. * @param id The id of the new node. * @return The newly created punctuation node. */ public makePunctuation(id: number): SemanticNode { let node = this.createNode(id); node.updateContent(SemanticAttr.invisibleComma()); node.role = SemanticRole.DUMMY; return node; } /** * Creates a punctuated node that serves as an index. * @param snode The semantic node that is being rebuilt. * @param collapsed A skeleton structure. * @param role The role of the new index node. */ // TODO (TS): any to Sexp! public makePunctuated( snode: SemanticNode, collapsed: any, role: SemanticRole) { let punctuated = this.createNode(collapsed[0]); punctuated.type = SemanticType.PUNCTUATED; punctuated.embellished = snode.embellished; punctuated.fencePointer = snode.fencePointer; punctuated.role = role; let cont = collapsed.splice(1, 1)[0].slice(1); punctuated.contentNodes = cont.map(this.makePunctuation.bind(this)); this.collapsedChildren_(collapsed); } /** * Creates an empty node that serves as an index. * @param snode The semantic node that is being rebuilt. * @param collapsed A skeleton structure. * @param role The role of the new index node. */ public makeEmpty(snode: SemanticNode, collapsed: number, role: SemanticRole) { let empty = this.createNode(collapsed); empty.type = SemanticType.EMPTY; empty.embellished = snode.embellished; empty.fencePointer = snode.fencePointer; empty.role = role; } /** * Creates an index node. * @param snode The semantic node that is being rebuilt. * @param collapsed A skeleton structure. * @param role The role of the new index node. */ public makeIndex( snode: SemanticNode, collapsed: Sexp, role: SemanticRole) { if (RebuildStree.isPunctuated(collapsed)) { this.makePunctuated(snode, collapsed, role); collapsed = (collapsed as any)[0]; return; } if (SemanticSkeleton.simpleCollapseStructure(collapsed) && !this.nodeDict[collapsed.toString()]) { this.makeEmpty(snode, (collapsed as number), role); } } /** * Rearranges semantic node if there is a collapse structure. * @param snode The semantic node. * @param collapsed The collapse structure. * @return The semantic node. */ public postProcess(snode: SemanticNode, collapsed: string): SemanticNode { let array = SemanticSkeleton.fromString(collapsed).array as any; // TODO (TS): Semantic types used as roles. if (((snode.type as any) as SemanticRole) === SemanticRole.SUBSUP) { let subscript = this.createNode(array[1][0]); subscript.type = SemanticType.SUBSCRIPT; subscript.role = SemanticRole.SUBSUP; snode.type = SemanticType.SUPERSCRIPT; subscript.embellished = snode.embellished; subscript.fencePointer = snode.fencePointer; this.makeIndex(snode, array[1][2], SemanticRole.RIGHTSUB); this.makeIndex(snode, array[2], SemanticRole.RIGHTSUPER); this.collapsedChildren_(array); return snode; } if (snode.type === SemanticType.SUBSCRIPT) { this.makeIndex(snode, array[2], SemanticRole.RIGHTSUB); this.collapsedChildren_(array); return snode; } if (snode.type === SemanticType.SUPERSCRIPT) { this.makeIndex(snode, array[2], SemanticRole.RIGHTSUPER); this.collapsedChildren_(array); return snode; } if (snode.type === SemanticType.TENSOR) { this.makeIndex(snode, array[2], SemanticRole.LEFTSUB); this.makeIndex(snode, array[3], SemanticRole.LEFTSUPER); this.makeIndex(snode, array[4], SemanticRole.RIGHTSUB); this.makeIndex(snode, array[5], SemanticRole.RIGHTSUPER); this.collapsedChildren_(array); return snode; } if (snode.type === SemanticType.PUNCTUATED) { if (RebuildStree.isPunctuated(array)) { let cont = array.splice(1, 1)[0].slice(1); snode.contentNodes = cont.map(this.makePunctuation.bind(this)); } return snode; } if (((snode.type as any) as SemanticRole) === SemanticRole.UNDEROVER) { let score = this.createNode(array[1][0]); if (snode.childNodes[1].role === SemanticRole.OVERACCENT) { score.type = SemanticType.OVERSCORE; snode.type = SemanticType.UNDERSCORE; } else { score.type = SemanticType.UNDERSCORE; snode.type = SemanticType.OVERSCORE; } score.role = SemanticRole.UNDEROVER; score.embellished = snode.embellished; score.fencePointer = snode.fencePointer; this.collapsedChildren_(array); return snode; } return snode; } /** * Creates a new semantic tree node and stores it. * @param id The id for that node. * @return The newly created node. */ public createNode(id: number): SemanticNode { let node = this.factory.makeNode(id); this.nodeDict[id.toString()] = node; return node; } /** * Recombines semantic nodes and children according to a given skeleton * structure. * @param collapsed Array of integer arrays. */ private collapsedChildren_(collapsed: Sexp) { let recurseCollapsed = (coll: any) => { let parent = this.nodeDict[coll[0]]; parent.childNodes = []; for (let j = 1, l = coll.length; j < l; j++) { let id = coll[j]; parent.childNodes.push( SemanticSkeleton.simpleCollapseStructure(id) ? this.nodeDict[id] : recurseCollapsed(id)); } return parent; }; recurseCollapsed(collapsed); } /** * Sets a parent for a node. * @param {string} id of the node. * @param {SemanticNode} snode The parent node. */ private setParent(id: string, snode: SemanticNode) { let mml = WalkerUtil.getBySemanticId(this.mathml, id); let sn = this.assembleTree(mml); sn.parent = snode; return sn; } }
the_stack
import { useEffect, useMemo, useState, useContext, useRef } from 'react'; import type { FormInstance } from 'antd'; import { Button, Collapse, Form, Popconfirm } from 'antd'; import { PlusOutlined, DeleteOutlined } from '@ant-design/icons'; import { getTimeZoneList } from './panelData'; import moment from 'moment'; import { CODE_TYPE, DATA_SOURCE_ENUM, FLINK_VERSIONS, formItemLayout, KAFKA_DATA_TYPE, } from '@/constant'; import classNames from 'classnames'; import stream from '@/api'; import { isAvro, isKafka } from '@/utils/is'; import { getColumnsByColumnsText } from '@/utils'; import SourceForm from './form'; import molecule from '@dtinsight/molecule'; import type { IDataSourceUsedInSyncProps, IFlinkSourceProps } from '@/interface'; import type { DefaultOptionType } from 'antd/lib/cascader'; import type { IRightBarComponentProps } from '@/services/rightBarService'; import { FormContext } from '@/services/rightBarService'; import './index.scss'; const { Panel } = Collapse; const DEFAULT_TYPE = DATA_SOURCE_ENUM.KAFKA_2X; /** * 创建源表的默认输入内容 */ const DEFAULT_INPUT_VALUE: IFormFieldProps[typeof NAME_FIELD][number] = { type: DEFAULT_TYPE, sourceId: undefined, topic: undefined, charset: CODE_TYPE.UTF_8, table: undefined, timeType: 1, timeTypeArr: [1], timeZone: ['Asia', 'Shanghai'], // 默认时区值 offset: 0, offsetUnit: 'SECOND', columnsText: undefined, parallelism: 1, offsetReset: 'latest', sourceDataType: KAFKA_DATA_TYPE.TYPE_JSON, }; /** * 表单收集的字段 */ export const NAME_FIELD = 'panelColumn'; interface IFormFieldProps { [NAME_FIELD]: Partial< Omit<IFlinkSourceProps, 'timeZone' | 'timestampOffset'> & { timeZone?: string[]; timestampOffset?: moment.Moment; } >[]; } export default function FlinkSourcePanel({ current }: IRightBarComponentProps) { const currentPage = current?.tab?.data || {}; const { form } = useContext(FormContext) as { form?: FormInstance<IFormFieldProps> }; const [panelActiveKey, setPanelActiveKey] = useState<string[]>([]); const [originOptionType, setOriginOptionType] = useState< Record<number, IDataSourceUsedInSyncProps[]> >({}); const [topicOptionType, setTopicOptionType] = useState<Record<number, string[]>>({}); // 时区数据 const [timeZoneData, setTimeZoneData] = useState<DefaultOptionType[]>([]); const isAddOrRemove = useRef(false); const initTimeZoneList = async () => { const list = await getTimeZoneList(); setTimeZoneData(list); }; // 获取数据源 const getTypeOriginData = async (type?: DATA_SOURCE_ENUM) => { if (type !== undefined) { const existData = originOptionType[type]; if (existData) { return; } const res = await stream.getTypeOriginData({ type }); if (res.code === 1) { // 没有新建对象来 setState,当有多个源表同时请求数据源的话,新建对象的话会导致旧对象会被新对象覆盖掉 setOriginOptionType((options) => ({ ...options, [type]: res.data })); } } }; const getTopicType = async (sourceId?: number) => { if (sourceId !== undefined) { // improve the performance const existTopic = topicOptionType[sourceId]; if (existTopic) { return; } const res = await stream.getTopicType({ sourceId }); if (res.code === 1) { setTopicOptionType((options) => ({ ...options, [sourceId]: res.data, })); } } }; /** * 添加或删除源表 * @param panelKey 删除的时候需要带上 panelKey */ const handlePanelChanged = (type: 'add' | 'delete', panelKey?: string) => { return new Promise<void>((resolve) => { if (type === 'add') { getTypeOriginData(DEFAULT_INPUT_VALUE.type); getTopicType(DEFAULT_INPUT_VALUE.sourceId); } else { const nextPanelActiveKey = panelActiveKey.filter((key) => { return panelKey !== key; }); setPanelActiveKey(nextPanelActiveKey); } // 记录下是否触发了添加或删除方法,用来在 handleFormValuesChange 进行标记 isAddOrRemove.current = true; resolve(); }); }; const handleSyncFormToTab = () => { const source = form?.getFieldsValue()[NAME_FIELD]; // 需要额外处理部分字段 const nextSource = source?.map((s) => { const next: Partial<IFlinkSourceProps> = { ...s, timeZone: s.timeZone?.join('/'), timestampOffset: s.timestampOffset?.valueOf(), }; return next; }); // 将表单的值保存至 tab 中 molecule.editor.updateTab({ id: current!.tab!.id, data: { ...current!.tab!.data, source: nextSource, }, }); }; const handleFormValuesChange = (changedValues: IFormFieldProps, values: IFormFieldProps) => { if (isAddOrRemove.current) { isAddOrRemove.current = false; // 如果是添加或者删除整个数据项同样触发该方法,但是我们仅仅希望这里只触发修改的方法 handleSyncFormToTab(); return; } // 当前正在修改的数据索引 const changeIndex = changedValues[NAME_FIELD].findIndex((col) => col); const changeKeys = Object.keys(changedValues[NAME_FIELD][changeIndex]); if (changeKeys.includes('type')) { const value = changedValues[NAME_FIELD][changeIndex].type; getTypeOriginData(value); const nextValues = { ...values }; nextValues[NAME_FIELD][changeIndex] = { ...DEFAULT_INPUT_VALUE, type: value }; if (isKafka(value)) { nextValues[NAME_FIELD][changeIndex].sourceDataType = value === DATA_SOURCE_ENUM.KAFKA_CONFLUENT ? KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT : KAFKA_DATA_TYPE.TYPE_JSON; } form?.setFieldsValue(nextValues); } if (changeKeys.includes('sourceId')) { const value = changedValues[NAME_FIELD][changeIndex].sourceId; getTopicType(value); const nextValues = { ...values }; nextValues[NAME_FIELD][changeIndex] = { ...DEFAULT_INPUT_VALUE, type: nextValues[NAME_FIELD][changeIndex].type, sourceDataType: nextValues[NAME_FIELD][changeIndex].sourceDataType, sourceId: value, }; form?.setFieldsValue(nextValues); } if (changeKeys.includes('columnsText')) { const value = changedValues[NAME_FIELD][changeIndex].columnsText; const cols = getColumnsByColumnsText(value); // timeColumn 是否需要重置 const timeColumnCheck = (columns: typeof cols) => { if (values[NAME_FIELD][changeIndex].timeColumn) { if ( !columns.find((c) => c.field === values[NAME_FIELD][changeIndex].timeColumn) ) { return undefined; } } return values[NAME_FIELD][changeIndex].timeColumn; }; const nextValues = { ...values }; nextValues[NAME_FIELD][changeIndex].timeColumn = timeColumnCheck(cols); form?.setFieldsValue(nextValues); } if (changeKeys.includes('sourceDataType')) { const value = changedValues[NAME_FIELD][changeIndex].sourceDataType; if (!isAvro(value)) { const nextValues = { ...values }; nextValues[NAME_FIELD][changeIndex].schemaInfo = undefined; form?.setFieldsValue(nextValues); } } if (changeKeys.includes('timeTypeArr')) { let value = changedValues[NAME_FIELD][changeIndex].timeTypeArr || []; // timeTypeArr 这个字段只有前端用,根据 timeTypeArr ,清空相应字段 // 不勾选 ProcTime,不传 procTime 名称字段 // 不勾选 EventTime,不传时间列、最大延迟时间字段 if (currentPage.componentVersion === FLINK_VERSIONS.FLINK_1_12) { const nextValues = { ...values }; const panel = nextValues[NAME_FIELD][changeIndex]; // 如果只勾选了 EventTime,则还需要同时勾选 ProcTime if (value.length === 1 && value[0] === 2) { value = [1, 2]; panel.timeTypeArr = [1, 2]; } if (!value.includes(1)) { panel.procTime = undefined; } if (!value.includes(2)) { panel.timeColumn = undefined; panel.offset = undefined; } form?.setFieldsValue(nextValues); } } if (changeKeys.includes('offsetReset')) { const nextValues = { ...values }; const panel = nextValues[NAME_FIELD][changeIndex]; panel.timestampOffset = undefined; panel.offsetValue = ''; form?.setFieldsValue(nextValues); } handleSyncFormToTab(); }; useEffect(() => { initTimeZoneList(); }, []); useEffect(() => { currentPage?.source?.forEach((s: IFlinkSourceProps) => { getTypeOriginData(s.type); getTopicType(s.sourceId); }); }, [current]); const initialValues = useMemo<IFormFieldProps>(() => { return { [NAME_FIELD]: (currentPage?.source as IFlinkSourceProps[]).map((s) => ({ ...s, timeZone: s.timeZone?.split('/'), timestampOffset: s.timestampOffset ? moment(s.timestampOffset) : undefined, })) || [], }; }, []); return ( <molecule.component.Scrollable> <div className="panel-content"> <Form<IFormFieldProps> {...formItemLayout} form={form} labelWrap onValuesChange={handleFormValuesChange} initialValues={initialValues} > <Form.List name={NAME_FIELD}> {(fields, { add, remove }) => ( <> <Collapse activeKey={panelActiveKey} bordered={false} onChange={(key) => setPanelActiveKey(key as string[])} destroyInactivePanel > {fields.map((field, index) => { const { sourceId, type, table } = form?.getFieldValue(NAME_FIELD)[index] || {}; return ( <Panel header={ <div className="input-panel-title"> <span>{` 源表 ${index + 1} ${ table ? `(${table})` : '' }`}</span> </div> } key={field.key.toString()} extra={ <Popconfirm placement="topLeft" title="你确定要删除此源表吗?" onConfirm={() => handlePanelChanged( 'delete', field.key.toString(), ).then(() => { remove(field.name); }) } {...{ onClick: (e: any) => { e.stopPropagation(); }, }} > <DeleteOutlined className={classNames('title-icon')} /> </Popconfirm> } style={{ position: 'relative' }} className="input-panel" > <SourceForm index={index} componentVersion={FLINK_VERSIONS.FLINK_1_12} topicOptionType={ topicOptionType[sourceId || -1] || [] } originOptionType={ originOptionType[type || -1] || [] } timeZoneData={timeZoneData} /> </Panel> ); })} </Collapse> <Button size="large" block onClick={() => handlePanelChanged('add').then(() => add({ ...DEFAULT_INPUT_VALUE }), ) } icon={<PlusOutlined />} > <span>添加源表</span> </Button> </> )} </Form.List> </Form> </div> </molecule.component.Scrollable> ); }
the_stack
import Button from '@material-ui/core/Button'; import Checkbox from '@material-ui/core/Checkbox'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogContentText from '@material-ui/core/DialogContentText'; import DialogTitle from '@material-ui/core/DialogTitle'; import FormControl from '@material-ui/core/FormControl'; import FormHelperText from '@material-ui/core/FormHelperText'; import Grid from '@material-ui/core/Grid'; import InputLabel from '@material-ui/core/InputLabel'; import ListItemText from '@material-ui/core/ListItemText'; import MenuItem from '@material-ui/core/MenuItem'; import MuiSelect from '@material-ui/core/Select'; import { makeStyles } from '@material-ui/core/styles'; import { Field, Form, Formik } from 'formik'; import { Select, TextField } from 'formik-material-ui'; import React from 'react'; import { useTranslation } from 'react-i18next'; import * as Yup from 'yup'; import { Channel, Package } from '../../api/apiDataTypes'; import { applicationsStore } from '../../stores/Stores'; import { ARCHES } from '../../utils/helpers'; import { REGEX_SEMVER } from '../../utils/regex'; const useStyles = makeStyles({ topSelect: { width: '10rem', }, }); function EditDialog(props: { data: any; show: boolean; create?: boolean; onHide: () => void }) { const classes = useStyles(); const [flatcarType, otherType] = [1, 4]; const [packageType, setPackageType] = React.useState( props.data.channel ? props.data.channel.type : flatcarType ); const [arch, setArch] = React.useState(props.data.channel ? props.data.channel.arch : 1); const { t } = useTranslation(); const isCreation = Boolean(props.create); function getFlatcarActionHash() { return props.data.channel.flatcar_action ? props.data.channel.flatcar_action.sha256 : ''; } function isFlatcarType(_type: number) { return _type === flatcarType; } function getChannelsNames(channelIds: string[]) { const channels = props.data.channels.filter((channel: Channel) => { return channelIds.includes(channel.id); }); return channels.map((channelObj: Channel) => { return channelObj.name; }); } function handlePackageTypeChange(event: React.ChangeEvent<{ name?: string; value: unknown }>) { setPackageType(event.target.value as number); } function handleArchChange(event: React.ChangeEvent<{ name?: string; value: unknown }>) { setArch(event.target.value as number); } //@todo add better types //@ts-ignore function handleSubmit(values, actions) { const data: Partial<Package> = { arch: typeof arch === 'string' ? parseInt(arch) : arch, filename: values.filename, description: values.description, url: values.url, version: values.version, type: packageType, size: values.size.toString(), hash: values.hash, application_id: isCreation && props.data.appID ? props.data.appID : props.data.channel.application_id, channels_blacklist: values.channelsBlacklist ? values.channelsBlacklist : [], }; if (isFlatcarType(packageType)) { data.flatcar_action = { sha256: values.flatcarHash }; } let pkgFunc: Promise<void>; if (isCreation) { pkgFunc = applicationsStore.createPackage(data); } else { pkgFunc = applicationsStore.updatePackage({ ...data, id: props.data.channel.id }); } pkgFunc .then(() => { props.onHide(); actions.setSubmitting(false); }) .catch(() => { actions.setSubmitting(false); actions.setStatus({ statusMessage: t( 'packages|Something went wrong, or the version you are trying to add already exists for the arch and package type. Check the form or try again later...' ), }); }); } function handleClose() { props.onHide(); } //@todo add better types //@ts-ignore function renderForm({ values, status, isSubmitting }) { const channels = props.data.channels ? props.data.channels : []; return ( <Form data-testid="package-edit-form"> <DialogContent> {status && status.statusMessage && ( <DialogContentText color="error">{status.statusMessage}</DialogContentText> )} <Grid container justify="space-between"> <Grid item> <FormControl margin="dense" className={classes.topSelect}> <InputLabel>Type</InputLabel> <MuiSelect value={packageType} onChange={handlePackageTypeChange}> <MenuItem value={otherType} key="other"> {t('packages|Other')} </MenuItem> <MenuItem value={flatcarType} key="flatcar"> {t('packages|Flatcar')} </MenuItem> </MuiSelect> </FormControl> </Grid> <Grid item> <FormControl margin="dense" fullWidth className={classes.topSelect} disabled={!isCreation} > <InputLabel>{t('packages|Architecture')}</InputLabel> <MuiSelect value={arch} onChange={handleArchChange}> {Object.keys(ARCHES).map((key: string) => { const archName = ARCHES[parseInt(key)]; return ( <MenuItem value={parseInt(key)} key={key}> {archName} </MenuItem> ); })} </MuiSelect> <FormHelperText>{t('packages|Cannot be changed once created.')}</FormHelperText> </FormControl> </Grid> </Grid> <Field name="url" component={TextField} margin="dense" label={t('packages|URL')} type="url" required fullWidth /> <Field name="filename" component={TextField} margin="dense" label={t('packages|Filename')} type="text" required fullWidth /> <Field name="description" component={TextField} margin="dense" label={t('packages|Description')} type="text" required fullWidth /> <Grid container justify="space-between" spacing={4}> <Grid item xs={6}> <Field name="version" component={TextField} margin="dense" label={t('packages|Version')} type="text" required helperText={t('packages|Use SemVer format (1.0.1)')} fullWidth /> </Grid> <Grid item xs={6}> <Field name="size" component={TextField} margin="dense" label={t('packages|Size')} type="number" required helperText={t('packages|In bytes')} fullWidth /> </Grid> </Grid> <Field name="hash" component={TextField} margin="dense" label={t('packages|Hash')} type="text" required helperText={t('packages|Tip: cat update.gz | openssl dgst -sha1 -binary | base64')} fullWidth /> {isFlatcarType(packageType) && ( <Field name="flatcarHash" component={TextField} margin="dense" label={t('packages|Flatcar Action SHA256')} type="text" required helperText={t('packages|Tip: cat update.gz | openssl dgst -sha256 -binary | base64')} fullWidth /> )} <FormControl margin="dense" fullWidth> <InputLabel>Channels Blacklist</InputLabel> <Field name="channelsBlacklist" component={Select} multiple renderValue={(selected: string[]) => getChannelsNames(selected).join(' / ')} > {channels .filter((channelItem: Channel) => channelItem.arch === arch) .map((packageItem: Channel) => { const label = packageItem.name; const isDisabled = !isCreation && packageItem.package && props.data.channel.version === packageItem.package.version; return ( <MenuItem value={packageItem.id} disabled={isDisabled} key={packageItem.id}> <Checkbox checked={values.channelsBlacklist.indexOf(packageItem.id) > -1} /> <ListItemText primary={label} secondary={ isDisabled ? t('packages|channel pointing to this package') : null } /> </MenuItem> ); })} </Field> <FormHelperText> Blacklisted channels cannot point to this package. <br /> Showing only channels with the same architecture ({ARCHES[arch]}). </FormHelperText> </FormControl> </DialogContent> <DialogActions> <Button onClick={handleClose} color="primary"> {t('frequent|Cancel')} </Button> <Button type="submit" disabled={isSubmitting} color="primary"> {isCreation ? t('frequent|Add') : t('frequent|Save')} </Button> </DialogActions> </Form> ); } const validation: { [key: string]: any; } = Yup.object().shape({ url: Yup.string().url(), filename: Yup.string() .max(100, t('packages|Must enter a valid filename (less than 100 characters)')) .required(t('frequent|Required')), // @todo: Validate whether the version already exists so we can provide // better feedback. version: Yup.string() .matches(REGEX_SEMVER, t('packages|Enter a valid semver (1.0.1)')) .required(t('frequent|Required')), size: Yup.number() .integer(t('packages|Must be an integer number')) .positive(t('packages|Must be a positive number')) .required(t('frequent|Required')), hash: Yup.string() .max(64, t('packages|Must be a valid hash (less than 64 characters)')) .required(t('frequent|Required')), }); let initialValues: { [key: string]: any } = { channelsBlacklist: [] }; if (!isCreation) { validation['flatcarHash'] = Yup.string() .max(64, t('packages|Must be a valid hash (less than 64 characters)')) .required(t('frequent|Required')); initialValues = { url: props.data.channel.url, filename: props.data.channel.filename, description: props.data.channel.description, version: props.data.channel.version, size: props.data.channel.size, hash: props.data.channel.hash, channelsBlacklist: props.data.channel.channels_blacklist ? props.data.channel.channels_blacklist : [], }; if (isFlatcarType(packageType)) { initialValues['flatcarHash'] = getFlatcarActionHash(); } } return ( <Dialog open={props.show} onClose={handleClose} aria-labelledby="form-dialog-title"> <DialogTitle> {isCreation ? t('packages|Add Package') : t('packages|Edit Package')} </DialogTitle> <Formik initialValues={initialValues} onSubmit={handleSubmit} validationSchema={validation} //@todo add better types //@ts-ignore render={renderForm} /> </Dialog> ); } export default EditDialog;
the_stack
import { BigIntLiteral, BooleanLiteral, NoSubstitutionTemplateLiteral, NullLiteral, NumericLiteral, RegularExpressionLiteral, StringLiteral, SyntaxKind, TemplateHead, TemplateMiddle, TemplateSpan, TemplateTail, } from 'typescript'; import { ILogger, } from '@aurelia/kernel'; import { Realm, ExecutionContext, } from '../realm.js'; import { $String, } from '../types/string.js'; import { $AnyNonEmpty, } from '../types/_shared.js'; import { $Object, } from '../types/object.js'; import { $Number, } from '../types/number.js'; import { $Null, } from '../types/null.js'; import { $Boolean, } from '../types/boolean.js'; import { I$Node, Context, $$AssignmentExpressionOrHigher, $assignmentExpression, $AssignmentExpressionNode, $AnyParentNode, $i, } from './_shared.js'; import { $$ESModuleOrScript, } from './modules.js'; import { $TemplateExpression, } from './expressions.js'; // #region Pseudo-literals export class $TemplateHead implements I$Node { public get $kind(): SyntaxKind.TemplateHead { return SyntaxKind.TemplateHead; } public constructor( public readonly node: TemplateHead, public readonly parent: $TemplateExpression, public readonly ctx: Context, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}.TemplateHead`, ) {} // http://www.ecma-international.org/ecma-262/#sec-template-literals-runtime-semantics-evaluation // 12.2.9.6 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $AnyNonEmpty { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.Evaluate(#${ctx.id})`); return intrinsics.undefined; // TODO: implement this } } export class $TemplateMiddle implements I$Node { public get $kind(): SyntaxKind.TemplateMiddle { return SyntaxKind.TemplateMiddle; } public constructor( public readonly node: TemplateMiddle, public readonly parent: $TemplateExpression | $TemplateSpan, public readonly ctx: Context, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}.TemplateMiddle`, ) {} // http://www.ecma-international.org/ecma-262/#sec-template-literals-runtime-semantics-evaluation // 12.2.9.6 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $AnyNonEmpty { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.Evaluate(#${ctx.id})`); return intrinsics.undefined; // TODO: implement this } } export class $TemplateTail implements I$Node { public get $kind(): SyntaxKind.TemplateTail { return SyntaxKind.TemplateTail; } public constructor( public readonly node: TemplateTail, public readonly parent: $TemplateExpression | $TemplateSpan, public readonly ctx: Context, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}.TemplateTail`, ) {} // http://www.ecma-international.org/ecma-262/#sec-template-literals-runtime-semantics-evaluation // 12.2.9.6 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $AnyNonEmpty { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.Evaluate(#${ctx.id})`); // TemplateSpans : TemplateTail // 1. Let tail be the TV of TemplateTail as defined in 11.8.6. // 2. Return the String value consisting of the code units of tail. return intrinsics.undefined; // TODO: implement this } } export class $TemplateSpan implements I$Node { public get $kind(): SyntaxKind.TemplateSpan { return SyntaxKind.TemplateSpan; } public readonly $expression: $$AssignmentExpressionOrHigher; public readonly $literal: $TemplateMiddle | $TemplateTail; public constructor( public readonly node: TemplateSpan, public readonly parent: $TemplateExpression, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.TemplateSpan`, ) { this.$expression = $assignmentExpression(node.expression as $AssignmentExpressionNode, this, ctx, -1); if (node.literal.kind === SyntaxKind.TemplateMiddle) { this.$literal = new $TemplateMiddle(node.literal, this, ctx); } else { this.$literal = new $TemplateTail(node.literal, this, ctx); } } // http://www.ecma-international.org/ecma-262/#sec-template-literals-runtime-semantics-evaluation // 12.2.9.6 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $AnyNonEmpty { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.Evaluate(#${ctx.id})`); // TemplateSpans : TemplateMiddleList TemplateTail // 1. Let head be the result of evaluating TemplateMiddleList. // 2. ReturnIfAbrupt(head). // 3. Let tail be the TV of TemplateTail as defined in 11.8.6. // 4. Return the string-concatenation of head and tail. // TemplateMiddleList : TemplateMiddle Expression // 1. Let head be the TV of TemplateMiddle as defined in 11.8.6. // 2. Let subRef be the result of evaluating Expression. // 3. Let sub be ? GetValue(subRef). // 4. Let middle be ? ToString(sub). // 5. Return the sequence of code units consisting of the code units of head followed by the elements of middle. // TemplateMiddleList : TemplateMiddleList TemplateMiddle Expression // 1. Let rest be the result of evaluating TemplateMiddleList. // 2. ReturnIfAbrupt(rest). // 3. Let middle be the TV of TemplateMiddle as defined in 11.8.6. // 4. Let subRef be the result of evaluating Expression. // 5. Let sub be ? GetValue(subRef). // 6. Let last be ? ToString(sub). // 7. Return the sequence of code units consisting of the elements of rest followed by the code units of middle followed by the elements of last. return intrinsics.undefined; // TODO: implement this } } // #endregion export class $NumericLiteral implements I$Node { public get $kind(): SyntaxKind.NumericLiteral { return SyntaxKind.NumericLiteral; } public readonly Value: $Number; // http://www.ecma-international.org/ecma-262/#sec-object-initializer-static-semantics-propname // 12.2.6.5 Static Semantics: PropName public readonly PropName: $String; // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredparenthesizedexpression // 12.2.1.1 Static Semantics: CoveredParenthesizedExpression public readonly CoveredParenthesizedExpression: $NumericLiteral = this; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-hasname // 12.2.1.2 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isfunctiondefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isidentifierref // 12.2.1.4 Static Semantics: IsIdentifierRef public readonly IsIdentifierRef: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-assignmenttargettype // 12.2.1.5 Static Semantics: AssignmentTargetType public readonly AssignmentTargetType: 'invalid' = 'invalid'; public constructor( public readonly node: NumericLiteral, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.NumericLiteral`, ) { const num = Number(node.text); this.PropName = new $String(realm, num.toString(), void 0, void 0, this); this.Value = new $Number(realm, num, void 0, void 0, this); } // http://www.ecma-international.org/ecma-262/#sec-literals-runtime-semantics-evaluation // 12.2.4.1 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $Number { ctx.checkTimeout(); // 1. Return the number whose value is MV of NumericLiteral as defined in 11.8.3. return this.Value; } // based on http://www.ecma-international.org/ecma-262/#sec-object-initializer-runtime-semantics-evaluation public EvaluatePropName( ctx: ExecutionContext, ): $String { ctx.checkTimeout(); return this.PropName; } } export class $BigIntLiteral implements I$Node { public get $kind(): SyntaxKind.BigIntLiteral { return SyntaxKind.BigIntLiteral; } // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredparenthesizedexpression // 12.2.1.1 Static Semantics: CoveredParenthesizedExpression public readonly CoveredParenthesizedExpression: $BigIntLiteral = this; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-hasname // 12.2.1.2 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isfunctiondefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isidentifierref // 12.2.1.4 Static Semantics: IsIdentifierRef public readonly IsIdentifierRef: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-assignmenttargettype // 12.2.1.5 Static Semantics: AssignmentTargetType public readonly AssignmentTargetType: 'invalid' = 'invalid'; public constructor( public readonly node: BigIntLiteral, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.BigIntLiteral`, ) {} public Evaluate( ctx: ExecutionContext, ): $Number { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; this.logger.debug(`${this.path}.Evaluate(#${ctx.id})`); return intrinsics['0']; // TODO: implement this } } export class $StringLiteral implements I$Node { public get $kind(): SyntaxKind.StringLiteral { return SyntaxKind.StringLiteral; } public readonly Value: $String; // http://www.ecma-international.org/ecma-262/#sec-string-literals-static-semantics-stringvalue // 11.8.4.1 Static Semantics: StringValue public readonly StringValue: $String; // http://www.ecma-international.org/ecma-262/#sec-object-initializer-static-semantics-propname // 12.2.6.5 Static Semantics: PropName public readonly PropName: $String; // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredparenthesizedexpression // 12.2.1.1 Static Semantics: CoveredParenthesizedExpression public readonly CoveredParenthesizedExpression: $StringLiteral = this; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-hasname // 12.2.1.2 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isfunctiondefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isidentifierref // 12.2.1.4 Static Semantics: IsIdentifierRef public readonly IsIdentifierRef: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-assignmenttargettype // 12.2.1.5 Static Semantics: AssignmentTargetType public readonly AssignmentTargetType: 'invalid' = 'invalid'; public constructor( public readonly node: StringLiteral, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.StringLiteral`, ) { const StringValue = this.StringValue = new $String(realm, node.text, void 0, void 0, this); this.PropName = StringValue; this.Value = StringValue; } // http://www.ecma-international.org/ecma-262/#sec-literals-runtime-semantics-evaluation // 12.2.4.1 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $String { ctx.checkTimeout(); // Literal : StringLiteral // 1. Return the StringValue of StringLiteral as defined in 11.8.4.1. return this.Value; } // based on http://www.ecma-international.org/ecma-262/#sec-object-initializer-runtime-semantics-evaluation public EvaluatePropName( ctx: ExecutionContext, ): $String { ctx.checkTimeout(); return this.PropName; } } export class $RegularExpressionLiteral implements I$Node { public get $kind(): SyntaxKind.RegularExpressionLiteral { return SyntaxKind.RegularExpressionLiteral; } // http://www.ecma-international.org/ecma-262/#sec-regexp-identifier-names-static-semantics-stringvalue // 21.2.1.6 Static Semantics: StringValue public readonly StringValue: string; // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredparenthesizedexpression // 12.2.1.1 Static Semantics: CoveredParenthesizedExpression public readonly CoveredParenthesizedExpression: $RegularExpressionLiteral = this; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-hasname // 12.2.1.2 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isfunctiondefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isidentifierref // 12.2.1.4 Static Semantics: IsIdentifierRef public readonly IsIdentifierRef: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-assignmenttargettype // 12.2.1.5 Static Semantics: AssignmentTargetType public readonly AssignmentTargetType: 'invalid' = 'invalid'; public constructor( public readonly node: RegularExpressionLiteral, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.RegularExpressionLiteral`, ) { this.StringValue = node.text; } // http://www.ecma-international.org/ecma-262/#sec-regular-expression-literals-runtime-semantics-evaluation // 12.2.8.2 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $Object { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // PrimaryExpression : RegularExpressionLiteral // 1. Let pattern be the String value consisting of the UTF16Encoding of each code point of BodyText of RegularExpressionLiteral. // 2. Let flags be the String value consisting of the UTF16Encoding of each code point of FlagText of RegularExpressionLiteral. // 3. Return RegExpCreate(pattern, flags). return intrinsics['%ObjectPrototype%']; // TODO: implement this } } export class $NoSubstitutionTemplateLiteral implements I$Node { public get $kind(): SyntaxKind.NoSubstitutionTemplateLiteral { return SyntaxKind.NoSubstitutionTemplateLiteral; } // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredparenthesizedexpression // 12.2.1.1 Static Semantics: CoveredParenthesizedExpression public readonly CoveredParenthesizedExpression: $NoSubstitutionTemplateLiteral = this; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-hasname // 12.2.1.2 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isfunctiondefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isidentifierref // 12.2.1.4 Static Semantics: IsIdentifierRef public readonly IsIdentifierRef: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-assignmenttargettype // 12.2.1.5 Static Semantics: AssignmentTargetType public readonly AssignmentTargetType: 'invalid' = 'invalid'; public constructor( public readonly node: NoSubstitutionTemplateLiteral, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.NoSubstitutionTemplateLiteral`, ) {} // http://www.ecma-international.org/ecma-262/#sec-template-literals-runtime-semantics-evaluation // 12.2.9.6 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $String { ctx.checkTimeout(); const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // TemplateLiteral : NoSubstitutionTemplate // 1. Return the String value whose code units are the elements of the TV of NoSubstitutionTemplate as defined in 11.8.6. return intrinsics['']; // TODO: implement this } } export class $NullLiteral implements I$Node { public get $kind(): SyntaxKind.NullKeyword { return SyntaxKind.NullKeyword; } public readonly Value: $Null; // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredparenthesizedexpression // 12.2.1.1 Static Semantics: CoveredParenthesizedExpression public readonly CoveredParenthesizedExpression: $NullLiteral = this; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-hasname // 12.2.1.2 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isfunctiondefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isidentifierref // 12.2.1.4 Static Semantics: IsIdentifierRef public readonly IsIdentifierRef: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-assignmenttargettype // 12.2.1.5 Static Semantics: AssignmentTargetType public readonly AssignmentTargetType: 'invalid' = 'invalid'; public constructor( public readonly node: NullLiteral, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.NullLiteral`, ) { this.Value = new $Null(realm, void 0, void 0, this); } // http://www.ecma-international.org/ecma-262/#sec-literals-runtime-semantics-evaluation // 12.2.4.1 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $Null { ctx.checkTimeout(); // Literal : NullLiteral // 1. Return null. return this.Value; } } export class $BooleanLiteral implements I$Node { public readonly $kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; public readonly Value: $Boolean; // http://www.ecma-international.org/ecma-262/#sec-static-semantics-coveredparenthesizedexpression // 12.2.1.1 Static Semantics: CoveredParenthesizedExpression public readonly CoveredParenthesizedExpression: $BooleanLiteral = this; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-hasname // 12.2.1.2 Static Semantics: HasName public readonly HasName: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isfunctiondefinition // 12.2.1.3 Static Semantics: IsFunctionDefinition public readonly IsFunctionDefinition: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-isidentifierref // 12.2.1.4 Static Semantics: IsIdentifierRef public readonly IsIdentifierRef: false = false; // http://www.ecma-international.org/ecma-262/#sec-semantics-static-semantics-assignmenttargettype // 12.2.1.5 Static Semantics: AssignmentTargetType public readonly AssignmentTargetType: 'invalid' = 'invalid'; public constructor( public readonly node: BooleanLiteral, public readonly parent: $AnyParentNode, public readonly ctx: Context, public readonly idx: number, public readonly mos: $$ESModuleOrScript = parent.mos, public readonly realm: Realm = parent.realm, public readonly depth: number = parent.depth + 1, public readonly logger: ILogger = parent.logger, public readonly path: string = `${parent.path}${$i(idx)}.BooleanLiteral`, ) { this.$kind = node.kind; this.Value = new $Boolean(realm, node.kind === SyntaxKind.TrueKeyword, void 0, void 0, this); } // http://www.ecma-international.org/ecma-262/#sec-literals-runtime-semantics-evaluation // 12.2.4.1 Runtime Semantics: Evaluation public Evaluate( ctx: ExecutionContext, ): $Boolean { ctx.checkTimeout(); // Literal : BooleanLiteral // 1. If BooleanLiteral is the token false, return false. // 2. If BooleanLiteral is the token true, return true. return this.Value; } }
the_stack
import * as os from "os"; import * as fs from "fs"; import * as path from "path"; import { Widgets, screen } from "neo-blessed"; import { Logger } from "../common/Logger"; import { BlessedPanel } from "./BlessedPanel"; import { FuncKeyBox } from "./FuncKeyBox"; import BottomFilesBox from "./BottomFileBox"; import { readerControl } from "../panel/readerControl"; import { Widget } from "./widget/Widget"; import { keyMappingExec, RefreshType, Hint, TerminalAllowKeys, Help, IHelpService } from "../config/KeyMapConfig"; import { BlessedMenu } from "./BlessedMenu"; import { BlessedMcd } from "./BlessedMcd"; import { BlessedEditor } from "./BlessedEditor"; import { CommandBox } from "./CommandBox"; import { exec } from "child_process"; import colors from "colors"; import selection, { Selection, ClipBoard } from "../panel/Selection"; import { ProgressFunc, ProgressResult, Reader } from "../common/Reader"; import { messageBox } from "./widget/MessageBox"; import { ProgressBox } from "./widget/ProgressBox"; import { StringUtils } from "../common/StringUtils"; import { Color } from "../common/Color"; import { inputBox } from "./widget/InputBox"; import { HintBox } from "./HintBox"; import { BlessedXterm } from "./BlessedXterm"; import { T } from "../common/Translation"; import { draw } from "./widget/BlessedDraw"; import { File } from "../common/File"; import { FileReader } from "../panel/FileReader"; import mainFrame from "./MainFrame"; import Configure from "../config/Configure"; import { ColorConfig } from "../config/ColorConfig"; const log = Logger("MainFrame"); let viewCount = 0; enum VIEW_TYPE { NORMAL = 0, VERTICAL_SPLIT = 1, HORIZONTAL_SPLIT = 2 } class ScrLockInfo { private _name: string; private _widget: Widget; private _time: number; constructor( name: string, widget: Widget = null ) { this._name = name; this._widget = widget; this._time = Date.now(); } get name() { return this._name; } get widget() { return this._widget; } isTimeOver() { return (Date.now() - this._time) > 1000; } toString() { return this._name; } setFocus() { if ( this.widget && this.widget instanceof Widget ) { log.debug( "setFocus() - %s", this.name ); this.widget.setFocus(); } else { log.debug( "NOT Focus !!! - %s", this.name ); } } } export abstract class BaseMainFrame implements IHelpService { protected screen: Widgets.Screen = null; protected viewType: VIEW_TYPE = VIEW_TYPE.NORMAL; protected baseWidget = null; protected blessedFrames: (BlessedMcd | BlessedPanel | BlessedXterm | BlessedEditor)[] = []; protected blessedMenu = null; protected funcKeyBox = null; protected bottomFilesBox: BottomFilesBox = null; protected hintBox = null; protected activeFrameNum = 0; protected commandBox: CommandBox = null; protected keyLockScreenArr: ScrLockInfo[] = []; constructor() {} viewName() { return "Common"; } public hasLock() { if ( this.keyLockScreenArr.length === 0 ) { return false; } else if ( this.keyLockScreenArr.length === 1 ) { const lockScreenItem = this.keyLockScreenArr[0]; if ( lockScreenItem.name === "keyEvent" && lockScreenItem.isTimeOver() ) { log.warn( "LOCK TIME OVER - keyLockRelase !!! - focused: %s", (this.screen.focused as any)?._widget); this.lockKeyRelease("keyEvent"); this.blessedFrames[this.activeFrameNum].setFocus(); return false; } } return true; } public hasLockAndLastFocus() { if ( this.keyLockScreenArr.length > 0 ) { process.nextTick( () => { this.screen.focusPop(); this.keyLockScreenArr[0].setFocus(); }); return true; } return false; } public lockKey(name: string, widget: Widget ) { const idx = this.keyLockScreenArr.findIndex( item => item.name === name ); if ( idx === -1 ) { log.info( "Key Lock: %s : %j ", name, this.keyLockScreenArr ); this.keyLockScreenArr.push( new ScrLockInfo(name, widget) ); } else { log.error( "Already Key Lock: %s : %j", name, this.keyLockScreenArr ); } } public lockKeyRelease(name: string) { const idx = this.keyLockScreenArr.findIndex( item => item.name === name ); if ( idx > -1 ) { const removedItem = this.keyLockScreenArr.splice(idx, 1); log.info( "Key Lock Release: %s : %j", removedItem, this.keyLockScreenArr ); } else { log.error( "Key Lock Relase: - Undefined [%s]", name ); } } protected async commandParsing( cmd: string, isInsideTerminal: boolean = false ): Promise<{ cmd: string; ask: boolean; prompt: boolean; background?: boolean; wait?: boolean; mterm?: boolean; root?: boolean; tmpDirRemoveFunc?: () => void; }> { const result = { cmd, ask: false, prompt: false, background: false, wait: false, mterm: false, root: false, tmpDirRemoveFunc: null }; if ( cmd ) { const panel = this.activePanel(); isInsideTerminal = isInsideTerminal || cmd.indexOf("%T") > -1; if ( panel instanceof BlessedPanel && panel.currentFile() ) { const wrap = (text) => { if ( os.platform() === "win32" ) { return `""${text}""`; } return isInsideTerminal ? `${text}` : `"${text}"`; }; let viewerFile = null; try { const viewerInfo = await this.getCurrentFileViewer( panel.currentFile() ); const { orgFile, tmpFile, endFunc } = viewerInfo || {}; viewerFile = tmpFile || orgFile || panel.currentFile(); result.tmpDirRemoveFunc = endFunc; } catch( e ) { log.error( e ); } /** %1,%F filename.ext (ex. test.txt) %N filename (ex. test) %E file extension name (ex. .ext) %S selected files (a.ext b.ext) %A current directory name(bin) %D execute MCD %Q ask before running. %P command text string edit before a script execution. %W Waiting after script execution. %B background execution %T execution over inside terminal %R root execution - linux, mac osx only (su - --command= ) %% % */ result.cmd = result.cmd.replace( /(%[1|F|N|E|S|A|D|Q|P|W|B|T|R])/g, (substr) => { if ( substr.match( /(%1|%F)/ ) ) { return wrap(viewerFile.fullname); } else if ( substr === "%N" ) { return wrap(path.parse(viewerFile.fullname).name); } else if ( substr === "%E" ) { return wrap(viewerFile.extname); } else if ( substr === "%S" ) { return panel.getSelectFiles().map(item => wrap(item.fullname)).join(" "); } else if ( substr === "%A" ) { return wrap(viewerFile.fullname); } else if ( substr === "%%" ) { return "%"; } else if ( substr === "%Q" ) { result.ask = true; return ""; } else if ( substr === "%B" ) { result.ask = true; return ""; } else if ( substr === "%P" ) { result.prompt = true; return ""; } else if ( substr === "%W" ) { result.wait = true; return ""; } else if ( substr === "%T" ) { result.mterm = true; return ""; } else if ( substr === "%R" ) { result.root = true; return ""; } return substr; }); } } log.debug( "commandParsing : %s", cmd ); return result; } viewRender() { const updateWidget = ( widget: Widget, opt ) => { widget.top = opt.top; widget.left = opt.left; widget.height = opt.height; widget.width = opt.width; widget.box.emit("resize"); widget.show(); }; const { width, height } = this.baseWidget; log.debug( "mainFrame: width [%d] height [%d]", width, height ); if ( this.viewType === VIEW_TYPE.NORMAL ) { const deActiveNum = (this.activeFrameNum + 1) % 2; this.blessedFrames[this.activeFrameNum].setBoxDraw(false); updateWidget( this.blessedFrames[this.activeFrameNum].getWidget(), { top: 1, left: 0, width: "100%", height: "100%-3" } ); this.blessedFrames[deActiveNum].hide(); } else if ( this.viewType === VIEW_TYPE.VERTICAL_SPLIT ) { this.blessedFrames[0].setBoxDraw(true); this.blessedFrames[1].setBoxDraw(true); updateWidget( this.blessedFrames[0].getWidget(), { top: 1, left: 0, width: "50%", height: "100%-3" } ); updateWidget( this.blessedFrames[1].getWidget(), { top: 1, left: "50%", width: "50%", height: "100%-3" } ); } else if ( this.viewType === VIEW_TYPE.HORIZONTAL_SPLIT ) { this.blessedFrames[0].setBoxDraw(false); this.blessedFrames[1].setBoxDraw(false); updateWidget( this.blessedFrames[0].getWidget(), { top: 1, left: 0, width: "100%", height: "50%-1" } ); updateWidget( this.blessedFrames[1].getWidget(), { top: "50%", left: 0, width: "100%", height: "50%-1" } ); } this.blessedFrames[this.activeFrameNum].setFocus(); if ( this.viewType === VIEW_TYPE.NORMAL && (this.screen.program as any).mouseEnabled ) { if (this.activeFocusObj() instanceof BlessedEditor || this.activeFocusObj() instanceof BlessedXterm) { this.screen.program.disableMouse(); } } else if ( !(this.screen.program as any).mouseEnabled ) { this.screen.program.enableMouse(); } } getLastPath() { try { return fs.readFileSync(os.homedir() + path.sep + ".m" + path.sep + "path", "utf8"); } catch ( e ) { log.error( e ); } return null; } async start() { this.screen = screen({ smartCSR: true, fullUnicode: true, dockBorders: false, useBCE: true, ignoreDockContrast: true, tabSize: 4, // debug: true, // dump: true, // log: process.env.HOME + "/.m/m2.log" }); this.screen.draw = (start, end) => { // log.debug( "draw: %d / %d", start, end ); draw.call( this.screen, start, end ); }; this.screen.enableMouse(); // eslint-disable-next-line @typescript-eslint/no-var-requires this.screen.title = "MDIR.js v" + require("../../package.json").version; this.baseWidget = new Widget( { parent: this.screen, left: 0, top: 0, width: "100%", height: "100%" } ); this.blessedMenu = new BlessedMenu({ parent: this.baseWidget }); this.funcKeyBox = new FuncKeyBox( { parent: this.baseWidget } ); this.bottomFilesBox = new BottomFilesBox( { parent: this.baseWidget } ); if ( Configure.instance().getOption("supportBgColorTransparent") === false ) { this.baseWidget.setColor(ColorConfig.instance().getBaseColor("default")); } this.blessedFrames = [ new BlessedPanel( { parent: this.baseWidget, viewCount: viewCount++ } ), new BlessedPanel( { parent: this.baseWidget, viewCount: viewCount++ } ) ]; this.hintBox = new HintBox( { parent: this.baseWidget } ); const lastPath = this.getLastPath(); for ( let i = 0; i < this.blessedFrames.length; i++ ) { const panel = this.blessedFrames[i]; if ( panel instanceof BlessedPanel ) { panel.setReader(readerControl("file")); //panel.getReader().onWatch( (event, filename) => this.onWatchDirectory(event, filename) ); try { await panel.read( i !== 0 ? (lastPath || ".") : ".", { allowThrow: true } ); } catch ( e ) { log.error( e ); await panel.read( "~" ); } } } if ( lastPath ) { this.viewType = VIEW_TYPE.VERTICAL_SPLIT; } this.viewRender(); this.eventStart(); this.screen.render(); } protected calledTime = Date.now(); onWatchDirectory( event, filename ) { log.debug( "onWatchDirectory [%s] [%s]", event, filename ); if ( Date.now() - this.calledTime > 1000 ) { if ( !this.hasLock() ) { process.nextTick( async () => { await this.refreshPromise(); this.execRefreshType( RefreshType.ALL ); this.calledTime = Date.now(); }); } } } eventStart() { this.screen.off("keypress"); this.screen.on("keypress", async (ch, keyInfo) => { if ( ch === "\u001c" && (global as any).debug ) { // Ctrl + | log.error( "force quit !!!" ); process.exit(0); return; } if ( this.hasLock() ) { log.debug( "_keyLockScreen !!! - %s", this.keyLockScreenArr.map( item => item.name )); log.debug( "current focus: %s", (this.screen.focused as any)?._widget ); return; } if ( this.commandBox ) { log.debug( "CommandBox running !!!" ); return; } const keyName = keyInfo.full || keyInfo.name; log.debug( "KEYPRESS [%s] - START", keyName ); const panel = this.activeFocusObj(); if ( !panel.hasFocus() ) { log.debug( "Not has FOCUS !!!" ); this.lockKey("keyEvent", panel); return; } const starTime = Date.now(); this.lockKey("keyEvent", panel); try { let searchBoxRefresh: RefreshType = RefreshType.NONE; if ( panel instanceof BlessedPanel || panel instanceof BlessedMcd ) { const result = await this.activeFocusObj().keyInputSearchFile(ch, keyInfo); if ( result === 1 ) { this.execRefreshType( RefreshType.OBJECT ); return; } else if ( result === -2 ) { searchBoxRefresh = RefreshType.ALL; } } const keyMappingExecute = async ( func?: () => RefreshType ) => { log.debug( "KEYPRESS - KEY START [%s] - (%dms)", keyInfo.name, Date.now() - starTime ); let type: RefreshType; try { let type: RefreshType = await keyMappingExec( panel, keyInfo ); if ( type === RefreshType.NONE ) { type = await keyMappingExec( this, keyInfo ); } if ( searchBoxRefresh === RefreshType.ALL ) { type = RefreshType.ALL; } if ( type !== RefreshType.NONE ) { this.execRefreshType( type ); } else { if ( func ) { type = func(); if ( searchBoxRefresh === RefreshType.ALL ) { type = RefreshType.ALL; } this.execRefreshType( type ); } } if ( panel.updateCursor ) { panel.updateCursor(); } } catch( e ) { log.error( e ); throw e; } finally { log.info( "KEYPRESS - KEY END [%s] - (%dms)", keyInfo.name, Date.now() - starTime ); } return type; }; if ( panel instanceof BlessedXterm ) { const keyPressFunc = () => { return panel.ptyKeyWrite(keyInfo); }; if ( TerminalAllowKeys.indexOf( keyName ) > -1 ) { await keyMappingExecute( keyPressFunc ); } else { keyPressFunc(); if ( panel.updateCursor ) { panel.updateCursor(); } } } else if ( panel instanceof BlessedEditor ) { await keyMappingExecute( () => { return panel.keyWrite( keyInfo ); }); } else { await keyMappingExecute(); } } catch ( e ) { log.error( "Event Exception: - [%s]", e.stack || e ); await messageBox( { parent: this.baseWidget, title: T("Error"), msg: e.stack || e, textAlign: "left", button: [ T("OK") ] }); } finally { this.lockKeyRelease("keyEvent"); } }); } execRefreshType( type: RefreshType ) { if ( type === RefreshType.ALL || type === RefreshType.ALL_NOFOCUS ) { log.info( "REFRESH - ALL - START"); this.screen.realloc(); this.blessedFrames.forEach( item => { if ( item instanceof BlessedPanel ) { item.resetViewCache(); } }); this.baseWidget.render(); this.screen.render(); log.info( "REFRESH - ALL - END"); } else if ( type === RefreshType.OBJECT || type === RefreshType.OBJECT_NOFOCUS ) { log.info( "REFRESH - OBJECT - START"); this.activeFocusObj().render(); if ( this.bottomFilesBox ) { this.bottomFilesBox.render(); } log.info( "REFRESH - OBJECT - END"); } if ( type === RefreshType.ALL || type === RefreshType.OBJECT ) { if ( this.commandBox && !this.commandBox.hasFocus() ) { this.commandBox.setFocus(); } else if ( !this.activeFocusObj().hasFocus() ) { this.activeFocusObj().setFocus(); } } } async refreshPromise() { for ( const item of this.blessedFrames ) { if ( item instanceof BlessedPanel ) { await item.refreshPromise(); } } return RefreshType.ALL; } async sshDisconnect() { const activePanel = this.activePanel(); if ( activePanel instanceof BlessedPanel ) { const reader = activePanel.getReader(); if ( reader ) { reader.destory(); } const fileReader = new FileReader(); // fileReader.onWatch( (event, filename) => this.onWatchDirectory(event, filename) ); activePanel.setReader( fileReader ); await activePanel.read("."); } } @Hint({ hint: T("Hint.Split"), order: 2 }) @Help(T("Help.SplitWindow")) split() { this.viewType++; if ( this.viewType > 2 ) { this.viewType = 0; } log.debug( "split: viewNumber [%d]", (this.viewType as number) ); this.viewRender(); return RefreshType.ALL; } protected abstract archivePromise( file: File, isQuit?: boolean ): Promise<void>; protected abstract terminalPromise(isEscape: boolean, shellCmd?: string, sftpReader?: Reader ): Promise<RefreshType>; @Hint({ hint: T("Hint.Quit"), order: 1, func: () => { const readerName = mainFrame().activePanel()?.getReader()?.readerName; return readerName === "sftp" ? T("Hint.Disconnect") : T("Hint.Quit"); }}) @Help(T("Help.Quit")) async quitPromise() { const panel = this.activePanel(); const reader = panel?.getReader(); const readerName = reader?.readerName; if ( readerName === "sftp") { const result = await messageBox( { parent: this.baseWidget, title: T("Question"), msg: T("Message.QuitSftp"), button: [ T("OK"), T("Cancel") ] }); if ( result === T("OK") ) { if ( panel instanceof BlessedXterm ) { await this.terminalPromise( true ); } else { await this.sshDisconnect(); } } return RefreshType.ALL; } if (readerName === "archive") { const file = await reader.rootDir(); file.name = ".."; await this.archivePromise(file, true); return RefreshType.ALL; } const result = await messageBox( { parent: this.baseWidget, title: T("Question"), msg: T("Message.QuitProgram"), button: [ T("OK"), T("Cancel") ] }); if ( result !== T("OK") ) { return RefreshType.NONE; } if (reader && reader.readerName === "file" ) { let lastPath = null; if ( panel instanceof BlessedXterm ) { lastPath = panel.getCurrentPath(); } else { lastPath = (await reader.currentDir()).fullname; } if ( lastPath && fs.existsSync(lastPath) ) { log.debug( "CHDIR : %s", lastPath ); process.chdir( lastPath ); try { fs.mkdirSync( os.homedir() + path.sep + ".m", { recursive: true, mode: 0o755 }); fs.writeFileSync( os.homedir() + path.sep + ".m" + path.sep + "path", lastPath, { mode: 0o644 } ); } catch( e ) { log.error( e ); } } } process.exit(0); return RefreshType.NONE; } @Hint({ hint: T("Hint.NextWindow"), order: 2 }) @Help( T("Help.NextWindow") ) nextWindow() { if ( this.viewType !== VIEW_TYPE.NORMAL ) { this.activeFrameNum++; if ( this.blessedFrames.length <= this.activeFrameNum ) { this.activeFrameNum = 0; } } else { this.activeFrameNum = 0; } log.debug( "this.activeFrameNum %d", this.activeFrameNum ); this.blessedFrames[ this.activeFrameNum ].setFocus(); this.baseWidget.render(); return RefreshType.ALL; } setActivePanel( frame: BlessedPanel | BlessedMcd | BlessedXterm | BlessedEditor ) { for ( let i = 0; i < this.blessedFrames.length; i++ ) { if ( Object.is( this.blessedFrames[i], frame ) && this.activeFrameNum !== i ) { this.activeFrameNum = i; this.blessedFrames[ this.activeFrameNum ].setFocus(); this.baseWidget.render(); break; } } } activePanel(): BlessedPanel | BlessedMcd | BlessedXterm | BlessedEditor { return this.blessedFrames[ this.activeFrameNum ]; } activeFocusObj(): any { if ( this.blessedMenu && this.blessedMenu.hasFocus() ) { return this.blessedMenu; } return this.activePanel(); } commandBoxShow() { const activePanel = this.activePanel(); if ( !(activePanel instanceof BlessedPanel) ) { return RefreshType.NONE; } /* if ( !(activePanel.getReader() instanceof FileReader) ) { return RefreshType.NONE; } */ if ( this.bottomFilesBox ) { this.bottomFilesBox.destroy(); this.bottomFilesBox = null; } log.info( "commandBoxShow !!!" ); this.commandBox = new CommandBox( { parent: this.baseWidget }, this.activePanel() ); this.commandBox.setFocus(); this.commandBox.on("blur", () => { log.info( "commandBoxShow !!! - blur %s", new Error().stack ); this.commandBoxClose(); }); log.info( "this.commandBox.setFocus !!!" ); return RefreshType.ALL_NOFOCUS; } @Help(T("Help.CommandBoxClose")) commandBoxClose() { if ( this.commandBox ) { this.commandBox.destroy(); this.commandBox = null; } this.bottomFilesBox = new BottomFilesBox( { parent: this.baseWidget } ); this.baseWidget.render(); return RefreshType.ALL; } @Hint({ hint: T("Hint.ConsoleView") }) @Help(T("Help.ConsoleView")) consoleViewPromise(): Promise<RefreshType> { return new Promise( (resolve) => { const program = this.screen.program; this.lockKey("consoleView", null); this.screen.leave(); program.once( "keypress", async () => { this.screen.enter(); this.screen.enableMouse(); await this.refreshPromise(); this.lockKeyRelease("consoleView"); resolve(RefreshType.ALL); }); }); } commandRun(cmd: string, fileRunMode = false ): Promise<void | RefreshType> { const activePanel = this.activePanel(); if ( !(activePanel instanceof BlessedPanel) ) { return new Promise( resolve => resolve() ); } if ( !fileRunMode ) { if ( os.platform() === "win32" && cmd.match( /^[a-zA-Z]\:$/ ) ) { return activePanel.read(cmd.toUpperCase()); } const cmds = cmd.split(" "); if ( cmds[0] === "cd" && cmds[1] ) { const chdirPath = cmds[1] === "-" ? activePanel.previousDir : cmds[1]; if ( cmds[1] === "~" ) { return activePanel.gotoHomePromise(); } return activePanel.read(chdirPath); } } if ( cmd === "quit" || cmd === "exit" ) { return this.quitPromise(); } if ( activePanel.getReader().readerName !== "file" ) { return new Promise( resolve => resolve() ); } process.chdir( activePanel.currentPath().fullname ); // eslint-disable-next-line no-async-promise-executor return new Promise( async (resolve) => { const program = this.screen.program; if ( !cmd ) { resolve(); return; } const cmdParse = await this.commandParsing( cmd ); this.lockKey("commandRun", null); this.screen.leave(); if ( fileRunMode ) { cmd = cmdParse.cmd; if ( os.platform() !== "win32" ) { if ( cmdParse.background ) { cmd += " &"; } if ( os.userInfo().username !== "root" && cmdParse.root ) { cmd = "su - " + cmd; } } } else { if ( process.platform === "win32" ) { cmd = "@chcp 65001 >nul & cmd /d/s/c " + cmdParse.cmd; } } process.stdout.write( colors.white("mdir.js $ ") + cmd + "\n"); exec(cmd, { encoding: "utf-8" }, (error, stdout, stderr) => { if (error) { console.error(error.message); } else { stderr && process.stderr.write(stderr); stdout && process.stdout.write(stdout); } const returnFunc = async () => { if ( cmdParse.tmpDirRemoveFunc ) { cmdParse.tmpDirRemoveFunc(); } this.screen.enter(); this.screen.enableMouse(); await this.refreshPromise(); this.lockKeyRelease("commandRun"); resolve(RefreshType.ALL); }; if ( !fileRunMode || cmdParse.wait ) { process.stdout.write( colors.yellow(T("Message.ANY_KEY_RETURN_M_JS")) + "\n" ); program.once( "keypress", returnFunc ); } else { returnFunc(); } }); }); } async methodRun( methodString, param ): Promise<RefreshType> { const item = methodString.split("."); const viewName: string = item[0] || ""; const methodName = item[1] || ""; let object = null; if ( viewName.toLowerCase() === this.activePanel().viewName().toLowerCase() ) { object = this.activePanel(); } else if ( /common/i.exec(viewName) ) { object = this; } let result = RefreshType.NONE; if ( object && object[ (methodName as string) ] ) { log.info( "methodRun [%s] - method: [ %s.%s(%s) ]", methodString, object.viewName(), methodName, param ? param.join(",") : "" ); if ( /(p|P)romise/.exec(methodName as string) ) { // eslint-disable-next-line prefer-spread result = await object[ (methodName as string) ].apply(object, param); } else { // eslint-disable-next-line prefer-spread result = object[ (methodName as string) ].apply(object, param); } } return result || RefreshType.OBJECT; } async getCurrentFileViewer( file: File ): Promise<{ orgFile: File; tmpFile: File; endFunc: () => void }> { const panel = this.activePanel(); if ( !panel ) { return null; } if ( !file && panel instanceof BlessedPanel ) { file = panel.currentFile(); } if ( !file ) { return null; } const reader = panel.getReader(); if ( reader instanceof FileReader ) { return { orgFile: file, tmpFile: null, endFunc: null }; } const progressBox = new ProgressBox( { title: T("Message.View"), msg: T("Message.Calculating"), cancel: () => { reader.isUserCanceled = true; }}, { parent: this.baseWidget } ); this.screen.render(); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); let copyBytes = 0; const befCopyInfo = { beforeTime: Date.now(), copyBytes }; const fullFileSize = 0; const refreshTimeMs = 300; const progressStatus: ProgressFunc = ( source, copySize, size, chunkLength ) => { copyBytes += chunkLength; const repeatTime = Date.now() - befCopyInfo.beforeTime; if ( repeatTime > refreshTimeMs ) { // const bytePerSec = Math.round((copyBytes - befCopyInfo.copyBytes) / repeatTime) * 1000; const lastText = (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(copyBytes, false, 1).trim()) + " / " + (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(fullFileSize, false, 1).trim()); progressBox.updateProgress( source.fullname, lastText, copyBytes, fullFileSize ); befCopyInfo.beforeTime = Date.now(); befCopyInfo.copyBytes = copyBytes; } return reader.isUserCanceled ? ProgressResult.USER_CANCELED : ProgressResult.SUCCESS; }; const result = await reader.viewer(file, progressStatus); progressBox.destroy(); this.screen.render(); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); return result; } @Hint({ hint: T("Hint.Remove") }) @Help( T("Help.Remove") ) async removePromise() { const result = await messageBox( { parent: this.baseWidget, title: T("Question"), msg: T("Message.REMOVE_SELECTED_FILES"), button: [ T("OK"), T("Cancel") ] }); if ( result !== T("OK") ) { return RefreshType.NONE; } const activePanel = this.activePanel(); if ( !(activePanel instanceof BlessedPanel) ) { return RefreshType.NONE; } const select = new Selection(); select.set( activePanel.getSelectFiles(), activePanel.currentPath(), ClipBoard.CLIP_NONE, activePanel.getReader() ); const reader = activePanel.getReader(); return await this.removeSelectFiles(select, reader); } async removeSelectFiles( select: Selection, reader: Reader ) { reader.isUserCanceled = false; const progressBox = new ProgressBox( { title: T("Message.Remove"), msg: T("Message.Calculating"), cancel: () => { reader.isUserCanceled = true; }}, { parent: this.baseWidget } ); this.screen.render(); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); if ( await select.expandDir() === false ) { progressBox.destroy(); return RefreshType.NONE; } const files = select.getFiles(); if ( !files || files.length === 0 ) { log.debug( "REMOVE FILES: 0"); progressBox.destroy(); return RefreshType.NONE; } // Sort in filename length descending order. files.sort( (a, b) => b.fullname.length - a.fullname.length); let beforeTime = Date.now(); const refreshTimeMs = 300; if ( [ "file", "sftp" ].indexOf(reader.readerName) > -1 ) { for ( let i = 0; i < files.length; i++ ) { const src = files[i]; try { if ( Date.now() - beforeTime > refreshTimeMs ) { progressBox.updateProgress( src.fullname, `${i+1} / ${files.length}`, i+1, files.length ); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); beforeTime = Date.now(); } if ( progressBox.getCanceled() ) { break; } await reader.remove( src ); log.debug( "REMOVE : [%s]", src.fullname); } catch ( err ) { const result2 = await messageBox( { parent: this.baseWidget, title: T("Error"), msg: err, button: [ T("Continue"), T("Cancel") ] }); if ( result2 === T("Cancel") ) { break; } } } } else { let copyBytes = 0; const befCopyInfo = { beforeTime: Date.now(), copyBytes }; const fullFileSize = 0; const progressStatus: ProgressFunc = ( source, copySize, size, chunkLength ) => { copyBytes += chunkLength; const repeatTime = Date.now() - befCopyInfo.beforeTime; if ( repeatTime > refreshTimeMs ) { // const bytePerSec = Math.round((copyBytes - befCopyInfo.copyBytes) / repeatTime) * 1000; const lastText = (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(copyBytes, false, 1).trim()) + " / " + (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(fullFileSize, false, 1).trim()); progressBox.updateProgress( source.fullname, lastText, copyBytes, fullFileSize ); befCopyInfo.beforeTime = Date.now(); befCopyInfo.copyBytes = copyBytes; } return reader.isUserCanceled ? ProgressResult.USER_CANCELED : ProgressResult.SUCCESS; }; await reader.remove( files, progressStatus ); } progressBox.destroy(); await this.refreshPromise(); return RefreshType.ALL; } @Hint({ hint: T("Hint.Cut"), order: 6 }) @Help( T("Help.Cut") ) clipboardCut() { const activePanel = this.activePanel(); if ( !(activePanel instanceof BlessedPanel) ) { return ; } selection().set( activePanel.getSelectFiles(), activePanel.currentPath(), ClipBoard.CLIP_CUT, activePanel.getReader() ); } @Hint({ hint: T("Hint.Copy"), order: 5 }) @Help( T("Help.Copy") ) clipboardCopy() { const activePanel = this.activePanel(); if ( !(activePanel instanceof BlessedPanel) ) { return ; } selection().set( activePanel.getSelectFiles(), activePanel.currentPath(), ClipBoard.CLIP_COPY, activePanel.getReader() ); } @Hint({ hint: T("Hint.Paste"), order: 7 }) @Help( T("Help.Paste") ) async clipboardPastePromise() { const activePanel = this.activePanel(); const clipSelected = selection(); let files = clipSelected.getFiles(); if ( !files || files.length === 0 ) { log.debug( "CLIPBOARD Length: 0"); return RefreshType.NONE; } if ( !(activePanel instanceof BlessedPanel) ) { return RefreshType.NONE; } const targetReader = activePanel.getReader(); targetReader.isUserCanceled = false; const progressBox = new ProgressBox( { title: clipSelected.getClipboard() === ClipBoard.CLIP_CUT ? T("Message.Cut") : T("Message.Copy"), msg: T("Message.Calculating"), cancel: () => { targetReader.isUserCanceled = true; } }, { parent: this.baseWidget } ); this.screen.render(); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); const filesCopyFunc = async (isMove: boolean = false) => { files = clipSelected.getFiles(); // Sort in filename length ascending order. files.sort( (a, b) => a.fullname.length - b.fullname.length); const fullFileSize = files.reduce( (sum, item) => sum + item.size, 0 ); const sourceBasePath = clipSelected.getSelecteBaseDir().fullname; let copyBytes = 0; const befCopyInfo = { beforeTime: Date.now(), copyBytes }; const refreshTimeMs = 300; const progressStatus: ProgressFunc = ( source, copySize, size, chunkLength ) => { copyBytes += chunkLength; const repeatTime = Date.now() - befCopyInfo.beforeTime; if ( repeatTime > refreshTimeMs ) { // const bytePerSec = Math.round((copyBytes - befCopyInfo.copyBytes) / repeatTime) * 1000; const lastText = (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(copyBytes, false, 1).trim()) + " / " + (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(fullFileSize, false, 1).trim()); progressBox.updateProgress( source.fullname, lastText, copyBytes, fullFileSize ); befCopyInfo.beforeTime = Date.now(); befCopyInfo.copyBytes = copyBytes; } return targetReader.isUserCanceled ? ProgressResult.USER_CANCELED : ProgressResult.SUCCESS; }; if ( activePanel instanceof BlessedPanel ) { if ( files[0].dirname === activePanel.currentPath().fullname ) { log.error( "source file and target file are the same." ); throw new Error(T("Message.SAME_SOURCE_AND_TARGET")); } const originalReader = clipSelected.getReader(); let anotherReader = activePanel.getReader(); if ( originalReader.readerName !== "file" ) { anotherReader = originalReader; } else if ( targetReader.readerName !== "file" ) { anotherReader = targetReader; } log.debug( "READER : [%s] => [%s]", originalReader.readerName, targetReader.readerName ); if ( [ "file", "sftp" ].indexOf(originalReader.readerName) > -1 && [ "file", "sftp" ].indexOf(targetReader.readerName) > -1 && files[0].fstype === clipSelected.getReader().readerName ) { let overwriteAll = false; for ( const src of files ) { if ( progressBox.getCanceled() ) { break; } if ( await originalReader.exist(src.fullname) === false ) { const result = await messageBox( { parent: this.baseWidget, title: T("Error"), msg: T("{{filename}}_FILE_NOT_EXISTS", { filename: src.name }), button: [ T("Skip"), T("Cancel") ] }); if ( result === T("Cancel") ) { break; } continue; } const targetBasePath = activePanel.currentPath().fullname; const target = src.clone(); let targetName = target.fullname.substr(sourceBasePath.length); if ( originalReader.sep() !== targetReader.sep() ) { if ( originalReader.sep() === "\\" ) { targetName = targetName.replace( /\\/g, targetReader.sep() ); } else if ( originalReader.sep() === "/" ) { targetName = targetName.replace( /\//g, targetReader.sep() ); } } if ( targetBasePath.substr(targetBasePath.length - 1, targetReader.sep().length) !== targetReader.sep() ) { target.fullname = targetBasePath + targetReader.sep() + targetName; } else { target.fullname = targetBasePath + targetName; } target.fstype = targetReader.readerName; if ( !overwriteAll && await targetReader.exist( target.fullname ) ) { const result = await messageBox( { parent: this.baseWidget, title: T("Copy"), msg: T("Message.{{filename}}_FILE_NOT_EXISTS", { filename: src.name }), button: [ T("Overwrite"), T("Skip"), T("Rename"), T("Overwrite All"), T("Skip All") ] }); if ( result === T("Skip") ) { continue; } if ( result === T("Overwrite All") ) { overwriteAll = true; } if ( result === T("Skip All") ) { break; } if ( result === T("Rename") ) { const result = await inputBox( { parent: this.baseWidget, title: T("Rename"), defaultText: src.name, button: [ T("OK"), T("Cancel") ] }); if ( result && result[1] === T("OK") && result[0] ) { target.fullname = targetBasePath + targetReader.sep() + result[0]; } else { continue; } } } try { if ( isMove && clipSelected.getClipboard() === ClipBoard.CLIP_CUT ) { await anotherReader.rename( src, target.fullname, progressStatus ); } else { if ( src.dir && !src.link ) { log.debug( "COPY DIR - [%s] => [%s]", src.fullname, target.fullname ); if ( await targetReader.exist(target.fullname) === false ) { await targetReader.mkdir( target ); } } else { log.debug( "COPY - [%s] => [%s]", src.fullname, target.fullname ); if ( anotherReader ) { await anotherReader.copy( src, null, target, progressStatus ); } } } } catch( err ) { if ( err === "USER_CANCEL" ) { break; } else { throw new Error(`${T("Error")}: ${src.name} - ${err}`); } } } } else if ( files[0].fstype === clipSelected.getReader().readerName ) { await anotherReader.copy( files, clipSelected.getSelecteBaseDir(), activePanel.currentPath(), progressStatus ); } } }; if ( clipSelected.getClipboard() === ClipBoard.CLIP_CUT && clipSelected.getReader().readerName === activePanel.getReader().readerName ) { try { await filesCopyFunc(true); log.debug( "FILE CUT - END"); progressBox.destroy(); await this.refreshPromise(); return RefreshType.ALL; } catch( err ) { log.error( err ); } } if ( await clipSelected.expandDir() === false ) { log.error( "Expend DIR : FALSE !!!"); progressBox.destroy(); return RefreshType.ALL; } try { await filesCopyFunc(); log.debug( "FILE COPY - END"); } catch( err ) { log.error( "FILE COPY FUNC ERROR - %s", err ); progressBox.destroy(); if ( err.message !== "USER_CANCEL" ) { await messageBox( { parent: this.baseWidget, title: T("Error"), msg: err.message, button: [ T("OK") ] }); } await this.refreshPromise(); return RefreshType.ALL; } progressBox.destroy(); if ( clipSelected.getClipboard() === ClipBoard.CLIP_CUT ) { log.debug( "FILE CUT(REMOVE) START"); await this.removeSelectFiles( clipSelected, clipSelected.getReader() ); } else { await this.refreshPromise(); } return RefreshType.ALL; } @Help(T("Help.NewFile")) async newFilePromise() { const panel = this.activePanel(); if ( panel instanceof BlessedPanel ) { const reader = panel.getReader(); const result = await inputBox( { parent: this.baseWidget, title: T("Message.CreateEmptyFile"), button: [ T("OK"), T("Cancel") ] }, { }); if ( result && result[1] === T("OK") && result[0] ) { if ( panel.getReader().readerName !== "file" ) { const progressBox = new ProgressBox( { title: T("Message.CreateEmptyFile"), msg: T("Message.Calculating"), cancel: () => { reader.isUserCanceled = true; }}, { parent: this.baseWidget } ); try { const reader = panel.getReader(); reader.isUserCanceled = false; this.screen.render(); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); let copyBytes = 0; const befCopyInfo = { beforeTime: Date.now(), copyBytes }; const fullFileSize = 0; const refreshTimeMs = 100; const progressStatus: ProgressFunc = ( source, copySize, size, chunkLength ) => { copyBytes += chunkLength; const repeatTime = Date.now() - befCopyInfo.beforeTime; if ( repeatTime > refreshTimeMs ) { // const bytePerSec = Math.round((copyBytes - befCopyInfo.copyBytes) / repeatTime) * 1000; const lastText = (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(copyBytes, false, 1).trim()) + " / " + (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(fullFileSize, false, 1).trim()); // + `(${StringUtils.sizeConvert(bytePerSec, false, 1).trim()}s)`; progressBox.updateProgress( source.fullname, lastText, copyBytes, fullFileSize ); befCopyInfo.beforeTime = Date.now(); befCopyInfo.copyBytes = copyBytes; } return reader.isUserCanceled ? ProgressResult.USER_CANCELED : ProgressResult.SUCCESS; }; await reader.newFile( panel.currentPath().fullname + reader.sep() + result[0], progressStatus ); } catch( e ) { log.error( e ); await messageBox( { parent: this.baseWidget, title: T("Error"), msg: e, button: [ T("OK") ] } ); } finally { progressBox.destroy(); } } else { try { reader.newFile( panel.currentPath().fullname + reader.sep() + result[0], null); } catch( e ) { log.error( e ); await messageBox( { parent: this.baseWidget, title: T("Error"), msg: e, button: [ T("OK") ] } ); } } } } await this.refreshPromise(); return RefreshType.ALL; } @Help(T("Help.Mkdir")) async mkdirPromise() { const panel = this.activePanel(); if ( panel instanceof BlessedPanel ) { const reader = panel.getReader(); const result = await inputBox( { parent: this.baseWidget, title: T("Message.MakeDirectory"), button: [ T("OK"), T("Cancel") ] }, { }); if ( result && result[1] === T("OK") && result[0] ) { if ( panel.getReader().readerName !== "file" ) { const progressBox = new ProgressBox( { title: T("Message.Copy"), msg: T("Message.Calculating"), cancel: () => { reader.isUserCanceled = true; }}, { parent: this.baseWidget } ); try { const reader = panel.getReader(); reader.isUserCanceled = false; this.screen.render(); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); let copyBytes = 0; const befCopyInfo = { beforeTime: Date.now(), copyBytes }; const fullFileSize = 0; const refreshTimeMs = 100; const progressStatus: ProgressFunc = ( source, copySize, size, chunkLength ) => { copyBytes += chunkLength; const repeatTime = Date.now() - befCopyInfo.beforeTime; if ( repeatTime > refreshTimeMs ) { // const bytePerSec = Math.round((copyBytes - befCopyInfo.copyBytes) / repeatTime) * 1000; const lastText = (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(copyBytes, false, 1).trim()) + " / " + (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(fullFileSize, false, 1).trim()); // + `(${StringUtils.sizeConvert(bytePerSec, false, 1).trim()}s)`; progressBox.updateProgress( source.fullname, lastText, copyBytes, fullFileSize ); befCopyInfo.beforeTime = Date.now(); befCopyInfo.copyBytes = copyBytes; } return reader.isUserCanceled ? ProgressResult.USER_CANCELED : ProgressResult.SUCCESS; }; await reader.mkdir( panel.currentPath().fullname + reader.sep() + result[0], progressStatus ); } catch( e ) { await messageBox( { parent: this.baseWidget, title: T("Error"), msg: e, button: [ T("OK") ] } ); } finally { progressBox.destroy(); } } else { try { reader.mkdir( panel.currentPath().fullname + reader.sep() + result[0], null); } catch( e ) { await messageBox( { parent: this.baseWidget, title: T("Error"), msg: e, button: [ T("OK") ] } ); } } } } await this.refreshPromise(); return RefreshType.ALL; } @Help(T("Help.Rename")) async renamePromise() { const panel = this.activePanel(); if ( panel instanceof BlessedPanel ) { const reader = panel.getReader(); const file = panel.currentFile(); if ( file.dir && file.name === ".." ) { return RefreshType.NONE; } const result = await inputBox( { parent: this.baseWidget, title: T("Message.Rename"), defaultText: file.name, button: [ T("OK"), T("Cancel") ] }, { }); if ( result && result[1] === T("OK") && result[0] ) { const progressBox = new ProgressBox( { title: T("Message.Rename"), msg: T("Message.Calculating"), cancel: () => { reader.isUserCanceled = true; }}, { parent: this.baseWidget } ); try { if ( reader.readerName !== "file ") { let copyBytes = 0; const befCopyInfo = { beforeTime: Date.now(), copyBytes }; const fullFileSize = 0; const refreshTimeMs = 300; this.screen.render(); await new Promise<void>( (resolve) => setTimeout( () => resolve(), 1 )); const progressStatus: ProgressFunc = ( source, copySize, size, chunkLength ) => { copyBytes += chunkLength; const repeatTime = Date.now() - befCopyInfo.beforeTime; if ( repeatTime > refreshTimeMs ) { // const bytePerSec = Math.round((copyBytes - befCopyInfo.copyBytes) / repeatTime) * 1000; const lastText = (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(copyBytes, false, 1).trim()) + " / " + (new Color(3, 0)).fontBlessFormat(StringUtils.sizeConvert(fullFileSize, false, 1).trim()); // + `(${StringUtils.sizeConvert(bytePerSec, false, 1).trim()}s)`; progressBox.updateProgress( source.fullname, lastText, copyBytes, fullFileSize ); befCopyInfo.beforeTime = Date.now(); befCopyInfo.copyBytes = copyBytes; } return reader.isUserCanceled ? ProgressResult.USER_CANCELED : ProgressResult.SUCCESS; }; await reader.rename( file, panel.currentPath().fullname + reader.sep() + result[0], progressStatus ); } else { reader.rename( file, panel.currentPath().fullname + reader.sep() + result[0] ); } panel.resetViewCache(); } catch( e ) { await messageBox( { parent: this.baseWidget, title: T("Error"), msg: e, button: [ T("OK") ] } ); } finally { progressBox.destroy(); } } } await this.refreshPromise(); return RefreshType.ALL; } }
the_stack
import * as React from "react" //import { load } from 'opentype.js' import { bumpAnnotations } from "./annotationLayerBehavior/annotationHandling" import Legend from "./Legend" import Annotation from "./Annotation" import * as labella from "labella" import SpanOrDiv from "./SpanOrDiv" import { AnnotationHandling, AnnotationTypes, AnnotationProps } from "./types/annotationTypes" import { LegendProps } from "./types/legendTypes" interface NoteType { key: string props: AnnotationProps } export interface AnnotationLayerProps { useSpans: boolean legendSettings?: LegendProps margin: { top?: number; left?: number; right?: number; bottom?: number } size: number[] axes?: React.ReactNode[] annotationHandling?: AnnotationHandling | AnnotationTypes annotations: Object[] pointSizeFunction?: Function labelSizeFunction?: Function svgAnnotationRule: Function htmlAnnotationRule: Function voronoiHover: Function position?: number[] } interface AnnotationLayerState { svgAnnotations: Object[] htmlAnnotations: Object[] adjustedAnnotationsKey?: string adjustedAnnotationsDataVersion?: string adjustedAnnotations: Object[] } function marginOffsetFn(orient, axisSettings, marginOffset) { if (typeof marginOffset === "number") { return marginOffset } if (axisSettings && axisSettings.find(d => d.props.orient === orient)) { return 50 } return 10 } function adjustedAnnotationKeyMapper(d) { const { note = {} } = d.props.noteData const { label } = note const id = d.props.noteData.id || `${d.props.noteData.x}-${d.props.noteData.y}` return `${id}-${label}` } function noteDataWidth(noteData, charWidth = 8) { const wrap = (noteData.note && noteData.note.wrap) || 120 const noteText = noteData.note.label || noteData.note.label || "" return Math.min(wrap, noteText.length * charWidth) } function noteDataHeight(noteData, charWidth = 8, lineHeight = 20) { const wrap = (noteData.note && noteData.note.wrap) || 120 const text = noteData.note.label || noteData.note.title || "" return ( Math.ceil((text.length * charWidth) / wrap) * lineHeight + (noteData.note.label && noteData.note.title ? lineHeight : 0) ) } class AnnotationLayer extends React.Component< AnnotationLayerProps, AnnotationLayerState > { constructor(props: AnnotationLayerProps) { super(props) this.state = { svgAnnotations: [], htmlAnnotations: [], adjustedAnnotations: [], adjustedAnnotationsKey: "", adjustedAnnotationsDataVersion: "" } } /* componentWillMount() { const fontLocation = this.props.fontLocation if (fontLocation) { load(fontLocation, function(err, font) { if (err) { return null } else { this.setState({ font }); } }); } } */ generateSVGAnnotations = ( props: AnnotationLayerProps, annotations: Object[] ): NoteType[] => { const renderedAnnotations = annotations .map((d, i) => props.svgAnnotationRule(d, i, props)) .filter(d => d !== null && d !== undefined) return renderedAnnotations } generateHTMLAnnotations = ( props: AnnotationLayerProps, annotations: Object[] ): Object[] => { const renderedAnnotations = annotations .map((d, i) => props.htmlAnnotationRule(d, i, props)) .filter(d => d !== null && d !== undefined) return renderedAnnotations } processAnnotations = ( adjustableAnnotations: NoteType[], annotationProcessor: AnnotationHandling, props: AnnotationLayerProps ) => { const { layout = { type: false } } = annotationProcessor if (layout.type === false) { return adjustableAnnotations } let { margin = { top: 0, bottom: 0, left: 0, right: 0 } } = props const { size, axes = [] } = props margin = typeof margin === "number" ? { top: margin, left: margin, right: margin, bottom: margin } : margin if (layout.type === "bump") { const adjustedAnnotations = bumpAnnotations( adjustableAnnotations, layout, size, props.pointSizeFunction, props.labelSizeFunction ) return adjustedAnnotations } else if (layout.type === "marginalia") { const { marginOffset, orient = "nearest", characterWidth = 8, lineHeight = 20, padding = 2, axisMarginOverride = {} } = layout const finalOrientation = orient === "nearest" ? ["left", "right", "top", "bottom"] : Array.isArray(orient) ? orient : [orient] const leftOn = finalOrientation.find(d => d === "left") const rightOn = finalOrientation.find(d => d === "right") const topOn = finalOrientation.find(d => d === "top") const bottomOn = finalOrientation.find(d => d === "bottom") const leftNodes = [] const rightNodes = [] const topNodes = [] const bottomNodes = [] adjustableAnnotations.forEach((aNote: NoteType) => { const noteData = aNote.props.noteData const noteX = noteData.x[0] || noteData.x const noteY = noteData.y[0] || noteData.y const leftDist = leftOn ? noteX : Infinity const rightDist = rightOn ? size[0] - noteX : Infinity const topDist = topOn ? noteY : Infinity const bottomDist = bottomOn ? size[1] - noteY : Infinity const minDist = Math.min(leftDist, rightDist, topDist, bottomDist) if (leftDist === minDist) { leftNodes.push(aNote) } else if (rightDist === minDist) { rightNodes.push(aNote) } else if (topDist === minDist) { topNodes.push(aNote) } else { bottomNodes.push(aNote) } }) //Adjust the margins based on which regions are active const leftForce = new labella.Force({ minPos: axisMarginOverride.top !== undefined ? 0 + axisMarginOverride.top : 0 - margin.top, maxPos: axisMarginOverride.bottom !== undefined ? size[1] - axisMarginOverride.bottom : bottomOn ? size[1] : size[1] + margin.bottom }) .nodes( leftNodes.map(d => { const noteY = d.props.noteData.y[0] || d.props.noteData.y return new labella.Node( noteY, noteDataHeight(d.props.noteData, characterWidth, lineHeight) + padding ) }) ) .compute() const rightForce = new labella.Force({ minPos: axisMarginOverride.top !== undefined ? 0 + axisMarginOverride.top : topOn ? 0 : 0 - margin.top, maxPos: axisMarginOverride.bottom !== undefined ? size[1] - axisMarginOverride.bottom : size[1] + margin.bottom }) .nodes( rightNodes.map(d => { const noteY = d.props.noteData.y[0] || d.props.noteData.y return new labella.Node( noteY, noteDataHeight(d.props.noteData, characterWidth, lineHeight) + padding ) }) ) .compute() const topForce = new labella.Force({ minPos: axisMarginOverride.left !== undefined ? 0 + axisMarginOverride.left : leftOn ? 0 : 0 - margin.left, maxPos: axisMarginOverride.right !== undefined ? size[0] - axisMarginOverride.right : size[0] + margin.right }) .nodes( topNodes.map(d => { const noteX = d.props.noteData.x[0] || d.props.noteData.x return new labella.Node( noteX, noteDataWidth(d.props.noteData, characterWidth) + padding ) }) ) .compute() const bottomForce = new labella.Force({ minPos: axisMarginOverride.left !== undefined ? 0 + axisMarginOverride.left : 0 - margin.left, maxPos: axisMarginOverride.right !== undefined ? size[0] - axisMarginOverride.right : rightOn ? size[0] : size[0] + margin.right }) .nodes( bottomNodes.map(d => { const noteX = d.props.noteData.x[0] || d.props.noteData.x return new labella.Node( noteX, noteDataWidth(d.props.noteData, characterWidth) + padding ) }) ) .compute() const bottomOffset = Math.max( ...bottomNodes.map( d => noteDataHeight(d.props.noteData, characterWidth, lineHeight) + padding ) ) const topOffset = Math.max( ...topNodes.map( d => noteDataHeight(d.props.noteData, characterWidth, lineHeight) + padding ) ) const leftOffset = Math.max( ...leftNodes.map( d => noteDataWidth(d.props.noteData, characterWidth) + padding ) ) const rightOffset = Math.max( ...rightNodes.map( d => noteDataWidth(d.props.noteData, characterWidth) + padding ) ) // const nodeOffsetHeight = Math.max() const leftSortedNodes = leftForce.nodes() const rightSortedNodes = rightForce.nodes() const topSortedNodes = topForce.nodes() const bottomSortedNodes = bottomForce.nodes() leftNodes.forEach((note, i) => { note.props.noteData.ny = leftSortedNodes[i].currentPos note.props.noteData.nx = 0 - leftSortedNodes[i].layerIndex * leftOffset - marginOffsetFn("left", axes, marginOffset) if (note.props.noteData.note) { note.props.noteData.note.orientation = note.props.noteData.note.orientation || "leftRight" note.props.noteData.note.align = note.props.noteData.note.align || "right" } }) rightNodes.forEach((note, i) => { note.props.noteData.ny = rightSortedNodes[i].currentPos note.props.noteData.nx = size[0] + rightSortedNodes[i].layerIndex * rightOffset + marginOffsetFn("right", axes, marginOffset) if (note.props.noteData.note) { note.props.noteData.note.orientation = note.props.noteData.note.orientation || "leftRight" note.props.noteData.note.align = note.props.noteData.note.align || "left" } }) topNodes.forEach((note, i) => { note.props.noteData.nx = topSortedNodes[i].currentPos note.props.noteData.ny = 0 - topSortedNodes[i].layerIndex * topOffset - marginOffsetFn("top", axes, marginOffset) }) bottomNodes.forEach((note, i) => { note.props.noteData.nx = bottomSortedNodes[i].currentPos note.props.noteData.ny = size[1] + bottomSortedNodes[i].layerIndex * bottomOffset + marginOffsetFn("bottom", axes, marginOffset) }) return adjustableAnnotations } return adjustableAnnotations } createAnnotations = (props: AnnotationLayerProps) => { let renderedSVGAnnotations = this.state.svgAnnotations, renderedHTMLAnnotations = [], adjustedAnnotations = this.state.adjustedAnnotations, adjustableAnnotationsKey = this.state.adjustedAnnotationsKey const adjustedAnnotationsKey = this.state.adjustedAnnotationsKey, adjustedAnnotationsDataVersion = this.state.adjustedAnnotationsDataVersion const { annotations, annotationHandling = false, size, svgAnnotationRule, htmlAnnotationRule } = props const annotationProcessor: AnnotationHandling = typeof annotationHandling === "object" ? annotationHandling : { layout: { type: annotationHandling }, dataVersion: "" } const { dataVersion = "" } = annotationProcessor if (svgAnnotationRule) { const initialSVGAnnotations: NoteType[] = this.generateSVGAnnotations( props, annotations ) const adjustableAnnotations = initialSVGAnnotations.filter( d => d.props && d.props.noteData && !d.props.noteData.fixedPosition ) const fixedAnnotations = initialSVGAnnotations.filter( d => !d.props || !d.props.noteData || d.props.noteData.fixedPosition ) adjustableAnnotationsKey = `${adjustableAnnotations .map(adjustedAnnotationKeyMapper) .join(",")}${JSON.stringify(annotationProcessor)}${size.join(",")}` if (annotationHandling === false) { adjustedAnnotations = adjustableAnnotations } if ( adjustedAnnotations.length !== adjustableAnnotations.length || adjustedAnnotationsKey !== adjustableAnnotationsKey || adjustedAnnotationsDataVersion !== dataVersion ) { adjustedAnnotations = this.processAnnotations( adjustableAnnotations, annotationProcessor, props ) } else { //Handle when style or other attributes change adjustedAnnotations = adjustableAnnotations.map((d: NoteType, i) => { const oldAnnotation = adjustedAnnotations[i] as NoteType const newNoteData = { ...oldAnnotation.props.noteData, ...d.props.noteData } return <Annotation key={d.key} noteData={newNoteData} /> }) } renderedSVGAnnotations = [...adjustedAnnotations, ...fixedAnnotations] } if (htmlAnnotationRule) { renderedHTMLAnnotations = this.generateHTMLAnnotations(props, annotations) } this.setState({ svgAnnotations: renderedSVGAnnotations, htmlAnnotations: renderedHTMLAnnotations, adjustedAnnotations: adjustedAnnotations, adjustedAnnotationsKey: adjustableAnnotationsKey, adjustedAnnotationsDataVersion: dataVersion }) } componentWillMount() { this.createAnnotations(this.props) } componentWillReceiveProps(nextProps: AnnotationLayerProps) { this.createAnnotations(nextProps) } render() { const { svgAnnotations, htmlAnnotations } = this.state const { useSpans, legendSettings, margin, size } = this.props let renderedLegend if (legendSettings) { const positionHash = { left: [15, 15], right: [size[0] + 15, 15] } const { position = "right", title = "Legend" } = legendSettings const legendPosition = positionHash[position] renderedLegend = ( <g transform={`translate(${legendPosition.join(",")})`}> <Legend {...legendSettings} title={title} position={position} /> </g> ) } return ( <SpanOrDiv span={useSpans} className="annotation-layer" style={{ position: "absolute", pointerEvents: "none", background: "none" }} > <svg className="annotation-layer-svg" height={size[1]} width={size[0]} style={{ background: "none", pointerEvents: "none", position: "absolute", left: `${margin.left}px`, top: `${margin.top}px`, overflow: "visible" }} > <g> {renderedLegend} {svgAnnotations} </g> </svg> <SpanOrDiv span={useSpans} className="annotation-layer-html" style={{ background: "none", pointerEvents: "none", position: "absolute", height: `${size[1]}px`, width: `${size[0]}px`, left: `${margin.left}px`, top: `${margin.top}px` }} > {htmlAnnotations} </SpanOrDiv> </SpanOrDiv> ) } } export default AnnotationLayer
the_stack
import * as React from 'react'; import './aplRendererWindow.css'; import { APLClient, APLWSRenderer, IAPLWSOptions, AudioPlayer, IAudioEventListener, IEnvironment } from 'apl-client'; import {IClient} from '../lib/messages/client'; import {IAPLCoreMessage, IAPLEventMessage} from '../lib/messages/messages'; import {FocusManager} from '../lib/focus/FocusManager'; import {AVSAudioPlayer} from '../lib/media/AVSAudioPlayer'; import {AVSVideoFactory} from '../lib/media/AVSVideo'; import {ActivityTracker} from '../lib/activity/ActivityTracker'; import { Timer } from '../lib/utils/timer'; import { IAPLRendererWindowConfig } from '../lib/config/IDeviceAppConfig'; type VisibilityProperty = import('csstype').Property.Visibility; const OVERLAY_WINDOW_ACTIVE_IN_MS : number = 750; const OVERLAY_WINDOW_INACTIVE_IN_MS : number = 250; const WINDOW_TRANSITION_IN_MS : number = 250; export enum APLRendererWindowState { INACTIVE = 0, ACTIVE = 1 } export interface IAPLRendererWindowProps { id : string; windowConfig : IAPLRendererWindowConfig; clearRenderer : boolean; client : WebsocketConnectionWrapper; refreshRenderer : boolean; focusManager : FocusManager; activityTracker : ActivityTracker; onRendererInit?() : void; onRendererDestroyed?() : void; aplCoreMessageHandlerCallback : (windowId : string, aplCoreMessageHandler : (message : IAPLCoreMessage) => void) => void; } export class WebsocketConnectionWrapper extends APLClient { protected client : IClient; private supportedExtensions : any; constructor(client : IClient) { super(); this.client = client; } public sendMessage(message : any) { this.client.sendMessage(message); } } export class WindowWebsocketClient extends APLClient { protected client : WebsocketConnectionWrapper; protected windowId : string; constructor(client : WebsocketConnectionWrapper) { super(); this.client = client; } public setWindowId(id : string) { this.windowId = id; } public sendMessage(message : any) { switch (message.type) { case 'executeCommands' : case 'renderComplete': case 'renderStaticDocument' : { message.windowId = this.windowId; this.client.sendMessage(message); break; } case 'displayMetrics': { const metricsEvent = { type: 'aplDisplayMetrics', windowId: this.windowId, payload: message }; this.client.sendMessage(metricsEvent); break; } default : { const aplEvent : IAPLEventMessage = { type: 'aplEvent', windowId: this.windowId, payload: message }; this.client.sendMessage(aplEvent); } } } public handleMessage(message : IAPLCoreMessage) { const unwrapped = message.payload; this.onMessage(unwrapped); } } interface IAPLRendererWindowState { windowState : APLRendererWindowState; } const DEFAULT_WINDOW_TRANSLATE : string = 'translate(0px,0px)'; type APLWindowFlexType = 'flex-start' | 'flex-end' | 'center'; export class APLRendererWindow extends React.Component<IAPLRendererWindowProps, IAPLRendererWindowState> { protected rendererViewportDiv : any; protected client : WindowWebsocketClient; protected windowConfig : IAPLRendererWindowConfig; protected renderer : APLWSRenderer; protected windowFlexAlignItems : APLWindowFlexType; protected windowFlexJustifyContent : APLWindowFlexType; protected windowInactiveTranslation : string; protected windowActiveTransition : string; protected windowInactiveTransition : string; protected windowActiveTransitionInMS : number; protected windowInactiveTransitionInMS : number; protected audioPlayer : AVSAudioPlayer; constructor(props : IAPLRendererWindowProps) { super(props); this.client = new WindowWebsocketClient(props.client); this.client.setWindowId(this.props.id); this.windowConfig = props.windowConfig; this.rendererViewportDiv = React.createRef(); const windowPosition = this.windowConfig.windowPosition || 'center'; this.windowFlexAlignItems = 'center'; this.windowFlexJustifyContent = 'center'; this.windowInactiveTranslation = DEFAULT_WINDOW_TRANSLATE; this.windowActiveTransitionInMS = OVERLAY_WINDOW_ACTIVE_IN_MS; this.windowInactiveTransitionInMS = OVERLAY_WINDOW_INACTIVE_IN_MS; let translateX : number = 0; let translateY : number = 0; let windowOpacityActiveTransitionInMs : number = 0; switch (windowPosition) { case 'bottom' : { this.windowFlexAlignItems = 'flex-end'; translateY = this.windowConfig.viewport.height; break; } case 'top' : { this.windowFlexAlignItems = 'flex-start'; translateY = -this.windowConfig.viewport.height; break; } case 'right' : { this.windowFlexJustifyContent = 'flex-end'; translateX = this.windowConfig.viewport.width; break; } case 'left' : { this.windowFlexJustifyContent = 'flex-start'; translateX = -this.windowConfig.viewport.width; break; } case 'center' : default : { this.windowActiveTransitionInMS = WINDOW_TRANSITION_IN_MS; this.windowInactiveTransitionInMS = WINDOW_TRANSITION_IN_MS; windowOpacityActiveTransitionInMs = WINDOW_TRANSITION_IN_MS; } } this.windowActiveTransition = 'visibility 1s, opacity ' + windowOpacityActiveTransitionInMs + 'ms linear'; this.windowInactiveTransition = 'visibility 1s, opacity ' + this.windowInactiveTransitionInMS + 'ms linear'; this.windowInactiveTranslation = 'translate(' + translateX + 'px,' + translateY + 'px)'; this.state = { windowState : APLRendererWindowState.INACTIVE }; const handleAPLCoreMessage = (message : IAPLCoreMessage) => { this.client.handleMessage(message); }; props.aplCoreMessageHandlerCallback(this.props.id, handleAPLCoreMessage); } public render() { let windowTransition : string = this.windowActiveTransition; let windowTransitionDelay = '0s'; let windowVisibility : VisibilityProperty = 'visible'; let windowTranslateTransition = DEFAULT_WINDOW_TRANSLATE; if (this.state.windowState === APLRendererWindowState.INACTIVE) { windowTransition = this.windowInactiveTransition; windowTransitionDelay = this.windowInactiveTransitionInMS + 'ms'; windowVisibility = 'hidden'; windowTranslateTransition = this.windowInactiveTranslation; } return ( <div className={'aplRendererWindow'} tabIndex={0} style={{ opacity: this.state.windowState, visibility: windowVisibility, alignItems : this.windowFlexAlignItems, justifyContent : this.windowFlexJustifyContent, transition: windowTransition }}> <div id={this.props.id} className={'aplRendererViewport'} style={{ transition: 'transform ' + this.windowActiveTransitionInMS + 'ms ease-out ' + windowTransitionDelay, transform: windowTranslateTransition }}> <div ref={this.rendererViewportDiv}> </div> </div> </div> ); } protected createAudioPlayer(eventListener : IAudioEventListener) : AudioPlayer { this.audioPlayer = new AVSAudioPlayer(this.props.focusManager, this.props.activityTracker, eventListener); return this.audioPlayer; } protected createRenderer() { const rendererElement : HTMLElement = this.rendererViewportDiv.current; const environment : IEnvironment = { agentName: 'SmartScreenSDK', agentVersion: '2.8', disallowVideo: this.windowConfig.disallowVideo, allowOpenUrl: this.windowConfig.allowOpenUrl, animationQuality: this.windowConfig.animationQuality }; const options : IAPLWSOptions = { view: rendererElement, theme: this.windowConfig.theme, viewport : this.windowConfig.viewport, mode: this.windowConfig.mode, environment, audioPlayerFactory: this.createAudioPlayer.bind(this), client: this.client, videoFactory: new AVSVideoFactory(this.props.focusManager, this.props.activityTracker), supportedExtensions: this.windowConfig.supportedExtensions } as any; this.destroyRenderer(); this.renderer = APLWSRenderer.create(options); this.renderer.init().then(() => { console.log(`APL Renderer init resolved with viewport: \ ${this.renderer.context.getViewportWidth()} x ${this.renderer.context.getViewportHeight()}`); rendererElement.style.display = 'flex'; rendererElement.style.overflow = 'hidden'; rendererElement.style.width = `${this.renderer.context.getViewportWidth()}px`; rendererElement.style.height = `${this.renderer.context.getViewportHeight()}px`; // onRendererInit callback if (!this.props.clearRenderer && this.props.onRendererInit) { this.props.onRendererInit(); } this.setState({ // Update state once we've rendered windowState : this.props.clearRenderer ? APLRendererWindowState.INACTIVE : APLRendererWindowState.ACTIVE }); this.client.sendMessage({ type: 'renderComplete', payload : { } }); }); } protected destroyRenderer() { if (this.renderer) { this.renderer.destroy(); (this.renderer as any) = undefined; // onRendererDestroyed callback if (this.props.onRendererDestroyed) { this.props.onRendererDestroyed(); } } } protected flushAudioPlayer() { if (this.audioPlayer) { this.audioPlayer.flush(); } } protected async setInactive() { this.setState({ windowState : APLRendererWindowState.INACTIVE }); // Flush audioPlayer for this window before destroying renderer this.flushAudioPlayer(); // Allow window to transition before destroying renderer await Timer.delay(this.windowInactiveTransitionInMS); // Make sure we didn't become active again before destroying if (this.props.clearRenderer) { this.destroyRenderer(); } } public componentWillReceiveProps(nextProps : IAPLRendererWindowProps) { if (nextProps.clearRenderer) { this.setInactive(); } } public componentWillUpdate() { if (this.props.refreshRenderer) { this.createRenderer(); } } public componentWillUnmount() { this.props.activityTracker.reset(); this.props.focusManager.reset(); this.destroyRenderer(); this.client.removeAllListeners(); } }
the_stack
///<reference path="./codemirror.d.ts" /> //-------------------------------------------------------------------------- // // Brackets declaration files // //-------------------------------------------------------------------------- declare module brackets { //-------------------------------------------------------------------------- // // FileSystem // //-------------------------------------------------------------------------- /** * FileSystem is a model object representing a complete file system. This object creates * and manages File and Directory instances, dispatches events when the file system changes, * and provides methods for showing 'open' and 'save' dialogs. * * The FileSystem must be initialized very early during application startup. * * There are three ways to get File or Directory instances: * * Use FileSystem.resolve() to convert a path to a File/Directory object. This will only * succeed if the file/directory already exists. * * Use FileSystem.getFileForPath()/FileSystem.getDirectoryForPath() if you know the * file/directory already exists, or if you want to create a new entry. * * Use Directory.getContents() to return all entries for the specified Directory. * * FileSystem dispatches the following events: * change - Sent whenever there is a change in the file system. The handler * is passed one argument -- entry. This argument can be... * * a File - the contents of the file have changed, and should be reloaded. * * a Directory - an immediate child of the directory has been added, removed, * or renamed/moved. Not triggered for "grandchildren". * * null - a 'wholesale' change happened, and you should assume everything may * have changed. * For changes made externally, there may be a significant delay before a "change" event * is dispatched. * rename - Sent whenever a File or Directory is renamed. All affected File and Directory * objects have been updated to reflect the new path by the time this event is dispatched. * This event should be used to trigger any UI updates that may need to occur when a path * has changed. * * FileSystem may perform caching. But it guarantees: * * File contents & metadata - reads are guaranteed to be up to date (cached data is not used * without first veryifying it is up to date). * * Directory structure / file listing - reads may return cached data immediately, which may not * reflect external changes made recently. (However, changes made via FileSystem itself are always * reflected immediately, as soon as the change operation's callback signals success). * * The FileSystem doesn't directly read or write contents--this work is done by a low-level * implementation object. This allows client code to use the FileSystem API without having to * worry about the underlying storage, which could be a local filesystem or a remote server. */ interface FileSystem { // should not expose thoses method one //init(impl, callback) //close(callback) //shouldShow /** * Return a File object for the specified path.This file may not yet exist on disk. * * @param path Absolute path of file. */ getFileForPath(path: string): File; /** * Return a Directory object for the specified path.This directory may not yet exist on disk. * * @param path Absolute path of directory. */ getDirectoryForPath(path: string): Directory; /** * Resolve a path. * * @param path The path to resolve * @param callback Callback resolved with a FileSystemError string or with the entry for the provided path. */ resolve(path: string, callback: (err: string, entry: FileSystemEntry, stat: FileSystemStats) => any): void; /** * Show an "Open" dialog and return the file(s)/directories selected by the user. * * @param allowMultipleSelection Allows selecting more than one file at a time * @param chooseDirectories Allows directories to be opened * @param title The title of the dialog * @param initialPath The folder opened inside the window initially. If initialPath * is not set, or it doesn't exist, the window would show the last * browsed folder depending on the OS preferences * @param fileTypes List of extensions that are allowed to be opened. A null value * allows any extension to be selected. * @param callback Callback resolved with a FileSystemError * string or the selected file(s)/directories. If the user cancels the * open dialog, the error will be falsy and the file/directory array will * be empty. */ showOpenDialog(allowMultipleSelection: boolean, chooseDirectories: boolean, title: string, initialPath: string, fileTypes: string[], callback: (err: string, files: string[]) => any): void; /** * Show a "Save" dialog and return the path of the file to save. * * @param title The title of the dialog. * @param initialPath The folder opened inside the window initially. If initialPath * is not set, or it doesn't exist, the window would show the last * browsed folder depending on the OS preferences. * @param proposedNewFilename Provide a new file name for the user. This could be based on * on the current file name plus an additional suffix * @param callback Callback that is resolved with a FileSystemError * string or the name of the file to save. If the user cancels the save, * the error will be falsy and the name will be empty. */ showSaveDialog(title: string, initialPath: string, proposedNewFilename: string, callback: (err: string, file: string) => any): void; /** * Start watching a filesystem root entry. * * @param entry The root entry to watch. If entry is a directory, * all subdirectories that aren't explicitly filtered will also be watched. * @param filter A function to determine whether * a particular name should be watched or ignored. Paths that are ignored are also * filtered from Directory.getContents() results within this subtree. * @param callback A function that is called when the watch has completed. * If the watch fails, the function will have a non-null FileSystemError string parametr. */ watch(entry: FileSystemEntry, filter: (file: string) => boolean, callback?: (file: string) => void): void; /** * Stop watching a filesystem root entry. * * @param {FileSystemEntry} entry - The root entry to stop watching. The unwatch will * if the entry is not currently being watched. * @param {function(?string)=} callback - A function that is called when the unwatch has * completed. If the unwatch fails, the function will have a non-null FileSystemError * string parameter. */ unwatch(entry: FileSystemEntry, callback?: (file: string) => void): void; /** * return true if the path is absolute * * @param path */ isAbsolutePath(path: string): boolean; /** * Add an event listener for a FileSystem event. * * @param event The name of the event * @param handler The handler for the event */ on(event: string, handler: (...args: any[]) => any): void; /** * Remove an event listener for a FileSystem event. * * @param event The name of the event * @param handler The handler for the event */ off(event: string, handler: (...args: any[]) => any): void; } /** * This is an abstract representation of a FileSystem entry, and the base class for the File and Directory classes. * FileSystemEntry objects are never created directly by client code. Use FileSystem.getFileForPath(), * FileSystem.getDirectoryForPath(), or Directory.getContents() to create the entry. */ interface FileSystemEntry { fullPath: string; name: string; parentPath: string; id: string; isFile: boolean; isDirectory: boolean; /** * Check to see if the entry exists on disk. Note that there will NOT be an * error returned if the file does not exist on the disk; in that case the * error parameter will be null and the boolean will be false. The error * parameter will only be truthy when an unexpected error was encountered * during the test, in which case the state of the entry should be considered * unknown. * * @param callback Callback with a FileSystemError * string or a boolean indicating whether or not the file exists. */ exists(callback: (err: string, exist: boolean) => any): void; /** * Returns the stats for the entry. * * @param callback Callback with a FileSystemError string or FileSystemStats object. */ stat(callback: (err: string, stat: FileSystemStats) => any): void; /** * Rename this entry. * * @param {string} newFullPath New path & name for this entry. * @param {function (?string)=} callback Callback with a single FileSystemError string parameter. */ rename(newFullPath: string, callback?: (err: string) => any): void; /** * Unlink (delete) this entry. For Directories, this will delete the directory * and all of its contents. * * @param callback Callback with a single FileSystemError string parameter. */ unlink(callback?: (err: string) => any): void; /** * Move this entry to the trash. If the underlying file system doesn't support move * to trash, the item is permanently deleted. * * @param callback Callback with a single FileSystemError string parameter. */ moveToTrash(callback?: (err: string) => any): void; /** * Visit this entry and its descendents with the supplied visitor function. * * @paramvisitor - A visitor function, which is applied to descendent FileSystemEntry objects. If the function returns false for * a particular Directory entry, that directory's descendents will not be visited. * @param {{failFast: boolean=, maxDepth: number=, maxEntries: number=}=} options * @param {function(?string)=} callback Callback with single FileSystemError string parameter. */ visit(visitor: (entry: FileSystemEntry) => boolean, options: {failFast?: boolean; maxDepth?: number; maxEntries?: number}, callbak: (err: string) => any): void; } /** * This class represents a directory on disk (this could be a local disk or cloud storage). This is a subclass of FileSystemEntry. */ interface Directory extends FileSystemEntry { /** * Read the contents of a Directory. * * @param callback Callback that is passed an error code or the stat-able contents * of the directory along with the stats for these entries and a * fullPath-to-FileSystemError string map of unstat-able entries * and their stat errors. If there are no stat errors then the last * parameter shall remain undefined. */ getContents(callback: (err: string, files: FileSystemEntry[], stats: FileSystemStats, errors: { [path: string]: string; }) => any): void; /** * Create a directory * * @param callback Callback resolved with a FileSystemError string or the stat object for the created directory. */ create(callback: (err: string, stat: FileSystemStats) => any): void; } /** * This class represents a file on disk (this could be a local disk or cloud storage). This is a subclass of FileSystemEntry. */ interface File extends FileSystemEntry { /** * Read a file. * * @param options Currently unused. * @param callback Callback that is passed the FileSystemError string or the file's contents and its stats. */ read(options: {}, callback: (err: string, data: string, stat: FileSystemStats) => any): void; /** * Write a file. * * @param data Data to write. * @param options Currently unused. * @param callback Callback that is passed the FileSystemError string or the file's new stats. */ write(data: string, options?: {}, callback?: (err: string, stat: FileSystemStats) => any ): void; } interface FileSystemStats { isFile: boolean; isDirectory: boolean; mtime: Date; size: number; } //-------------------------------------------------------------------------- // // Project // //-------------------------------------------------------------------------- /** * ProjectManager is the model for the set of currently open project. It is responsible for * creating and updating the project tree when projects are opened and when changes occur to * the file tree. * * This module dispatches these events: * - beforeProjectClose -- before _projectRoot changes * - beforeAppClose -- before Brackets quits entirely * - projectOpen -- after _projectRoot changes and the tree is re-rendered * - projectRefresh -- when project tree is re-rendered for a reason other than * a project being opened (e.g. from the Refresh command) * * These are jQuery events, so to listen for them you do something like this: * $(ProjectManager).on("eventname", handler); */ interface ProjectManager { /** * Returns the root folder of the currently loaded project, or null if no project is open (during * startup, or running outside of app shell). */ getProjectRoot(): Directory; /** * Returns the encoded Base URL of the currently loaded project, or empty string if no project * is open (during startup, or running outside of app shell). */ getBaseUrl(): string; /** * Sets the encoded Base URL of the currently loaded project. * @param {String} */ setBaseUrl(): string; /** * Returns true if absPath lies within the project, false otherwise. * Does not support paths containing ".." */ isWithinProject(absPath: string): boolean; /** * If absPath lies within the project, returns a project-relative path. Else returns absPath * unmodified. * Does not support paths containing ".." * @param absPath */ makeProjectRelativeIfPossible(absPath: string): string; /** * Returns false for files and directories that are not commonly useful to display. * * @param entry File or directory to filter */ shouldShow(entry: FileSystemEntry): boolean; /** * Returns true if fileName's extension doesn't belong to binary (e.g. archived) * @param fileName */ isBinaryFile(fileName: string): boolean; /** * Open a new project. Currently, Brackets must always have a project open, so * this method handles both closing the current project and opening a new project. * return {$.Promise} A promise object that will be resolved when the * project is loaded and tree is rendered, or rejected if the project path * fails to load. * * @param path Optional absolute path to the root folder of the project. * If path is undefined or null, displays a dialog where the user can choose a * folder to load. If the user cancels the dialog, nothing more happens. */ openProject(path?: string): JQueryPromise<any>; /** * Returns the File or Directory corresponding to the item selected in the sidebar panel, whether in * the file tree OR in the working set; or null if no item is selected anywhere in the sidebar. * May NOT be identical to the current Document - a folder may be selected in the sidebar, or the sidebar may not * have the current document visible in the tree & working set. */ getSelectedItem(): FileSystemEntry; /** * Returns an Array of all files for this project, optionally including * files in the working set that are *not* under the project root. Files filtered * out by shouldShow() OR isBinaryFile() are excluded. * * @param filter Optional function to filter * the file list (does not filter directory traversal). API matches Array.filter(). * @param includeWorkingSet If true, include files in the working set * that are not under the project root (*except* for untitled documents). * * @return {$.Promise} Promise that is resolved with an Array of File objects. */ getAllFiles(filter?: (file: File) => boolean, includeWorkingSet?: boolean): JQueryPromise<File[]>; /* TODO getInitialProjectPath; isWelcomeProjectPath; updateWelcomeProjectPath; createNewItem; renameItemInline; deleteItem; forceFinishRename; showInTree; refreshFileTree; getLanguageFilter; */ } //-------------------------------------------------------------------------- // // Document // //-------------------------------------------------------------------------- /** * DocumentManager maintains a list of currently 'open' Documents. It also owns the list of files in * the working set, and the notion of which Document is currently shown in the main editor UI area. * * Document is the model for a file's contents; it dispatches events whenever those contents change. * To transiently inspect a file's content, simply get a Document and call getText() on it. However, * to be notified of Document changes or to modify a Document, you MUST call addRef() to ensure the * Document instance 'stays alive' and is shared by all other who read/modify that file. ('Open' * Documents are all Documents that are 'kept alive', i.e. have ref count > 0). * * To get a Document, call getDocumentForPath(); never new up a Document yourself. * * Secretly, a Document may use an Editor instance to act as the model for its internal state. (This * is unavoidable because CodeMirror does not separate its model from its UI). Documents are not * modifiable until they have a backing 'master Editor'. Creation of the backing Editor is owned by * EditorManager. A Document only gets a backing Editor if it becomes the currentDocument, or if edits * occur in any Editor (inline or full-sized) bound to the Document; there is currently no other way * to ensure a Document is modifiable. * * A non-modifiable Document may still dispatch change notifications, if the Document was changed * externally on disk. * * Aside from the text content, Document tracks a few pieces of metadata - notably, whether there are * any unsaved changes. * * This module dispatches several events: * * - dirtyFlagChange -- When any Document's isDirty flag changes. The 2nd arg to the listener is the * Document whose flag changed. * - documentSaved -- When a Document's changes have been saved. The 2nd arg to the listener is the * Document that has been saved. * - documentRefreshed -- When a Document's contents have been reloaded from disk. The 2nd arg to the * listener is the Document that has been refreshed. * * - currentDocumentChange -- When the value of getCurrentDocument() changes. * * To listen for working set changes, you must listen to *all* of these events: * - workingSetAdd -- When a file is added to the working set (see getWorkingSet()). The 2nd arg * to the listener is the added File, and the 3rd arg is the index it was inserted at. * - workingSetAddList -- When multiple files are added to the working set (e.g. project open, multiple file open). * The 2nd arg to the listener is the array of added File objects. * - workingSetRemove -- When a file is removed from the working set (see getWorkingSet()). The * 2nd arg to the listener is the removed File. * - workingSetRemoveList -- When multiple files are removed from the working set (e.g. project close). * The 2nd arg to the listener is the array of removed File objects. * - workingSetSort -- When the workingSet array is reordered without additions or removals. * Listener receives no arguments. * * - workingSetDisableAutoSorting -- Dispatched in addition to workingSetSort when the reorder was caused * by manual dragging and dropping. Listener receives no arguments. * * - fileNameChange -- When the name of a file or folder has changed. The 2nd arg is the old name. * The 3rd arg is the new name. * - pathDeleted -- When a file or folder has been deleted. The 2nd arg is the path that was deleted. * * These are jQuery events, so to listen for them you do something like this: * $(DocumentManager).on("eventname", handler); * * Document objects themselves also dispatch some events - see Document docs for details. */ export interface DocumentManager { /** * Returns the Document that is currently open in the editor UI. May be null. * When this changes, DocumentManager dispatches a "currentDocumentChange" event. The current * document always has a backing Editor (Document._masterEditor != null) and is thus modifiable. */ getCurrentDocument(): Document; /** Changes currentDocument to null, causing no full Editor to be shown in the UI */ _clearCurrentDocument(): void; /** * Gets an existing open Document for the given file, or creates a new one if the Document is * not currently open ('open' means referenced by the UI somewhere). Always use this method to * get Documents; do not call the Document constructor directly. This method is safe to call * in parallel. * * If you are going to hang onto the Document for more than just the duration of a command - e.g. * if you are going to display its contents in a piece of UI - then you must addRef() the Document * and listen for changes on it. (Note: opening the Document in an Editor automatically manages * refs and listeners for that Editor UI). * * @param fullPath * @return {$.Promise} A promise object that will be resolved with the Document, or rejected * with a FileSystemError if the file is not yet open and can't be read from disk. */ getDocumentForPath(fullPath: string): JQueryPromise<Document>; /** * Returns the existing open Document for the given file, or null if the file is not open ('open' * means referenced by the UI somewhere). If you will hang onto the Document, you must addRef() * it; see {@link getDocumentForPath()} for details. * @param fullPath */ getOpenDocumentForPath(fullPath: string): Document; /** * Gets the text of a Document (including any unsaved changes), or would-be Document if the * file is not actually open. More efficient than getDocumentForPath(). Use when you're reading * document(s) but don't need to hang onto a Document object. * * If the file is open this is equivalent to calling getOpenDocumentForPath().getText(). If the * file is NOT open, this is like calling getDocumentForPath()...getText() but more efficient. * Differs from plain FileUtils.readAsText() in two ways: (a) line endings are still normalized * as in Document.getText(); (b) unsaved changes are returned if there are any. * * @param file */ getDocumentText(file: File): JQueryPromise<string>; /** * Creates an untitled document. The associated File has a fullPath that * looks like /some-random-string/Untitled-counter.fileExt. * * @param counter - used in the name of the new Document's File * @param fileExt - file extension of the new Document's File * @return {Document} - a new untitled Document */ createUntitledDocument(counter: number, fileExt: string): Document; /** * Returns a list of items in the working set in UI list order. May be 0-length, but never null. * * When a file is added this list, DocumentManager dispatches a "workingSetAdd" event. * When a file is removed from list, DocumentManager dispatches a "workingSetRemove" event. * To listen for ALL changes to this list, you must listen for both events. * * Which items belong in the working set is managed entirely by DocumentManager. Callers cannot * (yet) change this collection on their own. * */ getWorkingSet(): File[]; /** * Returns the index of the file matching fullPath in the working set. * Returns -1 if not found. * @param fullPath * @param list Pass this arg to search a different array of files. Internal * use only. * @returns {number} index */ findInWorkingSet(fullPath: string, list?: File[]): number; /*TODO findInWorkingSetAddedOrder() getAllOpenDocuments() setCurrentDocument() addToWorkingSet() addListToWorkingSet() removeFromWorkingSet() removeListFromWorkingSet() getNextPrevFile() swapWorkingSetIndexes() sortWorkingSet() beginDocumentNavigation() finalizeDocumentNavigation() closeFullEditor() closeAll() notifyFileDeleted() notifyPathNameChanged() notifyPathDeleted()*/ } /** * Model for the contents of a single file and its current modification state. * See DocumentManager documentation for important usage notes. * * Document dispatches these events: * * change -- When the text of the editor changes (including due to undo/redo). * * Passes ({Document}, {ChangeList}), where ChangeList is a linked list (NOT an array) * of change record objects. Each change record looks like: * * { from: start of change, expressed as {line: <line number>, ch: <character offset>}, * to: end of change, expressed as {line: <line number>, ch: <chracter offset>}, * text: array of lines of text to replace existing text, * next: next change record in the linked list, or undefined if this is the last record } * * The line and ch offsets are both 0-based. * * The ch offset in "from" is inclusive, but the ch offset in "to" is exclusive. For example, * an insertion of new content (without replacing existing content) is expressed by a range * where from and to are the same. * * If "from" and "to" are undefined, then this is a replacement of the entire text content. * * IMPORTANT: If you listen for the "change" event, you MUST also addRef() the document * (and releaseRef() it whenever you stop listening). You should also listen to the "deleted" * event. * * (FUTURE: this is a modified version of the raw CodeMirror change event format; may want to make * it an ordinary array) * * deleted -- When the file for this document has been deleted. All views onto the document should * be closed. The document will no longer be editable or dispatch "change" events. * */ interface Document { /** * The File for this document. Need not lie within the project. * If Document is untitled, this is an InMemoryFile object. */ file: File; /** * The Language for this document. Will be resolved by file extension in the constructor * @type {!Language} */ //TODO language: Language; /** * Whether this document has unsaved changes or not. * When this changes on any Document, DocumentManager dispatches a "dirtyFlagChange" event. */ isDirty: boolean; /** * Returns the document's current contents; may not be saved to disk yet. Whenever this * value changes, the Document dispatches a "change" event. * * @param useOriginalLineEndings If true, line endings in the result depend on the * Document's line endings setting (based on OS & the original text loaded from disk). * If false, line endings are always \n (like all the other Document text getter methods). */ getText(useOriginalLineEndings?: boolean): string; /** * Adds, replaces, or removes text. If a range is given, the text at that range is replaced with the * given new text; if text == "", then the entire range is effectively deleted. If 'end' is omitted, * then the new text is inserted at that point and all existing text is preserved. Line endings will * be rewritten to match the document's current line-ending style. * * IMPORTANT NOTE: Because of #1688, do not use this in cases where you might be * operating on a linked document (like the main document for an inline editor) * during an outer CodeMirror operation (like a key event that's handled by the * editor itself). A common case of this is code hints in inline editors. In * such cases, use `editor._codeMirror.replaceRange()` instead. This should be * fixed when we migrate to use CodeMirror's native document-linking functionality. * * @param text Text to insert or replace the range with * @param start Start of range, inclusive (if 'to' specified) or insertion point (if not) * @param end End of range, exclusive; optional * @param origin Optional string used to batch consecutive edits for undo. * If origin starts with "+", then consecutive edits with the same origin will be batched for undo if * they are close enough together in time. * If origin starts with "*", then all consecutive edit with the same origin will be batched for * undo. * Edits with origins starting with other characters will not be batched. * (Note that this is a higher level of batching than batchOperation(), which already batches all * edits within it for undo. Origin batching works across operations.) */ replaceRange(text: string, start: CodeMirror.Position, end?: CodeMirror.Position, origin?: string): void; /** * Returns the text of the given line (excluding any line ending characters) * @param index Zero-based line number */ getLine(index: number): string; /** * Sets the contents of the document. Treated as an edit. Line endings will be rewritten to * match the document's current line-ending style. * @param text The text to replace the contents of the document with. */ setText(text: string): void; //TODO imcomplete } //-------------------------------------------------------------------------- // // Editor // //-------------------------------------------------------------------------- /** * Editor is a 1-to-1 wrapper for a CodeMirror editor instance. It layers on Brackets-specific * functionality and provides APIs that cleanly pass through the bits of CodeMirror that the rest * of our codebase may want to interact with. An Editor is always backed by a Document, and stays * in sync with its content; because Editor keeps the Document alive, it's important to always * destroy() an Editor that's going away so it can release its Document ref. * * For now, there's a distinction between the "master" Editor for a Document - which secretly acts * as the Document's internal model of the text state - and the multitude of "slave" secondary Editors * which, via Document, sync their changes to and from that master. * * For now, direct access to the underlying CodeMirror object is still possible via _codeMirror -- * but this is considered deprecated and may go away. * * The Editor object dispatches the following events: * - keyEvent -- When any key event happens in the editor (whether it changes the text or not). * Event handlers are passed ({Editor}, {KeyboardEvent}). The 2nd arg is the raw DOM event. * Note: most listeners will only want to respond when event.type === "keypress". * - cursorActivity -- When the user moves the cursor or changes the selection, or an edit occurs. * Note: do not listen to this in order to be generally informed of edits--listen to the * "change" event on Document instead. * - scroll -- When the editor is scrolled, either by user action or programmatically. * - lostContent -- When the backing Document changes in such a way that this Editor is no longer * able to display accurate text. This occurs if the Document's file is deleted, or in certain * Document->editor syncing edge cases that we do not yet support (the latter cause will * eventually go away). * - optionChange -- Triggered when an option for the editor is changed. The 2nd arg to the listener * is a string containing the editor option that is changing. The 3rd arg, which can be any * data type, is the new value for the editor option. * * The Editor also dispatches "change" events internally, but you should listen for those on * Documents, not Editors. * * These are jQuery events, so to listen for them you do something like this: * $(editorInstance).on("eventname", handler); */ interface Editor { _codeMirror: CodeMirror.Editor; document: Document; getCursorPos(): CodeMirror.Position; getScrollPos(): {x: number; y: number}; getModeForSelection(): string; getSelection(boolean: boolean): { start: CodeMirror.Position; end: CodeMirror.Position }; setCursorPos(line: number, ch: number, center: boolean, expandTabs: boolean): void ; setScrollPos(x:number, y:number): void; indexFromPos(pos: {line:number; ch:number}): number; } interface EditorManager { registerInlineEditProvider(provider: InlineEditProvider, priority?: number): void; registerInlineDocsProvider(provider: InlineDocsProvider, priority?: number): void; registerJumpToDefProvider(provider: JumpDoDefProvider): void; getFocusedEditor(): Editor; /** * Returns the current active editor (full-sized OR inline editor). This editor may not * have focus at the moment, but it is visible and was the last editor that was given * focus. Returns null if no editors are active. * @see getFocusedEditor() * @returns {?Editor} */ getActiveEditor(): Editor; getCurrentFullEditor(): Editor; } //-------------------------------------------------------------------------- // // Editor // //-------------------------------------------------------------------------- /** * PreferencesManager * */ interface PreferencesManager extends Preferences { /** * Creates an extension-specific preferences manager using the prefix given. * A `.` character will be appended to the prefix. So, a preference named `foo` * with a prefix of `myExtension` will be stored as `myExtension.foo` in the * preferences files. * * @param prefix Prefix to be applied */ getExtensionPrefs(prefix: string): Preferences; /** * Get the full path to the user-level preferences file. * * @return Path to the preferences file */ getUserPrefFile(): string; /** * Context to look up preferences for the currently edited file. * This is undefined because this is the default behavior of PreferencesSystem.get. */ CURRENT_FILE: any; /** * Context to look up preferences in the current project. */ CURRENT_PROJECT: any; } interface Preferences { /** * Defines a new (prefixed) preference. * * @param id unprefixed identifier of the preference. Generally a dotted name. * @param type Data type for the preference (generally, string, boolean, number) * @param initial Default value for the preference * @param options Additional options for the pref. Can include name and description * that will ultimately be used in UI. * @return {Object} The preference object. */ definePreference(id: string, type: string, value: any, options?: { name?: string; description: string; }): any; /** * Get the prefixed preference object * * @param {string} id ID of the pref to retrieve. */ getPreference(id: string): any; /** * Gets the prefixed preference * * @param id Name of the preference for which the value should be retrieved * @param context Optional context object to change the preference lookup */ get(id: string, context?: any): any; /** * Gets the location in which the value of a prefixed preference has been set. * * @param id Name of the preference for which the value should be retrieved * @param context Optional context object to change the preference lookup * @return Object describing where the preferences came from */ getPreferenceLocation(id: string, context?: any): {scope: string; layer?: string; layerID?: any}; /** * Sets the prefixed preference * * @param id Identifier of the preference to set * @param value New value for the preference * @param options Specific location in which to set the value or the context to use when setting the value * @return true if a value was set */ set(id: string, value: any, options?: {location: any; context?: any; }): boolean; /** * Sets up a listener for events for this PrefixedPreferencesSystem. Only prefixed events * will notify. Optionally, you can set up a listener for a * specific preference. * * @param event Name of the event to listen for * @param preferenceID Name of a specific preference * @param handler Handler for the event */ on(event: string, preferenceId: string, handler: (...rest: any[]) => void): void; /** * Sets up a listener for events for this PrefixedPreferencesSystem. Only prefixed events * will notify. Optionally, you can set up a listener for a * specific preference. * * @param event Name of the event to listen for * @param handler Handler for the event */ on(event: string, handler: (...rest: any[]) => void): void; /** * Turns off the event handlers for a given event, optionally for a specific preference * or a specific handler function. * * @param event Name of the event for which to turn off listening * @param preferenceID Name of a specific preference * @param handler Specific handler which should stop being notified */ off(event: string, preferenceId: string, handler: (...rest: any[]) => void): void; /** * Turns off the event handlers for a given event, optionally for a specific preference * or a specific handler function. * * @param event Name of the event to listen for * @param handler Specific handler which should stop being notified */ off(event: string, handler: (...rest: any[]) => void): void; /** * Saves the preferences. If a save is already in progress, a Promise is returned for * that save operation. * * @return a promise resolved when the preferences are done saving. */ save(): JQueryPromise<void>; } //-------------------------------------------------------------------------- // // PanelManager // //-------------------------------------------------------------------------- /** * Represents a panel below the editor area (a child of ".content"). */ interface Panel { isVisible(): boolean; show(): void; hide(): void; setVisible(visible: boolean): void; $panel: JQuery } /** * Manages layout of panels surrounding the editor area, and size of the editor area (but not its contents). * * Updates panel sizes when the window is resized. Maintains the max resizing limits for panels, based on * currently available window size. * * Events: * - editorAreaResize -- When editor-holder's size changes for any reason (including panel show/hide * panel resize, or the window resize). * The 2nd arg is the new editor-holder height. * The 3rd arg is a refreshHint flag for internal EditorManager use. */ interface PanelManager { /** * Creates a new panel beneath the editor area and above the status bar footer. Panel is initially invisible. * * @param id Unique id for this panel. Use package-style naming, e.g. "myextension.feature.panelname" * @param $panel DOM content to use as the panel. Need not be in the document yet. * @param minSize Minimum height of panel in px. */ createBottomPanel(id: string, $panel: JQuery, minSize: number): Panel; } //-------------------------------------------------------------------------- // // Command // //-------------------------------------------------------------------------- interface CommandManager { execute(id: string, args: any): JQueryPromise<any>; register(name: string, id: string, callback: () => void): { setEnabled(enabled: boolean): void }; } //-------------------------------------------------------------------------- // // CodeHint // //-------------------------------------------------------------------------- interface CodeHintManager { registerHintProvider(hintProvider: CodeHintProvider, languageIds: string[], priority?: number): void; } interface HintResult { hints?: any []; match?: string; selectInitial?: boolean } interface CodeHintProvider { hasHints(editor: Editor, implicitChar: string): boolean; getHints(implicitChar: string): JQueryDeferred<HintResult>; insertHint(hint: any): void; } //-------------------------------------------------------------------------- // // Inspection // //-------------------------------------------------------------------------- interface CodeInspection { register(languageId: string, provider: InspectionProvider): void; Type: { ERROR: string; /** Maintainability issue, probable error / bad smell, etc. */ WARNING: string; /** Inspector unable to continue, code too complex for static analysis, etc. Not counted in error/warning tally. */ META: string; } } interface LintingError { pos: CodeMirror.Position; endPos?: CodeMirror.Position; message: string; type?: string; } interface InspectionProvider { name: string; scanFile?(content: string, path: string): { errors: LintingError[]; aborted: boolean }; scanFileAsync?(content: string, path: string): JQueryPromise<{ errors: LintingError[]; aborted: boolean }>; } //-------------------------------------------------------------------------- // // QuickEdit // //-------------------------------------------------------------------------- interface InlineEditProvider { (hostEditor: Editor, pos: CodeMirror.Position): JQueryPromise<InlineWidget> } //-------------------------------------------------------------------------- // // QuickOpen // //-------------------------------------------------------------------------- interface QuickOpen { /** * Creates and registers a new QuickOpenPlugin */ addQuickOpenPlugin<S>(def: QuickOpenPluginDef<S>): void; highlightMatch(item: any): string; } interface QuickOpenPluginDef<S> { /** * plug-in name, **must be unique** */ name: string; /** * language Ids array. Example: ["javascript", "css", "html"]. To allow any language, pass []. Required. */ languageIds: string[]; /** * called when quick open is complete. Plug-in should clear its internal state. Optional. */ done?: () => void; /** * takes a query string and a StringMatcher (the use of which is optional but can speed up your searches) * and returns an array of strings that match the query. Required. */ search: (request: string, stringMatcher: StringMatcher) => JQueryPromise<S[]>; /** * takes a query string and returns true if this plug-in wants to provide */ match: (query: string) => boolean; /** * performs an action when a result has been highlighted (via arrow keys, mouseover, etc.). */ itemFocus?: (result: S) => void; /** * performs an action when a result is chosen. */ itemSelect: (result: S) => void; /** * takes a query string and an item string and returns * a <LI> item to insert into the displayed search results. Optional. */ resultsFormatter?: (result: S) => string; /** * options to pass along to the StringMatcher (see StringMatch.StringMatcher for available options). */ matcherOptions?: StringMatcherOptions; /** * if provided, the label to show before the query field. Optional. */ label?: string; } interface StringMatcherOptions { preferPrefixMatches?: boolean; segmentedSearch?: boolean; } interface StringMatcher { match(target: string, query: string): { stringRanges: { text: string; matched: boolean; includesLastSegment: boolean}[]; matchGoodness: number; scoreDebug: any; } } //-------------------------------------------------------------------------- // // Todo // //-------------------------------------------------------------------------- interface InlineDocsProvider { (hostEditor: Editor, pos: CodeMirror.Position): JQueryPromise<InlineWidget> } interface JumpDoDefProvider { (hostEditor: Editor, pos: CodeMirror.Position): JQueryPromise<boolean> } interface InlineWidget { load(editor: Editor): void } module MultiRangeInlineEditor { class MultiRangeInlineEditor implements InlineWidget { constructor(ranges: MultiRangeInlineEditorRange[]); load(editor: Editor): void; } } interface MultiRangeInlineEditorRange { name: string; document: brackets.Document; lineStart: number; lineEnd: number; } function getModule(module: 'filesystem/FileSystem'): FileSystem; function getModule(module: 'document/DocumentManager'): brackets.DocumentManager; function getModule(module: 'project/ProjectManager'): brackets.ProjectManager; function getModule(module: 'editor/CodeHintManager'): CodeHintManager; function getModule(module: 'editor/EditorManager'): EditorManager; function getModule(module: 'editor/MultiRangeInlineEditor'): typeof MultiRangeInlineEditor; function getModule(module: 'language/CodeInspection'): CodeInspection; function getModule(module: 'view/PanelManager'): PanelManager; function getModule(module: 'command/CommandManager'): CommandManager; function getModule(module: 'search/QuickOpen'): QuickOpen; function getModule(module: 'preferences/PreferencesManager'): PreferencesManager; function getModule(module: string): any; }
the_stack
import { Component, Inject, OnDestroy, OnInit } from '@angular/core'; import { AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { combineLatest, EMPTY, from, Observable, Subject, zip } from 'rxjs'; import { catchError, filter, mergeMap, shareReplay, switchMap, takeUntil, tap } from 'rxjs/operators'; import { isEmpty } from 'lodash'; import { OrgSettingsUserDetailAddGroupDialogComponent, OrgSettingsUserDetailAddGroupDialogData, OrgSettingsUserDetailAddGroupDialogReturn, } from './org-settings-user-detail-add-group-dialog.component'; import { OrgSettingsUserGenerateTokenComponent, OrgSettingsUserGenerateTokenDialogData, } from './tokens/org-settings-user-generate-token.component'; import { UIRouterStateParams } from '../../../../ajs-upgraded-providers'; import { Environment } from '../../../../entities/environment/environment'; import { Group } from '../../../../entities/group/group'; import { User } from '../../../../entities/user/user'; import { EnvironmentService } from '../../../../services-ngx/environment.service'; import { GroupService } from '../../../../services-ngx/group.service'; import { RoleService } from '../../../../services-ngx/role.service'; import { SnackBarService } from '../../../../services-ngx/snack-bar.service'; import { UsersService } from '../../../../services-ngx/users.service'; import { GioConfirmDialogComponent, GioConfirmDialogData, } from '../../../../shared/components/gio-confirm-dialog/gio-confirm-dialog.component'; import { GioTableWrapperFilters } from '../../../../shared/components/gio-table-wrapper/gio-table-wrapper.component'; import { gioTableFilterCollection } from '../../../../shared/components/gio-table-wrapper/gio-table-wrapper.util'; import { UserHelper } from '../../../../entities/user/userHelper'; import { Token } from '../../../../entities/user/userTokens'; import { UsersTokenService } from '../../../../services-ngx/users-token.service'; interface UserVM extends User { organizationRoles: string; avatarUrl: string; badgeCSSClass: string; } interface EnvironmentDS { id: string; name?: string; description?: string; roles: string; } interface GroupDS { id: string; name: string; } interface ApiDS { id: string; version: string; visibility: string; } interface ApplicationDS { id: string; name: string; } interface TokenDS { id: string; name: string; createdAt: number; lastUseAt?: number; } @Component({ selector: 'org-settings-user-detail', template: require('./org-settings-user-detail.component.html'), styles: [require('./org-settings-user-detail.component.scss')], }) export class OrgSettingsUserDetailComponent implements OnInit, OnDestroy { user: UserVM; organizationRoles$ = this.roleService.list('ORGANIZATION').pipe(shareReplay()); environmentRoles$ = this.roleService.list('ENVIRONMENT').pipe(shareReplay()); apiRoles$ = this.roleService.list('API').pipe(shareReplay()); applicationRoles$ = this.roleService.list('APPLICATION').pipe(shareReplay()); organizationRolesControl: FormControl; environmentsRolesFormGroup: FormGroup; groupsRolesFormGroup: FormGroup; environmentsTableDS: EnvironmentDS[]; environmentsTableDisplayedColumns = ['name', 'description', 'roles']; groupsTableDS: GroupDS[]; groupsTableDisplayedColumns = ['name', 'groupAdmin', 'apiRoles', 'applicationRole', 'delete']; apisTableDS: ApiDS[]; apisTableDisplayedColumns = ['name', 'version', 'visibility']; applicationsTableDS: ApplicationDS[]; applicationsTableDisplayedColumns = ['name']; tokensTableDS: TokenDS[]; tokensTableDisplayedColumns = ['name', 'createdAt', 'lastUseAt', 'action']; openSaveBar = false; invalidStateSaveBar = false; private initialTableDS: Record< 'environmentsTableDS' | 'groupsTableDS' | 'apisTableDS' | 'applicationsTableDS' | 'tokensTableDS', unknown[] > = { apisTableDS: [], applicationsTableDS: [], environmentsTableDS: [], groupsTableDS: [], tokensTableDS: [] }; private unsubscribe$ = new Subject<boolean>(); constructor( private readonly usersService: UsersService, private readonly usersTokenService: UsersTokenService, private readonly roleService: RoleService, private readonly groupService: GroupService, private readonly snackBarService: SnackBarService, private readonly environmentService: EnvironmentService, private readonly matDialog: MatDialog, @Inject(UIRouterStateParams) private readonly ajsStateParams, ) {} ngOnInit(): void { combineLatest([ this.usersService.get(this.ajsStateParams.userId), this.environmentService.list(), this.usersService.getUserGroups(this.ajsStateParams.userId), ]) .pipe(takeUntil(this.unsubscribe$)) .subscribe(([user, environments, groups]) => { const organizationRoles = user.roles.filter((r) => r.scope === 'ORGANIZATION'); this.user = { ...user, organizationRoles: organizationRoles.map((r) => r.name ?? r.id).join(', '), avatarUrl: this.usersService.getUserAvatar(this.ajsStateParams.userId), badgeCSSClass: UserHelper.getStatusBadgeCSSClass(user), }; this.initOrganizationRolesForm(); this.environmentsTableDS = environments.map((e) => ({ id: e.id, name: e.name, description: e.description, roles: '' })); this.initialTableDS['environmentsTableDS'] = this.environmentsTableDS; this.initEnvironmentsRolesForm(environments); this.groupsTableDS = groups.map((g) => ({ id: g.id, name: g.name, })); this.initialTableDS['groupsTableDS'] = this.groupsTableDS; this.initGroupsRolesForm(groups); }); this.usersService .getMemberships(this.ajsStateParams.userId, 'api') .pipe(takeUntil(this.unsubscribe$)) .subscribe(({ metadata }) => { this.apisTableDS = Object.entries(metadata).map(([apiId, apiMetadata]: [string, any]) => ({ id: apiId, name: apiMetadata.name, version: apiMetadata.version, visibility: apiMetadata.visibility, })); this.initialTableDS['apisTableDS'] = this.apisTableDS; }); this.usersService .getMemberships(this.ajsStateParams.userId, 'application') .pipe(takeUntil(this.unsubscribe$)) .subscribe(({ metadata }) => { this.applicationsTableDS = Object.entries(metadata).map(([applicationId, applicationMetadata]: [string, any]) => ({ id: applicationId, name: applicationMetadata.name, })); this.initialTableDS['applicationsTableDS'] = this.applicationsTableDS; }); this.usersTokenService .getTokens(this.ajsStateParams.userId) .pipe(takeUntil(this.unsubscribe$)) .subscribe((response) => { this.tokensTableDS = response.map((token) => ({ id: token.id, createdAt: token.created_at, lastUseAt: token.last_use_at, name: token.name, })); this.initialTableDS['tokensTableDS'] = this.tokensTableDS; }); } ngOnDestroy() { this.unsubscribe$.next(true); this.unsubscribe$.complete(); } toggleSaveBar(open?: boolean) { this.openSaveBar = open ?? !this.openSaveBar; } onSaveBarSubmit() { let observableToZip: Observable<void>[] = []; // Organization if (this.organizationRolesControl.dirty) { observableToZip.push( this.usersService .updateUserRoles(this.user.id, 'ORGANIZATION', 'DEFAULT', this.organizationRolesControl.value) .pipe(takeUntil(this.unsubscribe$)), ); } // Environments if (this.environmentsRolesFormGroup.dirty) { observableToZip.push( from(Object.keys(this.environmentsRolesFormGroup.controls)).pipe( mergeMap((envId) => { const envRolesControl = this.environmentsRolesFormGroup.get(envId) as FormControl; if (envRolesControl.dirty) { return this.usersService.updateUserRoles(this.user.id, 'ENVIRONMENT', envId, envRolesControl.value); } // skip if no change on environment roles return EMPTY; }), ), ); } // Groups if (this.groupsRolesFormGroup.dirty) { observableToZip.push( from(Object.keys(this.groupsRolesFormGroup.controls)).pipe( mergeMap((groupId) => { const groupRolesFormGroup = this.groupsRolesFormGroup.get(groupId) as FormGroup; if (groupRolesFormGroup.dirty) { const { GROUP, API, APPLICATION } = groupRolesFormGroup.value; return this.groupService.addOrUpdateMemberships(groupId, [ { id: this.user.id, roles: [ { scope: 'GROUP' as const, name: GROUP ? 'ADMIN' : '' }, { scope: 'API' as const, name: API }, { scope: 'APPLICATION' as const, name: APPLICATION }, ], }, ]); } // skip if no change on groups roles return EMPTY; }), ), ); } // After all observables emit, emit all success message as an array zip(...observableToZip) .pipe( takeUntil(this.unsubscribe$), tap(() => { this.snackBarService.success('Roles successfully updated'); }), catchError(({ error }) => { this.snackBarService.error(error.message); return EMPTY; }), ) .subscribe(() => { observableToZip = []; this.toggleSaveBar(false); }); } onResetPassword() { this.matDialog .open<GioConfirmDialogComponent, GioConfirmDialogData>(GioConfirmDialogComponent, { width: '500px', data: { title: 'Reset user password', content: ` Are you sure you want to reset password of user <strong>${this.user.displayName}</strong> ? <br> The user will receive an email with a link to set a new password. `, confirmButton: 'Reset', }, role: 'alertdialog', id: 'resetUserPasswordConfirmDialog', }) .afterClosed() .pipe( takeUntil(this.unsubscribe$), filter((confirm) => confirm === true), switchMap(() => this.usersService.resetPassword(this.user.id)), tap(() => this.snackBarService.success(`The password of user "${this.user.displayName}" has been successfully reset`)), catchError(({ error }) => { this.snackBarService.error(error.message); return EMPTY; }), ) .subscribe(() => this.ngOnInit()); } onProcessRegistration(state: 'accept' | 'reject') { const wording = { accept: { content: `Are you sure you want to accept the registration request of <strong>${this.user.displayName}</strong> ?`, confirmButton: 'Accept', success: `User "${this.user.displayName}" has been accepted`, }, reject: { content: `Are you sure you want to reject the registration request of <strong>${this.user.displayName}</strong> ?`, confirmButton: 'Reject', success: `User "${this.user.displayName}" has been rejected`, }, }; this.matDialog .open<GioConfirmDialogComponent, GioConfirmDialogData>(GioConfirmDialogComponent, { width: '500px', data: { title: 'User registration', content: wording[state].content, confirmButton: wording[state].confirmButton, }, role: 'alertdialog', id: 'userRegistrationConfirmDialog', }) .afterClosed() .pipe( takeUntil(this.unsubscribe$), filter((confirm) => confirm === true), switchMap(() => this.usersService.processRegistration(this.user.id, state === 'accept')), tap(() => this.snackBarService.success(wording[state].success)), catchError(({ error }) => { this.snackBarService.error(error.message); return EMPTY; }), ) .subscribe(() => this.ngOnInit()); } onFiltersChanged(tableDSPropertyKey: string, filters: GioTableWrapperFilters) { let initialCollection = this.initialTableDS[tableDSPropertyKey]; if (!initialCollection) { // If no initial collection save the first one this.initialTableDS[tableDSPropertyKey] = this[tableDSPropertyKey]; initialCollection = this[tableDSPropertyKey]; } this[tableDSPropertyKey] = gioTableFilterCollection(initialCollection, filters, { searchTermIgnoreKeys: ['id'], }); } onSaveBarReset() { this.ngOnInit(); this.toggleSaveBar(false); } onDeleteGroupClick(group: Group) { this.matDialog .open<GioConfirmDialogComponent, GioConfirmDialogData>(GioConfirmDialogComponent, { width: '500px', data: { title: 'Delete user form the group', content: `Are you sure you want to delete the user from the group <strong>${group.name}</strong> ?`, confirmButton: 'Delete', }, role: 'alertdialog', id: 'removeGroupMemberConfirmDialog', }) .afterClosed() .pipe( takeUntil(this.unsubscribe$), filter((confirm) => confirm === true), switchMap(() => this.groupService.deleteMember(group.id, this.user.id)), tap(() => this.snackBarService.success(`"${this.user.displayName}" has been deleted from the group "${group.name}"`)), catchError(({ error }) => { this.snackBarService.error(error.message); return EMPTY; }), ) .subscribe(() => this.ngOnInit()); } onAddGroupClicked() { this.matDialog .open< OrgSettingsUserDetailAddGroupDialogComponent, OrgSettingsUserDetailAddGroupDialogData, OrgSettingsUserDetailAddGroupDialogReturn >(OrgSettingsUserDetailAddGroupDialogComponent, { width: '500px', data: { groupIdAlreadyAdded: this.groupsTableDS.map((g) => g.id), }, role: 'alertdialog', id: 'addGroupConfirmDialog', }) .afterClosed() .pipe( takeUntil(this.unsubscribe$), filter((groupeAdded) => !isEmpty(groupeAdded)), switchMap((groupeAdded) => this.groupService.addOrUpdateMemberships(groupeAdded.groupId, [ { id: this.user.id, roles: [ { scope: 'GROUP' as const, name: groupeAdded.isAdmin ? 'ADMIN' : '' }, { scope: 'API' as const, name: groupeAdded.apiRole }, { scope: 'APPLICATION' as const, name: groupeAdded.applicationRole }, ], }, ]), ), tap(() => { this.snackBarService.success('Roles successfully updated'); }), catchError(({ error }) => { this.snackBarService.error(error.message); return EMPTY; }), ) .subscribe(() => this.ngOnInit()); } private initOrganizationRolesForm() { const organizationRoles = this.user.roles.filter((r) => r.scope === 'ORGANIZATION'); this.organizationRolesControl = new FormControl({ value: organizationRoles.map((r) => r.id), disabled: this.user.status !== 'ACTIVE' }); this.organizationRolesControl.valueChanges.pipe(takeUntil(this.unsubscribe$)).subscribe(() => { this.toggleSaveBar(true); }); } private initEnvironmentsRolesForm(environments: Environment[]) { this.environmentsRolesFormGroup = new FormGroup( environments.reduce((result, environment) => { const userEnvRoles = this.user.envRoles[environment.id] ?? []; return { ...result, [environment.id]: new FormControl({ value: userEnvRoles.map((r) => r.id), disabled: this.user.status !== 'ACTIVE' }), }; }, {}), ); this.environmentsRolesFormGroup.valueChanges.pipe(takeUntil(this.unsubscribe$)).subscribe(() => { this.toggleSaveBar(true); }); } private initGroupsRolesForm(groups: Group[]) { const leastOneGroupRoleIsRequiredValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => { const groupRolesFormGroup = control as FormGroup; const GROUP = groupRolesFormGroup.get('GROUP').value; const API = groupRolesFormGroup.get('API').value; const APPLICATION = groupRolesFormGroup.get('APPLICATION').value; if (GROUP || API || APPLICATION) { return null; } return { leastOneIsRequired: true, }; }; this.groupsRolesFormGroup = new FormGroup({ ...groups.reduce((result, group) => { return { ...result, [group.id]: new FormGroup( { GROUP: new FormControl({ value: group.roles['GROUP'], disabled: this.user.status !== 'ACTIVE' }), API: new FormControl({ value: group.roles['API'], disabled: this.user.status !== 'ACTIVE' }), APPLICATION: new FormControl({ value: group.roles['APPLICATION'], disabled: this.user.status !== 'ACTIVE' }), }, [leastOneGroupRoleIsRequiredValidator], ), }; }, {}), }); this.groupsRolesFormGroup.valueChanges.pipe(takeUntil(this.unsubscribe$)).subscribe(() => { this.toggleSaveBar(true); }); this.groupsRolesFormGroup.statusChanges.pipe(takeUntil(this.unsubscribe$)).subscribe((status) => { this.invalidStateSaveBar = status !== 'VALID'; }); } onDeleteTokenClicked(token: TokenDS) { this.matDialog .open<GioConfirmDialogComponent, GioConfirmDialogData, boolean>(GioConfirmDialogComponent, { width: '450px', data: { title: 'Revoke a token', content: `Are you sure you want to revoke the token <strong>${token.name}</strong>?`, confirmButton: 'Remove', }, role: 'alertdialog', id: 'revokeUsersTokenDialog', }) .afterClosed() .pipe( takeUntil(this.unsubscribe$), filter((confirm) => confirm === true), switchMap(() => this.usersTokenService.revokeToken(this.ajsStateParams.userId, token.id)), tap(() => this.snackBarService.success(`Token successfully deleted!`)), catchError(({ error }) => { this.snackBarService.error(error.message); return EMPTY; }), ) .subscribe(() => this.ngOnInit()); } onGenerateTokenClicked() { this.matDialog .open<OrgSettingsUserGenerateTokenComponent, OrgSettingsUserGenerateTokenDialogData, Token>(OrgSettingsUserGenerateTokenComponent, { width: '750px', data: { userId: this.ajsStateParams.userId, }, role: 'dialog', id: 'generateTokenDialog', }) .afterClosed() .pipe(takeUntil(this.unsubscribe$)) .subscribe(() => this.ngOnInit()); } isServiceUser(): boolean { return !this.user.firstname; } }
the_stack
import {fakeAsync, TestBed, tick} from "@angular/core/testing"; import {ViewFileOptionsService} from "../../../../services/files/view-file-options.service"; import {ViewFileOptions} from "../../../../services/files/view-file-options"; import {ViewFile} from "../../../../services/files/view-file"; import {LoggerService} from "../../../../services/utils/logger.service"; import {MockStorageService} from "../../../mocks/mock-storage.service"; import {LOCAL_STORAGE, StorageService} from "angular-webstorage-service"; import {StorageKeys} from "../../../../common/storage-keys"; function createViewOptionsService(): ViewFileOptionsService { return new ViewFileOptionsService( TestBed.get(LoggerService), TestBed.get(LOCAL_STORAGE) ); } describe("Testing view file options service", () => { let viewOptionsService: ViewFileOptionsService; let storageService: StorageService; beforeEach(() => { TestBed.configureTestingModule({ providers: [ ViewFileOptionsService, LoggerService, {provide: LOCAL_STORAGE, useClass: MockStorageService}, ] }); viewOptionsService = TestBed.get(ViewFileOptionsService); storageService = TestBed.get(LOCAL_STORAGE); }); it("should create an instance", () => { expect(viewOptionsService).toBeDefined(); }); it("should forward default options", fakeAsync(() => { let count = 0; viewOptionsService.options.subscribe({ next: options => { expect(options.showDetails).toBe(false); expect(options.sortMethod).toBe(ViewFileOptions.SortMethod.STATUS); expect(options.selectedStatusFilter).toBeNull(); expect(options.nameFilter).toBeNull(); expect(options.pinFilter).toBe(false); count++; } }); tick(); expect(count).toBe(1); })); it("should forward updates to showDetails", fakeAsync(() => { let count = 0; let showDetails = null; viewOptionsService.options.subscribe({ next: options => { showDetails = options.showDetails; count++; } }); tick(); expect(count).toBe(1); viewOptionsService.setShowDetails(true); tick(); expect(showDetails).toBe(true); expect(count).toBe(2); viewOptionsService.setShowDetails(false); tick(); expect(showDetails).toBe(false); expect(count).toBe(3); // Setting same value shouldn't trigger an update viewOptionsService.setShowDetails(false); tick(); expect(showDetails).toBe(false); expect(count).toBe(3); })); it("should load showDetails from storage", fakeAsync(() => { spyOn(storageService, "get").and.callFake(key => { if (key === StorageKeys.VIEW_OPTION_SHOW_DETAILS) { return true; } }); // Recreate the service viewOptionsService = createViewOptionsService(); expect(storageService.get).toHaveBeenCalledWith(StorageKeys.VIEW_OPTION_SHOW_DETAILS); let count = 0; let showDetails = null; viewOptionsService.options.subscribe({ next: options => { showDetails = options.showDetails; count++; } }); tick(); expect(count).toBe(1); expect(showDetails).toBe(true); })); it("should save showDetails to storage", fakeAsync(() => { spyOn(storageService, "set"); viewOptionsService.setShowDetails(true); expect(storageService.set).toHaveBeenCalledWith( StorageKeys.VIEW_OPTION_SHOW_DETAILS, true ); viewOptionsService.setShowDetails(false); expect(storageService.set).toHaveBeenCalledWith( StorageKeys.VIEW_OPTION_SHOW_DETAILS, false ); })); it("should forward updates to sortMethod", fakeAsync(() => { let count = 0; let sortMethod = null; viewOptionsService.options.subscribe({ next: options => { sortMethod = options.sortMethod; count++; } }); tick(); expect(count).toBe(1); viewOptionsService.setSortMethod(ViewFileOptions.SortMethod.NAME_ASC); tick(); expect(sortMethod).toBe(ViewFileOptions.SortMethod.NAME_ASC); expect(count).toBe(2); viewOptionsService.setSortMethod(ViewFileOptions.SortMethod.NAME_DESC); tick(); expect(sortMethod).toBe(ViewFileOptions.SortMethod.NAME_DESC); expect(count).toBe(3); // Setting same value shouldn't trigger an update viewOptionsService.setSortMethod(ViewFileOptions.SortMethod.NAME_DESC); tick(); expect(sortMethod).toBe(ViewFileOptions.SortMethod.NAME_DESC); expect(count).toBe(3); })); it("should load sortMethod from storage", fakeAsync(() => { spyOn(storageService, "get").and.callFake(key => { if (key === StorageKeys.VIEW_OPTION_SORT_METHOD) { return ViewFileOptions.SortMethod.NAME_ASC; } }); // Recreate the service viewOptionsService = createViewOptionsService(); expect(storageService.get).toHaveBeenCalledWith(StorageKeys.VIEW_OPTION_SHOW_DETAILS); let count = 0; let sortMethod = null; viewOptionsService.options.subscribe({ next: options => { sortMethod = options.sortMethod; count++; } }); tick(); expect(count).toBe(1); expect(sortMethod).toBe(ViewFileOptions.SortMethod.NAME_ASC); })); it("should save sortMethod to storage", fakeAsync(() => { spyOn(storageService, "set"); viewOptionsService.setSortMethod(ViewFileOptions.SortMethod.NAME_ASC); expect(storageService.set).toHaveBeenCalledWith( StorageKeys.VIEW_OPTION_SORT_METHOD, ViewFileOptions.SortMethod.NAME_ASC ); viewOptionsService.setSortMethod(ViewFileOptions.SortMethod.NAME_DESC); expect(storageService.set).toHaveBeenCalledWith( StorageKeys.VIEW_OPTION_SORT_METHOD, ViewFileOptions.SortMethod.NAME_DESC ); })); it("should forward updates to selectedStatusFilter", fakeAsync(() => { let count = 0; let selectedStatusFilter = null; viewOptionsService.options.subscribe({ next: options => { selectedStatusFilter = options.selectedStatusFilter; count++; } }); tick(); expect(count).toBe(1); viewOptionsService.setSelectedStatusFilter(ViewFile.Status.EXTRACTED); tick(); expect(selectedStatusFilter).toBe(ViewFile.Status.EXTRACTED); expect(count).toBe(2); viewOptionsService.setSelectedStatusFilter(ViewFile.Status.QUEUED); tick(); expect(selectedStatusFilter).toBe(ViewFile.Status.QUEUED); expect(count).toBe(3); // Setting same value shouldn't trigger an update viewOptionsService.setSelectedStatusFilter(ViewFile.Status.QUEUED); tick(); expect(selectedStatusFilter).toBe(ViewFile.Status.QUEUED); expect(count).toBe(3); // Null should be allowed viewOptionsService.setSelectedStatusFilter(null); tick(); expect(selectedStatusFilter).toBeNull(); expect(count).toBe(4); })); it("should forward updates to nameFilter", fakeAsync(() => { let count = 0; let nameFilter = null; viewOptionsService.options.subscribe({ next: options => { nameFilter = options.nameFilter; count++; } }); tick(); expect(count).toBe(1); viewOptionsService.setNameFilter("tofu"); tick(); expect(nameFilter).toBe("tofu"); expect(count).toBe(2); viewOptionsService.setNameFilter("flower"); tick(); expect(nameFilter).toBe("flower"); expect(count).toBe(3); // Setting same value shouldn't trigger an update viewOptionsService.setNameFilter("flower"); tick(); expect(nameFilter).toBe("flower"); expect(count).toBe(3); // Null should be allowed viewOptionsService.setNameFilter(null); tick(); expect(nameFilter).toBeNull(); expect(count).toBe(4); })); it("should forward updates to pinFilter", fakeAsync(() => { let count = 0; let pinFilter = null; viewOptionsService.options.subscribe({ next: options => { pinFilter = options.pinFilter; count++; } }); tick(); expect(count).toBe(1); viewOptionsService.setPinFilter(true); tick(); expect(pinFilter).toBe(true); expect(count).toBe(2); viewOptionsService.setPinFilter(false); tick(); expect(pinFilter).toBe(false); expect(count).toBe(3); // Setting same value shouldn't trigger an update viewOptionsService.setPinFilter(false); tick(); expect(pinFilter).toBe(false); expect(count).toBe(3); })); it("should load pinFilter from storage", fakeAsync(() => { spyOn(storageService, "get").and.callFake(key => { if (key === StorageKeys.VIEW_OPTION_PIN) { return true; } }); // Recreate the service viewOptionsService = createViewOptionsService(); expect(storageService.get).toHaveBeenCalledWith(StorageKeys.VIEW_OPTION_PIN); let count = 0; let pinFilter = null; viewOptionsService.options.subscribe({ next: options => { pinFilter = options.pinFilter; count++; } }); tick(); expect(count).toBe(1); expect(pinFilter).toBe(true); })); it("should save pinFilter to storage", fakeAsync(() => { spyOn(storageService, "set"); viewOptionsService.setPinFilter(true); expect(storageService.set).toHaveBeenCalledWith( StorageKeys.VIEW_OPTION_PIN, true ); viewOptionsService.setPinFilter(false); expect(storageService.set).toHaveBeenCalledWith( StorageKeys.VIEW_OPTION_PIN, false ); })); });
the_stack
import Icon from 'polestar-icons'; import React, { Component } from 'react'; import { Spin, Row, Col, Card, Button, Input, Select } from 'antd'; import { Entity } from 'aframe'; import uuid from 'uuid/v4'; import AddEmpty from './AddEmpty'; import Scrollbar from './Scrollbar'; import Empty from './Empty'; import { formatTime, formatBytes } from '../../tools/UtilTools'; import { ImageDatabase } from '../../database'; import { UtilTools } from '../../tools'; export interface ITexture { id: string; url: string; name: string; type: string; size: number; width?: number; height?: number; duration?: number; file?: Blob; thumbnail?: Blob | string; } type FilterType = 'all' | 'image' | 'video' | 'audio' | 'image/video' | 'etc' | string; interface IProps { onClick?: (value?: any) => void; type?: FilterType; visible?: boolean; } interface IState { textures: ITexture[]; loading: boolean; searchTexture: string; selectedFilterType: FilterType; } const selectFilterTypes = [ { value: 'all', text: 'All' }, { value: 'image', text: 'Image' }, { value: 'video', text: 'Video' }, { value: 'audio', text: 'Audio' }, { value: 'etc', text: 'Etc.' }, ]; class Textures extends Component<IProps, IState> { state: IState = { textures: [], loading: false, searchTexture: '', selectedFilterType: 'all', }; componentDidMount() { this.getTextures(); } componentDidUpdate(prevProps: IProps) { if (this.props.visible && this.props.visible !== prevProps.visible) { this.getTextures(); } } /** * @description Get textures */ private getTextures = async () => { this.setState({ loading: true, }); try { const response = await ImageDatabase.allDocs(); const { total_rows, rows } = response; if (total_rows) { const fileList = rows.reduce((prev, row, index) => { const { doc, id } = row; const { _attachments, title } = doc; const attachment = _attachments[title]; const { data, content_type } = attachment; const file = new File([data], title, { type: content_type }); return Object.assign(prev, { [index]: { id, file, }, }); }, {}) as { [key: string]: { id: string; file: File } }; await this.handleAppendTexture(fileList); this.setState({ loading: false, }); } else { this.setState({ loading: false, }); } } catch (error) { this.setState({ loading: false, }); console.error(error.toString()); } }; /** * @description Handle file chooser in input element */ private handleAddTexture = () => { const { type } = this.props; const { selectedFilterType } = this.state; const allTypes = ['image/*', 'video/*', 'audio/*', '.obj', '.mtl', '.gltf', '.glb', '.patt']; const input = document.createElement('input'); input.setAttribute('type', 'file'); const setAcceptType = (type: string, input: Entity) => { if (type === 'image') { input.setAttribute('accept', allTypes[0]); } else if (type === 'video') { input.setAttribute('accept', allTypes[1]); } else if (type === 'audio') { input.setAttribute('accept', allTypes[2]); } else if (type === 'image/video') { input.setAttribute('accept', `${allTypes[0]}, ${allTypes[1]}`); } else if (type === 'etc') { allTypes.splice(0, 3); input.setAttribute('accept', allTypes.join(',')); } }; if (typeof type === 'undefined') { if (selectedFilterType === 'all') { input.setAttribute('accept', allTypes); } else { setAcceptType(selectedFilterType, input); } } else { setAcceptType(type, input); } input.setAttribute('multiple', true); input.hidden = true; input.onchange = (e: any) => { this.setState( { loading: true, }, async () => { const docs = Object.keys(e.target.files).map(key => { const file = e.target.files[parseInt(key, 10)] as File; return { _id: uuid(), title: file.name, _attachments: { [file.name]: { content_type: file.type.length ? file.type : 'application/octet-stream', data: file, }, }, }; }); try { await ImageDatabase.bulkDocs(docs); await this.getTextures(); } catch (error) { this.setState({ loading: false, }); console.error(error.toString()); } }, ); }; document.body.appendChild(input); // required for firefox input.click(); input.remove(); }; /** * @description Append textures * @param {{ id: string, file: File }[]} files */ private handleAppendTexture = async (files: { [key: string]: { id: string; file: File } }) => { const textures = (await Promise.all( Object.keys(files).map((value: string, index: number) => { return new Promise((resolve, reject) => { const { file, id } = files[parseInt(value, 10)]; const reader = new FileReader(); const type = file.type.length ? file.type : 'application/octet-stream'; reader.onloadend = () => { const url = window.URL.createObjectURL(file); if (file.type.includes('image')) { const image = new Image(); image.src = url; image.onload = () => { const texture: ITexture = { id, name: file.name, size: file.size, type, width: image.width, height: image.height, url, file, }; resolve(texture); }; } else if (file.type.includes('video')) { const video = document.createElement('video') as any; video.src = url; video.onloadedmetadata = () => { const texture: ITexture = { id, name: file.name, size: file.size, type, width: video.videoWidth, height: video.videoHeight, url, file, duration: video.duration, }; resolve(texture); }; } else if (file.type.includes('audio')) { const audio = new Audio(); audio.src = url; audio.onloadedmetadata = () => { const texture: ITexture = { id, name: file.name, size: file.size, type, url, file, duration: audio.duration, }; resolve(texture); }; } else { const texture: ITexture = { id, name: file.name, size: file.size, type, url, file, }; resolve(texture); } if (length === index + 1) { this.setState({ loading: false, }); } }; reader.onerror = reject; reader.readAsBinaryString(file); }); }), )) as ITexture[]; this.setState({ textures, }); }; /** * @description Select texture * @param {ITexture} texture */ private handleSelectTexture = (texture: ITexture) => { const { onClick } = this.props; if (onClick) { onClick(texture); } }; /** * @description Search texture * @param {string} searchTexture */ private handleSearchTexture = (searchTexture: string) => { this.setState({ searchTexture, }); }; /** * @description Select filter type * @param {FilterType} selectedFilterType */ private handleFilterType = (selectedFilterType: FilterType) => { this.setState({ selectedFilterType, }); }; /** * @description Render card actions * @param {ITexture} texture * @returns */ private renderCardActions = (texture: ITexture) => { return [ <Icon key="download" name="download" onClick={e => { e.stopPropagation(); UtilTools.saveBlob(texture.file, texture.name); }} />, <Icon key="delete" name="trash" onClick={async e => { e.stopPropagation(); await ImageDatabase.delete(texture.id); this.getTextures(); }} />, ]; }; /** * @description Render textures on card * @param {ITexture[]} textures * @param {string} searchTexture * @returns {React.ReactNode} */ private renderCardItems = (textures: ITexture[], searchTexture: string, selectedFilterType: string) => { const { type } = this.props; const items = textures .filter(texture => { if (type) { if (type === 'image/video') { if (selectedFilterType === 'all') { const filterTypes = type.split('/'); return texture.type.includes(filterTypes[0]) || texture.type.includes(filterTypes[1]); } return texture.type.includes(selectedFilterType); } else if (type === 'etc') { return texture.type.includes('application'); } return texture.type.includes(type); } else { if (selectedFilterType === 'all') { return true; } else if (selectedFilterType === 'etc') { return texture.type.includes('application'); } return texture.type.includes(selectedFilterType); } }) .filter(texture => texture.name.includes(searchTexture.toLowerCase())); return ( <Scrollbar> {items.length ? ( <Row gutter={16} style={{ margin: 0 }}> {items.map(texture => { let description; let cover; if (texture.type.includes('image')) { description = ( <> <div>{`${texture.width} x ${texture.height}`}</div> <div>{formatBytes(texture.size)}</div> </> ); cover = <img alt="exmaple" src={texture.url} />; } else if (texture.type.includes('video')) { description = ( <> <div>{formatTime(texture.duration)}</div> <div>{`${texture.width} x ${texture.height}`}</div> </> ); cover = <video src={texture.url} />; } else if (texture.type.includes('audio')) { description = ( <> <div>{formatTime(texture.duration)}</div> <div>{formatBytes(texture.size)}</div> </> ); cover = <img src="/images/audio.png" />; } else { description = formatBytes(texture.size); cover = <img src="/images/file.png" />; } return ( <Col key={texture.id} md={24} lg={12} xl={6} onClick={() => this.handleSelectTexture(texture)} > <Card hoverable={true} style={{ marginBottom: 16 }} bodyStyle={{ height: 100 }} cover={cover} actions={this.renderCardActions(texture)} > <Card.Meta title={texture.name} description={description} /> </Card> </Col> ); })} </Row> ) : ( <Empty /> )} </Scrollbar> ); }; /** * @description Render search * @returns {React.ReactNode} */ private renderSearch = () => { return ( <div style={{ flex: 1, padding: '0 16px' }}> <Input allowClear={true} placeholder="Search for Texture..." onChange={e => this.handleSearchTexture(e.target.value)} /> </div> ); }; /** * @description Render actions * @returns {React.ReactNode} */ private renderActions = () => { return ( <Button type="primary" onClick={this.handleAddTexture}> <Icon name="plus" /> </Button> ); }; /** * @description Render filter * @returns {React.ReactNode} */ private renderTypeFilter = () => { const { type } = this.props; return typeof type === 'undefined' ? ( <Select defaultValue={this.state.selectedFilterType} style={{ width: 120 }} onChange={this.handleFilterType} > {selectFilterTypes.map(filterType => { return ( <Select.Option key={filterType.value} value={filterType.value}> {filterType.text} </Select.Option> ); })} </Select> ) : type === 'image/video' ? ( <Select defaultValue={this.state.selectedFilterType} style={{ width: 120 }} onChange={this.handleFilterType} > {selectFilterTypes .filter( filterType => filterType.value === 'all' || filterType.value === 'image' || filterType.value === 'video', ) .map(filterType => { return ( <Select.Option key={filterType.value} value={filterType.value}> {filterType.text} </Select.Option> ); })} </Select> ) : null; }; render() { const { type } = this.props; const { textures, loading, searchTexture, selectedFilterType } = this.state; return ( <Spin spinning={loading}> {!textures.length ? ( typeof type === 'undefined' ? ( <AddEmpty onClick={this.handleAddTexture}> <Icon name="plus" style={{ marginRight: 4 }} /> {'New Texture'} </AddEmpty> ) : ( <Empty /> ) ) : ( <div style={{ display: 'flex', height: '100%', flexDirection: 'column' }}> <div style={{ display: 'flex', padding: '0 8px 16px 8px' }}> {this.renderTypeFilter()} {this.renderSearch()} {this.renderActions()} </div> <div style={{ flex: 1 }}> {this.renderCardItems(textures, searchTexture, selectedFilterType)} </div> </div> )} </Spin> ); } } export default Textures;
the_stack
import m from "mithril"; import {Agents} from "models/agents/agents"; import {AgentsJSON} from "models/agents/agents_json"; import {AgentsTestData} from "models/agents/spec/agents_test_data"; import {Environments, EnvironmentWithOrigin} from "models/new-environments/environments"; import test_data from "models/new-environments/spec/test_data"; import {ModalState} from "views/components/modal"; import {EditAgentsModal} from "views/pages/new-environments/edit_agents_modal"; import {TestHelper} from "views/pages/spec/test_helper"; describe("Edit Agents Modal", () => { const helper = new TestHelper(); let environment: EnvironmentWithOrigin, environments: Environments, agentsJSON: AgentsJSON; let normalAgentAssociatedWithEnvInXml: string, normalAgentAssociatedWithEnvInConfigRepo: string, elasticAgentAssociatedWithEnvInXml: string, unassociatedStaticAgent: string, unassociatedElasticAgent: string; let modal: EditAgentsModal; beforeEach(() => { jasmine.Ajax.install(); environments = new Environments(); const environmentJSON = test_data.environment_json(); environmentJSON.agents.push(test_data.agent_association_in_xml_json()); environment = EnvironmentWithOrigin.fromJSON(environmentJSON); environments.push(environment); agentsJSON = AgentsTestData.list(); agentsJSON._embedded.agents.push(AgentsTestData.elasticAgent()); agentsJSON._embedded.agents.push(AgentsTestData.elasticAgent()); //normal agent associated with environment in xml normalAgentAssociatedWithEnvInXml = environmentJSON.agents[0].uuid; agentsJSON._embedded.agents[0].uuid = normalAgentAssociatedWithEnvInXml; //normal agent associated with environment in config repo normalAgentAssociatedWithEnvInConfigRepo = environmentJSON.agents[1].uuid; agentsJSON._embedded.agents[1].uuid = normalAgentAssociatedWithEnvInConfigRepo; //elastic agent associated with environment in xml elasticAgentAssociatedWithEnvInXml = environmentJSON.agents[2].uuid; agentsJSON._embedded.agents[4].uuid = elasticAgentAssociatedWithEnvInXml; unassociatedStaticAgent = agentsJSON._embedded.agents[2].uuid; unassociatedElasticAgent = agentsJSON._embedded.agents[3].uuid; modal = new EditAgentsModal(environment, environments, Agents.fromJSON(agentsJSON), jasmine.createSpy("onSuccessfulSave")); helper.mount(() => modal.view()); }); afterEach(() => { helper.unmount(); jasmine.Ajax.uninstall(); }); it("should render available agents", () => { const availableAgentsSection = helper.byTestId(`available-agents`); const agent1Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInXml}`; const agent2Selector = `agent-checkbox-for-${unassociatedStaticAgent}`; expect(availableAgentsSection).toBeInDOM(); expect(availableAgentsSection).toContainText("Available Agents"); expect(helper.byTestId(agent1Selector, availableAgentsSection)).toBeInDOM(); expect(helper.byTestId(agent2Selector, availableAgentsSection)).toBeInDOM(); }); it("should render agents defined in config repo", () => { const configRepoAgentsSection = helper.byTestId(`agents-associated-with-this-environment-in-configuration-repository`); const agent1Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInConfigRepo}`; expect(configRepoAgentsSection).toBeInDOM(); expect(configRepoAgentsSection) .toContainText("Agents associated with this environment in configuration repository"); expect(helper.byTestId(agent1Selector, configRepoAgentsSection)).toBeInDOM(); }); it("should render elastic agents associated with the current environment", () => { const elasticAgentsSection = helper.byTestId(`elastic-agents-associated-with-this-environment`); const agent1Selector = `agent-checkbox-for-${elasticAgentAssociatedWithEnvInXml}`; expect(elasticAgentsSection).toBeInDOM(); expect(elasticAgentsSection).toContainText("Elastic Agents associated with this environment"); expect(helper.byTestId(agent1Selector, elasticAgentsSection)).toBeInDOM(); }); it("should render unavailable elastic agents not belonging to the current environment", () => { const elasticAgentsSection = helper.byTestId(`unavailable-agents-elastic-agents`); const agent1Selector = `agent-list-item-for-${unassociatedElasticAgent}`; expect(elasticAgentsSection).toBeInDOM(); expect(elasticAgentsSection).toContainText("Unavailable Agents (Elastic Agents)"); expect(helper.byTestId(agent1Selector, elasticAgentsSection)).toBeInDOM(); }); it("should toggle agent selection from environment on click", () => { const agent1Checkbox = helper.byTestId(`form-field-input-${normalAgentAssociatedWithEnvInXml}`) as HTMLInputElement; const agent2Checkbox = helper.byTestId(`form-field-input-${unassociatedStaticAgent}`) as HTMLInputElement; expect(agent1Checkbox.checked).toBe(true); expect(modal.agentsVM.selectedAgentUuids.includes(normalAgentAssociatedWithEnvInXml)).toBe(true); expect(agent2Checkbox.checked).toBe(false); expect(modal.agentsVM.selectedAgentUuids.includes(unassociatedStaticAgent)).toBe(false); helper.clickByTestId(`form-field-input-${normalAgentAssociatedWithEnvInXml}`); expect(agent1Checkbox.checked).toBe(false); expect(modal.agentsVM.selectedAgentUuids.includes(normalAgentAssociatedWithEnvInXml)).toBe(false); helper.clickByTestId(`form-field-input-${unassociatedStaticAgent}`); expect(agent2Checkbox.checked).toBe(true); expect(modal.agentsVM.selectedAgentUuids.includes(unassociatedStaticAgent)).toBe(true); }); it("should not allow toggling config repo agents", () => { const agent1Checkbox = helper.byTestId(`form-field-input-${normalAgentAssociatedWithEnvInConfigRepo}`) as HTMLInputElement; expect(agent1Checkbox.checked).toBe(true); expect(agent1Checkbox.disabled).toBe(true); }); it("should not allow toggling elastic agents", () => { const agent1Checkbox = helper.byTestId(`form-field-input-${elasticAgentAssociatedWithEnvInXml}`) as HTMLInputElement; expect(agent1Checkbox.checked).toBe(true); expect(agent1Checkbox.disabled).toBe(true); }); it("should render agent search box", () => { const searchInput = helper.byTestId("form-field-input-agent-search"); expect(searchInput).toBeInDOM(); expect(searchInput.getAttribute("placeholder")).toBe("agent hostname"); }); it("should bind search text with pipelines vm", () => { const searchText = "search-text"; modal.agentsVM.searchText(searchText); helper.redraw(); const searchInput = helper.byTestId("form-field-input-agent-search"); expect(searchInput).toHaveValue(searchText); }); it("should search for a particular agent", () => { const agent1Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInXml}`; const agent2Selector = `agent-checkbox-for-${unassociatedStaticAgent}`; const agent3Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInConfigRepo}`; const agent4Selector = `agent-checkbox-for-${elasticAgentAssociatedWithEnvInXml}`; const agent5Selector = `agent-list-item-for-${unassociatedElasticAgent}`; expect(helper.byTestId(agent1Selector)).toBeInDOM(); expect(helper.byTestId(agent2Selector)).toBeInDOM(); expect(helper.byTestId(agent3Selector)).toBeInDOM(); expect(helper.byTestId(agent4Selector)).toBeInDOM(); expect(helper.byTestId(agent5Selector)).toBeInDOM(); modal.agentsVM.searchText(agentsJSON._embedded.agents[0].hostname); m.redraw.sync(); expect(helper.byTestId(agent1Selector)).toBeInDOM(); expect(helper.byTestId(agent2Selector)).toBeFalsy(); expect(helper.byTestId(agent3Selector)).toBeFalsy(); expect(helper.byTestId(agent4Selector)).toBeFalsy(); expect(helper.byTestId(agent5Selector)).toBeFalsy(); }); it("should search for a partial agent name match", () => { const agent1Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInXml}`; const agent2Selector = `agent-checkbox-for-${unassociatedStaticAgent}`; const agent3Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInConfigRepo}`; const agent4Selector = `agent-checkbox-for-${elasticAgentAssociatedWithEnvInXml}`; const agent5Selector = `agent-list-item-for-${unassociatedElasticAgent}`; expect(helper.byTestId(agent1Selector)).toBeInDOM(); expect(helper.byTestId(agent2Selector)).toBeInDOM(); expect(helper.byTestId(agent3Selector)).toBeInDOM(); expect(helper.byTestId(agent4Selector)).toBeInDOM(); expect(helper.byTestId(agent5Selector)).toBeInDOM(); modal.agentsVM.searchText("Hostname"); m.redraw.sync(); expect(helper.byTestId(agent1Selector)).toBeInDOM(); expect(helper.byTestId(agent2Selector)).toBeInDOM(); expect(helper.byTestId(agent3Selector)).toBeInDOM(); }); it("should show no agents available message", () => { modal.agentsVM.agents(new Agents()); m.redraw.sync(); const expectedMessage = "There are no agents available!"; expect(helper.textByTestId("flash-message-info")).toContain(expectedMessage); }); it("should show no agents matching search text message when no agents matched the search text", () => { const agent1Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInXml}`; const agent2Selector = `agent-checkbox-for-${unassociatedStaticAgent}`; const agent3Selector = `agent-checkbox-for-${normalAgentAssociatedWithEnvInConfigRepo}`; const agent4Selector = `agent-checkbox-for-${elasticAgentAssociatedWithEnvInXml}`; const agent5Selector = `agent-list-item-for-${unassociatedElasticAgent}`; expect(helper.byTestId(agent1Selector)).toBeInDOM(); expect(helper.byTestId(agent2Selector)).toBeInDOM(); expect(helper.byTestId(agent3Selector)).toBeInDOM(); expect(helper.byTestId(agent4Selector)).toBeInDOM(); expect(helper.byTestId(agent5Selector)).toBeInDOM(); modal.agentsVM.searchText("blah-is-my-agent-hostname"); m.redraw.sync(); expect(helper.byTestId(agent1Selector)).toBeFalsy(); expect(helper.byTestId(agent2Selector)).toBeFalsy(); expect(helper.byTestId(agent3Selector)).toBeFalsy(); expect(helper.byTestId(agent4Selector)).toBeFalsy(); expect(helper.byTestId(agent5Selector)).toBeFalsy(); const expectedMessage = "No agents matching search text 'blah-is-my-agent-hostname' found!"; expect(helper.textByTestId("flash-message-info")).toContain(expectedMessage); }); it('should render buttons', () => { expect(helper.byTestId("cancel-button")).toBeInDOM(); expect(helper.byTestId("cancel-button")).toHaveText("Cancel"); expect(helper.byTestId("save-button")).toBeInDOM(); expect(helper.byTestId("save-button")).toHaveText("Save"); }); it('should disable save and cancel button if modal state is loading', () => { modal.modalState = ModalState.LOADING; m.redraw.sync(); expect(helper.byTestId("save-button")).toBeDisabled(); expect(helper.byTestId("cancel-button")).toBeDisabled(); expect(helper.byTestId("spinner")).toBeInDOM(); }); it('should not render pending agents', () => { helper.unmount(); agentsJSON._embedded.agents[2].agent_config_state = "Pending"; modal = new EditAgentsModal(environment, environments, Agents.fromJSON(agentsJSON), jasmine.createSpy("onSuccessfulSave")); helper.mount(() => modal.view()); const availableAgentsSection = helper.byTestId(`available-agents`); const agent2Selector = `agent-checkbox-for-${unassociatedStaticAgent}`; expect(availableAgentsSection).toBeInDOM(); expect(helper.byTestId(agent2Selector, availableAgentsSection)).not.toBeInDOM(); }); });
the_stack
import { CfnCondition } from './cfn-condition'; import { CfnRefElement } from './cfn-element'; import { CfnCreationPolicy, CfnDeletionPolicy, CfnUpdatePolicy } from './cfn-resource-policy'; import { Construct, IConstruct } from 'constructs'; import { Reference } from './reference'; import { RemovalPolicy, RemovalPolicyOptions } from './removal-policy'; /** * @stability stable */ export interface CfnResourceProps { /** * CloudFormation resource type (e.g. `AWS::S3::Bucket`). * * @stability stable */ readonly type: string; /** * Resource properties. * * @default - No resource properties. * @stability stable */ readonly properties?: { [name: string]: any; }; } /** * Represents a CloudFormation resource. * * @stability stable */ export declare class CfnResource extends CfnRefElement { /** * Check whether the given construct is a CfnResource. * * @stability stable */ static isCfnResource(construct: IConstruct): construct is CfnResource; /** * Options for this resource, such as condition, update policy etc. * * @stability stable */ readonly cfnOptions: ICfnResourceOptions; /** * AWS resource type. * * @stability stable */ readonly cfnResourceType: string; /** * AWS CloudFormation resource properties. * * This object is returned via cfnProperties * @internal */ protected readonly _cfnProperties: any; /** * An object to be merged on top of the entire resource definition. */ private readonly rawOverrides; /** * Logical IDs of dependencies. * * Is filled during prepare(). */ private readonly dependsOn; /** * Creates a resource construct. * * @stability stable */ constructor(scope: Construct, id: string, props: CfnResourceProps); /** * Sets the deletion policy of the resource based on the removal policy specified. * * @stability stable */ applyRemovalPolicy(policy: RemovalPolicy | undefined, options?: RemovalPolicyOptions): void; /** * Returns a token for an runtime attribute of this resource. * * Ideally, use generated attribute accessors (e.g. `resource.arn`), but this can be used for future compatibility * in case there is no generated attribute. * * @param attributeName The name of the attribute. * @stability stable */ getAtt(attributeName: string): Reference; /** * Adds an override to the synthesized CloudFormation resource. * * To add a * property override, either use `addPropertyOverride` or prefix `path` with * "Properties." (i.e. `Properties.TopicName`). * * If the override is nested, separate each nested level using a dot (.) in the path parameter. * If there is an array as part of the nesting, specify the index in the path. * * To include a literal `.` in the property name, prefix with a `\`. In most * programming languages you will need to write this as `"\\."` because the * `\` itself will need to be escaped. * * For example, * ```typescript * cfnResource.addOverride('Properties.GlobalSecondaryIndexes.0.Projection.NonKeyAttributes', ['myattribute']); * cfnResource.addOverride('Properties.GlobalSecondaryIndexes.1.ProjectionType', 'INCLUDE'); * ``` * would add the overrides * ```json * "Properties": { * "GlobalSecondaryIndexes": [ * { * "Projection": { * "NonKeyAttributes": [ "myattribute" ] * ... * } * ... * }, * { * "ProjectionType": "INCLUDE" * ... * }, * ] * ... * } * ``` * * @param path - The path of the property, you can use dot notation to override values in complex types. * @param value - The value. * @stability stable */ addOverride(path: string, value: any): void; /** * Syntactic sugar for `addOverride(path, undefined)`. * * @param path The path of the value to delete. * @stability stable */ addDeletionOverride(path: string): void; /** * Adds an override to a resource property. * * Syntactic sugar for `addOverride("Properties.<...>", value)`. * * @param propertyPath The path of the property. * @param value The value. * @stability stable */ addPropertyOverride(propertyPath: string, value: any): void; /** * Adds an override that deletes the value of a property from the resource definition. * * @param propertyPath The path to the property. * @stability stable */ addPropertyDeletionOverride(propertyPath: string): void; /** * Indicates that this resource depends on another resource and cannot be provisioned unless the other resource has been successfully provisioned. * * This can be used for resources across stacks (or nested stack) boundaries * and the dependency will automatically be transferred to the relevant scope. * * @stability stable */ addDependsOn(target: CfnResource): void; /** * Add a value to the CloudFormation Resource Metadata. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html * * Note that this is a different set of metadata from CDK node metadata; this * metadata ends up in the stack template under the resource, whereas CDK * node metadata ends up in the Cloud Assembly. * @stability stable */ addMetadata(key: string, value: any): void; /** * Retrieve a value value from the CloudFormation Resource Metadata. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html * * Note that this is a different set of metadata from CDK node metadata; this * metadata ends up in the stack template under the resource, whereas CDK * node metadata ends up in the Cloud Assembly. * @stability stable */ getMetadata(key: string): any; /** * Returns a string representation of this construct. * * @returns a string representation of this resource * @stability stable */ toString(): string; /** * Called by the `addDependency` helper function in order to realize a direct * dependency between two resources that are directly defined in the same * stacks. * * Use `resource.addDependsOn` to define the dependency between two resources, * which also takes stack boundaries into account. * * @internal */ _addResourceDependency(target: CfnResource): void; /** * Emits CloudFormation for this resource. * @internal */ _toCloudFormation(): object; /** * @stability stable */ protected get cfnProperties(): { [key: string]: any; }; /** * @stability stable */ protected renderProperties(props: { [key: string]: any; }): { [key: string]: any; }; /** * Return properties modified after initiation. * * Resources that expose mutable properties should override this function to * collect and return the properties object for this resource. * * @stability stable */ protected get updatedProperites(): { [key: string]: any; }; /** * @stability stable */ protected validateProperties(_properties: any): void; /** * Can be overridden by subclasses to determine if this resource will be rendered into the cloudformation template. * * @returns `true` if the resource should be included or `false` is the resource * should be omitted. * @stability stable */ protected shouldSynthesize(): boolean; } /** * @stability stable */ export declare enum TagType { /** * @stability stable */ STANDARD = "StandardTag", /** * @stability stable */ AUTOSCALING_GROUP = "AutoScalingGroupTag", /** * @stability stable */ MAP = "StringToStringMap", /** * @stability stable */ KEY_VALUE = "KeyValue", /** * @stability stable */ NOT_TAGGABLE = "NotTaggable" } /** * @stability stable */ export interface ICfnResourceOptions { /** * A condition to associate with this resource. * * This means that only if the condition evaluates to 'true' when the stack * is deployed, the resource will be included. This is provided to allow CDK projects to produce legacy templates, but noramlly * there is no need to use it in CDK projects. * * @stability stable */ condition?: CfnCondition; /** * Associate the CreationPolicy attribute with a resource to prevent its status from reaching create complete until AWS CloudFormation receives a specified number of success signals or the timeout period is exceeded. * * To signal a * resource, you can use the cfn-signal helper script or SignalResource API. AWS CloudFormation publishes valid signals * to the stack events so that you track the number of signals sent. * * @stability stable */ creationPolicy?: CfnCreationPolicy; /** * With the DeletionPolicy attribute you can preserve or (in some cases) backup a resource when its stack is deleted. * * You specify a DeletionPolicy attribute for each resource that you want to control. If a resource has no DeletionPolicy * attribute, AWS CloudFormation deletes the resource by default. Note that this capability also applies to update operations * that lead to resources being removed. * * @stability stable */ deletionPolicy?: CfnDeletionPolicy; /** * Use the UpdatePolicy attribute to specify how AWS CloudFormation handles updates to the AWS::AutoScaling::AutoScalingGroup resource. * * AWS CloudFormation invokes one of three update policies depending on the type of change you make or whether a * scheduled action is associated with the Auto Scaling group. * * @stability stable */ updatePolicy?: CfnUpdatePolicy; /** * Use the UpdateReplacePolicy attribute to retain or (in some cases) backup the existing physical instance of a resource when it is replaced during a stack update operation. * * @stability stable */ updateReplacePolicy?: CfnDeletionPolicy; /** * The version of this resource. * * Used only for custom CloudFormation resources. * * @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cfn-customresource.html * @stability stable */ version?: string; /** * The description of this resource. * * Used for informational purposes only, is not processed in any way * (and stays with the CloudFormation template, is not passed to the underlying resource, * even if it does have a 'description' property). * * @stability stable */ description?: string; /** * Metadata associated with the CloudFormation resource. * * This is not the same as the construct metadata which can be added * using construct.addMetadata(), but would not appear in the CloudFormation template automatically. * * @stability stable */ metadata?: { [key: string]: any; }; }
the_stack
import { simpleArray, oddArray, jsn, un1, un2, people, msdn, pets, mix, phrase } from "./data"; import {assert} from "chai"; import Linq from "../lib/linq"; import { Enumerable } from "../lib/enumerable"; describe('Deferred Execution -', function () { // Cast it('Cast()', function () { class a { } class b extends a { } let iterable = Linq<b>([]); assert.equal(iterable.Cast<a>(), iterable); }); // ChunkBy it('ChunkBy()', function () { let iterable = Linq(phrase).ChunkBy(o => o.key, o => o.value); var iterator = iterable[Symbol.iterator]() var arr = iterator.next().value as Array<string>; assert.equal(arr.length, 3); assert.equal(arr[0], "We"); assert.equal(arr[1], "think"); assert.equal(arr[2], "that"); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 1); assert.equal(arr[0], "Linq"); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 1); assert.equal(arr[0], "is"); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 1); assert.equal(arr[0], "really"); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 2); assert.equal(arr[0], "cool"); assert.equal(arr[1], "!"); assert.isTrue(iterator.next().done); }); it('ChunkBy() - Index', function () { let iterable = Linq(phrase).ChunkBy((o, i) => Math.max(3, i), o => o.value); var iterator = iterable[Symbol.iterator]() var arr = iterator.next().value as Array<string>; assert.equal(arr.length, 4); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 1); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 1); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 1); arr = iterator.next().value as Array<string>; assert.equal(arr.length, 1); assert.isTrue(iterator.next().done); }); it('ChunkBy() - Zero', function () { let iterable = Linq([{ key: 0, value: "0" }, { key: 0, value: "1" }, { key: 0, value: "2" }, { key: 0, value: "3" }, { key: 0, value: "4" }, { key: 0, value: "5" }, { key: 0, value: "6" }, { key: 0, value: "7" }, { key: 0, value: "!" }]) .ChunkBy(k => k.key, o => o.value); var iterator = iterable[Symbol.iterator]() var arr = iterator.next().value as Array<string>; assert.equal(arr.length, 9); assert.isTrue(iterator.next().done); }); it('ChunkBy() - Empty', function () { let iterable = Linq([]).ChunkBy(e => e); var iterator = iterable[Symbol.iterator]() assert.isTrue(iterator.next().done); }); // Concat it('Concat()', function () { var iterable = Linq([0, 1, 2]).Concat([3, 4]); var iterator = iterable[Symbol.iterator]() assert.equal(0, iterator.next().value); assert.equal(1, iterator.next().value); assert.equal(2, iterator.next().value); assert.equal(3, iterator.next().value); assert.equal(4, iterator.next().value); assert.isTrue(iterator.next().done); }); // Select it('Select()', function () { const actual = Linq(jsn).Select((a) => a.name).ToArray(); const expected = jsn.map(a => a.name); assert.sameOrderedMembers(actual, expected); }); it('Select() - With index', function () { const actual = Linq(jsn).Select((a: any, b: any) => b).ToArray(); const expected = jsn.map((a: any, b: any) => b); assert.sameOrderedMembers(actual, expected); }); // Distinct it('Distinct() - Number', function () { let iterable = Linq([0, 0, 1, 3, 5, 6, 5, 7, 8, 8]).Distinct(); let iterator = iterable[Symbol.iterator]() assert.equal(0, iterator.next().value); assert.equal(1, iterator.next().value); assert.equal(3, iterator.next().value); assert.equal(5, iterator.next().value); assert.equal(6, iterator.next().value); assert.equal(7, iterator.next().value); assert.equal(8, iterator.next().value); assert.isTrue(iterator.next().done); }); it('Distinct() - String', function () { let test = [ "add", "add", "subtract", "multiply", "hello", "class", "namespace", "namespace", "namespace"]; let iterable = Linq(test).Distinct(); let iterator = iterable[Symbol.iterator]() assert.equal("add", iterator.next().value); assert.equal("subtract", iterator.next().value); assert.equal("multiply", iterator.next().value); assert.equal("hello", iterator.next().value); assert.equal("class", iterator.next().value); assert.equal("namespace", iterator.next().value); assert.isTrue(iterator.next().done); }); it('Distinct() - Key', function () { let test = [ { id: 1, "name": "d" }, { id: 1, "name": "c" }, { id: 3, "name": "b" }, { id: 4, "name": "a" } ]; let iterable = Linq(test).Distinct(o => o.id); let iterator = iterable[Symbol.iterator]() assert.equal("d", (<any>iterator.next().value).name); assert.equal("b", (<any>iterator.next().value).name); assert.equal("a", (<any>iterator.next().value).name); assert.isTrue(iterator.next().done); }); // Where it('Where()', function () { let iterable = Linq(simpleArray).Where(a => a % 2 == 1); const expected = simpleArray.filter(a => a % 2 == 1); const actual = [...iterable]; assert.sameOrderedMembers(actual, expected); }); it('Where() - Index', function () { let iterable = Linq(simpleArray).Where((a: any, i: any) => i % 2 == 1); const expected = simpleArray.filter((a, i) => i % 2 == 1); const actual = [...iterable]; assert.sameOrderedMembers(actual, expected); }); // Skip it('Skip()', function () { let iterable = Linq(simpleArray).Skip(7); const expected = simpleArray.slice(7); const actual = [...iterable]; assert.sameOrderedMembers(actual, expected); }); it('SkipWhile()', function () { var iterable = Linq(simpleArray).SkipWhile((a) => a < 8); var iterator = iterable[Symbol.iterator]() assert.equal(8, iterator.next().value); assert.equal(9, iterator.next().value); assert.equal(10, iterator.next().value); assert.isTrue(iterator.next().done); }); it('SkipWhile() - Index', function () { var amounts = [ 5000, 2500, 9000, 8000, 6500, 4000, 1500, 5500]; var iterable = Linq(amounts).SkipWhile((amount, index) => amount > index * 1000); var iterator = iterable[Symbol.iterator]() assert.equal(4000, iterator.next().value); assert.equal(1500, iterator.next().value); assert.equal(5500, iterator.next().value); assert.isTrue(iterator.next().done); }); // Take it('Take()', function () { var iterable = Linq(simpleArray).Take(3); const expected = simpleArray.slice(0, 3); const actual = [...iterable]; assert.sameOrderedMembers(actual, expected); }); it('TakeWhile()', function () { var iterable = Linq(simpleArray).TakeWhile(a => a < 4); const expected = []; for(const item of simpleArray) { if(item < 4) expected.push(item); else break; } const actual = [...iterable]; assert.sameOrderedMembers(actual, expected); }); // Except it('Except()', function () { var iterable = Linq(simpleArray).Except([0, 2, 4, 6, 11]); var iterator = iterable[Symbol.iterator]() assert.equal(1, iterator.next().value); assert.equal(3, iterator.next().value); assert.equal(5, iterator.next().value); assert.equal(7, iterator.next().value); assert.equal(8, iterator.next().value); assert.equal(9, iterator.next().value); assert.equal(10, iterator.next().value); assert.isTrue(iterator.next().done); }); it('Except() - Key', function () { var iterable = Linq(un1).Except(un2, o => o.id ); var iterator = iterable[Symbol.iterator]() assert.equal(1, iterator.next().value.id); assert.equal(2, iterator.next().value.id); assert.equal(null, iterator.next().value.id); assert.isTrue(iterator.next().done); }); // Intersect it('Intersect()', function () { var iterable = Linq(simpleArray).Intersect([1, 3, 5, 11, 23, 44]); var iterator = iterable[Symbol.iterator]() assert.equal(1, iterator.next().value); assert.equal(3, iterator.next().value); assert.equal(5, iterator.next().value); assert.isTrue(iterator.next().done); }); it('Intersect() - Key', function () { var iterable = Linq(un1).Intersect(un2, o => o.id ); var iterator = iterable[Symbol.iterator]() assert.equal(3, iterator.next().value.id); assert.equal(3, iterator.next().value.id); assert.equal(4, iterator.next().value.id); assert.isTrue(iterator.next().done); }); // OfType it('OfType() - Number', function () { var iterable = Linq(mix).OfType(Number); var iterator = iterable[Symbol.iterator](); assert.equal(iterator.next().value, 0); assert.equal(iterator.next().value, 1); assert.equal(iterator.next().value, 2); assert.equal(iterator.next().value, 3); assert.isTrue(iterator.next().done); }); it('OfType() - Boolean', function () { var iterable = Linq(mix).OfType(Boolean); var iterator = iterable[Symbol.iterator](); assert.equal(iterator.next().value, true); assert.equal(iterator.next().value, false); assert.equal(iterator.next().value, true); assert.equal(iterator.next().value, false); assert.isTrue(iterator.next().done); }); it('OfType() - String', function () { var iterable = Linq(mix).OfType(String); var iterator = iterable[Symbol.iterator](); assert.equal(iterator.next().value, mix[2]); assert.equal(iterator.next().value, mix[3]); assert.equal(iterator.next().value, mix[4]); assert.isTrue(iterator.next().done); }); it('OfType() - Date', function () { var iterable = Linq(mix).OfType(Date); var iterator = iterable[Symbol.iterator](); assert.equal(iterator.next().value, mix[5]); assert.isTrue(iterator.next().done); }); it('OfType() - Symbol', function () { var iterable = Linq(mix).OfType(Symbol); var iterator = iterable[Symbol.iterator](); assert.equal(iterator.next().value, mix[7]); assert.isTrue(iterator.next().done); }); it('OfType() - Function', function () { var iterable = Linq(mix).OfType(Function); var iterator = iterable[Symbol.iterator](); assert.equal(iterator.next().value, mix[17]); assert.isTrue(iterator.next().done); }); it('OfType() - Object', function () { var iterable = Linq(mix).OfType(Object); var iterator = iterable[Symbol.iterator](); assert.equal(iterator.next().value, 1); assert.equal(iterator.next().value, mix[3]); assert.equal(iterator.next().value, mix[4]); assert.equal(iterator.next().value, mix[5]); assert.equal(iterator.next().value, mix[10]); assert.equal(iterator.next().value, mix[11]); assert.equal(iterator.next().value, mix[12]); assert.equal(iterator.next().value, mix[13]); assert.equal(iterator.next().value, mix[14]); assert.equal(iterator.next().value, mix[15]); assert.equal(iterator.next().value, mix[17]); assert.isTrue(iterator.next().done); }); // Union it('Union()', function () { var iterable = Linq([0, 1, 2, 2, 3, 4, 5, 6, 7]).Union([5, 6, 6, 7, 8, 9]); var iterator = iterable[Symbol.iterator]() assert.equal(0, iterator.next().value); assert.equal(1, iterator.next().value); assert.equal(2, iterator.next().value); assert.equal(3, iterator.next().value); assert.equal(4, iterator.next().value); assert.equal(5, iterator.next().value); assert.equal(6, iterator.next().value); assert.equal(7, iterator.next().value); assert.equal(8, iterator.next().value); assert.equal(9, iterator.next().value); assert.isTrue(iterator.next().done); }); it('Union() - Keyed', function () { var iterable = Linq(un1).Union(un2, (o) => o.id); var iterator = iterable[Symbol.iterator]() assert.equal(un1[0], iterator.next().value); assert.equal(un1[1], iterator.next().value); assert.equal(un1[2], iterator.next().value); assert.equal(un1[3], iterator.next().value); assert.equal(un1[5], iterator.next().value); assert.equal(un2[2], iterator.next().value); assert.equal(un2[3], iterator.next().value); assert.equal(un2[5], iterator.next().value); assert.isTrue(iterator.next().done); }); // Join it('Join()', function () { var iterable = Linq(people).Join(pets, person => person, pet => pet.Owner, (person, pet) => { return person.Name + " - " + pet.Name; }); var iterator = iterable[Symbol.iterator]() assert.equal("Hedlund, Magnus - Daisy", iterator.next().value); assert.equal("Adams, Terry - Barley", iterator.next().value); assert.equal("Adams, Terry - Boots", iterator.next().value); assert.equal("Adams, Terry - Barley", iterator.next().value); assert.equal("Adams, Terry - Boots", iterator.next().value); assert.equal("Weiss, Charlotte - Whiskers", iterator.next().value); assert.isTrue(iterator.next().done); }); it('Join() - Redundant', function () { var iterable = Linq(un1).Join(jsn, e => e.id, u => u.id, (e, u) => { return e.name + " - " + u.name; }); var iterator = iterable[Symbol.iterator]() assert.equal("q - d", iterator.next().value); assert.equal("w - c", iterator.next().value); assert.equal("e - b", iterator.next().value); assert.equal("e - b", iterator.next().value); assert.equal("r - a", iterator.next().value); assert.isTrue(iterator.next().done); }); it('Join() - ignore null key', function () { const nullPerson: { Name: string; } = null; const expectedPeople = people.slice(); expectedPeople.push(nullPerson); const actual = Linq(expectedPeople).Join( pets, person => person, pet => pet.Owner, (person, pet) => person.Name + " - " + pet.Name).ToArray(); const expected = [].concat(...expectedPeople .filter(person => person != null) .map(person => pets.filter(pet => pet.Owner === person).map(pet => person.Name + " - " + pet.Name))); assert.sameOrderedMembers(actual, expected); }); // GroupJoin it('GroupJoin()', function () { var iterable = Linq(people) .GroupJoin(pets, person => person, pet => pet.Owner, (person, petCollection) => { return { Owner: person.Name, Pets: !petCollection ? null : Linq(petCollection).Select(pet => pet.Name) .ToArray() }; }); var iterator = iterable[Symbol.iterator](); var result = iterator.next().value; assert.isTrue(Array.isArray(result.Pets)) assert.equal("Hedlund, Magnus", result.Owner); assert.equal(1, result.Pets.length); assert.equal("Daisy", result.Pets[0]); result = iterator.next().value; assert.equal("Adams, Terry", result.Owner); assert.equal(2, result.Pets.length); assert.equal("Barley", result.Pets[0]); assert.equal("Boots", result.Pets[1]); result = iterator.next().value; assert.equal("Adams, Terry", result.Owner); assert.equal(2, result.Pets.length); assert.equal("Barley", result.Pets[0]); assert.equal("Boots", result.Pets[1]); result = iterator.next().value; assert.equal(null, result.Owner); assert.equal(null, result.Pets); result = iterator.next().value; assert.equal("Weiss, Charlotte", result.Owner); assert.equal(1, result.Pets.length); assert.equal("Whiskers", result.Pets[0]); result = iterator.next().value; assert.equal(undefined, result.Owner); assert.equal(null, result.Pets); assert.isTrue(iterator.next().done); }); it('GroupJoin() - MSDN', function () { var iterable = Linq(msdn) .GroupJoin(pets, person => person, pet => pet.Owner, (person, petCollection) => { return { Owner: person.Name, Pets: Linq(petCollection).Select(pet => pet.Name) .ToArray() }; }); var iterator = iterable[Symbol.iterator](); var result = iterator.next().value; assert.isTrue(Array.isArray(result.Pets)) assert.equal("Hedlund, Magnus", result.Owner); assert.equal(1, result.Pets.length); assert.equal("Daisy", result.Pets[0]); result = iterator.next().value; assert.equal("Adams, Terry", result.Owner); assert.equal(2, result.Pets.length); assert.equal("Barley", result.Pets[0]); assert.equal("Boots", result.Pets[1]); result = iterator.next().value; assert.equal("Weiss, Charlotte", result.Owner); assert.equal(1, result.Pets.length); assert.equal("Whiskers", result.Pets[0]); assert.isTrue(iterator.next().done); }); it('GroupJoin() - QJesus', function () { const yx = [ { id: '1', batchNumber: 'ZKFM1' }, { id: '2', batchNumber: 'ZKFM' }, { id: '3', batchNumber: 'ZKFM1' } ]; const zx = [ { id: '1', value: 'zzz' }, { id: '2', value: 'xxx' }, ]; var join = Linq(yx).GroupJoin(zx, a => a.id, b => b.id, (a, temp) => ({ a, temp })) .ToArray(); assert.equal(3, join.length); }); // GroupBy it('GroupBy()', function () { const iterable: any = Linq(pets).GroupBy(pet => pet.Age); const expected = new Map<number, number>(pets.map(pet => [pet.Age, pets.filter(p => p.Age === pet.Age).length])); const actual = [...iterable[Symbol.iterator]()]; for(const [expectedAge, expectedLength] of expected) { const actualGroup = actual.find(group => group.key === expectedAge); assert.isDefined(actualGroup, `Missing expected group for pet.Age with key ${expectedAge}`); assert.equal(actualGroup.length, expectedLength, `Expected pet.Age ${expectedAge} with group of ${expectedLength} items but instead got ${actualGroup.length} items`); } }); it('GroupBy() - Element selector', function () { var iterable: any = Linq(pets).GroupBy(pet => pet.Age, pet => pet); const expected = new Map<number, number>(pets.map(pet => [pet.Age, pets.filter(p => p.Age === pet.Age).length])); const actual = [...iterable[Symbol.iterator]()]; for(const [expectedAge, expectedLength] of expected) { const actualGroup = actual.find(group => group.key === expectedAge); assert.isDefined(actualGroup, `Missing expected group for pet.Age with key ${expectedAge}`); assert.equal(actualGroup.length, expectedLength, `Expected pet.Age ${expectedAge} with group of ${expectedLength} items but instead got ${actualGroup.length} items`); } }); it('GroupBy() - Result selector', function () { var iterable: Enumerable<number> = Linq(pets).GroupBy( pet => pet.Age, pet => pet, (age, group) => age); const expected = new Set<number>(pets.map(pet => pet.Age)); const actual = [...iterable]; assert.equal(actual.length, expected.size, `Expected ${expected.size} groups by pet.Age but got ${actual.length}`); for(const expectedAge of expected) { const actualExists = actual.findIndex(age => age === expectedAge) > -1; assert.isTrue(actualExists, `Missing expected pet.Age ${expectedAge}`); } }); // SelectMany it('SelectMany()', function () { const iterable = Linq(jsn).SelectMany(a => a.ids); const actual = [...iterable]; const expected = [].concat(...jsn.map(a => a.ids)); assert.sameOrderedMembers(actual, expected); }); it('SelectMany() - Selector', function () { const iterable = Linq(jsn).SelectMany(a => a.ids, (t, s) => s); const actual = [...iterable]; const expected = [].concat(...jsn.map(a => a.ids.map(s => s))); assert.sameOrderedMembers(actual, expected); }); }); /** Copyright (c) ENikS. All rights reserved. */
the_stack
import type {Class} from "@swim/util"; import type {MemberFastenerClass} from "@swim/component"; import type {View} from "@swim/view"; import {Controller, TraitViewRef, TraitViewControllerRef} from "@swim/controller"; import type {GraphView} from "../graph/GraphView"; import type {GraphTrait} from "../graph/GraphTrait"; import {GraphController} from "../graph/GraphController"; import type {AxisView} from "../axis/AxisView"; import type {AxisTrait} from "../axis/AxisTrait"; import type {AxisController} from "../axis/AxisController"; import {TopAxisController} from "../axis/TopAxisController"; import {RightAxisController} from "../axis/RightAxisController"; import {BottomAxisController} from "../axis/BottomAxisController"; import {LeftAxisController} from "../axis/LeftAxisController"; import {ChartView} from "./ChartView"; import {ChartTrait} from "./ChartTrait"; import type {ChartControllerObserver} from "./ChartControllerObserver"; /** @public */ export interface ChartControllerAxisExt<D = unknown> { attachAxisTrait(axisTrait: AxisTrait<D>): void; detachAxisTrait(axisTrait: AxisTrait<D>): void; attachAxisView(axisView: AxisView<D>): void; detachAxisView(axisView: AxisView<D>): void; } /** @public */ export class ChartController<X = unknown, Y = unknown> extends GraphController<X, Y> { override readonly observerType?: Class<ChartControllerObserver<X, Y>>; @TraitViewRef<ChartController<X, Y>, ChartTrait<X, Y>, ChartView<X, Y>>({ traitType: ChartTrait, observesTrait: true, initTrait(chartTrait: ChartTrait<X, Y>): void { this.owner.graph.setTrait(chartTrait.graph.trait); const topAxisTrait = chartTrait.topAxis.trait; if (topAxisTrait !== null) { this.owner.topAxis.setTrait(topAxisTrait); } const rightAxisTrait = chartTrait.rightAxis.trait; if (rightAxisTrait !== null) { this.owner.rightAxis.setTrait(rightAxisTrait); } const bottomAxisTrait = chartTrait.bottomAxis.trait; if (bottomAxisTrait !== null) { this.owner.bottomAxis.setTrait(bottomAxisTrait); } const leftAxisTrait = chartTrait.leftAxis.trait; if (leftAxisTrait !== null) { this.owner.leftAxis.setTrait(leftAxisTrait); } }, deinitTrait(chartTrait: ChartTrait<X, Y>): void { const leftAxisTrait = chartTrait.leftAxis.trait; if (leftAxisTrait !== null) { this.owner.leftAxis.deleteTrait(leftAxisTrait); } const bottomAxisTrait = chartTrait.bottomAxis.trait; if (bottomAxisTrait !== null) { this.owner.bottomAxis.deleteTrait(bottomAxisTrait); } const rightAxisTrait = chartTrait.rightAxis.trait; if (rightAxisTrait !== null) { this.owner.rightAxis.deleteTrait(rightAxisTrait); } const topAxisTrait = chartTrait.topAxis.trait; if (topAxisTrait !== null) { this.owner.topAxis.deleteTrait(topAxisTrait); } this.owner.graph.setTrait(null); }, willAttachTrait(newChartTrait: ChartTrait<X, Y>): void { this.owner.callObservers("controllerWillAttachChartTrait", newChartTrait, this.owner); }, didDetachTrait(newChartTrait: ChartTrait<X, Y>): void { this.owner.callObservers("controllerDidDetachChartTrait", newChartTrait, this.owner); }, traitWillAttachTopAxis(topAxisTrait: AxisTrait<unknown>): void { this.owner.topAxis.setTrait(topAxisTrait); }, traitDidDetachTopAxis(topAxisTrait: AxisTrait<unknown>): void { this.owner.topAxis.setTrait(null); }, traitWillAttachRightAxis(rightAxisTrait: AxisTrait<unknown>): void { this.owner.rightAxis.setTrait(rightAxisTrait); }, traitDidDetachRightAxis(rightAxisTrait: AxisTrait<unknown>): void { this.owner.rightAxis.setTrait(null); }, traitWillAttachBottomAxis(bottomAxisTrait: AxisTrait<unknown>): void { this.owner.bottomAxis.setTrait(bottomAxisTrait); }, traitDidDetachBottomAxis(bottomAxisTrait: AxisTrait<unknown>): void { this.owner.bottomAxis.setTrait(null); }, traitWillAttachLeftAxis(leftAxisTrait: AxisTrait<unknown>): void { this.owner.leftAxis.setTrait(leftAxisTrait); }, traitDidDetachLeftAxis(leftAxisTrait: AxisTrait<unknown>): void { this.owner.leftAxis.setTrait(null); }, viewType: ChartView, initView(chartView: ChartView<X, Y>): void { const topAxisController = this.owner.topAxis.controller; if (topAxisController !== null) { topAxisController.axis.insertView(chartView); } const rightAxisController = this.owner.rightAxis.controller; if (rightAxisController !== null) { rightAxisController.axis.insertView(chartView); } const bottomAxisController = this.owner.bottomAxis.controller; if (bottomAxisController !== null) { bottomAxisController.axis.insertView(chartView); } const leftAxisController = this.owner.leftAxis.controller; if (leftAxisController !== null) { leftAxisController.axis.insertView(chartView); } if (this.owner.graph.view !== null || this.owner.graph.trait !== null) { this.owner.graph.insertView(chartView); } }, willAttachView(chartView: ChartView<X, Y>): void { this.owner.callObservers("controllerWillAttachChartView", chartView, this.owner); }, didDetachView(chartView: ChartView<X, Y>): void { this.owner.callObservers("controllerDidDetachChartView", chartView, this.owner); }, }) readonly chart!: TraitViewRef<this, ChartTrait<X, Y>, ChartView<X, Y>>; static readonly chart: MemberFastenerClass<ChartController, "chart">; @TraitViewRef<ChartController<X, Y>, GraphTrait<X, Y>, GraphView<X, Y>>({ extends: true, initTrait(graphTrait: GraphTrait<X, Y>): void { GraphController.graph.prototype.initTrait.call(this, graphTrait as GraphTrait); const chartView = this.owner.chart.view; if (chartView !== null) { this.insertView(chartView); } }, initView(graphView: GraphView<X, Y>): void { GraphController.graph.prototype.initView.call(this, graphView as GraphView); const chartView = this.owner.chart.view; if (chartView !== null) { this.insertView(chartView); } }, deinitView(graphView: GraphView<X, Y>): void { GraphController.graph.prototype.deinitView.call(this, graphView as GraphView); graphView.remove(); }, }) override readonly graph!: TraitViewRef<this, GraphTrait<X, Y>, GraphView<X, Y>>; static override readonly graph: MemberFastenerClass<ChartController, "graph">; @TraitViewControllerRef<ChartController<X, Y>, AxisTrait<X>, AxisView<X>, AxisController<X>, ChartControllerAxisExt<X>>({ implements: true, type: TopAxisController, binds: true, observes: true, get parentView(): View | null { return this.owner.chart.view; }, getTraitViewRef(controller: AxisController<X>): TraitViewRef<unknown, AxisTrait<X>, AxisView<X>> { return controller.axis; }, willAttachController(topAxisController: AxisController<X> ): void { this.owner.callObservers("controllerWillAttachTopAxis", topAxisController, this.owner); }, didAttachController(topAxisController: AxisController<X>): void { const topAxisTrait = topAxisController.axis.trait; if (topAxisTrait !== null) { this.attachAxisTrait(topAxisTrait); } const topAxisView = topAxisController.axis.view; if (topAxisView !== null) { this.attachAxisView(topAxisView); } }, willDetachController(topAxisController: AxisController<X>): void { const topAxisView = topAxisController.axis.view; if (topAxisView !== null) { this.detachAxisView(topAxisView); } const topAxisTrait = topAxisController.axis.trait; if (topAxisTrait !== null) { this.detachAxisTrait(topAxisTrait); } }, didDetachController(topAxisController: AxisController<X>): void { this.owner.callObservers("controllerDidDetachTopAxis", topAxisController, this.owner); }, controllerWillAttachAxisTrait(topAxisTrait: AxisTrait<X>): void { this.owner.callObservers("controllerWillAttachTopAxisTrait", topAxisTrait, this.owner); this.attachAxisTrait(topAxisTrait); }, controllerDidDetachAxisTrait(topAxisTrait: AxisTrait<X>): void { this.detachAxisTrait(topAxisTrait); this.owner.callObservers("controllerDidDetachTopAxisTrait", topAxisTrait, this.owner); }, attachAxisTrait(topAxisTrait: AxisTrait<X>): void { // hook }, detachAxisTrait(topAxisTrait: AxisTrait<X>): void { // hook }, controllerWillAttachAxisView(topAxisView: AxisView<X>): void { this.owner.callObservers("controllerWillAttachTopAxisView", topAxisView, this.owner); this.attachAxisView(topAxisView); }, controllerDidDetachAxisView(topAxisView: AxisView<X>): void { this.detachAxisView(topAxisView); this.owner.callObservers("controllerDidDetachTopAxisView", topAxisView, this.owner); }, attachAxisView(topAxisView: AxisView<X>): void { // hook }, detachAxisView(topAxisView: AxisView<X>): void { topAxisView.remove(); }, detectController(controller: Controller): AxisController<X> | null { return controller instanceof TopAxisController ? controller : null; }, }) readonly topAxis!: TraitViewControllerRef<this, AxisTrait<X>, AxisView<X>, AxisController<X>>; static readonly topAxis: MemberFastenerClass<ChartController, "topAxis">; @TraitViewControllerRef<ChartController<X, Y>, AxisTrait<Y>, AxisView<Y>, AxisController<Y>, ChartControllerAxisExt<Y>>({ implements: true, type: RightAxisController, binds: true, observes: true, get parentView(): View | null { return this.owner.chart.view; }, getTraitViewRef(controller: AxisController<Y>): TraitViewRef<unknown, AxisTrait<Y>, AxisView<Y>> { return controller.axis; }, willAttachController(rightAxisController: AxisController<Y>): void { this.owner.callObservers("controllerWillAttachRightAxis", rightAxisController, this.owner); }, didAttachController(rightAxisController: AxisController<Y>): void { const rightAxisTrait = rightAxisController.axis.trait; if (rightAxisTrait !== null) { this.attachAxisTrait(rightAxisTrait); } const rightAxisView = rightAxisController.axis.view; if (rightAxisView !== null) { this.attachAxisView(rightAxisView); } }, willDetachController(rightAxisController: AxisController<Y>): void { const rightAxisView = rightAxisController.axis.view; if (rightAxisView !== null) { this.detachAxisView(rightAxisView); } const rightAxisTrait = rightAxisController.axis.trait; if (rightAxisTrait !== null) { this.detachAxisTrait(rightAxisTrait); } }, didDetachController(rightAxisController: AxisController<Y>): void { this.owner.callObservers("controllerDidDetachRightAxis", rightAxisController, this.owner); }, controllerWillAttachAxisTrait(rightAxisTrait: AxisTrait<Y>): void { this.owner.callObservers("controllerWillAttachRightAxisTrait", rightAxisTrait, this.owner); this.attachAxisTrait(rightAxisTrait); }, controllerDidDetachAxisTrait(rightAxisTrait: AxisTrait<Y>): void { this.detachAxisTrait(rightAxisTrait); this.owner.callObservers("controllerDidDetachRightAxisTrait", rightAxisTrait, this.owner); }, attachAxisTrait(rightAxisTrait: AxisTrait<Y>): void { // hook }, detachAxisTrait(rightAxisTrait: AxisTrait<Y>): void { // hook }, controllerWillAttachAxisView(rightAxisView: AxisView<Y>): void { this.owner.callObservers("controllerWillAttachRightAxisView", rightAxisView, this.owner); this.attachAxisView(rightAxisView); }, controllerDidDetachAxisView(rightAxisView: AxisView<Y>): void { this.detachAxisView(rightAxisView); this.owner.callObservers("controllerDidDetachRightAxisView", rightAxisView, this.owner); }, attachAxisView(rightAxisView: AxisView<Y>): void { // hook }, detachAxisView(rightAxisView: AxisView<Y>): void { rightAxisView.remove(); }, detectController(controller: Controller): AxisController<Y> | null { return controller instanceof RightAxisController ? controller : null; }, }) readonly rightAxis!: TraitViewControllerRef<this, AxisTrait<Y>, AxisView<Y>, AxisController<Y>>; static readonly rightAxis: MemberFastenerClass<ChartController, "rightAxis">; @TraitViewControllerRef<ChartController<X, Y>, AxisTrait<X>, AxisView<X>, AxisController<X>, ChartControllerAxisExt<X>>({ implements: true, type: BottomAxisController, binds: true, observes: true, get parentView(): View | null { return this.owner.chart.view; }, getTraitViewRef(controller: AxisController<X>): TraitViewRef<unknown, AxisTrait<X>, AxisView<X>> { return controller.axis; }, willAttachController(bottomAxisController: AxisController<X>): void { this.owner.callObservers("controllerWillAttachBottomAxis", bottomAxisController, this.owner); }, didAttachController(bottomAxisController: AxisController<X>): void { const bottomAxisTrait = bottomAxisController.axis.trait; if (bottomAxisTrait !== null) { this.attachAxisTrait(bottomAxisTrait); } const bottomAxisView = bottomAxisController.axis.view; if (bottomAxisView !== null) { this.attachAxisView(bottomAxisView); } }, willDetachController(bottomAxisController: AxisController<X>): void { const bottomAxisView = bottomAxisController.axis.view; if (bottomAxisView !== null) { this.detachAxisView(bottomAxisView); } const bottomAxisTrait = bottomAxisController.axis.trait; if (bottomAxisTrait !== null) { this.detachAxisTrait(bottomAxisTrait); } }, didDetachController(bottomAxisController: AxisController<X>): void { this.owner.callObservers("controllerDidDetachBottomAxis", bottomAxisController, this.owner); }, controllerWillAttachAxisTrait(bottomAxisTrait: AxisTrait<X>): void { this.owner.callObservers("controllerWillAttachBottomAxisTrait", bottomAxisTrait, this.owner); this.attachAxisTrait(bottomAxisTrait); }, controllerDidDetachAxisTrait(bottomAxisTrait: AxisTrait<X>): void { this.detachAxisTrait(bottomAxisTrait); this.owner.callObservers("controllerDidDetachBottomAxisTrait", bottomAxisTrait, this.owner); }, attachAxisTrait(bottomAxisTrait: AxisTrait<X>): void { // hook }, detachAxisTrait(bottomAxisTrait: AxisTrait<X>): void { // hook }, controllerWillAttachAxisView(bottomAxisView: AxisView<X>): void { this.owner.callObservers("controllerWillAttachBottomAxisView", bottomAxisView, this.owner); this.attachAxisView(bottomAxisView); }, controllerDidDetachAxisView(bottomAxisView: AxisView<X>): void { this.detachAxisView(bottomAxisView); this.owner.callObservers("controllerDidDetachBottomAxisView", bottomAxisView, this.owner); }, attachAxisView(bottomAxisView: AxisView<X>): void { // hook }, detachAxisView(bottomAxisView: AxisView<X>): void { bottomAxisView.remove(); }, detectController(controller: Controller): AxisController<X> | null { return controller instanceof BottomAxisController ? controller : null; }, }) readonly bottomAxis!: TraitViewControllerRef<this, AxisTrait<X>, AxisView<X>, AxisController<X>>; static readonly bottomAxis: MemberFastenerClass<ChartController, "bottomAxis">; @TraitViewControllerRef<ChartController<X, Y>, AxisTrait<Y>, AxisView<Y>, AxisController<Y>, ChartControllerAxisExt<Y>>({ implements: true, type: LeftAxisController, binds: true, observes: true, get parentView(): View | null { return this.owner.chart.view; }, getTraitViewRef(controller: AxisController<Y>): TraitViewRef<unknown, AxisTrait<Y>, AxisView<Y>> { return controller.axis; }, willAttachController(leftAxisController: AxisController<Y>): void { this.owner.callObservers("controllerWillAttachLeftAxis", leftAxisController, this.owner); }, didAttachController(leftAxisController: AxisController<Y>): void { const leftAxisTrait = leftAxisController.axis.trait; if (leftAxisTrait !== null) { this.attachAxisTrait(leftAxisTrait); } const leftAxisView = leftAxisController.axis.view; if (leftAxisView !== null) { this.attachAxisView(leftAxisView); } }, willDetachController(leftAxisController: AxisController<Y>): void { const leftAxisView = leftAxisController.axis.view; if (leftAxisView !== null) { this.detachAxisView(leftAxisView); } const leftAxisTrait = leftAxisController.axis.trait; if (leftAxisTrait !== null) { this.detachAxisTrait(leftAxisTrait); } }, didDetachController(leftAxisController: AxisController<Y>): void { this.owner.callObservers("controllerDidDetachLeftAxis", leftAxisController, this.owner); }, controllerWillAttachAxisTrait(leftAxisTrait: AxisTrait<Y>): void { this.owner.callObservers("controllerWillAttachLeftAxisTrait", leftAxisTrait, this.owner); this.attachAxisTrait(leftAxisTrait); }, controllerDidDetachAxisTrait(leftAxisTrait: AxisTrait<Y>): void { this.detachAxisTrait(leftAxisTrait); this.owner.callObservers("controllerDidDetachLeftAxisTrait", leftAxisTrait, this.owner); }, attachAxisTrait(leftAxisTrait: AxisTrait<Y>): void { // hook }, detachAxisTrait(leftAxisTrait: AxisTrait<Y>): void { // hook }, controllerWillAttachAxisView(leftAxisView: AxisView<Y>): void { this.owner.callObservers("controllerWillAttachLeftAxisView", leftAxisView, this.owner); this.attachAxisView(leftAxisView); }, controllerDidDetachAxisView(leftAxisView: AxisView<Y>): void { this.detachAxisView(leftAxisView); this.owner.callObservers("controllerDidDetachLeftAxisView", leftAxisView, this.owner); }, attachAxisView(leftAxisView: AxisView<Y>): void { // hook }, detachAxisView(leftAxisView: AxisView<Y>): void { leftAxisView.remove(); }, detectController(controller: Controller): AxisController<Y> | null { return controller instanceof LeftAxisController ? controller : null; }, }) readonly leftAxis!: TraitViewControllerRef<this, AxisTrait<Y>, AxisView<Y>, AxisController<Y>>; static readonly leftAxis: MemberFastenerClass<ChartController, "leftAxis">; }
the_stack
import { localize } from '@opensumi/ide-core-common'; import { Color, RGBA } from '../../common/color'; import { registerColor, transparent, lighten, darken, lessProminent } from '../color-registry'; import { badgeBackground, badgeForeground } from './badge'; import { contrastBorder, activeContrastBorder, focusBorder, foreground } from './base'; import { backgroundColor, foregroundColor } from './basic-color'; export const editorErrorForeground = registerColor( 'editorError.foreground', { dark: '#F48771', light: '#E51400', hc: null }, localize('editorError.foreground', 'Foreground color of error squigglies in the editor.'), ); export const editorErrorBorder = registerColor( 'editorError.border', { dark: null, light: null, hc: Color.fromHex('#E47777').transparent(0.8) }, localize('errorBorder', 'Border color of error boxes in the editor.'), ); export const editorWarningForeground = registerColor( 'editorWarning.foreground', { dark: '#CCA700', light: '#E9A700', hc: null }, localize('editorWarning.foreground', 'Foreground color of warning squigglies in the editor.'), ); export const editorWarningBorder = registerColor( 'editorWarning.border', { dark: null, light: null, hc: Color.fromHex('#FFCC00').transparent(0.8) }, localize('warningBorder', 'Border color of warning boxes in the editor.'), ); export const editorInfoForeground = registerColor( 'editorInfo.foreground', { dark: '#75BEFF', light: '#75BEFF', hc: null }, localize('editorInfo.foreground', 'Foreground color of info squigglies in the editor.'), ); export const editorInfoBorder = registerColor( 'editorInfo.border', { dark: null, light: null, hc: Color.fromHex('#71B771').transparent(0.8) }, localize('infoBorder', 'Border color of info boxes in the editor.'), ); export const editorHintForeground = registerColor( 'editorHint.foreground', { dark: Color.fromHex('#eeeeee').transparent(0.7), light: '#6c6c6c', hc: null }, localize('editorHint.foreground', 'Foreground color of hint squigglies in the editor.'), ); export const editorHintBorder = registerColor( 'editorHint.border', { dark: null, light: null, hc: Color.fromHex('#eeeeee').transparent(0.8) }, localize('hintBorder', 'Border color of hint boxes in the editor.'), ); /** * Editor background color. * Because of bug https://monacotools.visualstudio.com/DefaultCollection/Monaco/_workitems/edit/13254 * we are *not* using the color white (or #ffffff, rgba(255,255,255)) but something very close to white. */ export const editorBackground = registerColor( 'editor.background', { light: '#fffffe', dark: '#1E1E1E', hc: backgroundColor }, localize('editorBackground', 'Editor background color.'), ); /** * Editor foreground color. */ export const editorForeground = registerColor( 'editor.foreground', { light: '#333333', dark: '#BBBBBB', hc: foregroundColor }, localize('editorForeground', 'Editor default foreground color.'), ); /** * Editor widgets */ export const editorWidgetForeground = registerColor( 'editorWidget.foreground', { dark: foreground, light: foreground, hc: foreground }, localize('editorWidgetForeground', 'Foreground color of editor widgets, such as find/replace.'), ); export const editorWidgetBackground = registerColor( 'editorWidget.background', { dark: '#252526', light: '#F3F3F3', hc: '#0C141F' }, localize('editorWidgetBackground', 'Background color of editor widgets, such as find/replace.'), ); export const editorWidgetBorder = registerColor( 'editorWidget.border', { dark: '#454545', light: '#C8C8C8', hc: contrastBorder }, localize( 'editorWidgetBorder', 'Border color of editor widgets. The color is only used if the widget chooses to have a border and if the color is not overridden by a widget.', ), ); export const editorWidgetResizeBorder = registerColor( 'editorWidget.resizeBorder', { light: null, dark: null, hc: null }, localize( 'editorWidgetResizeBorder', 'Border color of the resize bar of editor widgets. The color is only used if the widget chooses to have a resize border and if the color is not overridden by a widget.', ), ); /** * Editor selection colors. */ export const editorSelectionBackground = registerColor( 'editor.selectionBackground', { light: '#ADD6FF', dark: '#264F78', hc: '#f3f518' }, localize('editorSelectionBackground', 'Color of the editor selection.'), ); export const editorSelectionForeground = registerColor( 'editor.selectionForeground', { light: null, dark: null, hc: '#000000' }, localize('editorSelectionForeground', 'Color of the selected text for high contrast.'), ); export const editorInactiveSelection = registerColor( 'editor.inactiveSelectionBackground', { light: transparent(editorSelectionBackground, 0.5), dark: transparent(editorSelectionBackground, 0.5), hc: transparent(editorSelectionBackground, 0.5), }, localize( 'editorInactiveSelection', 'Color of the selection in an inactive editor. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const editorSelectionHighlight = registerColor( 'editor.selectionHighlightBackground', { light: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), dark: lessProminent(editorSelectionBackground, editorBackground, 0.3, 0.6), hc: null, }, localize( 'editorSelectionHighlight', 'Color for regions with the same content as the selection. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const editorSelectionHighlightBorder = registerColor( 'editor.selectionHighlightBorder', { light: null, dark: null, hc: activeContrastBorder }, localize('editorSelectionHighlightBorder', 'Border color for regions with the same content as the selection.'), ); /** * Editor find match colors. */ export const editorFindMatch = registerColor( 'editor.findMatchBackground', { light: '#A8AC94', dark: '#515C6A', hc: null }, localize('editorFindMatch', 'Color of the current search match.'), ); export const editorFindMatchHighlight = registerColor( 'editor.findMatchHighlightBackground', { light: '#EA5C0055', dark: '#EA5C0055', hc: null }, localize( 'findMatchHighlight', 'Color of the other search matches. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const editorFindRangeHighlight = registerColor( 'editor.findRangeHighlightBackground', { dark: '#3a3d4166', light: '#b4b4b44d', hc: null }, localize( 'findRangeHighlight', 'Color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const editorFindMatchBorder = registerColor( 'editor.findMatchBorder', { light: null, dark: null, hc: activeContrastBorder }, localize('editorFindMatchBorder', 'Border color of the current search match.'), ); export const editorFindMatchHighlightBorder = registerColor( 'editor.findMatchHighlightBorder', { light: null, dark: null, hc: activeContrastBorder }, localize('findMatchHighlightBorder', 'Border color of the other search matches.'), ); export const editorFindRangeHighlightBorder = registerColor( 'editor.findRangeHighlightBorder', { dark: null, light: null, hc: transparent(activeContrastBorder, 0.4) }, localize( 'findRangeHighlightBorder', 'Border color of the range limiting the search. The color must not be opaque so as not to hide underlying decorations.', ), true, ); /** * Editor hover */ export const editorHoverHighlight = registerColor( 'editor.hoverHighlightBackground', { light: '#ADD6FF26', dark: '#264f7840', hc: '#ADD6FF26' }, localize( 'hoverHighlight', 'Highlight below the word for which a hover is shown. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const editorHoverBackground = registerColor( 'editorHoverWidget.background', { light: editorWidgetBackground, dark: editorWidgetBackground, hc: editorWidgetBackground }, localize('hoverBackground', 'Background color of the editor hover.'), ); export const editorHoverBorder = registerColor( 'editorHoverWidget.border', { light: editorWidgetBorder, dark: editorWidgetBorder, hc: editorWidgetBorder }, localize('hoverBorder', 'Border color of the editor hover.'), ); export const editorHoverStatusBarBackground = registerColor( 'editorHoverWidget.statusBarBackground', { dark: lighten(editorHoverBackground, 0.2), light: darken(editorHoverBackground, 0.05), hc: editorWidgetBackground }, localize('statusBarBackground', 'Background color of the editor hover status bar.'), ); /** * Editor link colors */ export const editorActiveLinkForeground = registerColor( 'editorLink.activeForeground', { dark: '#4E94CE', light: Color.blue, hc: Color.cyan }, localize('activeLinkForeground', 'Color of active links.'), ); /** * Diff Editor Colors */ export const defaultInsertColor = new Color(new RGBA(155, 185, 85, 0.2)); export const defaultRemoveColor = new Color(new RGBA(255, 0, 0, 0.2)); export const diffInserted = registerColor( 'diffEditor.insertedTextBackground', { dark: defaultInsertColor, light: defaultInsertColor, hc: null }, localize( 'diffEditorInserted', 'Background color for text that got inserted. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const diffRemoved = registerColor( 'diffEditor.removedTextBackground', { dark: defaultRemoveColor, light: defaultRemoveColor, hc: null }, localize( 'diffEditorRemoved', 'Background color for text that got removed. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const diffInsertedOutline = registerColor( 'diffEditor.insertedTextBorder', { dark: null, light: null, hc: '#33ff2eff' }, localize('diffEditorInsertedOutline', 'Outline color for the text that got inserted.'), ); export const diffRemovedOutline = registerColor( 'diffEditor.removedTextBorder', { dark: null, light: null, hc: '#FF008F' }, localize('diffEditorRemovedOutline', 'Outline color for text that got removed.'), ); export const diffBorder = registerColor( 'diffEditor.border', { dark: null, light: null, hc: contrastBorder }, localize('diffEditorBorder', 'Border color between the two text editors.'), ); /** * Editor View Colors from editorColorRegistry */ export const editorLineHighlight = registerColor( 'editor.lineHighlightBackground', { dark: null, light: null, hc: null }, localize('lineHighlight', 'Background color for the highlight of line at the cursor position.'), ); export const editorLineHighlightBorder = registerColor( 'editor.lineHighlightBorder', { dark: '#282828', light: '#eeeeee', hc: '#f38518' }, localize('lineHighlightBorderBox', 'Background color for the border around the line at the cursor position.'), ); export const editorRangeHighlight = registerColor( 'editor.rangeHighlightBackground', { dark: '#ffffff0b', light: '#fdff0033', hc: null }, localize( 'rangeHighlight', 'Background color of highlighted ranges, like by quick open and find features. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const editorRangeHighlightBorder = registerColor( 'editor.rangeHighlightBorder', { dark: null, light: null, hc: activeContrastBorder }, localize('rangeHighlightBorder', 'Background color of the border around highlighted ranges.'), true, ); export const editorCursorForeground = registerColor( 'editorCursor.foreground', { dark: '#AEAFAD', light: Color.black, hc: Color.white }, localize('caret', 'Color of the editor cursor.'), ); export const editorCursorBackground = registerColor( 'editorCursor.background', null, localize( 'editorCursorBackground', 'The background color of the editor cursor. Allows customizing the color of a character overlapped by a block cursor.', ), ); export const editorWhitespaces = registerColor( 'editorWhitespace.foreground', { dark: '#e3e4e229', light: '#33333333', hc: '#e3e4e229' }, localize('editorWhitespaces', 'Color of whitespace characters in the editor.'), ); export const editorIndentGuides = registerColor( 'editorIndentGuide.background', { dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces }, localize('editorIndentGuides', 'Color of the editor indentation guides.'), ); export const editorActiveIndentGuides = registerColor( 'editorIndentGuide.activeBackground', { dark: editorWhitespaces, light: editorWhitespaces, hc: editorWhitespaces }, localize('editorActiveIndentGuide', 'Color of the active editor indentation guides.'), ); export const editorLineNumbers = registerColor( 'editorLineNumber.foreground', { dark: '#858585', light: '#237893', hc: Color.white }, localize('editorLineNumbers', 'Color of editor line numbers.'), ); const deprecatedEditorActiveLineNumber = registerColor( 'editorActiveLineNumber.foreground', { dark: '#c6c6c6', light: '#0B216F', hc: activeContrastBorder }, localize('editorActiveLineNumber', 'Color of editor active line number'), false, localize('deprecatedEditorActiveLineNumber', "Id is deprecated. Use 'editorLineNumber.activeForeground' instead."), ); export const editorActiveLineNumber = registerColor( 'editorLineNumber.activeForeground', { dark: deprecatedEditorActiveLineNumber, light: deprecatedEditorActiveLineNumber, hc: deprecatedEditorActiveLineNumber, }, localize('editorActiveLineNumber', 'Color of editor active line number'), ); export const editorRuler = registerColor( 'editorRuler.foreground', { dark: '#5A5A5A', light: Color.lightgrey, hc: Color.white }, localize('editorRuler', 'Color of the editor rulers.'), ); export const editorCodeLensForeground = registerColor( 'editorCodeLens.foreground', { dark: '#999999', light: '#999999', hc: '#999999' }, localize('editorCodeLensForeground', 'Foreground color of editor code lenses'), ); export const editorBracketMatchBackground = registerColor( 'editorBracketMatch.background', { dark: '#0064001a', light: '#0064001a', hc: '#0064001a' }, localize('editorBracketMatchBackground', 'Background color behind matching brackets'), ); export const editorBracketMatchBorder = registerColor( 'editorBracketMatch.border', { dark: '#888', light: '#B9B9B9', hc: '#fff' }, localize('editorBracketMatchBorder', 'Color for matching brackets boxes'), ); export const editorOverviewRulerBorder = registerColor( 'editorOverviewRuler.border', { dark: '#7f7f7f4d', light: '#7f7f7f4d', hc: '#7f7f7f4d' }, localize('editorOverviewRulerBorder', 'Color of the overview ruler border.'), ); const overviewRulerDefault = new Color(new RGBA(197, 197, 197, 1)); export const editorGutter = registerColor( 'editorGutter.background', { dark: editorBackground, light: editorBackground, hc: editorBackground }, localize( 'editorGutter', 'Background color of the editor gutter. The gutter contains the glyph margins and the line numbers.', ), ); export const overviewRulerCommentingRangeForeground = registerColor( 'editorGutter.commentRangeForeground', { dark: overviewRulerDefault, light: overviewRulerDefault, hc: overviewRulerDefault }, localize('editorGutterCommentRangeForeground', 'Editor gutter decoration color for commenting ranges.'), ); export const editorUnnecessaryCodeBorder = registerColor( 'editorUnnecessaryCode.border', { dark: null, light: null, hc: Color.fromHex('#fff').transparent(0.8) }, localize('unnecessaryCodeBorder', 'Border color of unnecessary (unused) source code in the editor.'), ); export const editorUnnecessaryCodeOpacity = registerColor( 'editorUnnecessaryCode.opacity', { dark: Color.fromHex('#000a'), light: Color.fromHex('#0007'), hc: null }, localize( 'unnecessaryCodeOpacity', 'Opacity of unnecessary (unused) source code in the editor. For example, "#000000c0" will render the code with 75% opacity. For high contrast themes, use the \'editorUnnecessaryCode.border\' theme color to underline unnecessary code instead of fading it out.', ), ); const rulerRangeDefault = new Color(new RGBA(0, 122, 204, 0.6)); export const overviewRulerRangeHighlight = registerColor( 'editorOverviewRuler.rangeHighlightForeground', { dark: rulerRangeDefault, light: rulerRangeDefault, hc: rulerRangeDefault }, localize( 'overviewRulerRangeHighlight', 'Overview ruler marker color for range highlights. The color must not be opaque so as not to hide underlying decorations.', ), true, ); export const overviewRulerError = registerColor( 'editorOverviewRuler.errorForeground', { dark: new Color(new RGBA(255, 18, 18, 0.7)), light: new Color(new RGBA(255, 18, 18, 0.7)), hc: new Color(new RGBA(255, 50, 50, 1)), }, localize('overviewRuleError', 'Overview ruler marker color for errors.'), ); export const overviewRulerWarning = registerColor( 'editorOverviewRuler.warningForeground', { dark: editorWarningForeground, light: editorWarningForeground, hc: editorWarningBorder }, localize('overviewRuleWarning', 'Overview ruler marker color for warnings.'), ); export const overviewRulerInfo = registerColor( 'editorOverviewRuler.infoForeground', { dark: editorInfoForeground, light: editorInfoForeground, hc: editorInfoBorder }, localize('overviewRuleInfo', 'Overview ruler marker color for infos.'), ); // < --- Editors --- > export const EDITOR_PANE_BACKGROUND = registerColor( 'editorPane.background', { dark: editorBackground, light: editorBackground, hc: editorBackground, }, localize( 'editorPaneBackground', 'Background color of the editor pane visible on the left and right side of the centered editor layout.', ), ); registerColor( 'editorGroup.background', { dark: null, light: null, hc: null, }, localize('editorGroupBackground', 'Deprecated background color of an editor group.'), false, localize( 'deprecatedEditorGroupBackground', 'Deprecated: Background color of an editor group is no longer being supported with the introduction of the grid editor layout. You can use editorGroup.emptyBackground to set the background color of empty editor groups.', ), ); export const EDITOR_GROUP_EMPTY_BACKGROUND = registerColor( 'editorGroup.emptyBackground', { dark: null, light: null, hc: null, }, localize( 'editorGroupEmptyBackground', 'Background color of an empty editor group. Editor groups are the containers of editors.', ), ); export const EDITOR_GROUP_FOCUSED_EMPTY_BORDER = registerColor( 'editorGroup.focusedEmptyBorder', { dark: null, light: null, hc: focusBorder, }, localize( 'editorGroupFocusedEmptyBorder', 'Border color of an empty editor group that is focused. Editor groups are the containers of editors.', ), ); export const EDITOR_GROUP_HEADER_TABS_BACKGROUND = registerColor( 'editorGroupHeader.tabsBackground', { dark: '#252526', light: '#F3F3F3', hc: null, }, localize( 'tabsContainerBackground', 'Background color of the editor group title header when tabs are enabled. Editor groups are the containers of editors.', ), ); export const EDITOR_GROUP_HEADER_NO_TABS_BACKGROUND = registerColor( 'editorGroupHeader.noTabsBackground', { dark: editorBackground, light: editorBackground, hc: editorBackground, }, localize( 'editorGroupHeaderBackground', 'Background color of the editor group title header when tabs are disabled (`"workbench.editor.showTabs": false`). Editor groups are the containers of editors.', ), ); export const EDITOR_GROUP_BORDER = registerColor( 'editorGroup.border', { dark: '#444444', light: '#E7E7E7', hc: contrastBorder, }, localize( 'editorGroupBorder', 'Color to separate multiple editor groups from each other. Editor groups are the containers of editors.', ), ); export const EDITOR_DRAG_AND_DROP_BACKGROUND = registerColor( 'editorGroup.dropBackground', { dark: Color.fromHex('#53595D').transparent(0.5), light: Color.fromHex('#2677CB').transparent(0.18), hc: null, }, localize( 'editorDragAndDropBackground', 'Background color when dragging editors around. The color should have transparency so that the editor contents can still shine through.', ), ); /** * Inline hints */ export const editorInlayHintForeground = registerColor( 'editorInlayHint.foreground', { dark: transparent(badgeForeground, 0.8), light: transparent(badgeForeground, 0.8), hc: badgeForeground }, localize('editorInlayHintForeground', 'Foreground color of inline hints'), ); export const editorInlayHintBackground = registerColor( 'editorInlayHint.background', { dark: transparent(badgeBackground, 0.6), light: transparent(badgeBackground, 0.3), hc: badgeBackground }, localize('editorInlayHintBackground', 'Background color of inline hints'), ); export const editorInlayHintTypeForeground = registerColor( 'editorInlayHintType.foreground', { dark: transparent(badgeForeground, 0.8), light: transparent(badgeForeground, 0.8), hc: badgeForeground }, localize('editorInlayHintForegroundTypes', 'Foreground color of inline hints for types'), ); export const editorInlayHintTypeBackground = registerColor( 'editorInlayHintType.background', { dark: transparent(badgeBackground, 0.6), light: transparent(badgeBackground, 0.3), hc: badgeBackground }, localize('editorInlayHintBackgroundTypes', 'Background color of inline hints for types'), ); export const editorInlayHintParameterForeground = registerColor( 'editorInlayHintParameter.foreground', { dark: transparent(badgeForeground, 0.8), light: transparent(badgeForeground, 0.8), hc: badgeForeground }, localize('editorInlayHintForegroundParameter', 'Foreground color of inline hints for parameters'), ); export const editorInlayHintParameterBackground = registerColor( 'editorInlayHintParameter.background', { dark: transparent(badgeBackground, 0.6), light: transparent(badgeBackground, 0.3), hc: badgeBackground }, localize('editorInlayHintBackgroundParameter', 'Background color of inline hints for parameters'), );
the_stack
declare const enum ChinaCRS { /** * 标准无偏坐标系 */ WGS84 = "WGS84", /** * 国测局(GCJ02)偏移坐标系 */ GCJ02 = "GCJ02", /** * 百度(BD09) 偏移坐标系 */ BAIDU = "BD09" } /** * 坐标系 枚举 */ declare const enum CRS { /** * Web墨卡托投影坐标系 */ EPSG3857 = "EPSG:3857", /** * WGS84地理坐标系 */ EPSG4326 = "EPSG:4326", /** * 中国大地2000 (CGCS2000)地理坐标系 */ EPSG4490 = "EPSG:4490", /** * CGCS2000 Gauss-Kruger Zone 平面投影,3度分带,横坐标前加带号。 * 范围:EPSG:4513 到 EPSG:4533 */ CGCS2000_GK_Zone_3 = "CGCS2000_GK_Zone_3", /** * CGCS2000 Gauss-Kruger Zone 平面投影,6度分带,横坐标前加带号。 * 范围:EPSG:4491 到 EPSG:4501 */ CGCS2000_GK_Zone_6 = "CGCS2000_GK_Zone_6", /** * CGCS2000 Gauss-Kruger CM 平面投影,3度分带,横坐标前不加带号。 * 范围:EPSG:4534 到 EPSG:4554 */ CGCS2000_GK_CM_3 = "CGCS2000_GK_CM_3", /** * CGCS2000 Gauss-Kruger CM 平面投影,6度分带,横坐标前不加带号。 * 范围:EPSG:4502 到 EPSG:4512 */ CGCS2000_GK_CM_6 = "CGCS2000_GK_CM_6" } /** * 事件类型 枚举(所有事件统一的入口) */ declare const enum EventType { /** * 添加对象 */ add = "add", /** * 移除对象 */ remove = "remove", /** * 添加矢量数据时[图层上监听时使用] */ addGraphic = "addGraphic", /** * 移除矢量数据时[图层上监听时使用] */ removeGraphic = "removeGraphic", /** * 添加图层[map上监听时使用] */ addLayer = "addLayer", /** * 移除图层[map上监听时使用] */ removeLayer = "removeLayer", /** * 更新了对象 */ update = "update", /** * 更新了style对象 */ updateStyle = "updateStyle", /** * 更新了attr对象 */ updateAttr = "updateAttr", /** * 显示了对象 */ show = "show", /** * 隐藏了对象 */ hide = "hide", /** * 开始 */ start = "start", /** * 变化了 */ change = "change", /** * 多个数据异步分析时,完成其中一个时的回调事件 */ endItem = "endItem", /** * 多个数据异步分析时,完成所有的回调事件 */ end = "end", /** * 完成 */ stop = "stop", /** * 完成加载,但未做任何其他处理前 */ loadBefore = "loadBefore", /** * 完成加载,执行所有内部处理后 */ load = "load", /** * 出错了 */ error = "error", /** * 完成加载配置信息 */ loadConfig = "loadConfig", /** * popup弹窗打开后 */ popupOpen = "popupOpen", /** * popup弹窗关闭 */ popupClose = "popupClose", /** * tooltip弹窗打开后 */ tooltipOpen = "tooltipOpen", /** * tooltip弹窗关闭 */ tooltipClose = "tooltipClose", /** * 左键单击 鼠标事件 */ click = "click", /** * 左键单击到矢量或模型数据时 鼠标事件 */ clickGraphic = "clickGraphic", /** * 左键单击到wms或arcgis瓦片服务的对应矢量数据时 */ clickTileGraphic = "clickTileGraphic", /** * 左键单击地图空白(未单击到矢量或模型数据)时 鼠标事件 */ clickMap = "clickMap", /** * 左键双击 鼠标事件 */ dblClick = "dblClick", /** * 左键鼠标按下 鼠标事件 */ leftDown = "leftDown", /** * 左键鼠标按下后释放 鼠标事件 */ leftUp = "leftUp", /** * 鼠标移动 鼠标事件 */ mouseMove = "mouseMove", /** * 鼠标移动(拾取目标,并延迟处理) 鼠标事件 */ mouseMoveTarget = "mouseMoveTarget", /** * 鼠标滚轮滚动 鼠标事件 */ wheel = "wheel", /** * 右键单击 鼠标事件 */ rightClick = "rightClick", /** * 右键鼠标按下 鼠标事件 */ rightDown = "rightDown", /** * 右键鼠标按下后释放 鼠标事件 */ rightUp = "rightUp", /** * 中键单击 鼠标事件 */ middleClick = "middleClick", /** * 中键鼠标按下 鼠标事件 */ middleDown = "middleDown", /** * 中键鼠标按下后释放 鼠标事件 */ middleUp = "middleUp", /** * 在触摸屏上两指缩放开始 鼠标事件 */ pinchStart = "pinchStart", /** * 在触摸屏上两指缩放结束 鼠标事件 */ pinchEnd = "pinchEnd", /** * 在触摸屏上两指移动 鼠标事件 */ pinchMove = "pinchMove", /** * 鼠标按下 [左中右3键都触发] 鼠标事件 */ mouseDown = "mouseDown", /** * 鼠标按下后释放 [左中右3键都触发] 鼠标事件 */ mouseUp = "mouseUp", /** * 鼠标移入 鼠标事件 */ mouseOver = "mouseOver", /** * 鼠标移出 鼠标事件 */ mouseOut = "mouseOut", /** * 按键按下 键盘事件 */ keydown = "keydown", /** * 按键按下后释放 键盘事件 */ keyup = "keyup", /** * 开始绘制 标绘事件 */ drawStart = "drawStart", /** * 正在移动鼠标中,绘制过程中鼠标移动了点 标绘事件 */ drawMouseMove = "drawMouseMove", /** * 绘制过程中增加了点 标绘事件 */ drawAddPoint = "drawAddPoint", /** * 绘制过程中删除了最后一个点 标绘事件 */ drawRemovePoint = "drawRemovePoint", /** * 创建完成 标绘事件 */ drawCreated = "drawCreated", /** * 开始编辑 标绘事件 */ editStart = "editStart", /** * 移动鼠标按下左键(LEFT_DOWN)标绘事件 */ editMouseDown = "editMouseDown", /** * 正在移动鼠标中,正在编辑拖拽修改点中(MOUSE_MOVE) 标绘事件 */ editMouseMove = "editMouseMove", /** * 编辑修改了点(LEFT_UP)标绘事件 */ editMovePoint = "editMovePoint", /** * 编辑删除了点 标绘事件 */ editRemovePoint = "editRemovePoint", /** * 图上编辑修改了相关style属性 标绘事件 */ editStyle = "editStyle", /** * 停止编辑 标绘事件 */ editStop = "editStop", /** * 标绘事件 */ move = "move", /** * 3dtiles模型,模型瓦片初始化完成 * 该回调只执行一次 */ initialTilesLoaded = "initialTilesLoaded", /** * 3dtiles模型,当前批次模型加载完成 * 该回调会执行多次,视角变化后重新加载一次完成后都会回调 */ allTilesLoaded = "allTilesLoaded", /** * 栅格瓦片图层,添加单个瓦片,开始加载瓦片(请求前) */ addTile = "addTile", /** * 栅格瓦片图层,添加单个瓦片 加载瓦片完成 */ addTileSuccess = "addTileSuccess", /** * 栅格瓦片图层,添加单个瓦片 加载瓦片出错了 */ addTileError = "addTileError", /** * 栅格瓦片图层,移除单个瓦片 */ removeTile = "removeTile", /** * 相机开启移动前 场景事件 */ cameraMoveStart = "cameraMoveStart", /** * 相机移动完成后 场景事件 */ cameraMoveEnd = "cameraMoveEnd", /** * 相机位置完成 场景事件 */ cameraChanged = "cameraChanged", /** * 场景更新前 场景事件 */ preUpdate = "preUpdate", /** * 场景更新后 场景事件 */ postUpdate = "postUpdate", /** * 场景渲染前 场景事件 */ preRender = "preRender", /** * 场景渲染后 场景事件 */ postRender = "postRender", /** * 场景渲染失败(需要刷新页面) */ renderError = "renderError", /** * 场景模式(2D/3D/哥伦布)变换前 场景事件 */ morphStart = "morphStart", /** * 完成场景模式(2D/3D/哥伦布)变换 场景事件 */ morphComplete = "morphComplete", /** * 时钟跳动 场景事件 */ clockTick = "clockTick" } /** * 矢量数据类型 */ declare const enum GraphicType { label, labelP, point, pointP, billboard, divBillboard, fontBillboard, billboardP, model, modelP, modelCombine, plane, planeP, box, boxP, circle, circleP, ellipse, cylinder, cylinderP, coneTrack, ellipsoid, ellipsoidP, polyline, curve, polylineP, polylineSP, polylineCombine, polylineVolume, polylineVolumeP, path, corridor, corridorP, wall, wallP, polygon, polygonP, polygonCombine, rectangle, rectangleP, frustum, water, div, divLightPoint, divUpLabel, divBoderLabel, particleSystem, video2D, video3D, flatBillboard, lightCone, scrollWall, diffuseWall, dynamicRiver, road, rectangularSensor, pit, attackArrow, attackArrowPW, attackArrowYW, doubleArrow, fineArrow, fineArrowYW, straightArrow, lune, sector, regular, isosTriangle, closeVurve, gatheringPlace, camberRadar, conicSensor, rectSensor, satelliteSensor, satellite } /** * 多语种文本配置, * 值为数组,对应{@link LangType}按照固定顺序排列,如:[中文简体,中文繁體,English] * @example * mars3d.Lang["_单击开始绘制"][mars3d.LangType.ZH] ="新的中文提示语句"; */ declare const Lang: string; /** * 语言类型 枚举 */ declare const enum LangType { /** * 简体中文 */ ZH = 0, /** * 繁体中文(香港、台湾等地区) */ ZHHK = 1, /** * English英文 en */ EN = 2 } /** * 图层类型 */ declare const enum LayerType { tdt, baidu, gaode, tencent, osm, google, bing, mapbox, ion, image, xyz, arcgis, arcgis_cache, wms, wmts, tms, gee, tileinfo, grid, terrain, group, graphic, graphicGroup, div, geojson, lodGraphic, wfs, arcgis_wfs, arcgis_wfs_single, model, tileset或3dtiles, czmGeojson, kml, czml, graticule, gaodePOI, osmBuildings, tdt_dm, supermap_s3m, supermap_img, supermap_mvt, mapv, echarts, heat, canvasWind, wind } /** * 材质 类型枚举 * @example * //Entity矢量对象 * let graphic = new mars3d.graphic.PolylineEntity({ * positions: [ * [117.169646, 31.769171], * [117.194579, 31.806466], * ], * style: { * width: 5, * material: mars3d.MaterialUtil.createMaterialProperty(mars3d.MaterialType.LineFlow, { * color: '#00ff00', * image: 'img/textures/LinkPulse.png', * speed: 5, * }), * }, * }) * graphicLayer.addGraphic(graphic) * * //Primitive矢量对象 * var primitive = new mars3d.graphic.PolylinePrimitive({ * positions: [ * [117.348938, 31.805369, 7.63], * [117.429496, 31.786715, 8.41], * ], * style: { * width: 5, * material: mars3d.MaterialUtil.createMaterial(mars3d.MaterialType.LineFlow, { * color: '#1a9850', * image: 'img/textures/ArrowOpacity.png', * speed: 10, * }), * }, * }) * graphicLayer.addGraphic(primitive) */ declare module "MaterialType" { /** * 通用:纯色颜色 材质 * @property [color = Cesium.Color.WHITE] - 颜色 */ const Color: string; /** * 通用:图片 材质 * @property image - 图片对象或图片地址 * @property [repeat = new Cesium.Cartesian2(1.0, 1.0)] - A {@link Cartesian2} Property specifying the number of times the image repeats in each direction. * @property [color = Cesium.Color.WHITE] - The color applied to the image * @property [transparent = false] - Set to true when the image has transparency (for example, when a png has transparent sections) */ const Image: string; /** * 通用:网格 材质 * @property [color = Cesium.Color.WHITE] - A Property specifying the grid {@link Color}. * @property [cellAlpha = 0.1] - A numeric Property specifying cell alpha values. * @property [lineCount = new Cesium.Cartesian2(8, 8)] - A {@link Cartesian2} Property specifying the number of grid lines along each axis. * @property [lineThickness = new Cesium.Cartesian2(1.0, 1.0)] - A {@link Cartesian2} Property specifying the thickness of grid lines along each axis. * @property [lineOffset = new Cesium.Cartesian2(0.0, 0.0)] - A {@link Cartesian2} Property specifying starting offset of grid lines along each axis. */ const Grid: string; /** * 通用:棋盘 材质 * @property [evenColor = Cesium.Color.WHITE] - A Property specifying the first {@link Cesium.Color}. * @property [oddColor = Cesium.Color.BLACK] - A Property specifying the second {@link Cesium.Color}. * @property [repeat = new Cesium.Cartesian2(2.0, 2.0)] - A {@link Cesium.Cartesian2} Property specifying how many times the tiles repeat in each direction. */ const Checkerboard: string; /** * 通用:条纹 材质 * @property [orientation = Cesium.StripeOrientation.HORIZONTAL] - 条纹方向 * @property [evenColor = Cesium.Color.WHITE] - A Property specifying the first {@link Color}. * @property [oddColor = Cesium.Color.BLACK] - A Property specifying the second {@link Color}. * @property [offset = 0] - A numeric Property specifying how far into the pattern to start the material. * @property [repeat = 1] - A numeric Property specifying how many times the stripes repeat. */ const Stripe: string; /** * 通用:水面 材质 * @property [baseWaterColor = new Cesium.Color(0.2, 0.3, 0.6, 1.0)] - 基础颜色 * @property [blendColor = new Cesium.Color(0.0, 1.0, 0.699, 1.0)] - 从水中混合到非水域时使用的rgba颜色对象。 * @property [specularMap] - 单一通道纹理用来指示水域的面积。 * @property [normalMap] - 水正常扰动的法线图。 * @property [frequency = 100] - 控制波数的数字。 * @property [animationSpeed = 0.01] - 控制水的动画速度的数字。 * @property [amplitude = 10] - 控制水波振幅的数字。 * @property [specularIntensity = 0.5] - 控制镜面反射强度的数字。 * @property [fadeFactor = 1.0] - fadeFactor */ const Water: string; /** * 线:虚线 材质 * @property [color = Cesium.Color.WHITE] - A Property specifying the {@link Color} of the line. * @property [gapColor = Cesium.Color.TRANSPARENT] - A Property specifying the {@link Color} of the gaps in the line. * @property [dashLength = 16.0] - A numeric Property specifying the length of the dash pattern in pixels. * @property [dashPattern = 255.0] - A numeric Property specifying a 16 bit pattern for the dash */ const PolylineDash: string; /** * 线:衬色线 材质 * @property [color = Cesium.Color.WHITE] - A Property specifying the {@link Color} of the line. * @property [outlineColor = Cesium.Color.BLACK] - A Property specifying the {@link Color} of the outline. * @property [outlineWidth = 1.0] - A numeric Property specifying the width of the outline, in pixels. */ const PolylineOutline: string; /** * 线:箭头 材质 * @property [color = Cesium.Color.WHITE] - 颜色 */ const PolylineArrow: string; /** * 线:高亮线 材质 * @property [color = Cesium.Color.WHITE] - A Property specifying the {@link Color} of the line. * @property [glowPower = 0.25] - 高亮强度,占总线宽的百分比表示。 * @property [taperPower = 1.0] - A numeric Property specifying the strength of the tapering effect, as a percentage of the total line length. If 1.0 or higher, no taper effect is used. */ const PolylineGlow: string; /** * 通用:图片 材质2 (没有加载完成前的白色闪烁,但也不支持纯白色的图片) * @property image - 图片对象或图片地址 * @property [opacity = 1.0] - 透明度 */ const Image2: string; /** * 线状: 流动图片效果 材质(适用于线和墙) * @property image - 背景图片URL * @property [color = new Cesium.Color(1, 0, 0, 1.0)] - 背景图片颜色 * @property [repeat = new Cesium.Cartesian2(1.0, 1.0)] - 横纵方向重复次数 * @property [axisY = false] - 是否Y轴朝上 * @property [speed = 10] - 速度,值越大越快 * @property [hasImage2 = false] - 是否有2张图片的混合模式 * @property [image2] - 第2张背景图片URL地址 * @property [color2 = new Cesium.Color(1, 1, 1)] - 第2张背景图片颜色 */ const LineFlow: string; /** * 线状: 流动颜色效果 材质 * @property [color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @property [speed = 2] - 速度,值越大越快 * @property [percent = 0.04] - 比例 * @property [alpha = 0.1] - 透明程度 0.0-1.0 */ const LineFlowColor: string; /** * 线状: OD线效果 材质 * @property [color = new Cesium.Color(1, 0, 0, 1.0)] - 运动对象的颜色 * @property [options.bgColor] - 线的背景颜色 * @property [startTime = 0] - 开始的时间 * @property [speed = 20] - 速度,值越大越快 * @property [options.bidirectional = 0] - 运行形式:0 正向运动 1 反向运动 2 双向运动 */ const ODLine: string; /** * 线状: 闪烁线 材质 * @property [color = new Cesium.Color(1.0, 0.0, 0.0, 0.7)] - 线颜色 * @property [speed = 10] - 速度,值越大越快 */ const LineFlicker: string; /** * 线状: 轨迹线 材质 * @property [color = new Cesium.Color(1.0, 0.0, 0.0, 0.7)] - 线颜色 * @property [speed = 5.0] - 速度,值越大越快 */ const LineTrail: string; /** * 墙体: 走马灯围墙 材质 * @property [image] - 背景图片URL * @property [color = new Cesium.Color(1.0, 0.0, 0.0, 0.7)] - 颜色 * @property [count = 1] - 数量 * @property [speed = 5.0] - 速度,值越大越快 */ const WallScroll: string; /** * 面状: 用于面状对象的 扫描线放大效果 材质 * @property [color = new Cesium.Color(1.0, 1.0, 0.0, 1.0)] - 扫描线颜色 * @property [speed = 10] - 扫描速度,值越大越快 */ const ScanLine: string; /** * 圆形: 扫描效果 材质 * @property image - 扫描图片URL地址 * @property [color = new Cesium.Color(1.0, 0.0, 0.0, 1.0)] - 颜色 */ const CircleScan: string; /** * 圆形: 扩散波纹效果 材质 * @property [color = new Cesium.Color(1.0, 1.0, 0.0, 1.0)] - 颜色 * @property [speed = 10] - 速度,值越大越快 * @property [count = 1] - 圆圈个数 * @property [gradient = 0.1] - 透明度的幂方(0-1),0表示无虚化效果,1表示虚化成均匀渐变 */ const CircleWave: string; /** * 圆形: 雷达线(圆+旋转半径线) 材质 * @property [color = new Cesium.Color(0.0, 1.0, 1.0, 0.7)] - 颜色 * @property [speed = 5.0] - 速度,值越大越快 */ const RadarLine: string; /** * 圆形: 波纹雷达扫描效果 材质 * @property [color = new Cesium.Color(0.0, 1.0, 1.0, 0.7)] - 颜色 * @property [speed = 5.0] - 速度,值越大越快 */ const RadarWave: string; /** * 面状: 文字贴图 材质 * @property text - 文本内容 * @property [font_family = "楷体"] - 字体 ,可选项:微软雅黑,宋体,楷体,隶书,黑体, * @property [font_size = 30] - 字体大小 * @property [font_weight = "normal"] - 是否加粗 ,可选项:bold (解释:是),normal (解释:否), * @property [font_style = "normal"] - 是否斜体 ,可选项:italic (解释:是),normal (解释:否), * @property [font = '30px normal normal 楷体'] - 上叙4个属性的一次性指定CSS字体的属性。 * @property [color = new Cesium.Color(1.0, 1.0, 0.0, 1.0)] - 填充颜色。 * @property [stroke = true] - 是否描边文本。 * @property [strokeColor = new Cesium.Color(1.0, 1.0, 1.0, 0.8)] - 描边的颜色。 * @property [strokeWidth = 2] - 描边的宽度。 * @property [backgroundColor = new Cesium.Color(1.0, 1.0, 1.0, 0.1)] - 画布的背景色。 * @property [padding = 10] - 要在文本周围添加的填充的像素大小。 * @property [textBaseline = 'top'] - 文本的基线。 */ const Text: string; /** * 矩形面: 轮播图 材质 * @property image - 图片URL * @property [color = Cesium.Color.WHITE] - 颜色和透明度 * @property [speed = 10] - 速度,值越大越快 * @property [pure = false] - 是否纯色 */ const RectSlide: string; /** * 面状: 渐变面 材质 * @property [color = new Cesium.Color(1.0, 1.0, 0.0, 0.5)] - 颜色 * @property [alphaPower = 1.5] - 透明度系数 * @property [diffusePower = 1.6] - 漫射系数 */ const PolyGradient: string; /** * 面状: 柏油路面效果 材质 * @property [asphaltColor = new Cesium.Color(0.15, 0.15, 0.15, 1.0)] - 沥青的颜色 * @property [bumpSize = 0.02] - 块大小 * @property [roughness = 0.2] - 粗糙度 */ const PolyAsphalt: string; /** * 面状:混合效果 材质 * @property [lightColor = new Cesium.Color(1.0, 1.0, 1.0, 0.5)] - 浅色的颜色 * @property [darkColor = new Cesium.Color(0.0, 0.0, 1.0, 0.5)] - 深色的颜色 * @property [frequency = 10.0] - 频率 */ const PolyBlob: string; /** * 面状:碎石面效果 材质 * @property [lightColor = new Cesium.Color(0.25, 0.25, 0.25, 0.75)] - 浅色的颜色 * @property [darkColor = new Cesium.Color(0.75, 0.75, 0.75, 0.75)] - 深色的颜色 * @property [frequency = 10.0] - 频率 */ const PolyFacet: string; /** * 面状:草地面效果 材质 * @property [grassColor = new Cesium.Color(0.25, 0.4, 0.1, 1.0)] - 草地的颜色 * @property [dirtColor = new Cesium.Color(0.1, 0.1, 0.1, 1.0)] - 泥土的颜色 * @property [patchiness = 1.5] - 斑块分布 */ const PolyGrass: string; /** * 面状:木材面效果 材质 * @property [lightWoodColor = new Cesium.Color(0.6, 0.3, 0.1, 1.0)] - 浅色的颜色 * @property [darkWoodColor = new Cesium.Color(0.4, 0.2, 0.07, 1.0)] - 深色的颜色 * @property [ringFrequency = 3.0] - 环频率 * @property [noiseScale = new Cesium.Cartesian2(0.7, 0.5)] - 噪波比例 * @property [grainFrequency = 27.0] - 颗粒的频率 */ const PolyWood: string; /** * 球体: 电弧球体效果 材质 * @property [color = new Cesium.Color(0.0, 1.0, 1.0, 0.7)] - 颜色 * @property [speed = 5.0] - 速度,值越大越快 */ const EllipsoidElectric: string; /** * 球体: 波纹球体效果 材质 * @property [color = new Cesium.Color(0.0, 1.0, 1.0, 0.7)] - 颜色 * @property [speed = 5.0] - 速度,值越大越快 */ const EllipsoidWave: string; /** * 圆锥: 条纹波纹扩散效果 * @property [color = new Cesium.Color(2, 1, 0.0, 0.8)] - 颜色 * @property [repeat = 30] - 圈数量 * @property [frameRate = 60] - 每秒刷新次数 */ const CylinderWave: string; } /** * 状态 枚举 */ declare const enum State { /** * 初始化 */ INITIALIZED = "inited", /** * 已添加到地图上 */ ADDED = "added", /** * 已移除地图 */ REMOVED = "removed", /** * 已销毁对象 */ DESTROY = "destroy" } /** * 地形类型 */ declare const enum TerrainType { /** * 无地形 */ NONE = "none", /** * 标准xyz瓦片地形 */ XYZ = "xyz", /** * arcgis地形 */ ARCGIS = "arcgis", /** * ION在线地形(cesium官方服务) */ ION = "ion", /** * GoogleEarth Enterprise 地形服务 */ GEE = "gee", /** * VR 地形 */ VR = "vr" } /** * SDK中涉及到的所有第3放地图服务的Token令牌key, * 【重要提示:为了避免后期失效,请全部重新赋值换成自己的key】 */ declare module "Token" { /** * Cesium官方的Ion服务key, * 官网: {@link https://cesium.com/ion/signin/} */ const enum ion { } /** * mapbox地图key, * 官网:{@link https://account.mapbox.com} */ const enum mapbox { } /** * 微软Bing地图key, * 官网: {@link https://www.bingmapsportal.com/Application} */ const enum bing { } /** * 天地图key数组, * 官网: {@link https://console.tianditu.gov.cn/api/key} */ const enum tiandituArr { } /** * 天地图key, */ const enum tianditu { } /** * 高德key数组, * 官网: {@link https://console.amap.com/dev/key/app} */ const enum gaodeArr { } /** * 高德key, */ const enum gaode { } /** * 百度key数组, * 官网: {@link http://lbsyun.baidu.com/apiconsole/key#/home} */ const enum baiduArr { } /** * 百度key, */ const enum baidu { } } /** * 控件 基类 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.insertIndex = null] - 可以自定义插入到父容器中的index顺序,默认是插入到最后面。 * @param [options.insertBefore = null] - 可以自定义插入到指定兄弟容器的前面,与insertIndex二选一。 */ declare class BaseControl extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; insertIndex?: Int; insertBefore?: HTMLElement; }); /** * 设置DOM容器的显示隐藏 */ show: boolean; /** * 当前控件的DOM对象 */ readonly container: HTMLElement; /** * 父容器DOM对象 */ readonly parentContainer: HTMLElement; /** * 父容器DOM对象的ID */ readonly parentContainerId: string; /** * 添加到地图上,同 map.addControl * @param map - 地图对象 * @returns 当前对象本身,可以链式调用 */ addTo(map: Map): this; /** * 从地图上移除,同map.removeControl * @param destroy - 是否调用destroy释放 * @returns 无 */ remove(destroy: boolean): void; /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; /** * 设置新的css样式信息 * @param style - css样式 * @returns 无 */ setStyle(style: any): void; /** * 设置对象的启用和禁用状态。 */ enabled: boolean; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } /** * 导航球控件 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.rotation = true] - 是否启用调整俯仰角(按中间区域往四周拖拽) * @param [options.className = 'mars3d-compass'] - 样式名称,可以外部自定义样式。 * @param [options.top] - css定位top位置, 如 top: '10px' * @param [options.bottom] - css定位bottom位置,支持配置'toolbar'自动跟随cesium-viewer-toolbar * @param [options.left] - css定位left位置 * @param [options.right] - css定位right位置 * @param [options.outerSvg] - 外部圆环区域的SVG图片 * @param [options.innerSvg] - 中心球区域的SVG图片 * @param [options.rotationArcSvg] - rotation为true时,按中间区域往四周拖拽时,调整俯仰角的对外部圆环的半弧遮盖SVG图片 */ declare class Compass extends BaseControl { constructor(options: { id?: string | number; enabled?: boolean; rotation?: boolean; className?: string; top?: string; bottom?: string; left?: string; right?: string; outerSvg?: string; innerSvg?: string; rotationArcSvg?: string; }); /** * 更新 外部圆环区域的SVG图片 * @param svg - SVG图片 * @returns 无 */ setOuterSvg(svg: string): void; /** * 更新 中心球区域的SVG图片 * @param svg - SVG图片 * @returns 无 */ setInnerSvg(svg: string): void; /** * 更新 按中间区域往四周拖拽时,调整俯仰角的对外部圆环的半弧遮盖SVG图片,rotation为true时有效 * @param svg - SVG图片 * @returns 无 */ setRotationSvg(svg: string): void; /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; } declare namespace DistanceLegend { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * distanceLegend.on(mars3d.EventType.change, function (event) { * console.log('比例尺发生变化', event) * }) * @property change - 比例尺发生变化 */ type EventType = { change: string; }; } /** * 比例尺 控件 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.top] - css定位top位置, 如 top: '10px' * @param [options.bottom] - css定位bottom位置 * @param [options.left] - css定位left位置 * @param [options.right] - css定位right位置 */ declare class DistanceLegend extends BaseControl { constructor(options: { id?: string | number; enabled?: boolean; top?: string; bottom?: string; left?: string; right?: string; }); /** * 当前比例尺值(单位:米) */ readonly distance: number; /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; } declare namespace LocationBar { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.change, function (event) { * console.log('数据变化了', event) * }) * @property change - 数据变化了 */ type EventType = { change: string; }; } /** * 鼠标经纬度等信息状态栏, * 一般在页面下侧区域 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.fps = false] - 是否显示实时FPS帧率 * @param [options.latDecimal = LatLngPoint.FormatLength] - 保留的{lat}和{lng}的小数位 * @param [options.template] - 展示的内容格式化字符串, 为数组时按多语言顺序定义,如[中文、繁体、英文] * 支持以下模版配置: * 【鼠标所在位置】 经度:{lng}, 纬度:{lat}, 海拔:{alt}米, * 【相机的】 方向角度:{heading}, 俯仰角度:{pitch}, 视高:{cameraHeight}米, * 【地图的】 层级:{level}, * @param [options.crs] - 按指定坐标系显示坐标值, 配置后template可以加模板:【鼠标所在位置对应的crs坐标系】 X或经度值:{crsx}, Y或纬度值:{crsy} * @param [options.crsDecimal = 1] - 保留的{crsx}和{crsy}的小数位 * @param [options.cacheTime = 100] - 鼠标移动的缓存时间 * @param [options.style] - 可以CSS样式,如: * @param [options.style.top] - css定位top位置, 如 top: '10px' * @param [options.style.bottom] - css定位bottom位置 * @param [options.style.left] - css定位left位置 * @param [options.style.right] - css定位right位置 */ declare class LocationBar extends BaseControl { constructor(options: { id?: string | number; enabled?: boolean; fps?: boolean; latDecimal?: number; template?: Sring | Sring[]; crs?: string | CRS; crsDecimal?: number; cacheTime?: number; style?: { top?: string; bottom?: string; left?: string; right?: string; }; }); /** * 显示的数据 */ readonly locationData: any; } /** * 卷帘对比 控件 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.leftLayer] - 左侧区域瓦片图层 * @param [options.leftLayer] - 右侧区域瓦片图层 */ declare class MapSplit extends BaseControl { constructor(options: { id?: string | number; enabled?: boolean; leftLayer?: BaseTileLayer; leftLayer?: BaseTileLayer; }); /** * 左侧区域瓦片图层 */ leftLayer: BaseTileLayer; /** * 右侧区域瓦片图层 */ rightLayer: BaseTileLayer; /** * 对瓦片图层设置卷帘方向 * @param layer - 图层 * @param splitDirection - 图层显示的方向 * @returns 无 */ setLayerSplitDirection(layer: BaseTileLayer | GroupLayer, splitDirection: Cesium.ImagerySplitDirection): void; /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; } /** * 鼠标旋转、放大时的按键效果美化图标 */ declare class MouseDownView extends BaseControl { } /** * 鹰眼地图 控件 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param options.basemap - 瓦片底图图层配置 * @param [options.layers] - 可以叠加显示的图层配置 * @param [options.scene] - 鹰眼地图场景参数 * @param [options.rectangle] - 矩形区域样式信息,不配置时不显示矩形。 * @param [options.style] - 可以CSS样式,如: * @param [options.style.top] - css定位top位置, 如 top: '10px' * @param [options.style.bottom] - css定位bottom位置 * @param [options.style.left] - css定位left位置 * @param [options.style.right] - css定位right位置 */ declare class OverviewMap extends BaseControl { constructor(options: { id?: string | number; enabled?: boolean; basemap: Map.basemapOptions; layers?: Map.layerOptions[]; scene?: Map.sceneOptions; rectangle?: RectangleEntity.StyleOptions; style?: { top?: string; bottom?: string; left?: string; right?: string; }; }); /** * 鹰眼小地图对象 */ smallMap: Map; /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; } declare namespace ToolButton { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * control.on(mars3d.EventType.click, function (event) { * console.log('单击了按钮', event) * }) * @property click - 单击了按钮 */ type EventType = { click: string; }; } /** * 工具栏 单个按钮控件 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.title = ''] - 按钮标题 * @param [options.icon = 'fa fa-tasks'] - 按钮字体图标class名 * @param [options.click] - 按钮单击后的回调方法 */ declare class ToolButton extends BaseControl { constructor(options: { id?: string | number; enabled?: boolean; title?: string; icon?: string; click?: (...params: any[]) => any; }); /** * 父容器DOM对象 */ readonly parentContainer: HTMLElement; } /** * 放大缩小按钮控件 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.zoomOutClass = 'fa fa-minus'] - 缩小按钮字体图标class名 * @param [options.zoomInClass = 'fa fa-plus'] - 放大按钮字体图标class名 */ declare class Zoom extends BaseControl { constructor(options: { id?: string | number; enabled?: boolean; zoomOutClass?: string; zoomInClass?: string; }); /** * 父容器DOM对象 */ readonly parentContainer: HTMLElement; } /** * 基础类,SDK中几乎所有类的基类,都是继承该基类的。 * @param options - 参数名称 */ declare class BaseClass { constructor(options: any); /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; /** * 绑定指定类型事件监听器 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ on(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): this; /** * 解除绑定指定类型事件监听器 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ off(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): this; /** * 触发指定类型的事件。 * @param type - 事件类型 * @param data - 传输的数据或对象,可在事件回调方法中event对象中获取进行使用 * @param [propagate = null] - 将事件传播给父类 (用addEventParent设置) * @returns 当前对象本身,可以链式调用 */ fire(type: EventType, data: any, propagate?: BaseClass): this; /** * 是否有绑定指定的事件 * @param type - 事件类型 * @param [propagate = null] - 是否判断指定的父类 (用addEventParent设置的) * @returns 是否存在 */ listens(type: EventType, propagate?: BaseClass): boolean; /** * 绑定一次性执行的指定类型事件监听器 * 与on类似,监听器只会被触发一次,然后被删除。 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ once(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): this; /** * 添加抛出事件到父类,它将接收传播的事件 * @param obj - 父类对象 * @returns 当前对象本身,可以链式调用 */ addEventParent(obj: any): this; /** * 移除抛出事件到父类 * @param obj - 父类对象 * @returns 当前对象本身,可以链式调用 */ removeEventParent(obj: any): this; /** * 是否绑定了抛出事件到指定父类 * @param obj - 父类对象 * @returns 当前对象本身,可以链式调用 */ hasEventParent(obj: any): this; } declare namespace BaseThing { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.add, function (event) { * console.log('添加了对象', event) * }) * @property add - 添加对象 * @property remove - 移除对象 */ type EventType = { add: string; remove: string; }; } /** * Thing对象(如特效、分析、管理类等) 的基类 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.stopPropagation = false] - 当前类中事件是否停止冒泡, false时:事件冒泡到map中。 */ declare class BaseThing extends BaseClass { constructor(options: { id?: string | number; enabled?: boolean; stopPropagation?: boolean; }); /** * 内置唯一标识ID */ readonly uuid: string; /** * 当前对象的状态 */ readonly state: State; /** * 是否已添加到地图 */ readonly isAdded: boolean; /** * 对象的id标识 */ id: string | number; /** * 设置对象的启用和禁用状态。 */ enabled: boolean; /** * 添加到地图上,同 map.addThing * @param map - 地图对象 * @returns 当前对象本身,可以链式调用 */ addTo(map: Map): this; /** * 从地图上移除,同map.removeThing * @param destroy - 是否调用destroy释放 * @returns 无 */ remove(destroy: boolean): void; /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } /** * 近地天空盒, 在场景周围绘制星星等太空背景。 * 天空盒子是用真正的赤道平均春分点(TEME)轴定义的。仅在3D中支持。当转换为2D或哥伦布视图时,天空盒会淡出。 * 天空盒子的大小不能超过{@link Cesium.Scene#maximumCubeMapSize}。 * @example * scene.skyBox = new mars3d.GroundSkyBox({ * sources : { * positiveX : 'skybox_px.png', * negativeX : 'skybox_nx.png', * positiveY : 'skybox_py.png', * negativeY : 'skybox_ny.png', * positiveZ : 'skybox_pz.png', * negativeZ : 'skybox_nz.png' * } * }); * @param options - 对象,具有以下属性: * @param [options.sources] - 天空盒的6个立方体映射面的图片url * @param [options.sources.positiveX] - 映射面的图片url * @param [options.sources.negativeX] - 映射面的图片url * @param [options.sources.positiveY] - 映射面的图片url * @param [options.sources.negativeY] - 映射面的图片url * @param [options.sources.positiveZ] - 映射面的图片url * @param [options.sources.negativeZ] - 映射面的图片url * @param [options.show = true] - 是否显示 */ declare class GroundSkyBox extends Cesium.SkyBox { constructor(options: { sources?: { positiveX?: string; negativeX?: string; positiveY?: string; negativeY?: string; positiveZ?: string; negativeZ?: string; }; show?: boolean; }); } /** * 坐标数组处理类 */ declare class LatLngArray { /** * 根据传入的各种对象数据数组,转换返回Cartesian3数组 * @param value - 坐标位置数组 * @returns 转换返回的Cartesian3数组 */ static toCartesians(value: String[] | any[][] | LatLngPoint[]): Cesium.Cartesian3[]; /** * 根据传入的各种对象数据数组,转换返回LatLngPoint数组 * @param value - 坐标位置数组 * @returns 转换返回的LatLngPoint数组 */ static toPoints(value: String[] | any[][] | Cesium.Cartesian3[]): LatLngPoint[]; /** * 根据传入的各种对象数据数组,转换返回经纬度坐标数组 * @param value - 坐标位置数组 * @param noAlt - 是否包含高度值 * @returns 经纬度坐标数组,示例:[ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] */ static toArray(value: String[] | any[][] | Cesium.Cartesian3[], noAlt: boolean): any[][]; } /** * 坐标点类(含经度、纬度、高度) * @param lng - 经度值, -180 至 180 * @param lat - 纬度值, -90 至 90 * @param alt - 高度(单位:米) */ declare class LatLngPoint { constructor(lng: number, lat: number, alt: number); /** * 经度值, -180 至 180 */ lng: number; /** * 纬度值, -180 至 180 */ lat: number; /** * 高度(单位:米) */ alt: number; /** * 复制一份对象 * @returns 无 */ clone(): void; /** * 格式化对象内的经纬度的小数位为6位,高度小数位为1位。 * @returns 当前对象本身,可以链式调用 */ format(): this; /** * 转换为数组对象 * @param noAlt - 是否包含高度值 * @returns 数组对象,示例[113.123456,31.123456,30.1] */ toArray(noAlt: boolean): any[]; /** * 转换为字符串对象 * @returns 符串,示例 "113.123456,31.123456,30.1" */ toString(): string; /** * 转换为笛卡尔坐标 * @param clone - 是否复制 * @returns 笛卡尔坐标 */ toCartesian(clone: boolean): Cesium.Cartesian3; /** * 转换为 地理坐标(弧度制) * @returns 地理坐标(弧度制) */ toCartographic(): Cesium.Cartographic; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: LatLngPoint): boolean; /** * 根据传入的各种对象数据,转换返回LatLngPoint对象 * @param position - 坐标位置 * @param [time = Cesium.JulianDate.now()] - Cesium坐标时,getValue传入的时间值 * @returns 转换返回的LatLngPoint对象 */ static parse(position: string | any[] | any | Cesium.Cartesian3 | any, time?: Cesium.JulianDate): LatLngPoint; /** * 根据数组数据,转换返回LatLngPoint对象 * 示例:[113.123456,31.123456,30.1] * @param arr - 坐标位置 * @returns 转换返回的LatLngPoint对象 */ static fromArray(arr: any[]): LatLngPoint; /** * 根据传入字符串,转换返回LatLngPoint对象 * 示例:"113.123456,31.123456,30.1" * @param str - 坐标位置字符串,逗号分割。 * @returns 转换返回的LatLngPoint对象 */ static fromString(str: string): LatLngPoint; /** * 根据传入的笛卡尔坐标,转换返回LatLngPoint对象 * @param cartesian - 坐标位置 * @param [time = Cesium.JulianDate.now()] - Cesium坐标时,getValue传入的时间值 * @returns 转换返回的LatLngPoint对象 */ static fromCartesian(cartesian: Cesium.Cartesian3 | any, time?: Cesium.JulianDate): LatLngPoint; /** * 根据传入的地理坐标(弧度制),转换返回LatLngPoint对象 * @param cartographic - 地理坐标(弧度制) * @returns 转换返回的LatLngPoint对象 */ static fromCartographic(cartographic: Cesium.Cartographic): LatLngPoint; /** * 经度纬度的格式化时的长度,默认为6 */ static FormatLength: number; /** * 高度的格式化时的长度,默认为1 */ static FormatAltLength: number; } /** * 特效 基类 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 */ declare class BaseEffect extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; }); /** * 特效对象 */ readonly target: Cesium.PostProcessStage; /** * 特效对象的uniforms * 一个对象,它的属性被用来设置片段着色器shader。 * <p> * 对象属性值可以是常量或函数。这个函数将在每一帧后处理阶段执行之前被调用。 * </p> * <p> * 常量值也可以是图像的URI、数据URI,或者可以用作纹理的HTML元素,如HTMLImageElement或HTMLCanvasElement。 * </p> * <p> * 如果这个后处理阶段是{@link Cesium.PostProcessStageComposite}中不串行执行的部分,那么常量值也可以是复合程序中另一个阶段的名称。这将设置统一的输出纹理与该名称的舞台。 * </p> */ readonly uniforms: any; } /** * 黑白效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.gradations = 4.0] - 渐变 */ declare class BlackAndWhiteEffect extends BaseEffect { constructor(options: { enabled?: boolean; gradations?: number; }); /** * 渐变 */ gradations: number; } /** * 泛光效果, 使明亮的区域更亮,黑暗的区域更暗。 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.contrast = 128] - 对比度,取值范围[-255.0,255.0] * @param [options.brightness = -0.3] - 亮度, 将输入纹理的RGB值转换为色相、饱和度和亮度(HSB),然后将该值添加到亮度中。 * @param [options.delta = 1.0] - 增量 * @param [options.sigma = 3.78] - delta和sigma用于计算高斯滤波器的权值。方程是 <code>exp((-0.5 * delta * delta) / (sigma * sigma))</code>。 * @param [options.stepSize = 5.0] - 步长,是下一个texel的距离 */ declare class BloomEffect extends BaseEffect { constructor(options: { enabled?: boolean; contrast?: number; brightness?: number; delta?: number; sigma?: number; stepSize?: number; }); /** * 对比度,取值范围[-255.0,255.0] */ contrast: number; /** * 亮度, 将输入纹理的RGB值转换为色相、饱和度和亮度(HSB),然后将该值添加到亮度中 */ brightness: number; /** * 增量.方程是 <code>exp((-0.5 * delta * delta) / (sigma * sigma))</code>。 */ delta: number; /** * delta和sigma用于计算高斯滤波器的权值。方程是 <code>exp((-0.5 * delta * delta) / (sigma * sigma))</code>。 */ sigma: number; /** * 步长,是下一个texel的距离 */ stepSize: number; } /** * 亮度 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.brightness = 2.0] - 亮度值 */ declare class BrightnessEffect extends BaseEffect { constructor(options: { enabled?: boolean; brightness?: number; }); /** * 亮度, 将输入纹理的RGB值转换为色相、饱和度和亮度(HSB),然后将该值添加到亮度中 */ brightness: number; } /** * 云团 效果 * @param options - 参数对象,包括以下: */ declare class CloudVolumeEffect extends BaseEffect { constructor(options: any); /** * 最大云彩距离 */ maxDis: number; /** * 第一个值:最低高度(相机低于这个高度就不显示云彩),第二个是最大高度 */ cloudLimit: number; /** * 最大透明度 */ maxAlpha: number; /** * 密度系数 */ density: number; /** * 光追步长 */ setpDis: number; } /** * 景深 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.focalDistance = 87] - 焦距,是以米为单位的距离来设定相机的焦距。 * @param [options.delta = 1.0] - 增量 * @param [options.sigma = 3.78] - delta和sigma用于计算高斯滤波器的权值。方程是 <code>exp((-0.5 * delta * delta) / (sigma * sigma))</code>。 * @param [options.stepSize = 5.0] - 步长,是下一个texel的距离 */ declare class DepthOfFieldEffect extends BaseEffect { constructor(options: { enabled?: boolean; focalDistance?: number; delta?: number; sigma?: number; stepSize?: number; }); /** * 焦距,是以米为单位的距离来设定相机的焦距。 */ focalDistance: number; /** * 增量.方程是 <code>exp((-0.5 * delta * delta) / (sigma * sigma))</code>。 */ delta: number; /** * delta和sigma用于计算高斯滤波器的权值。方程是 <code>exp((-0.5 * delta * delta) / (sigma * sigma))</code>。 */ sigma: number; /** * 步长,是下一个texel的距离 */ stepSize: number; } /** * 雾场景效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.fogByDistance = new Cesium.Cartesian4(10, 0.0, 1000, 0.9)] - 雾强度 * @param [options.color = Cesium.Color.WHITE] - 雾颜色 * @param [options.maxHeight = 9000] - 最高限定高度,超出该高度不显示雾场景效果 */ declare class FogEffect extends BaseEffect { constructor(options: { enabled?: boolean; fogByDistance?: Cesium.Cartesian4; color?: Cesium.Color; maxHeight?: number; }); /** * 雾强度 */ fogByDistance: Cesium.Cartesian4; /** * 雾颜色 */ color: Cesium.Color; /** * 最高限定高度,超出该高度不显示雾场景效果 */ maxHeight: number; } /** * 倒影效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 */ declare class InvertedEffect extends BaseEffect { constructor(options: { enabled?: boolean; }); } /** * 马赛克效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 */ declare class MosaicEffect extends BaseEffect { constructor(options: { enabled?: boolean; }); } /** * 夜视效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 */ declare class NightVisionEffect extends BaseEffect { constructor(options: { enabled?: boolean; }); } declare namespace OutlineEffect { /** * 选中对象的 轮廓线描边效果 支持的参数信息 * @property [width = 6] - 线宽,单位:像素px * @property [color = Cesium.Color.WHITE] - 轮廓线 颜色 * @property [colorHidden = color] - 被遮挡的轮廓线 颜色 * @property [showPlane = false] - 是否显示边缘同一个平面(按thresholdAngle属性定义) * @property [planeAngle = 10] - 如果两个三角面的法线间夹角小于该值 则标记为同一个平面。该值的单位:角度 * @property [glow = false] - 是否显示发光 * @property [glowPower = 1] - 发光强度 * @property [glowStrength = 3] - 发光的增量 * @property [onlySelected = false] - 只显示选中构件 */ type Options = { width?: number; color?: string | Cesium.Color; colorHidden?: string | Cesium.Color; showPlane?: boolean; planeAngle?: number; glow?: boolean; glowPower?: number; glowStrength?: number; onlySelected?: boolean; }; } /** * 选中对象的 轮廓线描边效果。 * @param options - 参数对象 * @param [options.enabled = true] - 对象的启用状态 */ declare class OutlineEffect extends BaseEffect { constructor(options: { enabled?: boolean; }); /** * 选中对象 */ selected: any | object[] | undefined; /** * 轮廓线 颜色 */ color: string | Cesium.Color; /** * 被遮挡的轮廓线 颜色 */ colorHidden: string | Cesium.Color; /** * 如果两个三角面的法线间夹角小于该值 则标记为同一个平面。该值的单位:角度 */ planeAngle: number; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; /** * 轮廓线 宽度,单位:像素px */ width: number; /** * 是否显示边缘同一个平面(按thresholdAngle属性定义) */ showPlane: boolean; /** * 是否显示发光 */ glow: boolean; /** * 发光强度 */ glowPower: number; /** * 发光的增量 */ glowStrength: number; /** * 只显示选中构件 */ onlySelected: boolean; } /** * 下雨效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.speed = 10] - 速度 * @param [options.size = 20] - 雨粒子大小 * @param [options.direction = -30] - 雨的方向(度),0度垂直向下 */ declare class RainEffect extends BaseEffect { constructor(options: { enabled?: boolean; speed?: number; size?: number; direction?: number; }); /** * 速度 */ speed: number; /** * 雨粒子大小 */ size: number; /** * 雨的方向(度),0度垂直向下 */ direction: number; } /** * 地面积雪 效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.alpha = 1.0] - 覆盖强度 0-1 * @param [options.maxHeight = 9000] - 最高限定高度,超出该高度不显示积雪效果 */ declare class SnowCoverEffect extends BaseEffect { constructor(options: { enabled?: boolean; alpha?: number; maxHeight?: number; }); /** * 最高限定高度,超出该高度不显示积雪效果 */ maxHeight: number; /** * 覆盖强度 0-1 */ alpha: number; } /** * 下雪效果 * @param options - 参数对象,包括以下: * @param [options.enabled = true] - 对象的启用状态 * @param [options.speed = 10] - 速度 */ declare class SnowEffect extends BaseEffect { constructor(options: { enabled?: boolean; speed?: number; }); /** * 速度 */ speed: number; } declare namespace BaseGraphic { /** * 矢量数据 通用构造参数 * @property [id = uuid()] - 矢量数据id标识 * @property [name = ''] - 矢量数据名称 * @property [show = true] - 矢量数据是否显示 * @property position - 【点状】矢量数据时的坐标位置,具体看子类实现 * @property positions - 【线面状(多点)】矢量数据时的坐标位置,具体看子类实现 * @property style - 矢量数据的 样式信息,具体见各类数据的说明 * @property [attr] - 矢量数据的 属性信息,可以任意附加属性。 * @property [geojson] - 允许直接传入geojson格式规范数据,内部自动解析。【部分矢量对象】 * @property [popup] - 当矢量数据支持popup弹窗时,绑定的值 * @property [popupOptions] - popup弹窗时的配置参数 * @property [tooltip] - 当矢量数据支持tooltip弹窗时,绑定的值 * @property [tooltipOptions] - tooltip弹窗时的配置参数 * @property [contextmenuItems] - 当矢量数据支持右键菜单时,绑定的值 * @property [stopPropagation = false] - 当前类中事件是否停止冒泡, false时:事件冒泡到layer种。 */ type ConstructorOptions = { id?: string | number; name?: string; show?: boolean; position: LatLngPoint | Cesium.Cartesian3; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: any; attr?: any; geojson?: any; popup?: any; popupOptions?: Popup.StyleOptions; tooltip?: any; tooltipOptions?: Tooltip.StyleOptions; contextmenuItems?: any; stopPropagation?: boolean; }; /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.click, function (event) { * console.log('单击了矢量数据对象', event) * }) * @property add - 添加对象 * @property remove - 移除对象 * @property show - 显示了对象 * @property hide - 隐藏了对象 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 */ type EventType = { add: string; remove: string; show: string; hide: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; }; } /** * 矢量数据 基础类 * @param options - 描述初始化构造参数选项的对象 */ declare class BaseGraphic extends BaseClass { constructor(options: BaseGraphic.ConstructorOptions); /** * 矢量数据类型 */ readonly type: string; /** * 内置唯一标识ID */ readonly uuid: string; /** * 对象的id标识 */ id: string | number; /** * 当前对象的状态 */ readonly state: State; /** * 是否已添加到图层 */ readonly isAdded: boolean; /** * 是否已经销毁了 */ readonly isDestroy: boolean; /** * 显示隐藏状态 */ show: boolean; /** * 名称 */ name: string; /** * 属性信息 */ attr: any; /** * 样式信息 */ style: any; /** * 中心点坐标(笛卡尔坐标) */ readonly center: Cesium.Cartesian3; /** * 中心点坐标 */ readonly centerPoint: LatLngPoint; /** * 添加到图层上,同 layer.addGraphic * @param layer - 图层对象 * @returns 当前对象本身,可以链式调用 */ addTo(layer: GraphicLayer): this; /** * 从图层上移除,同 layer.removeGraphic * @param hasDestory - 是否调用destroy释放 * @returns 无 */ remove(hasDestory: boolean): void; /** * 绑定Cesium内部对象进行相关管理。 * @param item - Cesium对象 * @returns 当前对象本身,可以链式调用 */ bindPickId(item: any): this; /** * 对象添加到图层前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到图层上的创建钩子方法, * 每次add时都会调用 * @param style - 完整样式信息 * @returns 无 */ _addedHook(style: any): void; /** * 对象从图层上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; /** * 设置 样式信息 的钩子方法 * @param newStyle - 本次更新的部分样式信息,内部会合并属性 * @returns 当前对象本身,可以链式调用 */ setStyle(newStyle: any): this; /** * 将矢量数据导出为GeoJSON格式规范对象。 * @param [options] - 参数对象: * @param [options.noAlt] - 不导出高度值 * @returns GeoJSON格式规范对象 */ toGeoJSON(options?: { noAlt?: boolean; }): any; /** * 将矢量数据的坐标、样式及属性等信息导出为对象,可以用于存储。 * @returns 导出的坐标、样式及属性等信息 */ toJSON(): any; /** * 获取矢量数据位置的 矩形边界值 * @param [isFormat = true] - 是否格式化,格式化时示例: { xmin: 73.16895, xmax: 134.86816, ymin: 12.2023, ymax: 54.11485 } * @returns isFormat:true时,返回格式化对象,isFormat:false时返回Cesium.Rectangle对象 */ getExtent(isFormat?: boolean): Cesium.Rectangle | any; /** * 飞行定位至 数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.minHeight] - 定位时相机的最小高度值,用于控制避免异常数据 * @param [options.maxHeight] - 定位时相机的最大高度值,用于控制避免异常数据 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; minHeight?: number; maxHeight?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; /** * 绑定鼠标移入或单击后的 对象高亮 * @param [options] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @param [options.type] - 事件类型,默认为鼠标移入高亮,也可以指定'click'单击高亮. * @returns 无 */ bindHighlight(options?: { type?: string; }): void; /** * 解绑鼠标移入或单击后的高亮处理 * @returns 无 */ unbindHighlight(): void; /** * 是否存在Popup绑定 * @returns 是否存在Popup绑定 */ hasPopup(): boolean; /** * 绑定鼠标单击对象后的弹窗。 * @param content - 弹窗内容html字符串,或者回调方法。 * @param options - 控制参数 * @returns 当前对象本身,可以链式调用 */ bindPopup(content: string | ((...params: any[]) => any), options: Popup.StyleOptions): this; /** * 解除绑定的鼠标单击对象后的弹窗。 * @param [stopPropagation = false] - 单击事件中是否继续冒泡查找 * @returns 当前对象本身,可以链式调用 */ unbindPopup(stopPropagation?: boolean): this; /** * 打开绑定的弹窗 * @param [position = this.center] - 矢量对象 或 显示的位置 * @param [event] - 用于抛出事件时的相关额外属性 * @returns 当前对象本身,可以链式调用 */ openPopup(position?: LatLngPoint | Cesium.Cartesian3, event?: any): this; /** * 关闭弹窗 * @returns 当前对象本身,可以链式调用 */ closePopup(): this; /** * 是否绑定了tooltip * @returns 是否绑定 */ hasTooltip(): boolean; /** * 绑定鼠标移入的弹窗 * @param content - 弹窗内容html字符串,或者回调方法。 * @param options - 控制参数 * @returns 当前对象本身,可以链式调用 */ bindTooltip(content: string | ((...params: any[]) => any), options: Tooltip.StyleOptions): this; /** * 解除绑定的鼠标移入对象后的弹窗。 * @param [stopPropagation = false] - 单击事件中是否继续冒泡查找 * @returns 当前对象本身,可以链式调用 */ unbindTooltip(stopPropagation?: boolean): this; /** * 打开绑定的tooltip弹窗 * @param [position = this.center] - 显示的位置,默认为矢量对象所在点或中心点位置 * @param [event] - 用于抛出事件时的相关额外属性 * @returns 当前对象本身,可以链式调用 */ openTooltip(position?: LatLngPoint | Cesium.Cartesian3, event?: any): this; /** * 关闭弹窗 * @returns 当前对象本身,可以链式调用 */ closeTooltip(): this; /** * 是否有绑定的右键菜单 * @returns 当前对象本身,可以链式调用 */ hasContextMenu(): this; /** * 获取绑定的右键菜单数组 * @returns 右键菜单数组 */ getContextMenu(): object[]; /** * 绑定右键菜单 * @example * graphic.bindContextMenu([ * { * text: '删除对象', * iconCls: 'fa fa-trash-o', * callback: function (e) { * let graphic = e.graphic * if (graphic) { * graphic.remove() * } * }, * }, * ]) * @param content - 右键菜单配置数组,数组中每一项包括: * @param [content.text] - 菜单文字 * @param [content.iconCls] - 小图标css * @param [content.show] - 菜单项是否显示的回调方法 * @param [content.callback] - 菜单项单击后的回调方法 * @param [content.children] - 当有二级子菜单时,配置数组。 * @param [options = {}] - 控制参数 * @param [options.offsetX] - 用于非规则对象时,横向偏移的px像素值 * @param [options.offsetY] - 用于非规则对象时,垂直方向偏移的px像素值 * @returns 当前对象本身,可以链式调用 */ bindContextMenu(content: { text?: string; iconCls?: string; show?: ((...params: any[]) => any) | boolean; callback?: (...params: any[]) => any; children?: object[]; }[], options?: { offsetX?: number; offsetY?: number; }): this; /** * 解除绑定的右键菜单 * @param [stopPropagation = false] - 单击事件中是否继续冒泡查找 * @returns 当前对象本身,可以链式调用 */ unbindContextMenu(stopPropagation?: boolean): this; /** * 打开右键菜单 * @param [position = this.center] - 矢量对象 或 显示的位置 * @returns 当前对象本身,可以链式调用 */ openContextMenu(position?: Cesium.Cartesian3): this; /** * 关闭右键菜单 * @returns 当前对象本身,可以链式调用 */ closeContextMenu(): this; /** * 显示小提示窗,一般用于鼠标操作的提示。 * @param position - 显示的屏幕坐标位置 或 笛卡尔坐标位置 * @param message - 显示的内容 * @returns 当前对象本身,可以链式调用 */ openSmallTooltip(position: Cesium.Cartesian2 | Cesium.Cartesian3, message: any): this; /** * 关闭小提示窗 * @returns 当前对象本身,可以链式调用 */ closeSmallTooltip(): this; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } /** * 大数据合并渲染Primitive对象基类 */ declare class BaseCombine extends BasePrimitive { /** * 数据集合数组 */ instances: object[]; /** * 根据 pickId 获取对应绑定的数据据对象 * @param pickId - 单个对象的pickid * @returns 对应绑定的数据对象 */ getPickedObject(pickId: string): any; /** * 更新颜色 * @param style - 样式信息 * @param [style.color = "#3388ff"] - 颜色 * @param [style.opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @param [index] - 更新的instances对象index值,为空时更新所有对象。 * @returns 空 */ setColorStyle(style: { color?: string | Cesium.Color; opacity?: number; }, index?: number | undefined): void; } declare namespace FlatBillboard { /** * 平放的图标 单个数据对象 * @property image - 图标URL * @property position - 位置坐标 * @property [angle = 0] - 图标的角度(角度值,0-360) */ type DataOptions = { image: string; position: Cesium.Cartesian3; angle?: number; }; } /** * 平放的图标 数据集合 (多个图标一起合并渲染) * @param options - 参数对象,包括以下: * @param options.instances - 数据集合数组 * @param options.style - 样式信息 * @param [options.style.width = 50] - 图标宽度 * @param [options.style.height = width] - 图标高度 * @param [options.style.distanceDisplayCondition = new Cesium.DistanceDisplayCondition(0, 5000000)] - 指定数据将显示在与摄像机的多大距离 * @param [options.scale3d = 0.8] - 二维和三维模式切换后图标的缩放比例。因为二三维模式使用不同渲染方式,可能存在大小偏差,可以该参数调优。 */ declare class FlatBillboard extends BaseCombine { constructor(options: { instances: FlatBillboard.DataOptions[]; style: { width?: number; height?: number; distanceDisplayCondition?: Cesium.DistanceDisplayCondition; }; scale3d?: number; }); /** * 数据集合数组 */ instances: FlatBillboard.DataOptions[]; /** * 指定数据将显示在与摄像机的多大距离 */ distanceDisplayCondition: Cesium.DistanceDisplayCondition; /** * 清除数据 * @returns 无 */ clear(): void; } declare namespace ModelCombine { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.load, function (event) { * console.log('模型加载完成', event) * }) * @property 通用 - 支持的父类的事件类型 * @property load - 完成加载,执行所有内部处理后 */ type EventType = { 通用: BasePrimitive.EventType; load: string; }; } /** * 大数据 gltf小模型集合 (合并渲染) Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.url] - glTF模型的URI的字符串或资源属性。 * @param [options.instances] - 集合信息数组,单个对象包括: * @param options.instances.position - 坐标位置 * @param [options.instances.style] - 样式信息(目前仅支持方向和比例参数) * @param [options.instances.attr] - 矢量数据的 属性信息,可以任意附加属性。 * @param [options.batchTable] - 实例化的3D贴图的批处理表。 * @param [options.requestType] - 请求类型,用于确定请求的优先级 * @param [options.gltf] - 一个glTF JSON对象,或者一个二进制的glTF缓冲区。 * @param [options.basePath = ''] - glTF JSON中路径相对的基本路径。 * @param [options.dynamic = false] - 提示实例模型矩阵是否会频繁更新。 * @param [options.allowPicking = true] - 当true时,每个glTF和Primitive都可以用{@link Cesium.Scene#pick}来拾取。 * @param [options.asynchronous = true] - 确定模型WebGL资源创建是否将分散在几个帧或块上,直到所有glTF文件加载完成。 * @param [options.incrementallyLoadTextures = true] - 确定模型加载后纹理是否会继续流进来。 * @param [options.shadows = ShadowMode.ENABLED] - 指定模型是投射还是接收来自光源的阴影。 * @param [options.imageBasedLightingFactor = new Cartesian2(1.0, 1.0)] - 指定来自基于图像的漫反射和镜面照明的贡献。 * @param [options.lightColor] - 光的颜色当遮光模型。当undefined场景的浅色被使用代替。 * @param [options.luminanceAtZenith = 0.2] - 太阳在天顶的亮度,单位是千坎德拉每平方米,用于这个模型的程序环境地图。 * @param [options.sphericalHarmonicCoefficients] - 三阶球面调和系数用于基于图像的漫射色彩照明。 * @param [options.specularEnvironmentMaps] - 一个KTX文件的URL,该文件包含高光照明的立方体映射和复杂的高光mipmaps。 * @param [options.backFaceCulling = true] - 是否剔除面向背面的几何图形。当为真时,背面剔除由glTF材质的双面属性决定;当为false时,禁用背面剔除。 * @param [options.debugShowBoundingVolume = false] - 仅供调试。查看模型的包围边界球。 * @param [options.debugWireframe = false] - 仅供调试。查看模型的三角网线框图。 * * * //以下是 模型动画相关 * @param [options.startTime] - 场景时间开始播放动画。当undefined时,动画从下一帧开始。 * @param [options.delay = 0.0] - 从startTime开始播放的延迟,以秒为单位。 * @param [options.stopTime] - 场景时间停止播放动画。当这是undefined,动画播放它的整个持续时间。 * @param [options.removeOnStop = false] - 当true时,动画在停止播放后被删除。 * @param [options.multiplier = 1.0] - 大于1.0的值增加动画播放的速度相对于场景时钟的速度;小于1.0会降低速度。 * @param [options.reverse = false] - 当true时,动画会反向播放。 * @param [options.loop = Cesium.ModelAnimationLoop.REPEAT] - 决定动画是否循环以及如何循环。 */ declare class ModelCombine extends BaseCombine { constructor(options: { url?: Cesium.Resource | string; instances?: { position: LatLngPoint | Cesium.Cartesian3; style?: ModelPrimitive.StyleOptions; attr?: any; }[]; batchTable?: Cesium3DTileBatchTable; requestType?: any; gltf?: any | ArrayBuffer | Uint8Array; basePath?: Cesium.Resource | string; dynamic?: boolean; allowPicking?: boolean; asynchronous?: boolean; incrementallyLoadTextures?: boolean; shadows?: Cesium.ShadowMode; imageBasedLightingFactor?: Cartesian2; lightColor?: Cartesian3; luminanceAtZenith?: number; sphericalHarmonicCoefficients?: Cesium.Cartesian3[]; specularEnvironmentMaps?: string; backFaceCulling?: boolean; debugShowBoundingVolume?: boolean; debugWireframe?: boolean; startTime?: Cesium.JulianDate; delay?: number; stopTime?: JulianDate; removeOnStop?: boolean; multiplier?: number; reverse?: boolean; loop?: Cesium.ModelAnimationLoop; }); } /** * 大数据面集合 (合并渲染) Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param [options.instances] - 面信息数组,单个对象包括: * @param options.instances.positions - 坐标位置 * @param [options.instances.style] - 样式信息 * @param [options.instances.attr] - 矢量数据的 属性信息,可以任意附加属性。 * @param [options.style] - 所有面的公共样式信息 * @param [options.highlight] - 鼠标移入或单击后的对应高亮的部分样式 * @param [options.highlight.type] - 触发高亮的方式,默认鼠标移入,可以指定为type:'click'为单击后高亮 */ declare class PolygonCombine extends BaseCombine { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; instances?: { positions: LatLngPoint[] | Cesium.Cartesian3[]; style?: PolygonPrimitive.StyleOptions; attr?: any; }[]; style?: PolygonPrimitive.StyleOptions; highlight?: { type?: string; }; }); /** * 样式信息 */ readonly style: any; /** * 高亮对象。 * @param [highlightStyle] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @returns 无 */ openHighlight(highlightStyle?: any): void; /** * 清除已选中的高亮 * @returns 无 */ closeHighlight(): void; } /** * 大数据线集合 (合并渲染) Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param [options.instances] - 线信息 数组,单个对象包括: * @param options.instances.positions - 坐标位置 * @param [options.instances.style] - 样式信息 * @param [options.instances.attr] - 矢量数据的 属性信息,可以任意附加属性。 * @param [options.style] - 所有线的公共样式信息 */ declare class PolylineCombine extends BaseCombine { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; instances?: { positions: LatLngPoint[] | Cesium.Cartesian3[]; style?: PolylinePrimitive.StyleOptions; attr?: any; }[]; style?: PolylinePrimitive.StyleOptions; }); /** * 样式信息 */ readonly style: any; } declare namespace DivBoderLabel { /** * 动态边框文本 支持的样式信息 * @property text - 文本内容 * @property [font_size = 15] - 字体大小 * @property [font_family = "楷体"] - 字体 ,可选项:微软雅黑,宋体,楷体,隶书,黑体 等 * @property [color = "#ccc"] - 文本CSS颜色 * @property [boderColor = "rgb(21, 209, 242)"] - 边框CSS颜色 * @property [width] - 面板宽度(px像素值),默认根据文本内容和字体大小自动计算 * @property [height] - 面板高度(px像素值),默认根据文本内容和字体大小自动计算 * @property [其他] - 支持父类的其他样式 */ type StyleOptions = { text: string; font_size?: number; font_family?: string; color?: string; boderColor?: string; width?: number; height?: number; 其他?: DivGraphic.StyleOptions; }; } /** * 动态边框文本 DIV点 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.depthTest = true] - 是否打开深度判断(true时判断是否在球背面) * @param [options.hasCache = true] - 是否启用缓存机制,如为true,在视角未变化时不重新渲染。 * @param [options.stopPropagation = false] - DIV中的鼠标事件是否停止冒泡 * @param [options.pointerEvents] - DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 * @param [options.hasEdit = true] - 是否允许编辑 * @param [options.testPoint] - 测试点 的对应样式 ,可以进行用于比较测试div的位置,方便调试CSS。 */ declare class DivBoderLabel extends DivGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: DivBoderLabel.StyleOptions; attr?: any; depthTest?: boolean; hasCache?: boolean; stopPropagation?: boolean; pointerEvents?: boolean; hasEdit?: boolean; testPoint?: PointEntity.StyleOptions; }); /** * 通过标绘 来创建DivGraphic * @param layer - 图层 * @param options - DivGraphic的构造参数 * @returns DIV点对象 */ static fromDraw(layer: DivLayer, options: any): DivGraphic; } declare namespace DivGraphic { /** * DIV点 支持的样式信息 * @property html - Html文本 * @property [horizontalOrigin] - 横向方向的定位 * @property [verticalOrigin] - 垂直方向的定位 * @property [offsetX] - 用于非规则div时,横向偏移的px像素值 * @property [offsetY] - 用于非规则div时,垂直方向偏移的px像素值 * @property [scaleByDistance = false] - 是否按视距缩放 * @property [scaleByDistance_far = 1000000] - 上限 * @property [scaleByDistance_farValue = 0.1] - 比例值 * @property [scaleByDistance_near = 1000] - 下限 * @property [scaleByDistance_nearValue = 1] - 比例值 * @property [distanceDisplayCondition = false] - 是否按视距显示 * @property [distanceDisplayCondition_far = 10000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [clampToGround = false] - 是否贴地 * @property [css_transform_origin = 'left bottom 0'] - DIV的 transform-origin css值 */ type StyleOptions = { html: string | Element; horizontalOrigin?: Cesium.HorizontalOrigin; verticalOrigin?: Cesium.VerticalOrigin; offsetX?: number; offsetY?: number; scaleByDistance?: boolean; scaleByDistance_far?: number; scaleByDistance_farValue?: number; scaleByDistance_near?: number; scaleByDistance_nearValue?: number; distanceDisplayCondition?: boolean; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; clampToGround?: boolean; css_transform_origin?: string; }; /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.click, function (event) { * console.log('单击了矢量数据对象', event) * }) * @property 通用 - 支持的父类的事件类型 * @property change - 变化了 * @property click - 左键单击 鼠标事件 * @property rightClick - 右键单击 鼠标事件 * @property mouseOver - 鼠标移入 鼠标事件 * @property mouseOut - 鼠标移出 鼠标事件 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 * @property drawStart - 开始绘制 标绘事件 * @property drawMouseMove - 正在移动鼠标中,绘制过程中鼠标移动了点 标绘事件 * @property drawCreated - 创建完成 标绘事件 * @property editStart - 开始编辑 标绘事件 * @property editMouseMove - 正在移动鼠标中,正在编辑拖拽修改点中(MOUSE_MOVE) 标绘事件 * @property editStop - 停止编辑 标绘事件 */ type EventType = { 通用: BaseGraphic.EventType; change: string; click: string; rightClick: string; mouseOver: string; mouseOut: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; drawStart: string; drawMouseMove: string; drawCreated: string; editStart: string; editMouseMove: string; editStop: string; }; } /** * DIV点 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.depthTest = true] - 是否打开深度判断(true时判断是否在球背面) * @param [options.hasCache = true] - 是否启用缓存机制,如为true,在视角未变化时不重新渲染。 * @param [options.hasZIndex = true] - 是否自动调整DIV的层级顺序,true时内部会给div设置0至9999999的zIndex值(如果与外部UI层有遮挡,外部DIV的zIndex请设置大于9999999的值),false时不设置。 * @param [options.stopPropagation = false] - DIV中的鼠标事件是否停止冒泡 * @param [options.pointerEvents] - DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。默认根据是否绑定事件等自动判断。 * @param [options.hasEdit = true] - 是否允许编辑 * @param [options.className] - 自定义的样式名 * @param [options.testPoint] - 测试点 的对应样式 ,可以进行用于比较测试div的位置,方便调试CSS。 */ declare class DivGraphic extends BaseGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: DivGraphic.StyleOptions; attr?: any; depthTest?: boolean; hasCache?: boolean; hasZIndex?: boolean; stopPropagation?: boolean; pointerEvents?: boolean; hasEdit?: boolean; className?: string; testPoint?: PointEntity.StyleOptions; }); /** * 位置坐标 (笛卡尔坐标), 赋值时可以传入LatLngPoint对象 */ position: Cesium.Cartesian3; /** * 位置坐标 (笛卡尔坐标) */ readonly point: LatLngPoint; /** * 位置坐标(数组对象),示例[113.123456,31.123456,30.1] */ readonly coordinate: any[]; /** * 是否显示测试点,可以进行用于比较测试div的位置,方便调试CSS。 */ testPoint: boolean; /** * DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 */ pointerEvents: boolean; /** * 对象是否存在鼠标事件相关绑定 */ readonly hasBindEvent: boolean; /** * 是否打开深度判断(true时判断是否在球背面) */ depthTest: boolean; /** * 是否贴地 */ clampToGround: boolean; /** * 对应的DOM元素 */ readonly container: Element; /** * 对应的DOM元素的id */ readonly containerId: string; /** * 设置或获取当前对象对应的Html */ html: string | Element; /** * 更新刷新下DIV的位置,可以外部主动驱动来更新。 * @returns 当前对象本身,可以链式调用 */ updateDivPosition(): this; /** * 隐藏当前对象 * @returns 无 */ hide(): void; /** * 设置并添加动画轨迹位置,按“指定时间”运动到达“指定位置”。 * @param point - 指定位置坐标 * @param [currTime = Cesium.JulianDate.now()] - 指定时间, 默认为当前时间5秒后。当为String时,可以传入'2021-01-01 12:13:00'; 当为Number时,可以传入当前时间延迟的秒数。 * @returns 当前对象本身,可以链式调用 */ addDynamicPosition(point: LatLngPoint | Cesium.Cartesian3, currTime?: Cesium.JulianDate | string | number): this; /** * 位置坐标(数组对象),示例[113.123456,31.123456,30.1] * @param noAlt - true时不导出高度值 * @returns 位置坐标(数组对象) */ getCoordinate(noAlt: boolean): any[]; /** * 高亮对象。 * @param [highlightStyle] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @returns 无 */ openHighlight(highlightStyle?: any): void; /** * 清除已选中的高亮 * @returns 无 */ closeHighlight(): void; /** * 开始绘制创建矢量数据,绘制的数据会加载在layer图层。 * @param layer - 图层 * @returns 无 */ startDraw(layer: DivLayer): void; /** * 停止绘制,如有未完成的绘制会自动删除 * @returns 无 */ stopDraw(): void; /** * 完成绘制和编辑,如有未完成的绘制会自动完成。 * 在移动端需要调用此方法来类似PC端双击结束。 * @returns 无 */ endDraw(): void; /** * 启用或禁用popup、tooltip、contextmenu内部控件, * 主要用于标绘时来关闭避免交互冲突。 * @param value - 是否启用 * @returns 无 */ enableControl(value: boolean): void; /** * 开始编辑对象 * @returns 无 */ startEditing(): void; /** * 停止编辑,释放正在编辑的对象。 * @returns 无 */ stopEditing(): void; /** * 通过标绘 来创建DivGraphic * @param layer - 图层 * @param options - DivGraphic的构造参数 * @returns DIV点对象 */ static fromDraw(layer: DivLayer, options: any): DivGraphic; /** * 中心点坐标(笛卡尔坐标) */ readonly center: Cesium.Cartesian3; } declare namespace DivLightPoint { /** * 动画的扩散div点 支持的样式信息 * @property [color = '#f33349'] - CSS颜色 * @property [其他] - 支持父类的其他样式 */ type StyleOptions = { color?: string; 其他?: DivGraphic.StyleOptions; }; } /** * 动画的扩散div点 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.depthTest = true] - 是否打开深度判断(true时判断是否在球背面) * @param [options.hasCache = true] - 是否启用缓存机制,如为true,在视角未变化时不重新渲染。 * @param [options.stopPropagation = false] - DIV中的鼠标事件是否停止冒泡 * @param [options.pointerEvents] - DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 * @param [options.hasEdit = true] - 是否允许编辑 * @param [options.testPoint] - 测试点 的对应样式 ,可以进行用于比较测试div的位置,方便调试CSS。 */ declare class DivLightPoint extends DivGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: DivLightPoint.StyleOptions; attr?: any; depthTest?: boolean; hasCache?: boolean; stopPropagation?: boolean; pointerEvents?: boolean; hasEdit?: boolean; testPoint?: PointEntity.StyleOptions; }); /** * 通过标绘 来创建DivGraphic * @param layer - 图层 * @param options - DivGraphic的构造参数 * @returns DIV点对象 */ static fromDraw(layer: DivLayer, options: any): DivGraphic; } declare namespace DivUpLabel { /** * 竖立的文本 支持的样式信息 * @property text - 文本内容 * @property [color = "white"] - 文本CSS颜色 * @property [font_size = 15] - 字体大小 * @property [font_family = "楷体"] - 字体 ,可选项:微软雅黑,宋体,楷体,隶书,黑体 等 * @property [lineHeight = 100] - 底部线的高度值(单位:px像素) * @property [circleSize = 10] - 底部圆圈的大小(单位:px像素) * @property [其他] - 支持父类的其他样式 */ type StyleOptions = { text: string; color?: string; font_size?: number; font_family?: string; lineHeight?: number; circleSize?: number; 其他?: DivGraphic.StyleOptions; }; } /** * 竖立的文本 DIV点 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.depthTest = true] - 是否打开深度判断(true时判断是否在球背面) * @param [options.hasCache = true] - 是否启用缓存机制,如为true,在视角未变化时不重新渲染。 * @param [options.stopPropagation = false] - DIV中的鼠标事件是否停止冒泡 * @param [options.pointerEvents] - DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 * @param [options.hasEdit = true] - 是否允许编辑 * @param [options.testPoint] - 测试点 的对应样式 ,可以进行用于比较测试div的位置,方便调试CSS。 */ declare class DivUpLabel extends DivGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: DivUpLabel.StyleOptions; attr?: any; depthTest?: boolean; hasCache?: boolean; stopPropagation?: boolean; pointerEvents?: boolean; hasEdit?: boolean; testPoint?: PointEntity.StyleOptions; }); /** * 通过标绘 来创建DivGraphic * @param layer - 图层 * @param options - DivGraphic的构造参数 * @returns DIV点对象 */ static fromDraw(layer: DivLayer, options: any): DivGraphic; } declare namespace ParticleSystem { /** * 粒子效果 支持的样式信息 * @property [image] - 粒子的图片URL * @property [emitter = new CircleEmitter(2.0)] - 系统的粒子发射器。 * @property [emissionRate = 5] - 每秒发射的粒子数。 * @property [bursts] - {@link ParticleBurst}的数组,周期性地发射粒子爆发。 * @property [loop = true] - 粒子系统完成后是否应该循环爆发。 * @property [particleSize = 25] - 粒子图片的Size大小(单位:像素) * @property [imageSize = new Cartesian2(1.0, 1.0)] - 粒子图片的Size大小(单位:像素),与particleSize二选一。 * @property [minimumImageSize] - 设置最小边界,宽度和高度,在此之上随机缩放粒子图像的像素尺寸。 * @property [maximumImageSize] - 设置最大边界,宽度和高度,在其以下随机缩放粒子图像的像素尺寸。 * @property [sizeInMeters] - 设置粒子的大小是米还是像素。true以米为单位设置粒子的大小;否则,大小以像素为单位。 * @property [scale = 1.0] - 设置在粒子生命周期内应用于粒子图像的比例。 * @property [startScale] - 粒子在出生时的比例(单位:相对于imageSize大小的倍数) * @property [endScale] - 粒子在死亡时的比例(单位:相对于imageSize大小的倍数) * @property [color = Color.WHITE] - 设置一个粒子在其生命周期内的颜色。 * @property [startColor] - 粒子出生时的颜色 * @property [endColor] - 当粒子死亡时的颜色 * @property [speed = 1.0] - 如果设置,则使用此值覆盖最小速度和最大速度输入。 * @property [minimumSpeed] - 设定以每秒米为单位的最小范围,超过这个范围粒子的实际速度将被随机选择。 * @property [maximumSpeed] - 设定以每秒米为单位的最大范围,低于这个范围粒子的实际速度将被随机选择。 * @property [lifetime = Number.MAX_VALUE] - 粒子系统释放粒子的时间,单位是秒。 * @property [particleLife = 5.0] - 如果设置了这个值,将覆盖minimumParticleLife和maximumParticleLife输入。 * @property [minimumParticleLife] - 设定一个粒子生命可能持续时间的最小界限(以秒为单位),在此之上一个粒子的实际生命将被随机选择。 * @property [maximumParticleLife] - 设置一个粒子生命可能持续时间的最大界限(以秒为单位),低于这个时间的粒子的实际生命将被随机选择。 * @property [mass = 1.0] - 设定粒子的最小和最大质量,单位为千克。 * @property [minimumMass] - 设定粒子质量的最小边界,单位为千克。一个粒子的实际质量将被选为高于这个值的随机数量。 * @property [maximumMass] - 设置粒子的最大质量,单位为千克。一个粒子的实际质量将被选为低于这个值的随机数量。 * @property [updateCallback] - 每一帧调用一个回调函数来更新一个粒子。 */ type StyleOptions = { image?: string; emitter?: ParticleEmitter; emissionRate?: number; bursts?: ParticleBurst[]; loop?: boolean; particleSize?: number; imageSize?: Cartesian2; minimumImageSize?: Cartesian2; maximumImageSize?: Cartesian2; sizeInMeters?: boolean; scale?: number; startScale?: number; endScale?: number; color?: Color; startColor?: Color; endColor?: Color; speed?: number; minimumSpeed?: number; maximumSpeed?: number; lifetime?: number; particleLife?: number; minimumParticleLife?: number; maximumParticleLife?: number; mass?: number; minimumMass?: number; maximumMass?: number; updateCallback?: ParticleSystem.updateCallback; }; } /** * 粒子效果 对象 * @param options - 参数对象,包括以下: * @param options.position - 坐标位置 * @param [options.modelMatrix] - 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵,可以替代position。 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.gravity = 0] - 重力因子,会修改速度矢量以改变方向或速度(基于物理的效果) * @param [options.target = new Cesium.Cartesian3(0, 0, 0)] - 粒子的方向,粒子喷射的目标方向。 * @param [options.transZ = 0] - 离地高度,Z轴方向上的偏离距离(单位:米) * @param [options.transX = 0] - X轴方向上的偏离距离(单位:米) * @param [options.transY = 0] - Y轴方向上的偏离距离(单位:米) * @param [options.maxHeight = 5000] - 最大视角高度(单位:米),超出该高度不显示粒子效果 * @param [options.hasDefUpdate = true] - 是否内部自动处理 updateCallback */ declare class ParticleSystem extends BasePointPrimitive { constructor(options: { position: LatLngPoint | Cesium.Cartesian3; modelMatrix?: Cesium.Matrix4; style: ParticleSystem.StyleOptions; attr?: any; gravity?: number; target?: Cesium.Cartesian3; transZ?: number; transX?: number; transY?: number; maxHeight?: number; hasDefUpdate?: boolean; }); /** * 最大视角高度(单位:米),超出该高度不显示粒子效果 */ maxHeight: number; /** * 重力因子,会修改速度矢量以改变方向或速度(基于物理的效果) */ gravity: number; /** * X轴方向上的偏离距离(单位:米) */ transX: number; /** * Y轴方向上的偏离距离(单位:米) */ transY: number; /** * 离地高度,Z轴方向上的偏离距离(单位:米) */ transZ: number; /** * 粒子的方向,粒子喷射的目标方向。 */ target: Cesium.Cartesian3; /** * 粒子图片的Size大小(单位:像素) */ particleSize: number; } declare namespace Popup { /** * Popup对象 支持的配置信息 * @property html - Html文本({content}部分,整体展示的DOM由template和html属性共同组成) * @property template - 公共部分外框部分html内容,需要加2处: * (1)用于填充html的地方写上{content}标识; * (2)关闭按钮加class样式:closeButton。 * 传空字符串或false时,不用内置模版。 * @property [horizontalOrigin] - 横向方向的定位 * @property [verticalOrigin] - 垂直方向的定位 * @property [offsetX] - 用于非规则div时,横向偏移的px像素值 * @property [offsetY] - 用于非规则div时,垂直方向偏移的px像素值 * @property [scaleByDistance = false] - 是否按视距缩放 * @property [scaleByDistance_far = 1000000] - 上限 * @property [scaleByDistance_farValue = 0.1] - 比例值 * @property [scaleByDistance_near = 1000] - 下限 * @property [scaleByDistance_nearValue = 1] - 比例值 * @property [distanceDisplayCondition = false] - 是否按视距显示 * @property [distanceDisplayCondition_far = 10000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [clampToGround = false] - 是否贴地 * @property [css_transform_origin = 'left bottom 0'] - DIV的 transform-origin css值 */ type StyleOptions = { html: string; template: string; horizontalOrigin?: Cesium.HorizontalOrigin; verticalOrigin?: Cesium.VerticalOrigin; offsetX?: number; offsetY?: number; scaleByDistance?: boolean; scaleByDistance_far?: number; scaleByDistance_farValue?: number; scaleByDistance_near?: number; scaleByDistance_nearValue?: number; distanceDisplayCondition?: boolean; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; clampToGround?: boolean; css_transform_origin?: string; }; } /** * Popup对象div点 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.depthTest = true] - 是否打开深度判断(true时判断是否在球背面) * @param [options.hasCache = true] - 是否启用缓存机制,如为true,在视角未变化时不重新渲染。 * @param [options.hasZIndex = true] - 是否自动调整DIV的层级顺序。 * @param [options.stopPropagation = true] - DIV中的鼠标事件是否停止冒泡 * @param [options.pointerEvents = true] - DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 * @param [options.hasEdit = false] - 是否允许编辑 * @param [options.testPoint] - 测试点 的对应样式 ,可以进行用于比较测试div的位置,方便调试CSS。 */ declare class Popup extends DivGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: Popup.StyleOptions; attr?: any; depthTest?: boolean; hasCache?: boolean; hasZIndex?: boolean; stopPropagation?: boolean; pointerEvents?: boolean; hasEdit?: boolean; testPoint?: PointEntity.StyleOptions; }); /** * 关联的触发对象 */ readonly target: BaseGraphic | BaseLayer | Map; /** * 通过标绘 来创建DivGraphic * @param layer - 图层 * @param options - DivGraphic的构造参数 * @returns DIV点对象 */ static fromDraw(layer: DivLayer, options: any): DivGraphic; } declare namespace Tooltip { /** * Tooltip对象 支持的配置信息 * @property html - Html文本({content}部分,整体展示的DOM由template和html属性共同组成) * @property template - 公共部分外框部分html内容,需要加:用于填充html的地方写上{content}标识。 传空字符串或false时,不用内置模版。 * @property [direction = "top"] - 显示的方向,可选值: top、bottom、center、right、left * @property [horizontalOrigin] - 横向方向的定位 * @property [verticalOrigin] - 垂直方向的定位 * @property [offsetX] - 用于非规则div时,横向偏移的px像素值 * @property [offsetY] - 用于非规则div时,垂直方向偏移的px像素值 * @property [scaleByDistance = false] - 是否按视距缩放 * @property [scaleByDistance_far = 1000000] - 上限 * @property [scaleByDistance_farValue = 0.1] - 比例值 * @property [scaleByDistance_near = 1000] - 下限 * @property [scaleByDistance_nearValue = 1] - 比例值 * @property [distanceDisplayCondition = false] - 是否按视距显示 * @property [distanceDisplayCondition_far = 10000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [clampToGround = false] - 是否贴地 * @property [css_transform_origin = 'left bottom 0'] - DIV的 transform-origin css值 */ type StyleOptions = { html: string; template: string | boolean; direction?: string; horizontalOrigin?: Cesium.HorizontalOrigin; verticalOrigin?: Cesium.VerticalOrigin; offsetX?: number; offsetY?: number; scaleByDistance?: boolean; scaleByDistance_far?: number; scaleByDistance_farValue?: number; scaleByDistance_near?: number; scaleByDistance_nearValue?: number; distanceDisplayCondition?: boolean; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; clampToGround?: boolean; css_transform_origin?: string; }; } /** * Tooltip对象div点 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.depthTest = true] - 是否打开深度判断(true时判断是否在球背面) * @param [options.hasCache = true] - 是否启用缓存机制,如为true,在视角未变化时不重新渲染。 * @param [options.hasZIndex = true] - 是否自动调整DIV的层级顺序。 * @param [options.stopPropagation = true] - DIV中的鼠标事件是否停止冒泡 * @param [options.pointerEvents = true] - DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 * @param [options.hasEdit = false] - 是否允许编辑 * @param [options.testPoint] - 测试点 的对应样式 ,可以进行用于比较测试div的位置,方便调试CSS。 */ declare class Tooltip extends Popup { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: Tooltip.StyleOptions; attr?: any; depthTest?: boolean; hasCache?: boolean; hasZIndex?: boolean; stopPropagation?: boolean; pointerEvents?: boolean; hasEdit?: boolean; testPoint?: PointEntity.StyleOptions; }); /** * 通过标绘 来创建DivGraphic * @param layer - 图层 * @param options - DivGraphic的构造参数 * @returns DIV点对象 */ static fromDraw(layer: DivLayer, options: any): Tooltip; } declare namespace Video3D { /** * 视频融合(投射3D,贴物体表面) 支持的样式信息 * @property opacity - 混合系数 0.0 - 1.0 * @property camera - 相机方向参数 * @property camera.direction - direction方向 * @property camera.up - up方向 * @property camera.right - right方向 * @property aspectRatio - 相机视野的宽高比例(垂直张角) * @property fov - 张角(弧度值) * @property fovDegree - 张角(角度值,0-180度) * @property [hiddenAreaColor = new Cesium.Color(0, 0, 0, 0.5)] - 无视频投影区域的颜色 * @property [color] - 当type为颜色时的,投射的颜色值 * @property [text] - 当为text文本时的,传入的文本内容 * @property [textStyles] - 当为text文本时的,文本样式,包括: * @property [textStyles.font = '23px 楷体'] - 使用的CSS字体。 * @property [textStyles.textBaseline = 'top'] - 文本的基线。 * @property [textStyles.fill = true] - 是否填充文本。 * @property [textStyles.stroke = true] - 是否描边文本。 * @property [textStyles.fillColor = new Cesium.Color(1.0, 1.0, 0.0, 1.0)] - 填充颜色。 * @property [textStyles.strokeColor = new Cesium.Color(1.0, 1.0, 1.0, 0.8)] - 描边的颜色。 * @property [textStyles.strokeWidth = 2] - 描边的宽度。 * @property [textStyles.backgroundColor = new Cesium.Color(1.0, 1.0, 1.0, 0.1)] - 画布的背景色。 * @property [textStyles.padding = 10] - 要在文本周围添加的填充的像素大小。 */ type StyleOptions = { opacity: number; camera: { direction: Cesium.Cartesian3; up: Cesium.Cartesian3; right: Cesium.Cartesian3; }; aspectRatio: number; fov: number; fovDegree: number; hiddenAreaColor?: Cesium.Color; color?: Cesium.Color; text?: string; textStyles?: { font?: string; textBaseline?: string; fill?: boolean; stroke?: boolean; fillColor?: Cesium.Color; strokeColor?: Cesium.Color; strokeWidth?: number; backgroundColor?: vColor; padding?: number; }; }; /** * 类型 */ enum Type { Video, Image, Color, Text } /** * 旋转的方向 */ enum RatateDirection { LEFT, RIGHT, TOP, BOTTOM, ALONG, INVERSE } } /** * 视频融合(投射3D,贴物体表面) * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 视点位置 * @param options.cameraPosition - 相机位置 * @param options.type - 投射的类型 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.url] - 当为图片或视频类型时,传入的图片或视频的路径 * @param [options.dom] - 当为视频类型时,传入了视频容器DOM,与url二选一 * @param [options.showFrustum = true] - 是否显示视椎体框线 */ declare class Video3D extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; cameraPosition: LatLngPoint | Cesium.Cartesian3; type: Video3D.Type; style: Video3D.StyleOptions; attr?: any; url?: string; dom?: HTMLElement | any; showFrustum?: boolean; }); /** * 相机位置(笛卡尔坐标) */ cameraPosition: Cesium.Cartesian3; /** * 相机位置 */ cameraPoint: LatLngPoint; /** * 相机位置 (数组对象),示例[113.123456,31.123456,30.1] */ cameraCoordinate: LatLngPoint; /** * 混合系数0-1 */ opacity: number; /** * 相机视野的宽高比例(垂直张角) */ aspectRatio: number; /** * 相机水平张角 (弧度值) */ fov: number; /** * 相机水平张角(角度值,0-180度) */ fovDegree: number; /** * 是否显示视椎体框线 */ showFrustum: boolean; /** * 暂停或播放 视频 */ play: boolean; /** * 无视频投影区域的颜色 */ hiddenAreaColor: Cesium.Color; /** * 当type为颜色时的,投射的颜色值 */ color: Cesium.Color; /** * 相机 */ readonly camera: Cesium.Color; /** * 将矢量数据的坐标、样式及属性等信息导出为对象,可以用于存储。 * @returns 导出的坐标、样式及属性等信息 */ toJSON(): any; /** * 旋转相机 * @param axis - 旋转的方向 * @param [rotateDegree = 0.5] - 旋转的角度 * @returns 无 */ rotateCamera(axis: Video3D.RatateDirection, rotateDegree?: number): void; /** * 定位至相机的第一视角 * @returns 无 */ flyTo(): void; } declare namespace BaseEntity { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.click, function (event) { * console.log('单击了矢量数据对象', event) * }) * @property 通用 - 支持的父类的事件类型 * @property click - 左键单击 鼠标事件 * @property rightClick - 右键单击 鼠标事件 * @property mouseOver - 鼠标移入 鼠标事件 * @property mouseOut - 鼠标移出 鼠标事件 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 * @property drawStart - 开始绘制 标绘事件 * @property drawMouseMove - 正在移动鼠标中,绘制过程中鼠标移动了点 标绘事件 * @property drawAddPoint - 绘制过程中增加了点 标绘事件 * @property drawRemovePoint - 绘制过程中删除了最后一个点 标绘事件 * @property drawCreated - 创建完成 标绘事件 * @property editStart - 开始编辑 标绘事件 * @property editMouseDown - 移动鼠标按下左键(LEFT_DOWN)标绘事件 * @property editMouseMove - 正在移动鼠标中,正在编辑拖拽修改点中(MOUSE_MOVE) 标绘事件 * @property editMovePoint - 编辑修改了点(LEFT_UP)标绘事件 * @property editRemovePoint - 编辑删除了点 标绘事件 * @property editStyle - 图上编辑修改了相关style属性 标绘事件 * @property editStop - 停止编辑 标绘事件 */ type EventType = { 通用: BaseGraphic.EventType; click: string; rightClick: string; mouseOver: string; mouseOut: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; drawStart: string; drawMouseMove: string; drawAddPoint: string; drawRemovePoint: string; drawCreated: string; editStart: string; editMouseDown: string; editMouseMove: string; editMovePoint: string; editRemovePoint: string; editStyle: string; editStop: string; }; } /** * Entity实体 矢量对象 基类 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class BaseEntity extends BaseGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 加载Entity数据的内部Cesium容器 */ readonly dataSource: Cesium.CustomDataSource; /** * 矢量数据对应的 Cesium内部对象 */ readonly entity: Cesium.Entity; /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.XXXGraphics; /** * 附加的label文本对象 */ readonly label: Cesium.Label | Cesium.LabelGraphics; /** * 是否正在编辑状态 */ readonly isEditing: boolean; /** * 高亮对象。 * @param [highlightStyle] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @returns 无 */ openHighlight(highlightStyle?: any): void; /** * 清除已选中的高亮 * @returns 无 */ closeHighlight(): void; /** * 高亮闪烁 Enity实体对象 * @param options - 参数 * @param [options.time = null] - 闪烁的时长(秒),未设置时不自动停止。 * @param [options.color = Cesium.Color.YELLOW] - 高亮的颜色 * @param [options.maxAlpha = 0.3] - 闪烁的最大透明度,从 0 到 maxAlpha 渐变 * @param [options.onEnd = null] - 播放完成后的回调方法 * @returns 高亮闪烁控制 对象 */ startFlicker(options: { time?: number; color?: Cesium.Color; maxAlpha?: number; onEnd?: (...params: any[]) => any; }): FlickerEntity; /** * 停止高亮闪烁 * @returns 无 */ stopFlicker(): void; /** * 设置透明度 * @param value - 透明度 * @returns 无 */ setOpacity(value: number): void; /** * 开始绘制矢量数据,绘制的数据会加载在layer图层。 * @param layer - 图层 * @returns 无 */ startDraw(layer: GraphicLayer): void; /** * 停止绘制 * @returns 无 */ stopDraw(): void; /** * 移除绘制的坐标中的重复点,比如快速单击或双击产生的冗余坐标。 * @returns 无 */ removeNearPoint(): void; /** * 完成绘制和编辑,如有未完成的绘制会自动完成。 * 在移动端需要调用此方法来类似PC端双击结束。 * @returns 无 */ endDraw(): void; /** * 启用或禁用所有内部控件(含tooltip、popup、contextmenu) * @param value - 是否启用 * @returns 无 */ enableControl(value: boolean): void; /** * 开始编辑对象 * @returns 无 */ startEditing(): void; /** * 停止编辑,释放正在编辑的对象。 * @returns 无 */ stopEditing(): void; } /** * 单个坐标的点状Entity矢量数据 基类 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param [options.orientation] - 指定实体方向的属性。 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.entity] - 传入外部已经构造好的Entity对象 * @param [options.hasEdit = true] - 是否允许编辑 * @param [options.maxCacheCount = 50] - 当使用addDynamicPosition设置为动画轨迹位置时,保留的坐标点数量 * @param [options.clampToTileset] - 当使用addDynamicPosition设置为动画轨迹位置时,是否进行贴模型。 * @param [options.frameRate = 30] - 当使用addDynamicPosition设置为动画轨迹位置时,并clampToTileset:true时,多少帧计算一次贴模型高度 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class BasePointEntity extends BaseEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; orientation?: Cesium.Property; drawShow?: boolean; addHeight?: number; entity?: Cesium.Entity; hasEdit?: boolean; maxCacheCount?: number; clampToTileset?: boolean; frameRate?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 编辑处理类 */ readonly EditClass: EditPoint; /** * 位置坐标 (笛卡尔坐标), 赋值时可以传入LatLngPoint对象 */ position: Cesium.Cartesian3; /** * 位置坐标 */ readonly point: LatLngPoint; /** * 位置坐标(数组对象),示例[113.123456,31.123456,30.1] */ readonly coordinate: any[]; /** * 中心点坐标 (笛卡尔坐标) */ readonly center: Cesium.Cartesian3; /** * 中心点坐标 */ readonly centerPoint: LatLngPoint; /** * 三维空间中的旋转。 */ readonly orientation: Cesium.Quaternion; /** * 四周方向角,0-360度角度值 */ heading: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右摆动的角度,0-360度角度值 */ roll: number; /** * 坐标对应的高度值(单位:米) */ height: number; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly modelMatrix: Cesium.Matrix4; /** * 是否显示3个方向轴,用于对比测试 */ debugAxis: boolean; /** * 显示3个方向轴时的对应轴长度,用于对比测试 */ debugAxisLength: number; /** * 贴模型分析时,排除的不进行贴模型计算的模型对象,默认是当前本身,可以是: primitives, entities 等 */ readonly objectsToExclude: object[] | undefined; /** * 更新 三维空间中的Quaternion旋转对象。 * @returns 更新后的Quaternion旋转对象 */ updateOrientation(): Cesium.Quaternion; /** * 清除addDynamicPosition添加的动态轨迹 * @returns 当前对象本身,可以链式调用 */ clearDynamicPosition(): this; /** * 设置并添加动画轨迹位置,按“指定时间”运动到达“指定位置”。 * @param point - 指定位置坐标 * @param [currTime = Cesium.JulianDate.now()] - 指定时间, 默认为当前时间5秒后。当为String时,可以传入'2021-01-01 12:13:00'; 当为Number时,可以传入当前时间延迟的秒数。 * @returns 当前对象本身,可以链式调用 */ addDynamicPosition(point: LatLngPoint | Cesium.Cartesian3, currTime?: Cesium.JulianDate | string | number): this; /** * 异步计算更新坐标进行贴地(或贴模型) * @param [options = {}] - 参数对象: * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 当前对象本身,可以链式调用 */ clampToGround(options?: { has3dtiles?: boolean; objectsToExclude?: object[]; callback: getSurfaceHeight_callback; }): this; /** * 位置坐标(数组对象),示例[113.123456,31.123456,30.1] * @param noAlt - true时不导出高度值 * @returns 位置坐标(数组对象) */ getCoordinate(noAlt: boolean): any[]; /** * 显示隐藏状态 */ show: boolean; } /** * 多个坐标的线面状 Entity矢量数据 基类 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.minPointNum = 2] - 绘制时,至少需要点的个数 * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.hasEdit = true] - 是否允许编辑 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class BasePolyEntity extends BaseEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; hasMoveEdit?: boolean; minPointNum?: number; maxPointNum?: number; addHeight?: number; hasEdit?: boolean; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 编辑处理类 */ readonly EditClass: EditPoly; /** * 中心点坐标 (笛卡尔坐标) */ readonly center: Cesium.Cartesian3; /** * 围合面的内部中心点坐标 */ readonly centerOfMass: Cesium.Cartesian3; /** * 边线的中心点坐标 */ readonly centerOfLine: Cesium.Cartesian3; /** * 距离(单位:米) */ readonly distance: number; /** * 面积(单位:平方米) */ readonly area: number; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; /** * 实际显示的坐标数组 (笛卡尔坐标), * 如标绘中时positions对应的可能只是控制点坐标或CallbackProperty属性 */ readonly positionsShow: Cesium.Cartesian3[]; /** * 位置坐标数组 */ readonly points: LatLngPoint[]; /** * 位置坐标(数组对象),示例 [ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] */ readonly coordinates: any[][]; /** * 坐标数据对应的矩形边界 */ readonly rectangle: Cesium.Rectangle; /** * 位置坐标(数组对象),示例 [ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] * @param noAlt - true时不导出高度值 * @returns 位置坐标(数组对象) */ getCoordinates(noAlt: boolean): any[][]; /** * 判断点是否在当前对象的坐标点围成的多边形内 * @param position - 需要判断的点 * @returns 是否在多边形内 */ isInPoly(position: Cesium.Cartesian3 | LatLngPoint): boolean; /** * 异步计算更新坐标进行贴地(或贴模型) * @param [options = {}] - 参数对象: * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param [options.offset = 0] - 可以按需增加偏移高度(单位:米),便于可视 * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 当前对象本身,可以链式调用 */ clampToGround(options?: { has3dtiles?: boolean; objectsToExclude?: object[]; offset?: number; callback: surfaceLineWork_callback; }): this; } declare namespace BillboardEntity { /** * 图标点 支持的样式信息 * @property [image] - 用于矢量对象的 图像、URI或Canvas * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [scale = 1] - 图像大小的比例 * @property [rotation = 0] - 旋转角度(弧度值),正北为0,逆时针旋转 * @property [rotationDegree = 0] - 旋转角度(度数值,0-360度),与rotation二选一 * @property [horizontalOrigin] - 横向方向的定位 * @property [verticalOrigin] - 垂直方向的定位 * @property [width] - 指定广告牌的宽度(以像素为单位),覆盖图片本身大小。 * @property [height] - 指定广告牌的高度(以像素为单位),覆盖图片本身大小。 * @property [hasPixelOffset = false] - 是否存在偏移量 * @property [pixelOffsetX = 0] - 横向偏移像素 * @property [pixelOffsetY = 0] - 纵向偏移像素 * @property [pixelOffset = Cartesian2.ZERO] - 指定像素偏移量。 * @property [scaleByDistance = false] - 是否按视距缩放 或 设置基于与相机的距离缩放点 * @property [scaleByDistance_far = 1000000] - 上限 * @property [scaleByDistance_farValue = 0.1] - 比例值 * @property [scaleByDistance_near = 1000] - 下限 * @property [scaleByDistance_nearValue = 1] - 比例值 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定该广告牌将显示在与摄像机的多大距离 * @property [distanceDisplayCondition_far = 10000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [clampToGround = false] - 是否贴地 * @property [heightReference = Cesium.HeightReference.NONE] - 指定高度相对于什么的属性。 * @property [visibleDepth = true] - 是否被遮挡 * @property [disableDepthTestDistance] - 指定从相机到禁用深度测试的距离。 * @property [color = Color.WHITE] - 附加的颜色 * @property [eyeOffset = Cartesian3.ZERO] - 眼偏移量 * @property [alignedAxis = Cartesian3.ZERO] - 指定单位旋转向量轴。 * @property [sizeInMeters] - 指定该广告牌的大小是否应该以米来度量。 * @property [translucencyByDistance] - 用于基于与相机的距离设置半透明度。 * @property [pixelOffsetScaleByDistance] - 用于基于与相机的距离设置pixelOffset。 * @property [imageSubRegion] - 定义用于广告牌的图像的子区域,而不是从左下角开始以像素为单位的整个图像。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { image?: string | HTMLCanvasElement; opacity?: number; scale?: number; rotation?: number; rotationDegree?: number; horizontalOrigin?: Cesium.HorizontalOrigin; verticalOrigin?: Cesium.VerticalOrigin; width?: number; height?: number; hasPixelOffset?: boolean; pixelOffsetX?: number; pixelOffsetY?: number; pixelOffset?: Cartesian2 | Number[]; scaleByDistance?: boolean | Cesium.NearFarScalar; scaleByDistance_far?: number; scaleByDistance_farValue?: number; scaleByDistance_near?: number; scaleByDistance_nearValue?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; clampToGround?: boolean; heightReference?: Cesium.HeightReference; visibleDepth?: boolean; disableDepthTestDistance?: number; color?: Cesium.Color; eyeOffset?: Cesium.Cartesian3; alignedAxis?: Cesium.Cartesian3; sizeInMeters?: boolean; translucencyByDistance?: Cesium.NearFarScalar; pixelOffsetScaleByDistance?: Cesium.NearFarScalar; imageSubRegion?: Cesium.BoundingRectangle; setHeight?: number; addHeight?: number; highlight?: BillboardEntity.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 图标点 Entity对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class BillboardEntity extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: BillboardEntity.StyleOptions; attr?: any; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.BillboardGraphics; /** * 图像、URI或Canvas */ image: string | HTMLCanvasElement; /** * 设置透明度 * @param value - 透明度 * @returns 无 */ setOpacity(value: number): void; /** * 开始执行弹跳动画 * @param [options] - 参数,包括 * @param [options.maxHeight = 50] - 弹跳的最大高度, 单位:像素 * @param [options.step = 1] - 弹跳增量, 控制速度,单位:像素 * @param [options.autoStop] - 是否自动停止,true时:会逐渐减弱至停止状态 * @returns 无 */ startBounce(options?: { maxHeight?: number; step?: number; autoStop?: boolean; }): void; /** * 停止弹跳动画 * @returns 无 */ stopBounce(): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): BillboardEntity; } declare namespace BoxEntity { /** * 盒子 支持的样式信息 * @property [dimensions] - 指定盒子的长度、宽度和高度。 * @property [dimensions_x = 100] - 盒子长度 * @property [dimensions_y = 100] - 盒子宽度 * @property [dimensions_z = 100] - 盒子高度 * @property [heading = 0] - 方向角 (度数值,0-360度) * @property [pitch = 0] - 俯仰角(度数值,0-360度) * @property [roll = 0] - 翻滚角(度数值,0-360度) * @property [fill = true] - 是否填充 * @property [materialType = "Color"] - 填充类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineWidth = 1.0] - 边框宽度 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [hasShadows = false] - 是否投射阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 是投射还是接收来自光源的阴影。 * @property [clampToGround = false] - 是否贴地 * @property [heightReference = Cesium.HeightReference.NONE] - 指定从实体位置到它的相对高度。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { dimensions?: Cesium.Cartesian3; dimensions_x?: number; dimensions_y?: number; dimensions_z?: number; heading?: number; pitch?: number; roll?: number; fill?: boolean; materialType?: string; material材质参数?: any; material?: Cesium.MaterialProperty | Cesium.Color; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineWidth?: string; outlineColor?: string | Cesium.Color; outlineOpacity?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; clampToGround?: boolean; heightReference?: Cesium.HeightReference; setHeight?: number; addHeight?: number; highlight?: BoxEntity.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 盒子 Entity对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.orientation] - 实体方向 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class BoxEntity extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: BoxEntity.StyleOptions; attr?: any; orientation?: Cesium.Property; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.BoxGraphics; /** * 编辑处理类 */ readonly EditClass: EditBox; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): BoxEntity; } declare namespace ConeTrack { /** * 圆锥追踪体 支持的样式信息 * @property [angle] - 圆锥追踪体张角(角度值,取值范围 0.01-89.99) * @property [bottomRadius = 100] - 不指定angle时,也可以直接指定圆锥底部半径(单位:米) * @property [length = 100] - 圆锥追踪体长度值(单位:米),没有指定targetPosition时有效 * @property [heading = 0] - 方向角 (度数值,0-360度),没有指定targetPosition时有效 * @property [pitch = 0] - 俯仰角(度数值,0-360度),没有指定targetPosition时有效 * @property [roll = 0] - 翻滚角(度数值,0-360度),没有指定targetPosition时有效 * @property [其他] - 支持父类其他样式 */ type StyleOptions = { angle?: number; bottomRadius?: number; length?: number; heading?: number; pitch?: number; roll?: number; 其他?: CylinderEntity.StyleOptions; }; } /** * 圆锥追踪体 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param [options.targetPosition] - 追踪的目标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class ConeTrack extends CylinderEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; targetPosition?: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: ConeTrack.StyleOptions; attr?: any; }); /** * 追踪的目标位置(确定了方向和距离) */ targetPosition: Cesium.Cartesian3; /** * 追踪的目标位置 */ readonly targetPoint: LatLngPoint; /** * 夹角,半场角度,取值范围 0.01-89.99 */ angle: number; } declare namespace CorridorEntity { /** * 走廊 支持的样式信息 * @property [width = 100] - 走廊宽度,指定走廊边缘之间的距离。 * @property [cornerType = "ROUNDED"] - 指定边角的样式。String可选项:ROUNDED (解释:圆滑),MITERED (解释:斜接),BEVELED (解释:斜切), * @property [height = 0] - 高程,圆相对于椭球面的高度。 * @property [heightReference = Cesium.HeightReference.NONE] - 指定高度相对于什么的属性。 * @property [diffHeight = 100] - 高度差(走廊本身的高度),与extrudedHeight二选一。 * @property [extrudedHeight] - 指定走廊挤压面相对于椭球面的高度。 * @property [extrudedHeightReference = Cesium.HeightReference.NONE] - 指定挤压高度相对于什么的属性。 * @property [fill = true] - 是否填充。 * @property [materialType = "Color"] - 填充类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后fillType和color属性将被覆盖。 * @property [outline = false] - 是否边框 * @property [outlineWidth = 1] - 边框宽度 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [granularity = Cesium.Math.RADIANS_PER_DEGREE] - 指定每个纬度和经度之间的距离。 * @property [hasShadows = false] - 是否投射阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定走廊是投射还是接收来自光源的阴影。 * @property [clampToGround = false] - 是否贴地 * @property [classificationType = Cesium.ClassificationType.BOTH] - 指定贴地时的覆盖类型,是只对地形、3dtiles 或 两者同时。 * @property [zIndex = 0] - 层级顺序,用于排序。只有在高度和挤压高度未定义,并且走廊是静态的情况下才有效果。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { width?: number; cornerType?: string | Cesium.CornerType; height?: number; heightReference?: Cesium.HeightReference; diffHeight?: number; extrudedHeight?: number; extrudedHeightReference?: Cesium.HeightReference; fill?: boolean; materialType?: string; material材质参数?: any; material?: Cesium.MaterialProperty | Cesium.Color; color?: string | Cesium.Color; opacity?: number; material?: Cesium.MaterialProperty | Cesium.Color; outline?: boolean; outlineWidth?: number; outlineColor?: string | Cesium.Color; outlineOpacity?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; granularity?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; clampToGround?: string; classificationType?: Cesium.ClassificationType; zIndex?: number; setHeight?: number; addHeight?: number; highlight?: CorridorEntity.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 走廊 Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.minPointNum = 2] - 绘制时,至少需要点的个数 * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class CorridorEntity extends BasePolyEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: CorridorEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; minPointNum?: number; maxPointNum?: number; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.CorridorGraphics; /** * 编辑处理类 */ readonly EditClass: EditCorridor; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): CorridorEntity; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; } /** * 曲线 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.minPointNum = 2] - 绘制时,至少需要点的个数 * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class CurveEntity extends PolylineEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: PolylineEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; minPointNum?: number; maxPointNum?: number; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): CurveEntity; } declare namespace DivBillboardEntity { /** * HTML转图片后的图标点Entity 支持的样式信息 * @property [图标点的参数] - 支持父类的所有样式信息 * @property html - Html内容 */ type StyleOptions = { 图标点的参数?: BillboardEntity.StyleOptions; html: string; }; } /** * HTML转图片后的 图标点Entity, * 需要引入html2canvas或domtoimage插件进行DOM转图片 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class DivBillboardEntity extends BillboardEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: DivBillboardEntity.StyleOptions; attr?: any; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): DivBillboardEntity; } /** * 标绘处理对应的编辑基类 */ declare class EditBase { /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: any; } /** * BoxEntity对象,标绘处理对应的编辑类 */ declare class EditBox extends EditBase { /** * 位置坐标 (笛卡尔坐标) */ position: Cesium.Cartesian3; } declare namespace FontBillboardEntity { /** * Font CSS字体点转图片后的图标点 Entity 支持的样式信息 * @property [图标点的参数] - 支持父类的所有样式信息 * @property [iconClass = "fa fa-automobile"] - 字体css样式 * @property [iconSize = 50] - 字体大小 * @property [color = '#ff0000'] - 字体颜色 */ type StyleOptions = { 图标点的参数?: BillboardEntity.StyleOptions; iconClass?: string; iconSize?: number; color?: string; }; } /** * Font CSS字体点转图片后的图标点 Entity, * 需要引入html2canvas或domtoimage插件进行DOM转图片 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class FontBillboardEntity extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: FontBillboardEntity.StyleOptions; attr?: any; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): FontBillboardEntity; } declare namespace LabelEntity { /** * 文本点 支持的样式信息 * @property [text = "文字"] - 文本内容,换行可以用换行符'\n'。 * @property [scale = 1.0] - 指定缩放比例。 * @property [horizontalOrigin] - 横向方向的定位 * @property [verticalOrigin] - 垂直方向的定位 * @property [font_family = "楷体"] - 字体 ,可选项:微软雅黑,宋体,楷体,隶书,黑体 等 * @property [font_size = 30] - 字体大小 * @property [font_weight = "normal"] - 是否加粗 ,可选项:bold (解释:是),normal (解释:否), * @property [font_style = "normal"] - 是否斜体 ,可选项:italic (解释:是),normal (解释:否), * @property [font = '30px normal normal 楷体'] - 上叙4个属性的一次性指定CSS字体的属性。 * @property [fill = true] - 是否填充 * @property [color = "#ffffff"] - 文本颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [outline = false] - 是否衬色 * @property [outlineColor = "#000000"] - 衬色颜色 * @property [outlineOpacity = 0.6] - 衬色透明度 * @property [outlineWidth = 2.0] - 衬色宽度 * @property [background = false] - 是否背景 * @property [backgroundColor = "#000000"] - 背景颜色 * @property [backgroundOpacity = 0.5] - 背景透明度 * @property [backgroundPadding = new Cesium.Cartesian2(7, 5)] - 背景内边距,指定文字与填充边界内容之间的空间(以像素为单位)。 * @property [hasPixelOffset = false] - 是否存在偏移量 * @property [pixelOffsetX = 0] - 横向偏移像素 * @property [pixelOffsetY = 0] - 纵向偏移像素 * @property [pixelOffset = Cartesian2.ZERO] - A {@link Cartesian2} Property specifying the pixel offset. * @property [pixelOffsetScaleByDistance] - A {@link NearFarScalar} Property used to set pixelOffset based on distance from the camera. * @property [eyeOffset = Cartesian3.ZERO] - A {@link Cartesian3} Property specifying the eye offset. * @property [scaleByDistance = false] - 是否按视距缩放 或 设定基于与相机的距离设置比例。 * @property [scaleByDistance_far = 1000000] - 上限 * @property [scaleByDistance_farValue = 0.1] - 比例值 * @property [scaleByDistance_near = 1000] - 下限 * @property [scaleByDistance_nearValue = 1] - 比例值 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [clampToGround = false] - 是否贴地 * @property [heightReference = Cesium.HeightReference.NONE] - 指定高度相对于什么的属性。 * @property [visibleDepth = true] - 是否被遮挡 * @property [disableDepthTestDistance] - 指定从相机到禁用深度测试的距离。 * @property [translucencyByDistance] - 用于基于与相机的距离设置半透明度。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) */ type StyleOptions = { text?: string; scale?: number; horizontalOrigin?: Cesium.HorizontalOrigin; verticalOrigin?: Cesium.VerticalOrigin; font_family?: string; font_size?: number; font_weight?: string; font_style?: string; font?: string; fill?: boolean; color?: string; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; outlineWidth?: number; background?: boolean; backgroundColor?: string | Cesium.Color; backgroundOpacity?: number; backgroundPadding?: number | Cesium.Cartesian2; hasPixelOffset?: boolean; pixelOffsetX?: number; pixelOffsetY?: number; pixelOffset?: Cesium.Cartesian2 | Number[]; pixelOffsetScaleByDistance?: Cesium.NearFarScalar; eyeOffset?: Cesium.Cartesian3; scaleByDistance?: boolean | Cesium.NearFarScalar; scaleByDistance_far?: number; scaleByDistance_farValue?: number; scaleByDistance_near?: number; scaleByDistance_nearValue?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; clampToGround?: boolean; heightReference?: Cesium.HeightReference; visibleDepth?: boolean; disableDepthTestDistance?: number; translucencyByDistance?: Cesium.NearFarScalar; setHeight?: number; addHeight?: number; }; } /** * 文字 Entity对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class LabelEntity extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: LabelEntity.StyleOptions; attr?: any; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.LabelGraphics; /** * 文本内容 */ readonly text: string; /** * 开始执行弹跳动画 * @param [options] - 参数,包括 * @param [options.maxHeight = 50] - 弹跳的最大高度, 单位:像素 * @param [options.step = 1] - 弹跳增量, 控制速度,单位:像素 * @param [options.autoStop] - 是否自动停止,true时:会逐渐减弱至停止状态 * @returns 无 */ startBounce(options?: { maxHeight?: number; step?: number; autoStop?: boolean; }): void; /** * 停止弹跳动画 * @returns 无 */ stopBounce(): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): LabelEntity; /** * 附加的label文本对象 */ readonly label: Cesium.Label | Cesium.LabelGraphics; } declare namespace PathEntity { /** * path路径 支持的样式信息 * @property [width = 1.0] - 以像素为单位指定宽度的数字属性。 * @property [color = "#FFFF00"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后fillType和color属性将被覆盖。 * @property [leadTime] - 指定要在保留path对象前面显示的秒数。 * @property [trailTime] - 指定要显示的对象后面的秒数。 * @property [resolution = 60] - 指定在对位置进行采样时步进的最大秒数。 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [label] - 支持附带文字的显示 */ type StyleOptions = { width?: number; color?: string; opacity?: number; material?: Cesium.MaterialProperty | Cesium.Color; leadTime?: number; trailTime?: number; resolution?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; setHeight?: number; addHeight?: number; label?: LabelEntity.StyleOptions; }; } /** * path路径 Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置(含时序的点集合) * @param [options.orientation] - 实体方向 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 设置是否显示 文本 和对应的样式 * @param [options.model] - 设置是否显示 gltf模型 和对应的样式 * @param [options.point] - 设置是否显示 像素点 和对应的样式,如果不设置gltf模型时,可以选择该项。 * @param [options.billboard] - 设置是否显示 图标 和对应的样式,如果不设置gltf模型时,可以选择该项。 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class PathEntity extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: Cesium.SampledPositionProperty; orientation?: Cesium.Property; style: PathEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; model?: ModelEntity.StyleOptions; point?: PointEntity.StyleOptions; billboard?: BillboardEntity.StyleOptions; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.PathGraphics; /** * 获取当前时间的三维空间中的旋转。 */ readonly orientationShow: Cesium.Quaternion; /** * 获取当前时间的方向角 */ readonly hpr: Cesium.HeadingPitchRoll; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右摆动的角度,0-360度角度值 */ roll: number; /** * 定位至当前时间所在的位置 (非相机位置) * @param [options = {}] - 具有以下属性的对象: * @param options.radius - 相机距离目标点的距离(单位:米) * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行持续时间(秒)。如果省略,内部会根据飞行距离计算出理想的飞行时间。 * @param [options.endTransform] - 表示飞行完成后摄像机将位于的参考帧的变换矩阵。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机的飞行角度高于该值,请在飞行过程中调整俯仰角度以向下看,并将地球保持在视口中。 * @param [options.flyOverLongitude] - 地球上2点之间总是有两种方式。此选项会迫使相机选择战斗方向以在该经度上飞行。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyToPoint(options?: { radius: number; heading: number; pitch: number; roll: number; duration?: number; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; easingFunction?: EasingFunction.Callback; }): void; /** * 位置坐标 (笛卡尔坐标), 赋值时可以传入LatLngPoint对象 */ position: Cesium.Cartesian3; } declare namespace PlaneEntity { /** * 平面 支持的样式信息 * @property [dimensions] - 指定平面的宽度和高度。 * @property [dimensions_x = 100] - 长度 * @property [dimensions_y = 100] - 宽度 * @property [plane] - 指定平面的法线和距离。 * @property [plane_normal = "z"] - 方向 ,可选项:x (解释:X轴),y (解释:Y轴),z (解释:Z轴), * @property [plane_distance = 0] - 偏移距离 * @property [heading = 0] - 方向角 (度数值,0-360度) * @property [pitch = 0] - 俯仰角(度数值,0-360度) * @property [roll = 0] - 翻滚角(度数值,0-360度) * @property [fill = true] - 是否填充 * @property [materialType = "Color"] - 填充类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [randomColor = false] - 是否随机颜色 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineWidth = 1] - 边框宽度 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定平面是投射还是接收来自光源的阴影。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { dimensions?: Cesium.Cartesian2; dimensions_x?: number; dimensions_y?: number; plane?: Cesium.Plane; plane_normal?: string; plane_distance?: number; heading?: number; pitch?: number; roll?: number; fill?: boolean; materialType?: string; material材质参数?: any; material?: Cesium.MaterialProperty | Cesium.Color; randomColor?: boolean; color?: string; opacity?: number; outline?: boolean; outlineWidth?: string; outlineColor?: string | Cesium.Color; outlineOpacity?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; setHeight?: number; addHeight?: number; highlight?: PlaneEntity.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 平面 Entity对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.orientation] - 实体方向 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class PlaneEntity extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: PlaneEntity.StyleOptions; attr?: any; orientation?: Cesium.Property; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.PlaneGraphics; /** * 编辑处理类 */ readonly EditClass: EditPlane; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PlaneEntity; } declare namespace PointEntity { /** * 像素点 支持的样式信息 * @property [pixelSize = 10] - 像素大小 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [outlineWidth = 2] - 边框宽度 * @property [scaleByDistance = false] - 是否按视距缩放 或 指定用于基于距离缩放点。 * @property [scaleByDistance_far = 1000000] - 上限 * @property [scaleByDistance_farValue = 0.1] - 比例值 * @property [scaleByDistance_near = 1000] - 下限 * @property [scaleByDistance_nearValue = 1] - 比例值 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 10000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [visibleDepth = true] - 是否被遮挡 * @property [disableDepthTestDistance] - 指定从相机到禁用深度测试的距离。 * @property [translucencyByDistance] - 用于基于与相机的距离设置半透明度。 * @property [clampToGround = false] - 是否贴地 * @property [heightReference = Cesium.HeightReference.NONE] - 指定高度相对于什么的属性。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { pixelSize?: number; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; outlineWidth?: number; scaleByDistance?: boolean | Cesium.NearFarScalar; scaleByDistance_far?: number; scaleByDistance_farValue?: number; scaleByDistance_near?: number; scaleByDistance_nearValue?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; visibleDepth?: boolean; disableDepthTestDistance?: number; translucencyByDistance?: Cesium.NearFarScalar; clampToGround?: boolean; heightReference?: Cesium.HeightReference; setHeight?: number; addHeight?: number; highlight?: PointEntity.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 像素点 Entity对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class PointEntity extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: PointEntity.StyleOptions; attr?: any; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.PointGraphics; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PointEntity; } declare namespace PolylineEntity { /** * 线 支持的样式信息 * @property [materialType = "Color"] - 线型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [width = 4] - 线宽 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [randomColor = false] - 是否随机颜色 * @property [depthFailMaterial] - 指定当折线位于地形之下时用于绘制折线的材质。 * @property [closure = false] - 是否闭合 * @property [outline = false] - 是否衬色 * @property [outlineColor = "#ffffff"] - 衬色颜色 * @property [outlineWidth = 2] - 衬色宽度 * @property [depthFail = false] - 是否显示遮挡 * @property [depthFailColor = "#ff0000"] - 遮挡处颜色 * @property [depthFailOpacity = 0.2] - 遮挡处透明度 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [arcType = Cesium.ArcType.GEODESIC] - 折线段必须遵循的线的类型。 * @property [granularity = Cesium.Math.RADIANS_PER_DEGREE] - 如果arcType不是arcType.none,则指定每个纬度和经度之间的角距离的数字属性。 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定对象是投射还是接收来自光源的阴影。 * @property [clampToGround = false] - 是否贴地 * @property [classificationType = Cesium.ClassificationType.BOTH] - 指定贴地时的覆盖类型,是只对地形、3dtiles 或 两者同时。 * @property [zIndex = 0] - 层级顺序,指定用于排序地面几何的zIndex。只有当' clampToGround '为真且支持地形上的折线时才会有效果。 * @property [setHeight = 0] - 指定坐标高度值,或数组指定每个点的高度(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值,或数组指定每个点增加的高度(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示,额外支持: * @property [label.position] - 文字所在位置,默认是矢量对象本身的center属性值。支持配置 'center':围合面的内部中心点坐标,'{xxxx}'配置属性字段, 或者直接指定坐标值。 * @property [label.showAll] - MultiPolygon和MultiLineString时,是否显示所有注记,默认只在最大坐标数的面或线上显示。 */ type StyleOptions = { materialType?: string; material材质参数?: any; material?: Cesium.MaterialProperty | Cesium.Color; width?: number; color?: string | Cesium.Color; opacity?: number; randomColor?: boolean; depthFailMaterial?: Cesium.MaterialProperty | Color; closure?: boolean; outline?: boolean; outlineColor?: string | Cesium.Color; outlineWidth?: number; depthFail?: boolean; depthFailColor?: string; depthFailOpacity?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; arcType?: Cesium.ArcType; granularity?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; clampToGround?: boolean; classificationType?: Cesium.ClassificationType; zIndex?: number; setHeight?: number | Number[]; addHeight?: number | Number[]; highlight?: PolylineEntity.StyleOptions; label?: { position?: string | LatLngPoint; showAll?: boolean; }; }; } /** * 线 Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.minPointNum = 2] - 绘制时,至少需要点的个数 * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class PolylineEntity extends BasePolyEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: PolylineEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; minPointNum?: number; maxPointNum?: number; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.PolylineGraphics; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; } declare namespace PolylineVolumeEntity { /** * 管道线 支持的样式信息 * @property [radius = 10] - 半径 * @property [shape = "pipeline"] - 形状类型 或 定义要挤压的形状。类型可选项:pipeline (解释:空心管),circle (解释:实心管),star (解释:星状管), * @property [fill = true] - 是否填充 * @property [color = "#FFFF00"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后fillType和color属性将被覆盖。 * @property [outline = false] - 是否边线 * @property [outlineWidth = 1.0] - 边线宽度 * @property [outlineColor = "#ffffff"] - 边线颜色 * @property [outlineOpacity = opacity] - 边框透明度 * @property [cornerType = CornerType.ROUNDED] - 指定边角的样式。 * @property [granularity = Cesium.Math.RADIANS_PER_DEGREE] - 指定每个纬度点和经度点之间的角距离。 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [hasShadows = false] - 是否投射阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定管道是否投射或接收来自光源的阴影。 * @property [setHeight = 0] - 指定坐标高度值,或数组指定每个点的高度(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值,或数组指定每个点增加的高度(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { radius?: number; shape?: string | Cesium.Cartesian2[]; fill?: boolean; color?: string; opacity?: number; material?: Cesium.MaterialProperty | Cesium.Color; outline?: boolean; outlineWidth?: number; outlineColor?: string | Cesium.Color; outlineOpacity?: number; cornerType?: Cesium.CornerType; granularity?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; setHeight?: number | Number[]; addHeight?: number | Number[]; highlight?: PolylineVolumeEntity.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 管道线 Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.minPointNum = 2] - 绘制时,至少需要点的个数 * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class PolylineVolumeEntity extends BasePolyEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: PolylineVolumeEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; minPointNum?: number; maxPointNum?: number; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.PolylineVolumeEntity; /** * 编辑处理类 */ readonly EditClass: EditPoly; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineVolumeEntity; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; } declare namespace RectangleEntity { /** * 矩形 支持的样式信息 * @property [fill = true] - 是否填充 * @property [materialType = "Color"] - 填充类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineWidth = 1] - 边框宽度 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [outlineStyle] - 边框的完整自定义样式,会覆盖outlineWidth、outlineColor等参数。 * @property [height = 0] - 高程,圆相对于椭球面的高度。 * @property [heightReference = Cesium.HeightReference.NONE] - 指定高度相对于什么的属性。 * @property [diffHeight = 100] - 高度差(走廊本身的高度),与extrudedHeight二选一。 * @property [extrudedHeight] - 指定走廊挤压面相对于椭球面的高度。 * @property [extrudedHeightReference = Cesium.HeightReference.NONE] - 指定挤压高度相对于什么的属性。 * @property [rotation = 0] - 旋转角度(弧度值),正北为0,逆时针旋转 * @property [rotationDegree = 0] - 旋转角度(度数值,0-360度),与rotation二选一 * @property [stRotation = 0] - 矩形纹理的角度(弧度值),正北为0,逆时针旋转 * @property [stRotationDegree = 0] - 矩形纹理的角度(度数值,0-360度),与stRotation二选一 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定矩形是投射还是接收来自光源的阴影。 * @property [granularity = Cesium.Math.RADIANS_PER_DEGREE] - 指定矩形上各点之间的角距离。 * @property [clampToGround = false] - 是否贴地 * @property [classificationType = Cesium.ClassificationType.BOTH] - 指定贴地时的覆盖类型,是只对地形、3dtiles 或 两者同时。 * @property [zIndex = 0] - 层级顺序,指定用于排序地面几何的zIndex。只有当矩形为常量且没有指定height或extrdedheight时才有效果。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { fill?: boolean; materialType?: string; material材质参数?: any; material?: Cesium.MaterialProperty | Cesium.Color; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineWidth?: number; outlineColor?: string | Cesium.Color; outlineOpacity?: number; outlineStyle?: PolylineEntity.StyleOptions; height?: number; heightReference?: Cesium.HeightReference; diffHeight?: number; extrudedHeight?: number; extrudedHeightReference?: Cesium.HeightReference; rotation?: number; rotationDegree?: number; stRotation?: number; stRotationDegree?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; granularity?: number; clampToGround?: string; classificationType?: Cesium.ClassificationType; zIndex?: number; setHeight?: number; addHeight?: number; highlight?: RectangleEntity.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 矩形 Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.rectangle - 矩形范围,与positions二选一。 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.minPointNum = 2] - 绘制时,至少需要点的个数 * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class RectangleEntity extends BasePolyEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; rectangle: Cesium.Rectangle | Cesium.PositionProperty; style: RectangleEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; minPointNum?: number; maxPointNum?: number; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.RectangleGraphics; /** * 编辑处理类 */ readonly EditClass: EditRectangle; /** * 矩形的边线坐标集合(笛卡尔坐标) */ outlinePositions: Cesium.Cartesian3[]; /** * 矩形的边线坐标集合(经纬度二维数组),示例 [ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7], …… ] */ readonly outlineCoordinates: any[][]; /** * 坐标数据对应的矩形边界对象 */ rectangle: Cesium.Rectangle; /** * 将矢量数据导出为GeoJSON格式规范对象。 * @param [options] - 参数对象: * @param [options.outline] - 是否导出边线的坐标 * @param [options.closure] - 导出outline时,是否闭合,true时会添加第0个点进行闭合。 * @param [options.noAlt] - 不导出高度值 * @returns GeoJSON格式规范对象 */ toGeoJSON(options?: { outline?: boolean; closure?: boolean; noAlt?: boolean; }): any; /** * 获取矩形的4个边线坐标集合(笛卡尔坐标) * @param [closure = true] - 是否闭合,true时会添加第0个点进行闭合。 * @returns 边线坐标数组 */ getOutlinePositions(closure?: boolean): Cesium.Cartesian3[]; /** * 获取矩形的4个边线坐标集合(经纬度二维数组) * @param [closure = true] - 是否闭合,true时会添加第0个点进行闭合。 * @param noAlt - 是否包含高度值 * @returns 边线坐标数组(经纬度二维数组) */ getOutlineCoordinates(closure?: boolean, noAlt: boolean): any[][]; /** * 判断点是否在矩形内 * @param position - 需要判断的点 * @returns 是否在矩形内 */ isInPoly(position: Cesium.Cartesian3 | LatLngPoint): boolean; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): RectangleEntity; /** * 中心点坐标 (笛卡尔坐标) */ readonly center: Cesium.Cartesian3; /** * 距离(单位:米) */ readonly distance: number; /** * 面积(单位:平方米) */ readonly area: number; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; /** * 位置坐标数组 */ readonly points: LatLngPoint[]; /** * 飞行定位至 数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.minHeight] - 定位时相机的最小高度值,用于控制避免异常数据 * @param [options.maxHeight] - 定位时相机的最大高度值,用于控制避免异常数据 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; minHeight?: number; maxHeight?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } declare namespace RectangularSensor { /** * 相控阵雷达 支持的样式信息 * @property radius - 半径 * @property [xHalfAngle = 0] - 传感器水平半角(弧度值) * @property [xHalfAngleDegree = 0] - 传感器水平半角(度数值,0-360度),与xHalfAngle二选一 * @property [yHalfAngle = 0] - 传感器垂直半角(弧度值) * @property [yHalfAngleDegree = 0] - 传感器垂直半角(度数值,0-360度),与yHalfAngle二选一 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 0.4] - 透明度 * @property [material = new Cesium.Color(0.0, 1.0, 1.0, 0.4)] - 指定用于填充的材质,指定material后color属性将被覆盖。 * @property [lineColor = "#ffffff"] - 边线颜色 * @property [lineOpacity = 0.6] - 边线透明度 * @property [heading = 0] - 方向角 (度数值,0-360度) * @property [pitch = 0] - 俯仰角(度数值,0-360度) * @property [roll = 0] - 翻滚角(度数值,0-360度) * @property [showScanPlane = true] - 是否显示扫描面 * @property [scanPlaneColor = new Cesium.Color(0.0, 1.0, 1.0, 1.0)] - 扫描面颜色 * @property [scanPlaneOpacity = 0.9] - 扫描面透明度 * @property [scanPlaneMode = 'vertical'] - 扫描面方向模式,可选值:vertical(解释:垂直方向)、horizontal(解释:水平方向) * @property [scanPlaneRate = 3] - 扫描速率 * @property [showSectorLines = true] - 是否显示扇面的线 * @property [showSectorSegmentLines = true] - 是否显示扇面和圆顶面连接的线 * @property [showLateralSurfaces = true] - 是否显示侧面 * @property [lateralSurfaceMaterial] - 侧面材质 * @property [showDomeSurfaces = true] - 是否显示圆顶表面 * @property [domeSurfaceMaterial] - 圆顶表面材质 * @property [showDomeLines = true] - 是否显示圆顶面线 * @property [showIntersection = true] - 是否显示与地球相交的线 * @property [intersectionColor = Cesium.Color.WHITE] - 与地球相交的线的颜色 * @property [intersectionWidth = 5.0] - 与地球相交的线的宽度(像素) * @property [slice = 32] - 切分程度 * @property [depthTest = true] - 是否被遮挡 */ type StyleOptions = { radius: number; xHalfAngle?: number; xHalfAngleDegree?: number; yHalfAngle?: number; yHalfAngleDegree?: number; color?: string; opacity?: number; material?: Cesium.MaterialProperty | Cesium.Color; lineColor?: string | Cesium.Color; lineOpacity?: number; heading?: number; pitch?: number; roll?: number; showScanPlane?: boolean; scanPlaneColor?: string | Cesium.Color; scanPlaneOpacity?: number; scanPlaneMode?: number; scanPlaneRate?: number; showSectorLines?: boolean; showSectorSegmentLines?: boolean; showLateralSurfaces?: boolean; lateralSurfaceMaterial?: Cesium.MaterialProperty; showDomeSurfaces?: boolean; domeSurfaceMaterial?: Cesium.MaterialProperty; showDomeLines?: boolean; showIntersection?: boolean; intersectionColor?: Cesium.Color; intersectionWidth?: Cesium.Color; slice?: number; depthTest?: boolean; }; } /** * 相控阵雷达 Entity对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.orientation] - 实体方向 * @param [options.drawShow = true] - 绘制时,是否自动隐藏entity,可避免拾取坐标存在问题。 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class RectangularSensor extends BasePointEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; style: RectangularSensor.StyleOptions; attr?: any; orientation?: Cesium.Property; drawShow?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: RectangularSensorGraphics; /** * 圆的半径(单位:米) */ radius: number; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): RectangularSensor; } declare namespace Video2D { /** * 视频融合(投射2D平面) 支持的样式信息 * @property [面的参数] - 支持父类的所有样式信息 * @property camera - 相机方向参数 * @property camera.direction - direction方向 * @property camera.up - up方向 * @property camera.right - right方向 * @property dis - 投射距离 * @property fov - 张角(弧度值) * @property fovDegree - 张角(角度值,0-180度) * @property aspectRatio - 相机视野的宽高比例(垂直张角) * @property stRotation - UV旋转(弧度值) * @property stRotationDegree - UV旋转(角度值,0-360度) */ type StyleOptions = { 面的参数?: PolygonEntity.StyleOptions; camera: { direction: Cesium.Cartesian3; up: Cesium.Cartesian3; right: Cesium.Cartesian3; }; dis: number; fov: number; fovDegree: number; aspectRatio: number; stRotation: number; stRotationDegree: number; }; /** * 旋转的方向 */ enum RatateDirection { LEFT, RIGHT, TOP, BOTTOM, ALONG, INVERSE } } /** * 视频融合(投射2D平面), * 根据相机位置、方向等参数,在相机前面生成一个PolygonEntity面,然后贴视频纹理 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的部分参数 * @param options.position - 坐标位置 * @param options.dom - 视频对应的video标签 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.showFrustum = true] - 是否显示视椎体框线 * @param [options.reverse = false] - 是否反转计算得到的坐标 */ declare class Video2D extends PolygonEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3 | Cesium.PositionProperty; dom: HTMLElement; style: Video2D.StyleOptions; attr?: any; showFrustum?: boolean; reverse?: boolean; }); /** * 位置坐标 (笛卡尔坐标), 赋值时可以传入LatLngPoint对象 */ position: Cesium.Cartesian3; /** * 位置坐标 (笛卡尔坐标) */ readonly point: LatLngPoint; /** * 位置坐标(数组对象),示例[113.123456,31.123456,30.1] */ readonly coordinate: any[]; /** * 暂停或播放 视频 */ play: boolean; /** * 多边形纹理的角度(弧度值),正北为0,逆时针旋转 */ stRotation: number; /** * 相机水平张角 (弧度值) */ fov: number; /** * 相机水平张角(角度值,0-180度) */ fovDegree: number; /** * 相机视野的宽高比例(垂直张角) */ aspectRatio: number; /** * 投射距离(单位:米) */ dis: number; /** * 是否显示视椎体框线 */ showFrustum: boolean; /** * 将矢量数据的坐标、样式及属性等信息导出为对象,可以用于存储。 * @returns 导出的坐标、样式及属性等信息 */ toJSON(): any; /** * 定位至相机的第一视角 * @returns 无 */ flyTo(): void; /** * 旋转相机 * @param axis - 旋转的方向 * @param [rotateDegree = 0.05] - 旋转的角度 * @returns 无 */ rotateCamera(axis: Video2D.RatateDirection, rotateDegree?: number): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): Video2D; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 或 Cesium.PolygonHierarchy */ positions: Cesium.Cartesian3[]; } declare namespace WallEntity { /** * 墙 支持的样式信息 * @property [diffHeight = 100] - 墙高 * @property [minimumHeights] - 没有指定diffHeight时,可以指定用于墙壁底部而不是球体表面的高度数组。 * @property [maximumHeights] - 没有指定diffHeight时,可以指定用于墙顶的高度数组,而不是每个位置的高度。 * @property [fill = true] - 是否填充 * @property [materialType = "Color"] - 填充类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material = Cesium.Color.WHITE] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [closure = false] - 是否闭合 * @property [outline = false] - 是否边框 * @property [outlineWidth = 1] - 边框宽度 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定墙壁是投射还是接收来自光源的阴影。 * @property [granularity = Cesium.Math.RADIANS_PER_DEGREE] - 指定每个纬度点和经度点之间的角距离。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示,额外支持: * @property [label.position] - 文字所在位置,默认是矢量对象本身的center属性值。支持配置 'center':围合面的内部中心点坐标,'{xxxx}'配置属性字段, 或者直接指定坐标值。 * @property [label.showAll] - MultiPolygon和MultiLineString时,是否显示所有注记,默认只在最大坐标数的面或线上显示。 */ type StyleOptions = { diffHeight?: number; minimumHeights?: number[]; maximumHeights?: number[]; fill?: boolean; materialType?: string; material材质参数?: any; material?: Cesium.MaterialProperty | Cesium.Color; color?: string; opacity?: number; closure?: boolean; outline?: boolean; outlineWidth?: string; outlineColor?: string | Cesium.Color; outlineOpacity?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; granularity?: number; setHeight?: number; addHeight?: number; highlight?: WallEntity.StyleOptions; label?: { position?: string | LatLngPoint; showAll?: boolean; }; }; } /** * 墙 Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.minPointNum = 2] - 绘制时,至少需要点的个数 * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class WallEntity extends BasePolyEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: WallEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; minPointNum?: number; maxPointNum?: number; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 矢量数据对应的 Cesium内部对象的具体类型对象 */ readonly entityGraphic: Cesium.WallGraphics; /** * 编辑处理类 */ readonly EditClass: EditWall; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): WallEntity; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; } /** * 攻击箭头 Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class AttackArrow extends PolygonEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: PolygonEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): AttackArrow; } /** * 攻击箭头(平尾) Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class AttackArrowPW extends PolygonEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: PolygonEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): AttackArrowPW; } /** * 攻击箭头(燕尾) Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class AttackArrowYW extends PolygonEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: PolygonEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): AttackArrowYW; } /** * 闭合曲面(3个点) Entity矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.hasMoveEdit = true] - 绘制时,是否可以整体平移 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.availability] - 与该对象关联的可用性(如果有的话)。 * @param [options.description] - 指定此实体的HTML描述的字符串属性(infoBox中展示)。 * @param [options.viewFrom] - 观察这个物体时建议的初始偏移量。 * @param [options.parent] - 要与此实体关联的父实体。 * @param [options.onBeforeCreate] - 在 new Cesium.Entity(addattr) 前的回调方法,可以对addattr做额外个性化处理。 */ declare class CloseVurve extends PolygonEntity { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[] | Cesium.PositionProperty; style: PolygonEntity.StyleOptions; attr?: any; hasMoveEdit?: boolean; addHeight?: number; availability?: Cesium.TimeIntervalCollection; description?: Cesium.Property | string; viewFrom?: Cesium.Property; parent?: Cesium.Entity; onBeforeCreate?: (...params: any[]) => any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): CloseVurve; } /** * 角度量算对象, * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class AngleMeasure extends PolylineEntity { constructor(options: { style: PolylineEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 测量结果 */ readonly measured: any; /** * 更新测量结果的文本 * @param unit - 计量单位,{@link MeasureUtil#formatDistance} 可选值:auto、m、km、mile、zhang 等。auto时根据距离值自动选用k或km * @returns 无 */ updateText(unit: string): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 面积测量对象, * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class AreaMeasure extends PolygonEntity { constructor(options: { style: PolygonEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 测量结果 */ readonly measured: any; /** * 更新测量结果的文本 * @param unit - 计量单位,{@link MeasureUtil#formatArea} 可选值:计量单位,可选值:auto、m、km、mu、ha 。auto时根据面积值自动选用m或km * @returns 无 */ updateText(unit: string): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; /** * 开始绘制矢量数据,绘制的数据会加载在layer图层。 * @param layer - 图层 * @returns 无 */ startDraw(layer: GraphicLayer): void; } /** * 贴地面积量算对象, * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class AreaSurfaceMeasure extends AreaMeasure { constructor(options: { style: PolygonEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 距离量算对象, * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class DistanceMeasure extends PolylineEntity { constructor(options: { style: PolylineEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 测量结果 */ readonly measured: any; /** * 更新测量结果的文本 * @param unit - 计量单位,{@link MeasureUtil#formatDistance} 可选值:auto、m、km、mile、zhang 等。auto时根据距离值自动选用k或km * @returns 无 */ updateText(unit: string): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 贴地距离量算对象 * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class DistanceSurfaceMeasure extends DistanceMeasure { constructor(options: { style: PolylineEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 高度量算对象, * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class HeightMeasure extends PolylineEntity { constructor(options: { style: PolylineEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 测量结果 */ readonly measured: any; /** * 更新测量结果的文本 * @param unit - 计量单位,{@link MeasureUtil#formatDistance} 可选值:auto、m、km、mile、zhang 等。auto时根据距离值自动选用k或km * @returns 无 */ updateText(unit: string): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 三角高度量算对象, * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class HeightTriangleMeasure extends HeightMeasure { constructor(options: { style: PolylineEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 更新测量结果的文本 * @param unit - 计量单位,{@link MeasureUtil#formatDistance} 可选值:auto、m、km、mile、zhang 等。auto时根据距离值自动选用k或km * @returns 无 */ updateText(unit: string): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 坐标量算对象, * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class PointMeasure extends PointEntity { constructor(options: { style: PointEntity.StyleOptions; attr?: any; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 剖面量算对象 * 非直接调用,由 Measure 类统一创建及管理 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.label] - 测量结果文本的样式 */ declare class SectionMeasure extends DistanceMeasure { constructor(options: { style: PolylineEntity.StyleOptions; attr?: any; label?: LabelEntity.StyleOptions; }); /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 体积量算对象(方量), * 非直接调用,由 Measure 类统一创建及管理。<br /> * * 1. 挖方量: 计算“基准面”到地表之间的凸出部分进行挖掉的体积。<br /> * 2. 填方量:计算“基准面”与“墙底部”之间的缺少部分进行填平的体积。 * @param options - 参数对象,包括以下: * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.polygonWallStyle] - 围墙面的样式 * @param [options.label] - 测量结果文本的样式 * @param [options.heightLabel = true] - 是否显示各边界点高度值文本 * @param [options.offsetLabel = false] - 是否显示各边界点高度差文本 * @param [options.labelHeight] - 各边界点高度结果文本的样式 */ declare class VolumeMeasure extends AreaMeasure { constructor(options: { style: PolygonEntity.StyleOptions; attr?: any; polygonWallStyle?: PolygonEntity.StyleOptions; label?: LabelEntity.StyleOptions; heightLabel?: boolean; offsetLabel?: boolean; labelHeight?: LabelEntity.StyleOptions; }); /** * 面内的最高地表高度 */ readonly polygonMaxHeight: number; /** * 基准面 高度, * 1. 挖方量: 计算“基准面”到地表之间的凸出部分进行挖掉的体积。<br /> * 2. 填方量:计算“基准面”与“墙底部”之间的缺少部分进行填平的体积。 */ height: number; /** * 底部高度, * 会影响 填方量:计算“基准面高度”与“底部高度”之间的缺少部分进行填平的体积。 */ minHeight: number; /** * 最高高度,对应墙的高度, * 不影响测量结果,只是显示效果的区别。 */ maxHeight: number; /** * 更新测量结果的文本 * @param unit - 计量单位,{@link MeasureUtil#formatArea} 可选值:计量单位,可选值:auto、m、km、mu、ha 。auto时根据面积值自动选用m或km * @returns 无 */ updateText(unit: string): void; /** * 通过鼠标拾取高度,赋值给基准面 * @param callback - 拾取完成后的回调方法 * @returns 无 */ selecteHeight(callback: (...params: any[]) => any): void; /** * 通过标绘 来创建矢量对象 * @param layer - 图层 * @param options - 矢量对象的构造参数 * @returns 矢量对象 */ static fromDraw(layer: GraphicLayer, options: any): PolylineEntity; } /** * 单个坐标的点状 Primitive图元 矢量对象 基类 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.position - 坐标位置 * @param [options.modelMatrix] - 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵,可以替代position。 */ declare class BasePointPrimitive extends BasePrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; modelMatrix?: Cesium.Matrix4; }); /** * 位置坐标 (笛卡尔坐标), 赋值时可以传入LatLngPoint对象 */ position: Cesium.Cartesian3; /** * 位置坐标 */ readonly point: LatLngPoint; /** * 位置坐标(数组对象),示例[113.123456,31.123456,30.1] */ readonly coordinate: any[]; /** * 中心点坐标 (笛卡尔坐标) */ readonly center: Cesium.Cartesian3; /** * 中心点坐标 */ readonly centerPoint: LatLngPoint; /** * 坐标对应的高度值(单位:米) */ height: number; /** * 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵。 */ readonly modelMatrix: Cesium.Matrix4; /** * 四周方向角,0-360度角度值 */ heading: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右搬动的角度,0-360度角度值 */ roll: number; /** * 设置并添加动画轨迹位置,按“指定时间”运动到达“指定位置”。 * @param point - 指定位置坐标 * @param [currTime = Cesium.JulianDate.now()] - 指定时间, 默认为当前时间5秒后。当为String时,可以传入'2021-01-01 12:13:00'; 当为Number时,可以传入当前时间延迟的秒数。 * @returns 当前对象本身,可以链式调用 */ addDynamicPosition(point: LatLngPoint | Cesium.Cartesian3, currTime?: Cesium.JulianDate | string | number): this; /** * 异步计算更新坐标进行贴地(或贴模型) * @param [options = {}] - 参数对象: * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 当前对象本身,可以链式调用 */ clampToGround(options?: { has3dtiles?: boolean; objectsToExclude?: object[]; callback: getSurfaceHeight_callback; }): this; /** * 位置坐标(数组对象),示例[113.123456,31.123456,30.1] * @param noAlt - true时不导出高度值 * @returns 位置坐标(数组对象) */ getCoordinate(noAlt: boolean): any[]; } /** * 多个坐标的线面状 Primitive图元 矢量对象 基类 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.positions - 坐标位置 */ declare class BasePolyPrimitive extends BasePrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; }); /** * 中心点坐标 (笛卡尔坐标) */ readonly center: Cesium.Cartesian3; /** * 围合面的内部中心点坐标 */ readonly centerOfMass: Cesium.Cartesian3; /** * 边线的中心点坐标 */ readonly centerOfLine: Cesium.Cartesian3; /** * 距离(单位:米) */ readonly distance: number; /** * 面积(单位:平方米) */ readonly area: number; /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; /** * 位置坐标数组 */ readonly points: LatLngPoint[]; /** * 位置坐标(数组对象),示例 [ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] */ readonly coordinates: any[][]; /** * 坐标数据对应的矩形边界 */ readonly rectangle: Cesium.Rectangle; /** * 位置坐标(数组对象),示例 [ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] * @param noAlt - true时不导出高度值 * @returns 位置坐标(数组对象) */ getCoordinates(noAlt: boolean): any[][]; /** * 判断点是否在当前对象的坐标点围成的多边形内 * @param position - 需要判断的点 * @returns 是否在多边形内 */ isInPoly(position: Cesium.Cartesian3 | LatLngPoint): boolean; /** * 异步计算更新坐标进行贴地(或贴模型) * @param [options = {}] - 参数对象: * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param [options.offset = 0] - 可以按需增加偏移高度(单位:米),便于可视 * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 当前对象本身,可以链式调用 */ clampToGround(options?: { has3dtiles?: boolean; objectsToExclude?: object[]; offset?: number; callback: surfaceLineWork_callback; }): this; } declare namespace BasePrimitive { /** * Primitive 通用参数(不含Billboard、Label、Point、Model、Polyline) * @property [appearance] - [cesium原生]用于渲染图元的外观。 * @property [attributes] - [cesium原生]每个实例的属性。 * @property [depthFailAppearance] - 当深度测试失败时,用于为该图元着色的外观。 * @property [vertexCacheOptimize = false] - 当true,几何顶点优化前和后顶点着色缓存。 * @property [interleave = false] - 当true时,几何顶点属性被交叉,这可以略微提高渲染性能,但会增加加载时间。 * @property [compressVertices = true] - 当true时,几何顶点被压缩,这将节省内存。提升效率。 * @property [releaseGeometryInstances = true] - 当true时,图元不保留对输入geometryInstances的引用以节省内存。 * @property [allowPicking = true] - 当true时,每个几何图形实例只能通过{@link Scene#pick}进行挑选。当false时,保存GPU内存。 * @property [cull = true] - 当true时,渲染器会根据图元的边界体积来剔除它们的截锥和地平线。设置为false,如果你手动剔除图元,可以获得较小的性能提升。 * @property [asynchronous = true] - 确定该图元是异步创建还是阻塞创建,直到就绪。 * @property [debugShowBoundingVolume = false] - 仅供调试。确定该图元命令的边界球是否显示。 * @property [debugShowShadowVolume = false] - 仅供调试。贴地时,确定是否绘制了图元中每个几何图形的阴影体积。必须是true创建卷之前要释放几何图形或选项。releaseGeometryInstance必须是false。 */ type ConstructorOptions = { appearance?: Cesium.Appearance; attributes?: Cesium.Appearance; depthFailAppearance?: Appearance; vertexCacheOptimize?: boolean; interleave?: boolean; compressVertices?: boolean; releaseGeometryInstances?: boolean; allowPicking?: boolean; cull?: boolean; asynchronous?: boolean; debugShowBoundingVolume?: boolean; debugShowShadowVolume?: boolean; }; /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.click, function (event) { * console.log('单击了矢量数据对象', event) * }) * @property 通用 - 支持的父类的事件类型 * @property click - 左键单击 鼠标事件 * @property rightClick - 右键单击 鼠标事件 * @property mouseOver - 鼠标移入 鼠标事件 * @property mouseOut - 鼠标移出 鼠标事件 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 */ type EventType = { 通用: BaseGraphic.EventType; click: string; rightClick: string; mouseOver: string; mouseOut: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; }; } /** * Primitive图元 矢量对象 基类 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - Primitive通用参数 */ declare class BasePrimitive extends BaseGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; }); /** * 当加载primitive数据的内部Cesium容器 */ primitiveCollection: Cesium.PrimitiveCollection; /** * 矢量数据对应的 Cesium内部对象 */ readonly primitive: Cesium.Primitive; /** * 返回实例可修改的属性。{@link Cesium.GeometryInstance} * @example * var attributes = primitiveGraphic.geometryInstanceAttributes; * attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.AQUA); * attributes.show = Cesium.ShowGeometryInstanceAttribute.toValue(true); */ readonly geometryInstanceAttributes: any; /** * 对应材质的uniforms * 一个对象,它的属性被用来设置片段着色器shader。 * <p> * 对象属性值可以是常量或函数。这个函数将在每一帧后处理阶段执行之前被调用。 * </p> * <p> * 常量值也可以是图像的URI、数据URI,或者可以用作纹理的HTML元素,如HTMLImageElement或HTMLCanvasElement。 * </p> */ readonly uniforms: any | undefined; /** * 附加的label文本对象 */ readonly label: Cesium.Label; /** * 高亮对象。 * @param [highlightStyle] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @returns 无 */ openHighlight(highlightStyle?: any): void; /** * 清除已选中的高亮 * @returns 无 */ closeHighlight(): void; } declare namespace BillboardPrimitive { /** * 图标点 Primitive矢量数据 支持的样式信息 * @property [所有] - 与 BillboardEntity 相同 * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { 所有?: BillboardEntity.StyleOptions; highlight?: BillboardPrimitive.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 图标点 Primitive矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class BillboardPrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: BillboardPrimitive.StyleOptions; attr?: any; }); /** * 当加载primitive数据的内部Cesium容器 */ readonly primitiveCollection: Cesium.BillboardCollection; /** * 图像、URI或Canvas */ image: string | HTMLCanvasElement; } declare namespace BoxPrimitive { /** * 盒子 支持的样式信息 * @property [dimensions] - 指定盒子的长度、宽度和高度。 * @property [dimensions_x = 100] - 盒子长度 * @property [dimensions_y = 100] - 盒子宽度 * @property [dimensions_z = 100] - 盒子高度 * @property [heading = 0] - 方向角 (度数值,0-360度) * @property [pitch = 0] - 俯仰角(度数值,0-360度) * @property [roll = 0] - 翻滚角(度数值,0-360度) * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [materialSupport = MaterialAppearance.MaterialSupport.TEXTURED] - 将被支持的材质类型。 * * //以下是 这是MaterialAppearance的参数 * @property [flat = false] - 当true时,在片段着色器中使用平面着色,不考虑光照。 * @property [faceForward = !closed] - 当true时,片段着色器根据需要翻转表面的法线,以确保法线面向查看器以避免黑点。 * @property [translucent = true] - 当true时,几何图形将显示为半透明,因此{@link Cesium.PerInstanceColorAppearance#renderState}将启用alpha混合。 * @property [closed = false] - 当true时,几何图形将被关闭,因此{@link Cesium.PerInstanceColorAppearance#renderState}启用了背面剔除。 * @property [vertexShaderSource] - 可选的GLSL顶点着色器源,覆盖默认的顶点着色器。 * @property [fragmentShaderSource] - 可选的GLSL片段着色器源覆盖默认的片段着色器。 * @property [renderState] - 可选渲染状态,以覆盖默认渲染状态。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { dimensions?: Cesium.Cartesian3; dimensions_x?: number; dimensions_y?: number; dimensions_z?: number; heading?: number; pitch?: number; roll?: number; materialType?: string; material材质参数?: any; material?: Material; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; materialSupport?: MaterialAppearance.MaterialSupportType; flat?: boolean; faceForward?: boolean; translucent?: boolean; closed?: boolean; vertexShaderSource?: string; fragmentShaderSource?: string; renderState?: any; setHeight?: number; addHeight?: number; highlight?: BoxPrimitive.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 盒子 Primitive图元矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.modelMatrix] - 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵,可以替代position。 */ declare class BoxPrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: BoxPrimitive.StyleOptions; attr?: any; modelMatrix?: Cesium.Matrix4; }); } declare namespace CirclePrimitive { /** * 圆 支持的样式信息 * @property [radius = 100] - 半径 * @property [height = 0] - 高程,圆相对于椭球面的高度。 * @property [diffHeight = 100] - 高度差(圆柱本身的高度),与extrudedHeight二选一。 * @property [extrudedHeight] - 指定圆的挤压面相对于椭球面的高度。 * @property [stRotation = 0] - 椭圆纹理的角度(弧度值),正北为0,逆时针旋转 * @property [stRotationDegree = 0] - 椭圆纹理的角度(度数值,0-360度),与stRotation二选一 * @property [granularity = Cesium.Math.RADIANS_PER_DEGREE] - 指定椭圆上各点之间的角距离。 * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [materialSupport = Cesium.MaterialAppearance.MaterialSupport.TEXTURED] - 将被支持的材质类型。 * @property [clampToGround = false] - 是否贴地 * @property [classificationType = Cesium.ClassificationType.BOTH] - 指定贴地时的覆盖类型,是只对地形、3dtiles 或 两者同时。 * @property [classification = false] - 是否为ClassificationPrimitive ,分类基元 表示Scene要高亮显示的包围几何的体积 * * //以下是 这是MaterialAppearance的参数 * @property [flat = false] - 当true时,在片段着色器中使用平面着色,不考虑光照。 * @property [faceForward = !closed] - 当true时,片段着色器根据需要翻转表面的法线,以确保法线面向查看器以避免黑点。 * @property [translucent = true] - 当true时,几何图形将显示为半透明,因此{@link Cesium.PerInstanceColorAppearance#renderState}将启用alpha混合。 * @property [closed = false] - 当true时,几何图形将被关闭,因此{@link Cesium.PerInstanceColorAppearance#renderState}启用了背面剔除。 * @property [vertexShaderSource] - 可选的GLSL顶点着色器源,覆盖默认的顶点着色器。 * @property [fragmentShaderSource] - 可选的GLSL片段着色器源覆盖默认的片段着色器。 * @property [renderState] - 可选渲染状态,以覆盖默认渲染状态。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { radius?: number; height?: number; diffHeight?: number; extrudedHeight?: number; stRotation?: number; stRotationDegree?: number; granularity?: number; materialType?: string; material材质参数?: any; material?: Material; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; materialSupport?: Cesium.MaterialAppearance.MaterialSupportType; clampToGround?: string; classificationType?: Cesium.ClassificationType; classification?: boolean; flat?: boolean; faceForward?: boolean; translucent?: boolean; closed?: boolean; vertexShaderSource?: string; fragmentShaderSource?: string; renderState?: any; setHeight?: number; addHeight?: number; highlight?: CirclePrimitive.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 圆 Primitive图元矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.modelMatrix] - 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵,可以替代position。 */ declare class CirclePrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: CirclePrimitive.StyleOptions; attr?: any; modelMatrix?: Cesium.Matrix4; }); /** * 圆的半径(单位:米) */ radius: number; /** * 判断点是否在圆内 * @param position - 需要判断的点 * @returns 是否在圆内 */ isInPoly(position: Cesium.Cartesian3 | LatLngPoint): boolean; /** * 飞行定位至 数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.minHeight] - 定位时相机的最小高度值,用于控制避免异常数据 * @param [options.maxHeight] - 定位时相机的最大高度值,用于控制避免异常数据 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; minHeight?: number; maxHeight?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } declare namespace CorridorPrimitive { /** * 走廊 Primitive图元 支持的样式信息 * @property [width = 100] - 走廊宽度,指定走廊边缘之间的距离。 * @property [cornerType = "ROUNDED"] - 指定边角的样式。String可选项:ROUNDED (解释:圆滑),MITERED (解释:斜接),BEVELED (解释:斜切), * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [height = 0] - 高程,圆相对于椭球面的高度。 * @property [diffHeight = 100] - 高度差(走廊本身的高度),与extrudedHeight二选一。 * @property [extrudedHeight] - 指定走廊挤压面相对于椭球面的高度。 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定对象是投射还是接收来自光源的阴影。 * @property [clampToGround = false] - 是否贴地 * @property [classificationType = Cesium.ClassificationType.BOTH] - 指定贴地时的覆盖类型,是只对地形、3dtiles 或 两者同时。 * @property [classification = false] - 是否为ClassificationPrimitive ,分类基元 表示Scene要高亮显示的包围几何的体积 * * * //以下是 这是MaterialAppearance的参数 * @property [flat = false] - 当true时,在片段着色器中使用平面着色,不考虑光照。 * @property [faceForward = !closed] - 当true时,片段着色器根据需要翻转表面的法线,以确保法线面向查看器以避免黑点。 * @property [translucent = true] - 当true时,几何图形将显示为半透明,因此{@link Cesium.PerInstanceColorAppearance#renderState}将启用alpha混合。 * @property [closed = false] - 当true时,几何图形将被关闭,因此{@link Cesium.PerInstanceColorAppearance#renderState}启用了背面剔除。 * @property [vertexShaderSource] - 可选的GLSL顶点着色器源,覆盖默认的顶点着色器。 * @property [fragmentShaderSource] - 可选的GLSL片段着色器源覆盖默认的片段着色器。 * @property [renderState] - 可选渲染状态,以覆盖默认渲染状态。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [label] - 支持附带文字的显示 */ type StyleOptions = { width?: number; cornerType?: string | Cesium.CornerType; materialType?: string; material材质参数?: any; material?: Material; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; height?: number; diffHeight?: number; extrudedHeight?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; clampToGround?: boolean; classificationType?: Cesium.ClassificationType; classification?: boolean; flat?: boolean; faceForward?: boolean; translucent?: boolean; closed?: boolean; vertexShaderSource?: string; fragmentShaderSource?: string; renderState?: any; setHeight?: number; addHeight?: number; label?: LabelPrimitive.StyleOptions; }; } /** * 走廊 Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class CorridorPrimitive extends BasePolyPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: CorridorPrimitive.StyleOptions; attr?: any; }); } declare namespace FrustumPrimitive { /** * 四棱锥体 支持的样式信息 * @property [angle] - 四棱锥体张角(角度值,取值范围 0.01-89.99) * @property [angle2 = angle] - 四棱锥体张角2,(角度值,取值范围 0.01-89.99) * @property [length = 100] - 长度值(单位:米),没有指定targetPosition时有效 * @property [heading = 0] - 方向角 (度数值,0-360度),没有指定targetPosition时有效 * @property [pitch = 0] - 俯仰角(度数值,0-360度),没有指定targetPosition时有效 * @property [roll = 0] - 翻滚角(度数值,0-360度),没有指定targetPosition时有效 * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [materialSupport = MaterialAppearance.MaterialSupport.TEXTURED] - 将被支持的材质类型。 * @property [flat = false] - 当true时,在片段着色器中使用平面着色,不考虑光照。 * @property [faceForward = !closed] - 当true时,片段着色器根据需要翻转表面的法线,以确保法线面向查看器以避免黑点。 * @property [translucent = true] - 当true时,几何图形将显示为半透明,因此{@link Cesium.PerInstanceColorAppearance#renderState}将启用alpha混合。 * @property [closed = false] - 当true时,几何图形将被关闭,因此{@link Cesium.PerInstanceColorAppearance#renderState}启用了背面剔除。 * @property [vertexShaderSource] - 可选的GLSL顶点着色器源,覆盖默认的顶点着色器。 * @property [fragmentShaderSource] - 可选的GLSL片段着色器源覆盖默认的片段着色器。 * @property [renderState] - 可选渲染状态,以覆盖默认渲染状态。 * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { angle?: number; angle2?: number; length?: number; heading?: number; pitch?: number; roll?: number; materialType?: string; material材质参数?: any; material?: Material; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; materialSupport?: MaterialAppearance.MaterialSupportType; flat?: boolean; faceForward?: boolean; translucent?: boolean; closed?: boolean; vertexShaderSource?: string; fragmentShaderSource?: string; renderState?: any; highlight?: FrustumPrimitive.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 四棱锥体 Primitive图元矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.position - 坐标位置 * @param [options.targetPosition] - 追踪的目标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class FrustumPrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; targetPosition?: LatLngPoint | Cesium.Cartesian3; style: FrustumPrimitive.StyleOptions; attr?: any; }); /** * 圆锥追踪的目标(确定了方向和距离) */ targetPosition: Cesium.Cartesian3; /** * 圆锥追踪的目标位置坐标 */ readonly targetPoint: LatLngPoint; /** * 夹角,半场角度,取值范围 0.01-89.99 */ angle: number; /** * 夹角2,半场角度,取值范围 0.01-89.99 */ angle2: number; /** * 求当前位置射线与地球相交点 */ readonly groundPosition: Cesium.Cartesian3; /** * 获取射线向地面与地球的4个交点坐标 * @param [time = Cesium.JulianDate.now()] - 指定的时间值 * @returns 坐标数组 */ getRayEarthPositions(time?: Cesium.JulianDate): Cesium.Cartesian3[]; /** * 四周方向角,0-360度角度值 */ heading: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右搬动的角度,0-360度角度值 */ roll: number; } declare namespace LabelPrimitive { /** * 文字 支持的样式信息(与LabelEntity相同) * @property [所有] - 与LabelEntity相同 */ type StyleOptions = { 所有?: LabelEntity.StyleOptions; }; } /** * 文字 Primitive矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class LabelPrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: LabelPrimitive.StyleOptions; attr?: any; }); /** * 当加载primitive数据的内部Cesium容器 */ readonly primitiveCollection: Cesium.LabelCollection; /** * 文本内容 */ readonly text: string; } declare namespace LightCone { /** * 光锥体 支持的样式信息 * @property [color = '#00ffff'] - 颜色 * @property [radius = 100] - 锥体底部半径。(单位:米) * @property [height = 1000] - 锥体高度,相对于椭球面的高度。(单位:米) */ type StyleOptions = { color?: string | Cesium.Color; radius?: number; height?: number; }; } /** * 光锥体 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class LightCone extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: LightCone.StyleOptions; attr?: any; }); /** * 颜色 */ color: Cesium.Color; } declare namespace ModelPrimitive { /** * gltf小模型 支持的样式信息 * @property [url] - glTF模型的URI的字符串或资源属性。 * @property [scale = 1] - 整体缩放比例 * @property [scaleX = 1] - X轴方向缩放比例 * @property [scaleY = 1] - Y轴方向缩放比例 * @property [scaleZ = 1] - Z轴方向缩放比例 * @property [heading = 0] - 方向角 (度数值,0-360度) * @property [pitch = 0] - 俯仰角(度数值,0-360度) * @property [roll = 0] - 翻滚角(度数值,0-360度) * @property [minimumPixelSize = 0.0] - 指定模型的近似最小像素大小,而不考虑缩放。 * @property [maximumScale] - 模型的最大比例尺寸。minimumPixelSize的上限。 * @property [fill = false] - 是否填充,指定与模型渲染颜色混合 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [colorBlendMode = ColorBlendMode.HIGHLIGHT] - 指定颜色如何与模型混合。 * @property [colorBlendAmount = 0.5] - 当colorBlendMode为MIX时指定颜色强度的数字属性。0.0的值表示模型渲染的颜色,1.0的值表示纯色,任何介于两者之间的值表示两者的混合。 * @property [silhouette = false] - 是否轮廓 * @property [silhouetteColor = "#ffffff"] - 轮廓颜色 * @property [silhouetteSize = 2] - 轮廓宽度 * @property [silhouetteAlpha = 0.8] - 轮廓透明度 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayPoint] - 当视角距离超过一定距离后(distanceDisplayCondition_far定义的) 后显示为 像素点 对象的样式,仅在distanceDisplayCondition设置时有效。 * @property [distanceDisplayBillboard] - 当视角距离超过一定距离后(distanceDisplayCondition_far定义的) 后显示为 图标 对象的样式,仅在distanceDisplayCondition设置时有效。 * @property [hasShadows = true] - 是否阴影 * @property [shadows = ShadowMode.ENABLED] - 指定模型是投射还是接收来自光源的阴影。 * @property [clampToGround = false] - 是否贴地 * @property [heightReference = Cesium.HeightReference.NONE] - 指定高度相对于什么的属性。 * @property [incrementallyLoadTextures = true] - 确定模型加载后纹理是否会继续流进来。 * @property [runAnimations = true] - 指定模型中指定的glTF动画是否应该启动。 * @property [clampAnimations = true] - 指定在没有关键帧的情况下,glTF动画是否应该保持最后一个姿势。 * @property [imageBasedLightingFactor = new Cartesian2(1.0, 1.0)] - 指定来自基于图像的漫反射和镜面照明的贡献。 * @property [lightColor] - 在为模型着色时指定光的颜色的属性。当undefined场景的浅色被使用代替。 * @property [nodeTransformations] - 一个对象,其中键是节点的名称,值是{@link TranslationRotationScale}属性,描述要应用到该节点的转换。该转换是在节点的现有转换之后(如glTF中指定的那样)应用的,并且不会替换节点的现有转换。 * @property [articulations] - An object, where keys are composed of an articulation name, a single space, and a stage name, and the values are numeric properties. * @property [clippingPlanes] - 用于裁剪模型的Plane平面集合 * @property [allowPicking = true] - 当true时,每个glTF和Primitive都可以用{@link Cesium.Scene#pick}来拾取。 * @property [asynchronous = true] - 确定模型WebGL资源创建是否将分散在几个帧或块上,直到所有glTF文件加载完成。 * @property [dequantizeInShader = true] - 确定一个{@link https://github.com/google/draco|Draco}编码的模型是否在GPU上被去量化。这减少了编码模型的总内存使用量。 * @property [backFaceCulling = true] - 是否剔除面向背面的几何图形。当为真时,背面剔除是由材料的双面属性决定的;当为false时,禁用背面剔除。如果{@link Model#color}是半透明的,或者{@link Model#silhouette}大于0.0,则背面不会被剔除。 * @property [debugShowBoundingVolume = false] - 仅供调试。查看模型的包围边界球。 * @property [debugWireframe = false] - 仅供调试。查看模型的三角网线框图。 * * //以下是 以下是 模型动画相关 * @property [startTime] - 场景时间开始播放动画。当undefined时,动画从下一帧开始。 * @property [delay = 0.0] - 从startTime开始播放的延迟,以秒为单位。 * @property [stopTime] - 场景时间停止播放动画。当这是undefined,动画播放它的整个持续时间。 * @property [removeOnStop = false] - 当true时,动画在停止播放后被删除。 * @property [multiplier = 1.0] - 大于1.0的值增加动画播放的速度相对于场景时钟的速度;小于1.0会降低速度。 * @property [reverse = false] - 当true时,动画会反向播放。 * @property [loop = Cesium.ModelAnimationLoop.REPEAT] - 决定动画是否循环以及如何循环。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { url?: string | Cesium.Resource; scale?: number; scaleX?: number; scaleY?: number; scaleZ?: number; heading?: number; pitch?: number; roll?: number; minimumPixelSize?: number; maximumScale?: number; fill?: boolean; color?: string | Cesium.Color; opacity?: number; colorBlendMode?: Cesium.ColorBlendMode; colorBlendAmount?: number; silhouette?: boolean; silhouetteColor?: string | Cesium.Color; silhouetteSize?: number; silhouetteAlpha?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_near?: number; distanceDisplayCondition_far?: number; distanceDisplayPoint?: PointEntity.StyleOptions; distanceDisplayBillboard?: BillboardEntity.StyleOptions; hasShadows?: boolean; shadows?: Cesium.ShadowMode; clampToGround?: boolean; heightReference?: Cesium.HeightReference; incrementallyLoadTextures?: boolean; runAnimations?: boolean; clampAnimations?: boolean; imageBasedLightingFactor?: Cesium.Cartesian2; lightColor?: Color; nodeTransformations?: Cesium.PropertyBag | { [key: string]: Cesium.TranslationRotationScale; }; articulations?: Cesium.PropertyBag | { [key: string]: number; }; clippingPlanes?: Cesium.ClippingPlaneCollection; allowPicking?: boolean; asynchronous?: boolean; dequantizeInShader?: boolean; backFaceCulling?: boolean; debugShowBoundingVolume?: boolean; debugWireframe?: boolean; startTime?: Cesium.JulianDate; delay?: number; stopTime?: JulianDate; removeOnStop?: boolean; multiplier?: number; reverse?: boolean; loop?: Cesium.ModelAnimationLoop; setHeight?: number; addHeight?: number; highlight?: ModelPrimitive.StyleOptions; label?: LabelEntity.StyleOptions; }; /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.load, function (event) { * console.log('模型加载完成', event) * }) * @property 通用 - 支持的父类的事件类型 * @property load - 完成加载,执行所有内部处理后 */ type EventType = { 通用: BasePrimitive.EventType; load: string; }; } /** * gltf小模型 Primitive图元矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.modelMatrix] - 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵,可以替代position。 * @param [options.appearance] - [cesium原生]用于渲染图元的外观。 * @param [options.attributes] - [cesium原生]每个实例的属性。 */ declare class ModelPrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: ModelPrimitive.StyleOptions; attr?: any; modelMatrix?: Cesium.Matrix4; appearance?: Cesium.Appearance; attributes?: Cesium.Appearance; }); /** * 模型整体的缩放比例 */ scale: number; /** * X轴方向缩放比例 */ scaleX: number; /** * Y轴方向缩放比例 */ scaleY: number; /** * Z轴方向缩放比例 */ scaleZ: number; /** * 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵。 */ readonly modelMatrix: Cesium.Matrix4; } declare namespace PlanePrimitive { /** * 平面 支持的样式信息 * @property [dimensions] - 指定平面的宽度和高度。 * @property [dimensions_x = 100] - 长度 * @property [dimensions_y = 100] - 宽度 * @property [plane_normal = "z"] - 方向 ,可选项:x (解释:X轴),y (解释:Y轴),z (解释:Z轴), * @property [heading = 0] - 方向角 (度数值,0-360度) * @property [pitch = 0] - 俯仰角(度数值,0-360度) * @property [roll = 0] - 翻滚角(度数值,0-360度) * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [materialSupport = MaterialAppearance.MaterialSupport.TEXTURED] - 将被支持的材质类型。 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * * //以下是 这是MaterialAppearance的参数 * @property [flat = false] - 当true时,在片段着色器中使用平面着色,不考虑光照。 * @property [faceForward = !closed] - 当true时,片段着色器根据需要翻转表面的法线,以确保法线面向查看器以避免黑点。 * @property [translucent = true] - 当true时,几何图形将显示为半透明,因此{@link Cesium.PerInstanceColorAppearance#renderState}将启用alpha混合。 * @property [closed = false] - 当true时,几何图形将被关闭,因此{@link Cesium.PerInstanceColorAppearance#renderState}启用了背面剔除。 * @property [vertexShaderSource] - 可选的GLSL顶点着色器源,覆盖默认的顶点着色器。 * @property [fragmentShaderSource] - 可选的GLSL片段着色器源覆盖默认的片段着色器。 * @property [renderState] - 可选渲染状态,以覆盖默认渲染状态。 * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 */ type StyleOptions = { dimensions?: Cesium.Cartesian2; dimensions_x?: number; dimensions_y?: number; plane_normal?: string; heading?: number; pitch?: number; roll?: number; color?: string | Cesium.Color; opacity?: number; materialType?: string; material材质参数?: any; material?: Material; materialSupport?: MaterialAppearance.MaterialSupportType; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; flat?: boolean; faceForward?: boolean; translucent?: boolean; closed?: boolean; vertexShaderSource?: string; fragmentShaderSource?: string; renderState?: any; highlight?: PlanePrimitive.StyleOptions; label?: LabelEntity.StyleOptions; }; } /** * 平面 Primitive图元矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.modelMatrix] - 将图元(所有几何实例)从模型转换为世界坐标的4x4变换矩阵,可以替代position。 */ declare class PlanePrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: PlanePrimitive.StyleOptions; attr?: any; modelMatrix?: Cesium.Matrix4; }); /** * 用于指定位置的矩阵 */ readonly modelMatrix: Cesium.Matrix4; } declare namespace PointPrimitive { /** * 像素点 支持的样式信息 * @property [pixelSize = 10] - 像素大小 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [outlineWidth = 2] - 边框宽度 * @property [scaleByDistance = false] - 是否按视距缩放 或 指定用于基于距离缩放点。 * @property [scaleByDistance_far = 1000000] - 上限 * @property [scaleByDistance_farValue = 0.1] - 比例值 * @property [scaleByDistance_near = 1000] - 下限 * @property [scaleByDistance_nearValue = 1] - 比例值 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 10000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [visibleDepth = true] - 是否被遮挡 * @property [disableDepthTestDistance] - 指定从相机到禁用深度测试的距离。 * @property [translucencyByDistance] - 用于基于与相机的距离设置半透明度。 * @property [setHeight = 0] - 指定坐标高度值(常用于图层中配置) * @property [addHeight = 0] - 在现有坐标基础上增加的高度值(常用于图层中配置) * @property [label] - 支持附带文字的显示 */ type StyleOptions = { pixelSize?: number; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; outlineWidth?: number; scaleByDistance?: boolean | Cesium.NearFarScalar; scaleByDistance_far?: number; scaleByDistance_farValue?: number; scaleByDistance_near?: number; scaleByDistance_nearValue?: number; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; visibleDepth?: boolean; disableDepthTestDistance?: number; translucencyByDistance?: Cesium.NearFarScalar; setHeight?: number; addHeight?: number; label?: LabelPrimitive.StyleOptions; }; } /** * 像素点 Primitive矢量数据 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.frameRate = 1] - 当postion为CallbackProperty时,多少帧获取一次数据。用于控制效率,如果卡顿就把该数值调大一些。 */ declare class PointPrimitive extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: PointPrimitive.StyleOptions; attr?: any; frameRate?: number; }); /** * 当加载primitive数据的内部Cesium容器 */ readonly primitiveCollection: Cesium.PointPrimitiveCollection; } declare namespace PolygonPrimitive { /** * 面 Primitive图元 支持的样式信息 * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [randomColor = false] - 是否随机颜色 * @property [image] - 当为贴图时,贴图的url * @property [stRotation = 0] - 多边形纹理的角度(弧度值),正北为0,逆时针旋转 * @property [stRotationDegree = 0] - 多边形纹理的角度(度数值,0-360度),与stRotation二选一 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [height = 0] - 高程,圆相对于椭球面的高度。 * @property [diffHeight = 100] - 高度差(走廊本身的高度),与extrudedHeight二选一。 * @property [extrudedHeight] - 指定走廊挤压面相对于椭球面的高度。 * @property [granularity = Cesium.Math.RADIANS_PER_DEGREE] - 指定每个纬度点和经度点之间的角距离。 * @property [closeTop = true] - 当为false时,离开一个挤压多边形的顶部打开。 * @property [closeBottom = true] - 当为false时,离开挤压多边形的底部打开。 * @property [arcType = Cesium.ArcType.GEODESIC] - 多边形的边缘必须遵循的线条类型。 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定对象是投射还是接收来自光源的阴影。 * @property [clampToGround = false] - 是否贴地 * @property [classificationType = Cesium.ClassificationType.BOTH] - 指定贴地时的覆盖类型,是只对地形、3dtiles 或 两者同时。 * @property [classification = false] - 是否为ClassificationPrimitive ,分类基元 表示Scene要高亮显示的包围几何的体积 * * //以下是 这是MaterialAppearance的参数 * @property [flat = false] - 当true时,在片段着色器中使用平面着色,不考虑光照。 * @property [faceForward = !closed] - 当true时,片段着色器根据需要翻转表面的法线,以确保法线面向查看器以避免黑点。 * @property [translucent = true] - 当true时,几何图形将显示为半透明,因此{@link Cesium.PerInstanceColorAppearance#renderState}将启用alpha混合。 * @property [closed = false] - 当true时,几何图形将被关闭,因此{@link Cesium.PerInstanceColorAppearance#renderState}启用了背面剔除。 * @property [vertexShaderSource] - 可选的GLSL顶点着色器源,覆盖默认的顶点着色器。 * @property [fragmentShaderSource] - 可选的GLSL片段着色器源覆盖默认的片段着色器。 * @property [renderState] - 可选渲染状态,以覆盖默认渲染状态。 * @property [buffer] - 对坐标进行缓冲扩大buffer指定的半径范围,单位:米。如用于单体化建筑物扩大点方便鼠标拾取。 * @property [setHeight] - 指定坐标高度值,或数组指定每个点的高度(常用于图层中配置) * @property [addHeight] - 在现有坐标基础上增加的高度值,或数组指定每个点增加的高度(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 ,额外支持: * @property [label.position] - 文字所在位置,默认是矢量对象本身的center属性值。支持配置 'center':围合面的内部中心点坐标,'{xxxx}'配置属性字段, 或者直接指定坐标值。 * @property [label.showAll] - MultiPolygon和MultiLineString时,是否显示所有注记,默认只在最大坐标数的面或线上显示。 */ type StyleOptions = { materialType?: string; material材质参数?: any; material?: Material; color?: string | Cesium.Color; opacity?: number; randomColor?: boolean; image?: string; stRotation?: number; stRotationDegree?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; height?: number; diffHeight?: number; extrudedHeight?: number; granularity?: number; closeTop?: boolean | boolean; closeBottom?: boolean | boolean; arcType?: Cesium.ArcType; hasShadows?: boolean; shadows?: Cesium.ShadowMode; clampToGround?: boolean; classificationType?: Cesium.ClassificationType; classification?: boolean; flat?: boolean; faceForward?: boolean; translucent?: boolean; closed?: boolean; vertexShaderSource?: string; fragmentShaderSource?: string; renderState?: any; buffer?: number; setHeight?: number | Number[]; addHeight?: number | Number[]; highlight?: PolygonPrimitive.StyleOptions; label?: { position?: string | LatLngPoint; showAll?: boolean; }; }; } /** * 面 Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class PolygonPrimitive extends BasePolyPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: PolygonPrimitive.StyleOptions; attr?: any; }); /** * 位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[]; /** * 中心点坐标 (笛卡尔坐标) */ readonly center: Cesium.Cartesian3; } declare namespace PolylinePrimitive { /** * 线 Primitive图元 支持的样式信息 * @property [width = 4] - 线宽 * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [randomColor = false] - 是否随机颜色 * @property [closure = false] - 是否闭合 * @property [distanceDisplayCondition = false] - 是否按视距显示 或 指定此框将显示在与摄像机的多大距离。 * @property [distanceDisplayCondition_far = 100000] - 最大距离 * @property [distanceDisplayCondition_near = 0] - 最小距离 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定对象是投射还是接收来自光源的阴影。 * @property [clampToGround = false] - 是否贴地 * @property [classificationType = Cesium.ClassificationType.BOTH] - 指定贴地时的覆盖类型,是只对地形、3dtiles 或 两者同时。 * @property [setHeight] - 指定坐标高度值,或数组指定每个点的高度(常用于图层中配置) * @property [addHeight] - 在现有坐标基础上增加的高度值,或数组指定每个点增加的高度(常用于图层中配置) * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 ,额外支持: * @property [label.position] - 文字所在位置,默认是矢量对象本身的center属性值。支持配置 'center':围合面的内部中心点坐标,'{xxxx}'配置属性字段, 或者直接指定坐标值。 * @property [label.showAll] - MultiPolygon和MultiLineString时,是否显示所有注记,默认只在最大坐标数的面或线上显示。 */ type StyleOptions = { width?: number; materialType?: string; material材质参数?: any; material?: Material; color?: string | Cesium.Color; opacity?: number; randomColor?: boolean; closure?: boolean; distanceDisplayCondition?: boolean | Cesium.DistanceDisplayCondition; distanceDisplayCondition_far?: number; distanceDisplayCondition_near?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; clampToGround?: boolean; classificationType?: Cesium.ClassificationType; setHeight?: number | Number[]; addHeight?: number | Number[]; highlight?: PolylineSimplePrimitive.StyleOptions; label?: { position?: string | LatLngPoint; showAll?: boolean; }; }; } /** * 线 Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class PolylinePrimitive extends BasePolyPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: PolylinePrimitive.StyleOptions; attr?: any; }); /** * 当加载primitive数据的内部Cesium容器 */ primitiveCollection: Cesium.PrimitiveCollection; } /** * 简单线 Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class PolylineSimplePrimitive extends BasePolyPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: PolylinePrimitive.StyleOptions; attr?: any; }); } declare namespace Road { /** * 道路 支持的样式信息 * @property image - 图片材质URL * @property [width = 20] - 道路 宽度。(单位:米) * @property [height = 0] - 道路 高度,相对于椭球面的高度。(单位:米) * @property [axisY = true] - 是否uv交换(图片横竖切换) */ type StyleOptions = { image: string; width?: number; height?: number; axisY?: boolean; }; } /** * 道路 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class Road extends DynamicRiver { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: Road.StyleOptions; attr?: any; }); } declare namespace WallPrimitive { /** * 墙 Primitive图元 支持的样式信息 * @property [diffHeight = 100] - 墙高 * @property [materialType = "Color"] - 填充材质类型 ,可选项:{@link MaterialType} * @property [material材质参数] - 根据具体{@link MaterialType}来确定 * @property [material] - 指定用于填充的材质,指定material后`materialType`和`material材质参数`将被覆盖。 * @property [color = "#3388ff"] - 颜色 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0 * @property [outline = false] - 是否边框 * @property [outlineColor = "#ffffff"] - 边框颜色 * @property [outlineOpacity = 0.6] - 边框透明度 * @property [hasShadows = false] - 是否阴影 * @property [shadows = Cesium.ShadowMode.DISABLED] - 指定折线是投射还是接收来自光源的阴影。 * * //以下是 这是MaterialAppearance的参数 * @property [flat = false] - 当true时,在片段着色器中使用平面着色,不考虑光照。 * @property [faceForward = !closed] - 当true时,片段着色器根据需要翻转表面的法线,以确保法线面向查看器以避免黑点。 * @property [translucent = true] - 当true时,几何图形将显示为半透明,因此{@link Cesium.PerInstanceColorAppearance#renderState}将启用alpha混合。 * @property [closed = false] - 当true时,几何图形将被关闭,因此{@link Cesium.PerInstanceColorAppearance#renderState}启用了背面剔除。 * @property [vertexShaderSource] - 可选的GLSL顶点着色器源,覆盖默认的顶点着色器。 * @property [fragmentShaderSource] - 可选的GLSL片段着色器源覆盖默认的片段着色器。 * @property [renderState] - 可选渲染状态,以覆盖默认渲染状态。 * @property [highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式,创建Graphic后也可以openHighlight、closeHighlight方法来手动调用 * @property [label] - 支持附带文字的显示 ,额外支持: * @property [label.position] - 文字所在位置,默认是矢量对象本身的center属性值。支持配置 'center':围合面的内部中心点坐标,'{xxxx}'配置属性字段, 或者直接指定坐标值。 * @property [label.showAll] - MultiPolygon和MultiLineString时,是否显示所有注记,默认只在最大坐标数的面或线上显示。 */ type StyleOptions = { diffHeight?: number; materialType?: string; material材质参数?: any; material?: Material; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; outlineOpacity?: number; hasShadows?: boolean; shadows?: Cesium.ShadowMode; flat?: boolean; faceForward?: boolean; translucent?: boolean; closed?: boolean; vertexShaderSource?: string; fragmentShaderSource?: string; renderState?: any; highlight?: WallPrimitive.StyleOptions; label?: { position?: string | LatLngPoint; showAll?: boolean; }; }; } /** * 墙 Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class WallPrimitive extends BasePolyPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: WallPrimitive.StyleOptions; attr?: any; }); } declare namespace Water { /** * 水面 Primitive图元 支持的样式信息 * @property [baseWaterColor = "#123e59"] - 基础颜色 * @property [blendColor = "#123e59"] - 从水中混合到非水域时使用的rgba颜色对象。 * @property [specularMap] - 单一通道纹理用来指示水域的面积。 * @property [normalMap] - 水正常扰动的法线图。 * @property [frequency = 8000] - 控制波数的数字。 * @property [animationSpeed = 0.03] - 控制水的动画速度的数字。 * @property [amplitude = 5.0] - 控制水波振幅的数字。 * @property [specularIntensity = 0.8] - 控制镜面反射强度的数字。 * @property [fadeFactor = 1.0] - fadeFactor * @property [opacity = 0.8] - 透明度,取值范围:0.0-1.0 * @property [clampToGround = false] - 是否贴地 * @property [options.父类参数] - 支持父类的参数 */ type StyleOptions = { baseWaterColor?: string; blendColor?: string; specularMap?: string; normalMap?: string; frequency?: number; animationSpeed?: number; amplitude?: number; specularIntensity?: number; fadeFactor?: number; opacity?: number; clampToGround?: boolean; }; } /** * 水域面 Primitive图元 矢量对象 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.通用参数P] - 支持所有Primitive通用参数 * @param options.positions - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class Water extends PolygonPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; 通用参数P?: BasePrimitive.ConstructorOptions; positions: LatLngPoint[] | Cesium.Cartesian3[]; style: Water.StyleOptions; attr?: any; }); } declare namespace BaseRoamLine { /** * wall 类型shading 支持的参数, * 效果是飞机飞行轨迹线下的投射墙体效果。 * @property [type = 'wall'] - 类型 * @property [通用参数] - wall墙体对象支持的所有参数 * @property [maxDistance] - 设置保留的轨迹长度值(单位:米),不设置时保留所有的轨迹 */ type WallShadingOptions = { type?: string; 通用参数?: WallEntity.StyleOptions; maxDistance?: number; }; /** * cylinder 类型shading 支持的参数, * 效果是飞机飞行时的圆锥体投射效果。 * @property [type = 'cylinder'] - 类型 * @property [通用参数] - 圆锥对象支持的所有参数 */ type CylinderShadingOptions = { type?: string; 通用参数?: CylinderEntity.StyleOptions; }; /** * circle 类型shading 支持的参数, * 比如步行时的人员所在位置的扩散圆圈效果 * @property [type = 'circle'] - 类型 * @property [通用参数] - 圆锥对象支持的所有参数 */ type CircleShadingOptions = { type?: string; 通用参数?: CircleEntity.StyleOptions; }; /** * polyline 类型shading 支持的参数, * 【历史】走过的轨迹线,可以替代本身的path来设置贴地线的效果 * @property [type = 'polyline'] - 类型 * @property [通用参数] - 线对象支持的所有参数 * @property [maxDistance] - 设置保留的轨迹长度值(单位:米),不设置时保留所有的轨迹 */ type PolylineShadingOptions = { type?: string; 通用参数?: PolylineEntity.StyleOptions; maxDistance?: number; }; /** * polylineGoing 类型shading 支持的参数, * 【将来】将要走的轨迹线,可以替代本身的path来设置贴地线的效果 * @property [type = 'polylineGoing'] - 类型 * @property [通用参数] - 线对象支持的所有参数 */ type PolylineGoingShadingOptions = { type?: string; 通用参数?: PolylineEntity.StyleOptions; }; } /** * 漫游路线管理类 基类 */ declare class BaseRoamLine extends BaseGraphic { /** * 动态时序坐标位置, * Cesium原生动态属性对象 */ readonly property: Cesium.SampledPositionProperty; /** * 加载Entity数据的内部Cesium容器 */ readonly dataSource: Cesium.CustomDataSource; /** * 当前时间对应的坐标位置 (笛卡尔坐标) */ readonly position: Cesium.Cartesian3; /** * 贴模型分析时,排除的不进行贴模型计算的模型对象,默认是当前本身,可以是: primitives, entities 等 */ readonly objectsToExclude: object[] | undefined; /** * 中心点坐标(笛卡尔坐标),popup/tooltip等功能会使用 */ readonly center: Cesium.SampledPositionProperty; /** * 已经飞行过的点的 index */ readonly indexForFlyOK: Int; /** * 获取三维空间中的旋转。 */ readonly orientation: Cesium.Quaternion; /** * 获取当前hpr角度。 */ readonly hpr: Cesium.HeadingPitchRoll; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly matrix: Cesium.Matrix4; /** * 四周方向角,弧度值 */ readonly headingRadians: number; /** * 四周方向角,0-360度角度值 */ readonly heading: number; /** * 俯仰角,上下摇摆的角度,弧度值 */ readonly pitchRadians: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右摆动的角度,弧度值 */ readonly rollRadians: number; /** * 滚转角,左右摆动的角度,0-360度角度值 */ roll: number; /** * 求当前位置射线与地球相交点 */ readonly groundPosition: Cesium.Cartesian3; /** * 倍速 */ multiplier: number; /** * 是否暂停状态 */ isPause: boolean; /** * 获取当前矩阵 * @param offest - 偏移值 * @param offest.x - X轴方向偏移值,单位:米 * @param offest.y - Y轴方向偏移值,单位:米 * @param offest.z - Z轴方向偏移值,单位:米 * @returns 当前矩阵 */ computeModelMatrix(offest: { x: number; y: number; z: number; }): Cesium.Matrix4; /** * 更新角度 * @param isAuto - 是否基于轨迹自动计算角度 * @param [opts] - isAuto为false时,赋值的新角度值 * @param [opts.pitch] - 俯仰角,上下摇摆的角度,0-360度角度值 * @param [opts.roll] - 滚转角,左右摆动的角度,0-360度角度值 * @returns 无 */ updateAngle(isAuto: boolean, opts?: { pitch?: number; roll?: number; }): void; /** * 更新视角模式 * @param cameraOptions - 参数,包括: * @param cameraOptions.type - 视角模式类型,包括:'':无、'gs':跟随视角、'dy':第一视角、'sd':上帝视角 * @param [cameraOptions.radius] - 'gs'跟随视角时的 初始俯仰距离值(单位:米) * @param [cameraOptions.heading] - 'gs'跟随视角时的 初始方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param [cameraOptions.pitch] - 'gs'跟随视角时的 初始俯仰角度值,绕纬度线旋转角度, 0至360 * * @param [cameraOptions.followedX = 50] - 'dy'锁定第一视角时,距离运动点的距离(后方) * @param [cameraOptions.followedZ = 10] - 'dy'锁定第一视角或'sd'上帝视角时,距离运动点的高度(上方) * @returns 无 */ setCameraOptions(cameraOptions: { type: string; radius?: number; heading?: number; pitch?: number; followedX?: number; followedZ?: followedZ; }): void; /** * 按类型 添加单个投影 * @param item - 参数,按类型分别支持: * @param [item.wall] - wall类型所支持的参数 * @param [item.cylinder] - cylinder类型所支持的参数 * @param [item.circle] - circle类型所支持的参数 * @param [item.polyline] - polyline类型所支持的参数 * @param [item.polylineGoing] - polylineGoing类型所支持的参数 * @returns 构造完成的投影对象 */ addShading(item: { wall?: BaseRoamLine.WallShadingOptions; cylinder?: BaseRoamLine.CylinderShadingOptions; circle?: BaseRoamLine.CircleShadingOptions; polyline?: BaseRoamLine.PolylineShadingOptions; polylineGoing?: BaseRoamLine.PolylineGoingShadingOptions; }): Cesium.Entity | undefined; /** * 移除单个投影 * @param entity - 可以 构造的投影矢量对象 或 传入type类型 ,未传入时删除最后添加的一个投影 * @returns 无 */ removeShading(entity: Cesium.Entity | string | null): void; /** * 添加wall 轨迹墙投影 * @param options - 投影构造参数 * @returns 构造完成的投影对象 */ addWallShading(options: BaseRoamLine.WallShadingOptions): Cesium.Entity | undefined; /** * 添加cylinder 圆锥立体投影 * @param options - 投影构造参数 * @returns 构造完成的投影对象 */ addCylinderShading(options: BaseRoamLine.CylinderShadingOptions): Cesium.Entity | undefined; /** * 添加circle扩散圆投影 * @param options - 投影构造参数 * @returns 构造完成的投影对象 */ addCircleShading(options: BaseRoamLine.CircleShadingOptions): Cesium.Entity | undefined; /** * 添加 polyline 或 polylineGoing 路线 投影 * @param options - 投影构造参数 * @returns 构造完成的投影对象 */ addPolylineShading(options: BaseRoamLine.PolylineShadingOptions | BaseRoamLine.PolylineGoingShadingOptions): Cesium.Entity | undefined; /** * 视角定位至路线范围 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.minHeight] - 定位时相机的最小高度值,用于控制避免异常数据 * @param [options.maxHeight] - 定位时相机的最大高度值,用于控制避免异常数据 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyTo(options?: { radius: number; scale?: number; minHeight?: number; maxHeight?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): void; /** * 定位至当前时间所在的位置 (非相机位置) * @param [options = {}] - 具有以下属性的对象: * @param options.radius - 相机距离目标点的距离(单位:米) * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行持续时间(秒)。如果省略,内部会根据飞行距离计算出理想的飞行时间。 * @param [options.endTransform] - 表示飞行完成后摄像机将位于的参考帧的变换矩阵。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机的飞行角度高于该值,请在飞行过程中调整俯仰角度以向下看,并将地球保持在视口中。 * @param [options.flyOverLongitude] - 地球上2点之间总是有两种方式。此选项会迫使相机选择战斗方向以在该经度上飞行。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyToPoint(options?: { radius: number; heading: number; pitch: number; roll: number; duration?: number; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; easingFunction?: EasingFunction.Callback; }): void; /** * 暂停 * @returns 无 */ pause(): void; /** * 继续 * @returns 无 */ proceed(): void; /** * 将轨迹数据转换为CZML格式数据 * @returns CZML格式数据 */ toCZML(): any; } declare namespace DynamicRoamLine { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.change, function (event) { * console.log('坐标发生了变化', event) * }) * @property 通用 - 支持的父类的事件类型 * @property change - 变化了 * @property click - 左键单击 鼠标事件 * @property rightClick - 右键单击 鼠标事件 * @property mouseOver - 鼠标移入 鼠标事件 * @property mouseOut - 鼠标移出 鼠标事件 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 */ type EventType = { 通用: BaseGraphic.EventType; change: string; click: string; rightClick: string; mouseOver: string; mouseOut: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; }; } /** * 动态漫游路线管理类 【动态传入的数据】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param [options.maxCacheCount = 50] - 保留的坐标点数量 * @param [options.hasCache = true] - 是否记录缓存,提高效率 * @param [options.fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @param [options.label] - 设置是否显示 文本 和对应的样式 * @param [options.model] - 设置是否显示 gltf模型 和对应的样式 * @param [options.billboard] - 设置是否显示 图标 和对应的样式,如果不设置gltf模型时,可以选择该项。 * @param [options.point] - 设置是否显示 图标 和对应的样式,如果不设置gltf模型时,可以选择该项。 * @param [options.circle] - 设置是否显示 圆对象 和对应的样式 * @param [options.shadow] - 设置投影或附加的对象,支持类型: * @param [options.shadow.wall] - wall类型所支持的参数 * @param [options.shadow.cylinder] - cylinder类型所支持的参数 * @param [options.shadow.circle] - circle类型所支持的参数 * @param [options.shadow.polyline] - polyline类型所支持的参数 * @param [options.shadow.polylineGoing] - polylineGoing类型所支持的参数 * @param [options.camera] - 视角模式设置,包括: * @param [options.camera.type] - 视角模式类型,包括:'':无、'gs':跟随视角、'dy':第一视角、'sd':上帝视角 * @param [options.camera.radius] - 'gs'跟随视角时的 初始俯仰距离值(单位:米) * @param [options.camera.heading] - 'gs'跟随视角时的 初始方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param [options.camera.pitch] - 'gs'跟随视角时的 初始俯仰角度值,绕纬度线旋转角度, 0至360 * @param [options.camera.followedX = 50] - 锁定第一视角时,距离运动点的距离(后方) * @param [options.camera.followedZ = 10] - 'dy'锁定第一视角或'sd'上帝视角时,距离运动点的高度(上方) * @param [options.camera.offsetX = 0] - 'dy'锁定第一视角时,锁定点的本身的X轴方向(前后)偏移值 * @param [options.camera.offsetY = 0] - 'dy'锁定第一视角时,锁定点的本身的Y轴方向(横向)偏移值 * @param [options.camera.offsetZ = 0] - 'dy'锁定第一视角时,锁定点的本身的Z轴方向(高度)偏移值 * @param [options.clampToTileset = false] - 是否贴3dtiles模型上(贴模型效率较慢,按需开启) * @param [options.frameRate = 30] - 当clampToTileset:true时,控制贴模型的效率,多少帧计算一次贴模型高度, * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,默认是当前本身,可以是: primitives, entities, 或 3D Tiles features */ declare class DynamicRoamLine extends BaseRoamLine { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; maxCacheCount?: number; hasCache?: boolean; fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame; label?: LabelEntity.StyleOptions; model?: ModelEntity.StyleOptions; billboard?: BillboardEntity.StyleOptions; point?: PointEntity.StyleOptions; circle?: CircleEntity.StyleOptions; shadow?: { wall?: BaseRoamLine.WallShadingOptions; cylinder?: BaseRoamLine.CylinderShadingOptions; circle?: BaseRoamLine.CircleShadingOptions; polyline?: BaseRoamLine.PolylineShadingOptions; polylineGoing?: BaseRoamLine.PolylineGoingShadingOptions; }[]; camera?: { type?: string; radius?: number; heading?: number; pitch?: number; followedX?: number; followedZ?: number; offsetX?: number; offsetY?: number; offsetZ?: number; }; clampToTileset?: boolean; frameRate?: number; objectsToExclude?: object[]; }); /** * 将轨迹数据转换为CZML格式数据 * @example * //更新车辆的轨迹 * let path = [{"lng":117.086419,"lat":31.803459,"time":"2020-11-25 10:00:00"},{"lng":117.061666,"lat":31.812281,"time":"2020-11-25 10:01:02"}] * car.updatePath(path) * * //或 * let path = [{"longitude":117.086419,"latitude":31.803459,"datetime":"2020-11-25 10:00:00"},{"longitude":117.061666,"latitude":31.812281,"datetime":"2020-11-25 10:01:02"}] * car.updatePath(path, { * timeColumn: 'datetime', * getPosition: function (item) { * return Cesium.Cartesian3.fromDegrees(parseFloat(item.longitude), parseFloat(item.lat), 0) * }, * }) * @param points - 轨迹点数据数组,包含时间、经度、纬度值 即可。 * @param [options = {}] - 参数对象: * @param [options.timeColumn = 'time'] - 时间字段的名称 * @param [options.getPosition] - 构造单条数据内的构造坐标点的回调方法,如果points数据中已有position或lat\lng\alt字段也可以不传回调方法。 * @returns 无 */ updatePath(points: object[], options?: { timeColumn?: any; getPosition?: (...params: any[]) => any; }): void; /** * 动态时序坐标位置, * Cesium原生动态属性对象 */ readonly property: Cesium.SampledPositionProperty; } declare namespace RoamLine { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.change, function (event) { * console.log('坐标发生了变化', event) * }) * @property 通用 - 支持的父类的事件类型 * @property start - 开始 * @property change - 变化了 * @property endItem - 完成points其中一个点时的回调事件 * @property end - 完成所有漫游的回调事件 * @property click - 左键单击 鼠标事件 * @property rightClick - 右键单击 鼠标事件 * @property mouseOver - 鼠标移入 鼠标事件 * @property mouseOut - 鼠标移出 鼠标事件 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 */ type EventType = { 通用: BaseGraphic.EventType; start: string; change: string; endItem: string; end: string; click: string; rightClick: string; mouseOver: string; mouseOut: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; }; } /** * 飞行漫游路线管理类 【静态一次性传入的数据】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.positions - 轨迹的 坐标数组 * @param options.speed - 轨迹的 速度( 单位:千米/小时) * @param [options.timeField = 'time'] - 当points数组中已有时间值,请传入该值的字段名称,同时speed将失效,已实际传入时间字段为准。 * @param [options.offsetHeight = 0] - 轨迹偏移增加的高度 * @param [options.startTime = clock.currentTime] - 轨迹的开始时间 * @param [options.pauseTime = 0] - 每个点的停留时长(单位:秒) * @param [options.multiplier = 1] - 轨迹播放的倍率 * @param [options.hasCache = true] - 是否记录缓存,提高效率 * @param [options.fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @param [options.interpolation = false] - 是否LagrangePolynomialApproximation插值,对轨迹进行圆弧状插值 * @param [options.interpolationDegree = 2] - 当interpolation为true时,使用的插值程度。 * @param [options.showStop = false] - 是否在start前或stop后显示模型等对象 * @param [options.label] - 设置是否显示 文本 和对应的样式 * @param [options.showGroundHeight = false] - 是否求准确的 地面海拔 和 离地高度 (没有此需求时可以关闭,提高效率) * @param [options.model] - 设置是否显示 gltf模型 和对应的样式 * @param [options.billboard] - 设置是否显示 图标 和对应的样式,如果不设置gltf模型时,可以选择该项。 * @param [options.point] - 设置是否显示 图标 和对应的样式,如果不设置gltf模型时,可以选择该项。 * @param [options.path] - 设置是否显示 轨迹路线 和对应的样式 * @param [options.circle] - 设置是否显示 圆对象 和对应的样式 * @param [options.shadow] - 设置投影或附加的对象,支持类型: * @param [options.shadow.wall] - wall类型所支持的参数 * @param [options.shadow.cylinder] - cylinder类型所支持的参数 * @param [options.shadow.circle] - circle类型所支持的参数 * @param [options.shadow.polyline] - polyline类型所支持的参数 * @param [options.shadow.polylineGoing] - polylineGoing类型所支持的参数 * @param [options.camera] - 视角模式设置,包括: * @param [options.camera.type] - 视角模式类型,包括:'':无、'gs':跟随视角、'dy':第一视角、'sd':上帝视角 * @param [options.camera.radius] - 'gs'跟随视角时的 初始俯仰距离值(单位:米) * @param [options.camera.heading] - 'gs'跟随视角时的 初始方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param [options.camera.pitch] - 'gs'跟随视角时的 初始俯仰角度值,绕纬度线旋转角度, 0至360 * * @param [options.camera.followedX = 50] - 锁定第一视角时,距离运动点的距离(后方) * @param [options.camera.followedZ = 10] - 'dy'锁定第一视角或'sd'上帝视角时,距离运动点的高度(上方) * @param [options.camera.offsetX = 0] - 'dy'锁定第一视角时,锁定点的本身的X轴方向(前后)偏移值 * @param [options.camera.offsetY = 0] - 'dy'锁定第一视角时,锁定点的本身的Y轴方向(横向)偏移值 * @param [options.camera.offsetZ = 0] - 'dy'锁定第一视角时,锁定点的本身的Z轴方向(高度)偏移值 * @param [options.clockRange] - 指定播放的模式 * @param [options.clockLoop = false] - 是否循环播放,等价于clockRange:Cesium.ClockRange.LOOP_STOP * @param [options.autoStop = false] - 是否自动停止 * * //以下是 clampToGround中使用的 * @param [options.splitNum = 100] - 当clampToGround计算时,插值数,等比分割的个数 * @param [options.minDistance = null] - 当clampToGround计算时,插值最小间隔(单位:米),优先级高于splitNum * @param [options.offset = 0] - 当clampToGround计算时,可以按需增加偏移高度(单位:米),便于可视 * @param [options.clampToTileset = false] - 是否贴3dtiles模型上(贴模型效率较慢,按需开启) * @param [options.frameRate = 30] - 当clampToTileset:true时,控制贴模型的效率,多少帧计算一次贴模型高度, * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,默认是当前本身,可以是: primitives, entities, 或 3D Tiles features */ declare class RoamLine extends BaseRoamLine { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; positions: any[][] | LatLngPoint[]; speed: any[][] | number; timeField?: string; offsetHeight?: number; startTime?: string | Cesium.JulianDate; pauseTime?: number | ((...params: any[]) => any); multiplier?: number; hasCache?: boolean; fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame; interpolation?: boolean; interpolationDegree?: boolean; showStop?: boolean; label?: LabelEntity.StyleOptions; showGroundHeight?: boolean; model?: ModelEntity.StyleOptions; billboard?: BillboardEntity.StyleOptions; point?: PointEntity.StyleOptions; path?: PathEntity.StyleOptions; circle?: CircleEntity.StyleOptions; shadow?: { wall?: BaseRoamLine.WallShadingOptions; cylinder?: BaseRoamLine.CylinderShadingOptions; circle?: BaseRoamLine.CircleShadingOptions; polyline?: BaseRoamLine.PolylineShadingOptions; polylineGoing?: BaseRoamLine.PolylineGoingShadingOptions; }[]; camera?: { type?: string; radius?: number; heading?: number; pitch?: number; followedX?: number; followedZ?: number; offsetX?: number; offsetY?: number; offsetZ?: number; }; clockRange?: Cesium.ClockRange; clockLoop?: boolean; autoStop?: boolean; splitNum?: number; minDistance?: number; offset?: number; clampToTileset?: boolean; frameRate?: number; objectsToExclude?: object[]; }); /** * 当前飞行过的positions轨迹点数组的index顺序 */ readonly currIndex: number; /** * 是否已启动 */ readonly isStart: boolean; /** * 当前实时信息 */ readonly info: any; /** * 开始飞行漫游 * @returns 无 */ start(): void; /** * 停止飞行漫游 * @returns 无 */ stop(): void; /** * 计算贴地线 * @param callback - 计算完成的回调方法 * @returns 无 */ clampToGround(callback: (...params: any[]) => any): void; /** * 获取剖面数据 * @param callback - 计算完成的回调方法 * @returns 无 */ getTerrainHeight(callback: (...params: any[]) => any): void; /** * 动态时序坐标位置, * Cesium原生动态属性对象 */ readonly property: Cesium.SampledPositionProperty; } declare namespace BaseGraphicLayer { /** * 矢量数据图层 通用构造参数 * @property [id = uuid()] - 图层id标识 * @property [pid = -1] - 图层父级的id,一般图层管理中使用 * @property [name = '未命名'] - 图层名称 * @property [show = true] - 图层是否显示 * @property [center] - 图层自定义定位视角{@link Map#setCameraView} * @property center.lng - 经度值, 180 - 180 * @property center.lat - 纬度值, -90 - 90 * @property center.alt - 高度值 * @property center.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0-360 * @property center.pitch - 俯仰角度值,绕纬度线旋转角度, 0-360 * @property center.roll - 翻滚角度值,绕经度线旋转角度, 0-360 * @property [extent = null] - 图层自定义定位的矩形区域,与center二选一即可。 {@link Map#flyToExtent} * @property extent.xmin - 最小经度值, -180 至 180 * @property extent.xmax - 最大纬度值, -180 至 180 * @property extent.ymin - 最小纬度值, -90 至 90 * @property extent.ymax - 最大纬度值, -90 至 90 * @property [extent.height = 0] - 矩形高度值 * @property [flyTo] - 加载完成数据后是否自动飞行定位到数据所在的区域。 * @property [popup] - 绑定的popup弹窗值,也可以bindPopup方法绑定,支持:'all'、数组、字符串模板,当为数组时支持: * @property popup.field - 字段名称 * @property popup.name - 显示的对应自定义名称 * @property [popup.type] - 默认为label文本,也可以支持:'button'按钮,'html' html内容。 * @property [popup.callback] - 当type为'button'按钮时,单击后触发的事件。 * @property [popup.html] - 当type为'html'时,对于拼接的html内容。 * @property [popup.format] - 使用window上有效的格式化js方法名称或function回调方法,来格式化字符串值。 * @property [popup.unit] - 追加的计量单位 或 其他字符串后缀。 * @property [popupOptions] - popup弹窗时的配置参数 * @property [tooltip] - 绑定的tooltip弹窗值,也可以bindTooltip方法绑定,参数与popup属性完全相同。 * @property [tooltipOptions] - tooltip弹窗时的配置参数 * @property [contextmenuItems] - 绑定的右键菜单值,也可以bindContextMenu方法绑定 * @property [opacity = 1.0] - 透明度(部分图层),取值范围:0.0-1.0 * @property [zIndex] - 控制图层的叠加层次(部分图层),默认按加载的顺序进行叠加,但也可以自定义叠加顺序,数字大的在上面。 */ type ConstructorOptions = { id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: { lng: number; lat: number; alt: number; heading: number; pitch: number; roll: number; }; extent?: { xmin: number; xmax: number; ymin: number; ymax: number; height?: number; }; flyTo?: boolean; popup?: { field: string; name: string; type?: string; callback?: string; html?: string; format?: string | ((...params: any[]) => any); unit?: string; }; popupOptions?: Popup.StyleOptions; tooltip?: string | any[] | ((...params: any[]) => any); tooltipOptions?: Tooltip.StyleOptions; contextmenuItems?: any; opacity?: number; zIndex?: number; }; /** * 图层类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.click, function (event) { * console.log('单击了矢量数据对象', event) * }) * @property add - 添加对象 * @property remove - 移除对象 * @property show - 显示了对象 * @property hide - 隐藏了对象 * @property click - 左键单击 鼠标事件 * @property rightClick - 右键单击 鼠标事件 * @property mouseOver - 鼠标移入 鼠标事件 * @property mouseOut - 鼠标移出 鼠标事件 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 */ type EventType = { add: string; remove: string; show: string; hide: string; click: string; rightClick: string; mouseOver: string; mouseOut: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; }; } /** * 矢量数据图层 Base基类 * @param options - 描述初始化构造参数选项的对象 */ declare class BaseGraphicLayer extends BaseLayer { constructor(options: BaseGraphicLayer.ConstructorOptions); /** * 绑定鼠标移入或单击后的 对象高亮 * @param [options] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @param [options.type] - 事件类型,默认为鼠标移入高亮,也可以指定'click'单击高亮. * @returns 无 */ bindHighlight(options?: { type?: string; }): void; /** * 解绑鼠标移入或单击后的高亮处理 * @returns 无 */ unbindHighlight(): void; /** * 是否存在Popup绑定,判断图层及内部所有矢量数据 * @returns 是否存在Popup绑定 */ hasPopup(): boolean; /** * 绑定鼠标单击对象后的弹窗。 * @param content - 弹窗内容html字符串,或者回调方法。 * @param options - 控制参数 * @returns 当前对象本身,可以链式调用 */ bindPopup(content: string | ((...params: any[]) => any), options: Popup.StyleOptions): this; /** * 解除绑定的鼠标单击对象后的弹窗。 * @param [stopPropagation = false] - 单击事件中是否继续冒泡查找 * @returns 当前对象本身,可以链式调用 */ unbindPopup(stopPropagation?: boolean): this; /** * 打开绑定的弹窗 * @param position - 矢量对象 或 显示的位置 * @returns 当前对象本身,可以链式调用 */ openPopup(position: BaseGraphic | LatLngPoint | Cesium.Cartesian3): this; /** * 关闭弹窗 * @returns 当前对象本身,可以链式调用 */ closePopup(): this; /** * 是否绑定了tooltip * @returns 是否绑定 */ hasTooltip(): boolean; /** * 绑定鼠标移入的弹窗 * @param content - 弹窗内容html字符串,或者回调方法。 * @param options - 控制参数 * @returns 当前对象本身,可以链式调用 */ bindTooltip(content: string | ((...params: any[]) => any), options: Tooltip.StyleOptions): this; /** * 解除绑定的鼠标移入对象后的弹窗。 * @param [stopPropagation = false] - 单击事件中是否继续冒泡查找 * @returns 当前对象本身,可以链式调用 */ unbindTooltip(stopPropagation?: boolean): this; /** * 打开绑定的tooltip弹窗 * @param position - graphic矢量对象 或 显示的位置 * @returns 当前对象本身,可以链式调用 */ openTooltip(position: BaseGraphic | LatLngPoint | Cesium.Cartesian3): this; /** * 关闭弹窗 * @returns 当前对象本身,可以链式调用 */ closeTooltip(): this; /** * 是否有绑定的右键菜单 * @returns 当前对象本身,可以链式调用 */ hasContextMenu(): this; /** * 获取绑定的右键菜单数组 * @returns 右键菜单数组 */ getContextMenu(): object[]; /** * 绑定右键菜单 * @example * //在layer上绑定右键菜单 * graphicLayer.bindContextMenu([ * { * text: '删除对象', * iconCls: 'fa fa-trash-o', * callback: function (e) { * let graphic = e.graphic * if (graphic) { * graphicLayer.removeGraphic(graphic) * } * }, * }, * { * text: '计算长度', * iconCls: 'fa fa-medium', * show: function (e) { * let graphic = e.graphic * return graphic.type === 'polyline' * }, * callback: function (e) { * let graphic = e.graphic * let strDis = mars3d.MeasureUtil.formatDistance(graphic.distance) * haoutil.alert('该对象的长度为:' + strDis) * }, * }, * ]) * @param content - 右键菜单配置数组,数组中每一项包括: * @param [content.text] - 菜单文字 * @param [content.iconCls] - 小图标css * @param [content.show] - 菜单项是否显示的回调方法 * @param [content.callback] - 菜单项单击后的回调方法 * @param [content.children] - 当有二级子菜单时,配置数组。 * @param [options = {}] - 控制参数 * @param [options.offsetX] - 用于非规则对象时,横向偏移的px像素值 * @param [options.offsetY] - 用于非规则对象时,垂直方向偏移的px像素值 * @returns 当前对象本身,可以链式调用 */ bindContextMenu(content: { text?: string; iconCls?: string; show?: ((...params: any[]) => any) | boolean; callback?: (...params: any[]) => any; children?: object[]; }[], options?: { offsetX?: number; offsetY?: number; }): this; /** * 解除绑定的右键菜单 * @param [stopPropagation = false] - 单击事件中是否继续冒泡查找 * @returns 当前对象本身,可以链式调用 */ unbindContextMenu(stopPropagation?: boolean): this; /** * 打开右键菜单 * @param position - 矢量对象 或 显示的位置 * @returns 当前对象本身,可以链式调用 */ openContextMenu(position: BaseGraphic | Cesium.Cartesian3): this; /** * 关闭右键菜单 * @returns 当前对象本身,可以链式调用 */ closeContextMenu(): this; /** * 显示小提示窗,一般用于鼠标操作的提示。 * @param position - 显示的屏幕坐标位置 或 笛卡尔坐标位置 * @param message - 显示的内容 * @returns 当前对象本身,可以链式调用 */ openSmallTooltip(position: Cesium.Cartesian2 | Cesium.Cartesian3, message: any): this; /** * 关闭小提示窗 * @returns 当前对象本身,可以链式调用 */ closeSmallTooltip(): this; } /** * 图层对象 的基类 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.opacity = 1] - 透明度,取值范围:0.0-1.0 * @param [options.center] - 图层自定义定位视角 * @param [options.popup] - 当图层支持popup弹窗时,绑定的值 * @param [options.popupOptions] - popup弹窗时的配置参数,还包括: * @param [options.popupOptions.titleField] - 固定的标题名称 * @param [options.popupOptions.titleField] - 标题对应的属性字段名称 * @param [options.popupOptions.noTitle] - 不显示标题 * @param [options.tooltip] - 当图层支持tooltip弹窗时,绑定的值 * @param [options.tooltipOptions] - tooltip弹窗时的配置参数,还包括: * @param [options.tooltipOptions.titleField] - 固定的标题名称 * @param [options.tooltipOptions.titleField] - 标题对应的属性字段名称 * @param [options.tooltipOptions.noTitle] - 不显示标题 * @param [options.contextmenuItems] - 当图层支持右键菜单时,绑定的值 * @param [options.stopPropagation = false] - 当前类中事件是否停止冒泡, false时:事件冒泡到map中。 */ declare class BaseLayer extends BaseClass { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; opacity?: number; center?: any; popup?: string | any[] | ((...params: any[]) => any) | any; popupOptions?: { titleField?: string; titleField?: string; noTitle?: string; }; tooltip?: string | any[] | ((...params: any[]) => any) | any; tooltipOptions?: { titleField?: string; titleField?: string; noTitle?: string; }; contextmenuItems?: any; stopPropagation?: boolean; }); /** * 内置唯一标识ID */ readonly uuid: string; /** * 对象的pid标识 */ pid: string | number; /** * 对象的id标识 */ id: string | number; /** * 名称 标识 */ name: string; /** * 图层类型 */ readonly type: string; /** * 当前对象的状态 */ readonly state: State; /** * 是否已添加到地图 */ readonly isAdded: boolean; /** * 是否已经销毁了 */ readonly isDestroy: boolean; /** * 显示隐藏状态 */ show: boolean; /** * 是否可以调整透明度 */ readonly hasOpacity: boolean; /** * 透明度,取值范围:0.0-1.0 */ opacity: number; /** * 添加到地图上,同 map.addThing * @param map - 地图对象 * @returns 当前对象本身,可以链式调用 */ addTo(map: Map): this; /** * 从地图上移除,同map.removeThing * @param destroy - 是否调用destroy释放 * @returns 无 */ remove(destroy: boolean): void; /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; /** * 显示错误弹窗, * 调用cesium的cesiumWidget.showErrorPanel * @param title - 标题 * @param error - 错误内容对象 * @returns 当前对象本身,可以链式调用 */ showError(title: string, error: any): this; /** * 入场动画后再执行flyTo,直接调用flyTo可能造成入场动画失败。 * @returns 当前对象本身,可以链式调用 */ flyToByAnimationEnd(): this; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; /** * 更新图层参数 * @param options - 与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; /** * 将图层转为Json简单对象,用于存储后再传参加载 * @returns Json简单对象 */ toJSON(): any; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } declare namespace CzmGeoJsonLayer { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.load, function (event) { * console.log('矢量数据对象加载完成', event) * }) * @property 通用 - 支持的父类的事件类型 * @property load - 完成加载,执行所有内部处理后 * @property addGraphic - 添加矢量数据时 */ type EventType = { 通用: BaseGraphicLayer.EventType; load: string; addGraphic: string; }; } /** * GeoJSON数据图层(ceisum原生),该类中矢量数据是使用ceisum原生方法加载的entity对象。 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url] - geojson文件或服务url地址 * @param [options.data] - geojson格式规范数据对象,与url二选一即可。 * @param [options.format] - 可以对加载的geojson数据进行格式化或转换操作 * @param [options.symbol] - 矢量数据的style样式 * @param options.symbol.styleOptions - 点数据时的Style样式,可以附加 model {@link ModelEntity.StyleOptions} 或 point {@link PointEntity.StyleOptions} * @param options.symbol.styleOptions - 线数据时的Style样式,可以附加 corridor {@link CorridorEntity.StyleOptions} * @param options.symbol.styleOptions - 面数据时的Style样式 * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [options.symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, entity, styleOpt){ return { color: "#ff0000" }; } */ declare class CzmGeoJsonLayer extends BaseGraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url?: string; data?: any; format?: (...params: any[]) => any; symbol?: { styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }; }); /** * GeoJsonDataSource 对象 */ readonly layer: Cesium.GeoJsonDataSource; /** * Entity矢量数据 集合 */ readonly entities: Cesium.EntityCollection; /** * 当存在 文字primitive 数据的内部Cesium容器 */ readonly labelCollection: Cesium.LabelCollection; /** * 是否可以调整图层顺序(在同类型图层间) */ readonly hasZIndex: boolean; /** * 图层顺序,数字大的在上面。(当hasZIndex为true时) */ zIndex: number; /** * 是否贴地 */ readonly clampToGround: boolean; /** * 加载新数据 或 刷新数据 * @param [newOptions = {}] - 新设定的参数,会与类的构造参数合并。 * @param [newOptions.url] - geojson文件或服务url地址 * @param [newOptions.data] - geojson格式规范数据对象,与url二选一即可。 * @param [newOptions.类参数] - 包含当前类支持的所有参数 * @param [newOptions.通用参数] - 包含父类支持的所有参数 * @returns 当前对象本身,可以链式调用 */ load(newOptions?: { url?: string; data?: any; 类参数?: any; 通用参数?: BaseGraphicLayer.ConstructorOptions; }): this; /** * 加载新数据 或 刷新数据 * @param symbol - 设置新的symbol 矢量数据样式. {@link GraphicType} * @param symbol.styleOptions - Style样式,每种不同类型数据都有不同的样式,具体见各矢量数据的style参数。{@link GraphicType} * @param [symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @returns 当前对象本身,可以链式调用 */ updateStyle(symbol: { styleOptions: any; styleField?: string; styleFieldOptions?: any; }): this; /** * 添加label文本注记 * @param position - 坐标位置 * @param labelattr - label文本的属性 * @param attr - 属性信息 * @returns label文本对象 */ lblAddFun(position: Cesium.Cartesian3 | Cesium.XXXPositionProperty, labelattr: any, attr: any): Cesium.Label; /** * 设置透明度 * @param value - 透明度 * @returns 无 */ setOpacity(value: number): void; /** * 获取Entity矢量对象上绑定的 数据 * @param entity - Entity矢量对象 * @returns 数据 */ getEntityAttr(entity: Cesium.Entity): any; /** * 清除所有数据 * @returns 当前对象本身,可以链式调用 */ clear(): this; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } /** * CZML数据图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url] - CZML文件或服务url地址 * @param [options.data] - CZML格式规范数据对象,与url二选一即可。 * @param [options.format] - 可以对加载的CZML数据进行格式化或转换操作 */ declare class CzmlLayer extends CzmGeoJsonLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url?: string; data?: any; format?: (...params: any[]) => any; }); /** * 加载新数据 或 刷新数据 * @param [newOptions = {}] - 新设定的参数,会与类的构造参数合并。 * @param [newOptions.data] - CZML格式规范数据对象,与url二选一即可。 * @param [newOptions.url] - CZML文件或服务url地址 * @param [options.proxy] - 加载资源时要使用的代理服务url。 * @param [options.templateValues] - 一个对象,用于替换Url中的模板值的键/值对 * @param [options.queryParameters] - 一个对象,其中包含在检索资源时将发送的查询参数。比如:queryParameters: {'access_token': '123-435-456-000'} * @param [options.headers] - 一个对象,将发送的其他HTTP标头。比如:headers: { 'X-My-Header': 'valueOfHeader' } * @param [newOptions.类参数] - 包含当前类支持的所有参数 * @param [newOptions.通用参数] - 包含父类支持的所有参数 * @returns 当前对象本身,可以链式调用 */ load(newOptions?: { data?: any; url?: string; 类参数?: any; 通用参数?: BaseGraphicLayer.ConstructorOptions; }): this; /** * 获取Entity矢量对象上绑定的 数据 * @param entity - Entity矢量对象 * @returns 数据 */ getEntityAttr(entity: Cesium.Entity): any; } /** * KML数据图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url] - KML文件或服务url地址 * @param [options.data] - 已解析的KML文档或包含二进制KMZ数据或已解析的KML文档的Blob,与url二选一即可。 * @param [options.format] - 可以对加载的KML数据进行格式化或转换操作 * @param [options.symbol] - 矢量数据的style样式 * @param options.symbol.styleOptions - 点数据时的Style样式,可以附加 model {@link ModelEntity.StyleOptions} 或 point {@link PointEntity.StyleOptions} * @param options.symbol.styleOptions - 线数据时的Style样式,可以附加 corridor {@link CorridorEntity.StyleOptions} * @param options.symbol.styleOptions - 面数据时的Style样式 * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [options.symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, entity, styleOpt){ return { color: "#ff0000" }; } */ declare class KmlLayer extends CzmGeoJsonLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url?: string; data?: Document | Blob; format?: (...params: any[]) => any; symbol?: { styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }; }); /** * 加载新数据 或 刷新数据 * @param [newOptions = {}] - 新设定的参数,会与类的构造参数合并。 * @param [newOptions.data] - 已解析的KML文档或包含二进制KMZ数据或已解析的KML文档的Blob,与url二选一即可。 * @param [newOptions.url] - KML文件或服务url地址 * @param [options.proxy] - 加载资源时要使用的代理服务url。 * @param [options.templateValues] - 一个对象,用于替换Url中的模板值的键/值对 * @param [options.queryParameters] - 一个对象,其中包含在检索资源时将发送的查询参数。比如:queryParameters: {'access_token': '123-435-456-000'} * @param [options.headers] - 一个对象,将发送的其他HTTP标头。比如:headers: { 'X-My-Header': 'valueOfHeader' } * @param [newOptions.类参数] - 包含当前类支持的所有参数 * @param [newOptions.通用参数] - 包含父类支持的所有参数 * @returns 当前对象本身,可以链式调用 */ load(newOptions?: { data?: Document | Blob; url?: string; 类参数?: any; 通用参数?: BaseGraphicLayer.ConstructorOptions; }): this; /** * 获取Entity矢量对象上绑定的 数据 * @param entity - Entity矢量对象 * @returns 数据 */ getEntityAttr(entity: Cesium.Entity): any; } /** * ArcGIS WFS服务图层, * 按瓦片网格分块分层加载。 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - ArcGIS服务地址, 示例:'http://server.mars3d.cn/arcgis/rest/services/mars/hefei/MapServer/37', * @param [options.token] - 用于通过ArcGIS MapServer服务进行身份验证的ArcGIS令牌。 * @param [options.where] - 用于筛选数据的where查询条件 * @param [options.wkid] - 当非标准EPSG标号时,可以指定wkid值。 * @param [options.parameters] - 要在URL中 传递给WFS服务GetFeature请求的其他参数。 * @param [options.headers] - 将被添加到HTTP请求头。 * @param [options.proxy] - 加载资源时使用的代理。 * @param [options.IdField = 'id'] - 数据中唯一标识的属性字段名称,默认读取 id或objectid或OBJECTID * @param options.debuggerTileInfo - 是否开启测试显示瓦片信息 * @param [options.minimumLevel = 0] - 图层所支持的最低层级,当地图小于该级别时,平台不去请求服务数据。【影响效率的重要参数】 * @param [options.maximumLevel] - 图层所支持的最大层级,当地图大于该级别时,平台不去请求服务数据。 * @param options.rectangle - 瓦片数据的矩形区域范围 * @param options.rectangle.xmin - 最小经度值, -180 至 180 * @param options.rectangle.xmax - 最大纬度值, -180 至 180 * @param options.rectangle.ymin - 最小纬度值, -90 至 90 * @param options.rectangle.ymax - 最大纬度值, -90 至 90 * @param options.bbox - bbox规范的瓦片数据的矩形区域范围,与rectangle二选一即可。 * @param options.debuggerTileInfo - 是否开启测试显示瓦片信息 * @param [options.buildings] - 标识当前图层为建筑物白膜类型数据 * @param [options.buildings.bottomHeight] - 建筑物底部高度(如:0) 属性字段名称(如:{bottomHeight}) * @param [options.buildings.cloumn = 1] - 层数,楼的实际高度 = height*cloumn * @param [options.buildings.height = 3.5] - 层高的 固定层高数值(如:10) 或 属性字段名称(如:{height}) * @param options.clustering - 设置聚合相关参数[entity点类型时]: * @param [options.clustering.enabled = false] - 是否开启聚合 * @param [options.clustering.pixelRange = 20] - 多少像素矩形范围内聚合 * @param [options.clustering.clampToGround = true] - 是否贴地 * @param [options.clustering.radius = 28] - 圆形图标的整体半径大小(单位:像素) * @param [options.clustering.radiusIn = radius-5] - 圆形图标的内圆半径大小(单位:像素) * @param [options.clustering.fontColor = '#ffffff'] - 数字的颜色 * @param [options.clustering.color = 'rgba(181, 226, 140, 0.6)'] - 圆形图标的背景颜色,默认自动处理 * @param [options.clustering.colorIn = 'rgba(110, 204, 57, 0.5)'] - 圆形图标的内圆背景颜色,默认自动处理 * @param [options.symbol] - 矢量数据的style样式,为Function时是完全自定义的回调处理 symbol(attr, style, feature) * @param [options.symbol.type] - 标识数据类型,默认是根据数据生成 point、polyline、polygon * @param options.symbol.styleOptions - Style样式,每种不同类型数据都有不同的样式,具体见各矢量数据的style参数。{@link GraphicType} * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [options.symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, styleOpt){ return { color: "#ff0000" }; } */ declare class ArcGisWfsLayer extends LodGraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url: string; token?: string; where?: string; wkid?: number; parameters?: any; headers?: any; proxy?: Cesium.Proxy; IdField?: string; debuggerTileInfo: boolean; minimumLevel?: number; maximumLevel?: number; rectangle: { xmin: number; xmax: number; ymin: number; ymax: number; }; bbox: Number[]; debuggerTileInfo: boolean; buildings?: { bottomHeight?: string; cloumn?: string; height?: string | number; }; clustering: { enabled?: boolean; pixelRange?: number; clampToGround?: boolean; radius?: number; radiusIn?: number; fontColor?: string; color?: string; colorIn?: string; }; symbol?: { type?: GraphicType; styleOptions: any; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }; }); /** * 更新where条件后 刷新数据 * @param where - 筛选条件 * @returns 无 */ setWhere(where: string): void; } /** * ArcGIS WFS服务图层, * 一次性请求加载,适合少量数据时使用。 * @param options - 参数对象,包括以下: * @param options.url - ArcGIS服务地址, 示例:'http://server.mars3d.cn/arcgis/rest/services/mars/hefei/MapServer/37', * @param [options.token] - 用于通过ArcGIS MapServer服务进行身份验证的ArcGIS令牌。 * @param [options.where] - 用于筛选数据的where查询条件 * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.format] - 可以对加载的geojson数据进行格式化或转换操作 * @param [options.buildings] - 标识当前图层为建筑物白膜类型数据 * @param [options.buildings.bottomHeight] - 建筑物底部高度(如:0) 属性字段名称(如:{bottomHeight}) * @param [options.buildings.cloumn = 1] - 层数,楼的实际高度 = height*cloumn * @param [options.buildings.height = 3.5] - 层高的 固定层高数值(如:10) 或 属性字段名称(如:{height}) * @param [options.symbol] - 矢量数据的style样式,为Function时是完全自定义的回调处理 symbol(attr, style, feature) * @param options.symbol.styleOptions - 点数据时的Style样式,可以附加 model {@link ModelEntity.StyleOptions} 或 point {@link PointEntity.StyleOptions} * @param options.symbol.styleOptions - 线数据时的Style样式,可以附加 corridor {@link CorridorEntity.StyleOptions} * @param options.symbol.styleOptions - 面数据时的Style样式 * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [options.symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, entity, styleOpt){ return { color: "#ff0000" }; } */ declare class ArcGisWfsSingleLayer extends GeoJsonLayer { constructor(options: { url: string; token?: string; where?: string; 通用参数?: BaseGraphicLayer.ConstructorOptions; format?: (...params: any[]) => any; buildings?: { bottomHeight?: string; cloumn?: string; height?: string | number; }; symbol?: { styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }; }); /** * 更新where条件后 刷新数据 * @param where - 筛选条件 * @returns 无 */ setWhere(where: string): void; /** * 加载新数据 或 刷新数据 * @param [newOptions] - 新设定的参数,会与类的构造参数合并。 * @param [newOptions.url] - geojson文件或服务url地址 * @param [newOptions.data] - geojson格式规范数据对象,与url二选一即可。 * @param [newOptions.类参数] - 包含当前类支持的所有参数 * @param [newOptions.通用参数] - 包含父类支持的所有参数 * @returns 当前对象本身,可以链式调用 */ load(newOptions?: { url?: string; data?: any; 类参数?: any; 通用参数?: BaseGraphicLayer.ConstructorOptions; }): this; } /** * DIV图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.hasEdit = false] - 是否可编辑 * @param [options.isAutoEditing = true] - 完成标绘时是否自动启动编辑(需要hasEdit:true时) * @param [options.isContinued = false] - 是否连续标绘 * @param [options.data = null] - 需要自动加载的数据,内部自动生成Graphic对象。{@link GraphicUtil#.create} * @param [options.pointerEvents = true] - DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 */ declare class DivLayer extends GraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; hasEdit?: boolean; isAutoEditing?: boolean; isContinued?: boolean; data?: any | object[]; pointerEvents?: boolean; }); /** * 容纳 {@link DivGraphic} 数据的DOM容器 */ readonly container: Element; /** * 当加载 DivGraphic 数据的DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 */ pointerEvents: boolean; } /** * 高德在线POI图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.key = mars3d.Token.gaodeArr] - 高德KEY,在实际项目中请使用自己申请的高德KEY,因为我们的key不保证长期有效。 * @param [options.minimumLevel = 0] - 图层所支持的最低层级,当地图小于该级别时,平台不去请求服务数据。【影响效率的重要参数】 * @param [options.maximumLevel] - 图层所支持的最大层级,当地图大于该级别时,平台不去请求服务数据。 * @param options.rectangle - 瓦片数据的矩形区域范围 * @param options.rectangle.xmin - 最小经度值, -180 至 180 * @param options.rectangle.xmax - 最大纬度值, -180 至 180 * @param options.rectangle.ymin - 最小纬度值, -90 至 90 * @param options.rectangle.ymax - 最大纬度值, -90 至 90 * @param options.bbox - bbox规范的瓦片数据的矩形区域范围,与rectangle二选一即可。 * @param options.debuggerTileInfo - 是否开启测试显示瓦片信息 * @param options.clustering - 设置聚合相关参数: * @param [options.clustering.enabled = false] - 是否开启聚合 * @param [options.clustering.pixelRange = 20] - 多少像素矩形范围内聚合 * @param [options.clustering.clampToGround = true] - 是否贴地 * @param [options.clustering.radius = 28] - 圆形图标的整体半径大小(单位:像素) * @param [options.clustering.radiusIn = radius-5] - 圆形图标的内圆半径大小(单位:像素) * @param [options.clustering.fontColor = '#ffffff'] - 数字的颜色 * @param [options.clustering.color = 'rgba(181, 226, 140, 0.6)'] - 圆形图标的背景颜色,默认自动处理 * @param [options.clustering.colorIn = 'rgba(110, 204, 57, 0.5)'] - 圆形图标的内圆背景颜色,默认自动处理 * @param [options.symbol] - 矢量数据的style样式 * @param options.symbol.styleOptions - 点的Style样式。 * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 */ declare class GeodePoiLayer extends LodGraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; key?: String[]; minimumLevel?: number; maximumLevel?: number; rectangle: { xmin: number; xmax: number; ymin: number; ymax: number; }; bbox: Number[]; debuggerTileInfo: boolean; clustering: { enabled?: boolean; pixelRange?: number; clampToGround?: boolean; radius?: number; radiusIn?: number; fontColor?: string; color?: string; colorIn?: string; }; symbol?: { styleOptions: BillboardEntity.StyleOptions | PointEntity.StyleOptions; styleField?: string; styleFieldOptions?: any; }; }); /** * 获取配置的高德Key(多个时轮询) */ readonly key: string; } declare namespace GeoJsonLayer { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.load, function (event) { * console.log('矢量数据对象加载完成', event) * }) * @property 通用 - 支持的base父类的事件类型 * @property 通用 - 支持的父类的事件类型 * @property load - 完成加载,执行所有内部处理后 */ type EventType = { 通用: GraphicLayer.EventType; 通用: GraphicLayer.EventType; load: string; }; } /** * 加载展示 GeoJSON数据 的图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url] - SDK标绘生产的geojson文件或服务url地址 * @param [options.data] - SDK标绘生产的geojson格式规范数据对象,与url二选一即可。 * @param [options.crs] - 原始数据的坐标系,如'EPSG:3857' * @param [options.format] - 可以对加载的geojson数据进行格式化或转换操作 * @param [options.onCreateGraphic] - 解析geojson后,外部自定义方法来创建Graphic对象 * @param [options.proxy] - 加载资源时要使用的代理服务url。 * @param [options.templateValues] - 一个对象,用于替换Url中的模板值的键/值对 * @param [options.queryParameters] - 一个对象,其中包含在检索资源时将发送的查询参数。比如:queryParameters: {'access_token': '123-435-456-000'} * @param [options.headers] - 一个对象,将发送的其他HTTP标头。比如:headers: { 'X-My-Header': 'valueOfHeader' } * @param [options.symbol] - 矢量数据的style样式,为Function时是完全自定义的回调处理 symbol(attr, style, feature) * @param [options.symbol.type] - 标识数据类型,默认是根据数据生成 point、polyline、polygon * @param options.symbol.styleOptions - Style样式,每种不同类型数据都有不同的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [options.symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, styleOpt){ return { color: "#ff0000" }; } * @param [options.buildings] - 标识当前图层为建筑物白膜类型数据 * @param [options.buildings.bottomHeight] - 建筑物底部高度(如:0) 属性字段名称(如:{bottomHeight}) * @param [options.buildings.cloumn = 1] - 层数,楼的实际高度 = height*cloumn * @param [options.buildings.height = 3.5] - 层高的 固定层高数值(如:10) 或 属性字段名称(如:{height}) * @param [options.mask] - 标识是否绘制区域边界的反选遮罩层 */ declare class GeoJsonLayer extends GraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url?: string; data?: any; crs?: string; format?: (...params: any[]) => any; onCreateGraphic?: (...params: any[]) => any; proxy?: string; templateValues?: any; queryParameters?: any; headers?: any; symbol?: { type?: GraphicType; styleOptions: any; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }; buildings?: { bottomHeight?: string; cloumn?: string; height?: string | number; }; mask?: boolean | any; }); /** * 加载新数据 或 刷新数据 * @param [newOptions] - 新设定的参数,会与类的构造参数合并。 * @param [newOptions.url] - geojson文件或服务url地址 * @param [newOptions.data] - geojson格式规范数据对象,与url二选一即可。 * @param [newOptions.类参数] - 包含当前类支持的所有参数 * @param [newOptions.通用参数] - 包含父类支持的所有参数 * @returns 当前对象本身,可以链式调用 */ load(newOptions?: { url?: string; data?: any; 类参数?: any; 通用参数?: BaseGraphicLayer.ConstructorOptions; }): this; } /** * 矢量数据图层组,主要用于 多图层的标绘 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.center] - 图层自定义定位视角 * @param [options.layers] - 子图层数组,每个子图层的配置见按各类型图层配置即可。 */ declare class GraphicGroupLayer extends GroupLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; layers?: GraphicLayer[]; }); /** * 是否可以编辑 */ readonly hasEdit: boolean; /** * 当前激活的图层 */ selectedLayer: GraphicLayer; /** * 创建并添加指定名称的图层 * @param name - 图层名称 * @returns 创建完成的图层 */ createLayer(name: string): GraphicLayer; /** * 删除指定名称的图层 * @param name - 图层名称 * @returns 是否删除成功 */ deleteLayer(name: string): boolean; /** * 删除所有没有数据的矢量图层 * @returns 当前对象本身,可以链式调用 */ deleteEmptyLayer(): this; /** * 移动矢量对象到新分组 * @param graphic - 矢量对象 * @param layer - 图层 * @returns 无 */ moveToLayer(graphic: BaseGraphic, layer: GraphicLayer): void; /** * 获取图层内 所有矢量数据 * @returns 矢量数据数组 */ getGraphics(): BaseGraphic[]; /** * 根据id或uuid取矢量数据对象 * @param id - 矢量数据id或uuid * @returns 矢量数据对象 */ getGraphicById(id: string | number): BaseGraphic; /** * 遍历所有矢量数据并将其作为参数传递给回调函数 * @param method - 回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ eachGraphic(method: (...params: any[]) => any, context: any): this; /** * 清除图层内所有矢量数据 * @param [hasDestory = false] - 是否释放矢量对象 * @returns 无 */ clear(hasDestory?: boolean): void; /** * 将图层数据导出为GeoJSON格式规范对象。 * @param [options] - 参数对象: * @param [options.noAlt] - 不导出高度值 * @returns GeoJSON格式规范对象 */ toGeoJSON(options?: { noAlt?: boolean; }): any; /** * 加载转换GeoJSON格式规范数据为Graphic后加载到图层中。 * @param geojson - GeoJSON格式规范数据 * @param [options] - 加载控制参数,包含: * @param [options.clear = false] - 是否清除图层已有数据 * @param [options.flyTo = false] - 是否加载完成后进行飞行到数据区域 * @param [options.style] - 可以设置指定style样式 * @param [options.layer] - 指定导入所有数据到指定的图层 * @returns 转换后的Graphic对象数组 */ loadGeoJSON(geojson: string | any, options?: { clear?: boolean; flyTo?: boolean; style?: any; layer?: string; }): BaseGraphic[]; /** * 开始绘制矢量数据,绘制的数据会加载在当前图层。 * @param options - Graphic构造参数,包含: * @param options.type - 类型 * @param [options.其他] - 按type支持{@link GraphicType}类的构造方法参数 * @returns 创建完成的矢量数据对象 */ startDraw(options: { type: GraphicType; 其他?: any; }): BaseGraphic; /** * 停止绘制,如有未完成的绘制会自动删除 * @returns 当前对象本身,可以链式调用 */ stopDraw(): this; /** * 激活编辑,绑定相关处理,同 hasEdit=true * @returns 当前对象本身,可以链式调用 */ activateEdit(): this; /** * 释放编辑,解除绑定相关事件,同 hasEdit=false * @returns 当前对象本身,可以链式调用 */ disableEdit(): this; } declare namespace GraphicLayer { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.load, function (event) { * console.log('矢量数据对象加载完成', event) * }) * @property 通用 - 支持的父类的事件类型 * @property addGraphic - 添加矢量数据时 * @property removeGraphic - 移除矢量数据时 * @property drawStart - 开始绘制 标绘事件 * @property drawMouseMove - 正在移动鼠标中,绘制过程中鼠标移动了点 标绘事件 * @property drawAddPoint - 绘制过程中增加了点 标绘事件 * @property drawRemovePoint - 绘制过程中删除了最后一个点 标绘事件 * @property drawCreated - 创建完成 标绘事件 * @property editStart - 开始编辑 标绘事件 * @property editMouseDown - 移动鼠标按下左键(LEFT_DOWN)标绘事件 * @property editMouseMove - 正在移动鼠标中,正在编辑拖拽修改点中(MOUSE_MOVE) 标绘事件 * @property editMovePoint - 编辑修改了点(LEFT_UP)标绘事件 * @property editRemovePoint - 编辑删除了点 标绘事件 * @property editStyle - 图上编辑修改了相关style属性 标绘事件 * @property editStop - 停止编辑 标绘事件 */ type EventType = { 通用: BaseGraphicLayer.EventType; addGraphic: string; removeGraphic: string; drawStart: string; drawMouseMove: string; drawAddPoint: string; drawRemovePoint: string; drawCreated: string; editStart: string; editMouseDown: string; editMouseMove: string; editMovePoint: string; editRemovePoint: string; editStyle: string; editStop: string; }; } /** * 矢量数据图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.hasEdit = false] - 是否自动激活编辑(true时,单击后自动激活编辑) * @param [options.isAutoEditing = true] - 完成标绘时是否自动启动编辑(需要hasEdit:true时) * @param [options.isContinued = false] - 是否连续标绘 * @param [options.isRestorePositions = false] - 在标绘和编辑结束时,是否将坐标还原为普通值,true: 停止编辑时会有闪烁,但效率要好些。 * @param [options.data = null] - 需要自动加载的数据,内部自动生成Graphic对象。{@link GraphicUtil#.create} * @param options.clustering - 点数据时,设置聚合相关参数: * @param [options.clustering.enabled = false] - 是否开启聚合 * @param [options.clustering.pixelRange = 20] - 多少像素矩形范围内聚合 * @param [options.clustering.clampToGround = true] - 是否贴地 * @param [options.clustering.radius = 26] - 内置样式时,圆形图标的半径大小(单位:像素) * @param [options.clustering.fontColor = '#ffffff'] - 内置样式时,数字的颜色 * @param [options.clustering.color = 'rgba(181, 226, 140, 0.6)'] - 内置样式时,圆形图标的背景颜色 * @param [options.clustering.opacity = 0.5] - 内置样式时,圆形图标的透明度 * @param [options.clustering.borderWidth = 5] - 圆形图标的边框宽度(单位:像素),0不显示 * @param [options.clustering.borderColor = 'rgba(110, 204, 57, 0.5)'] - 内置样式时,圆形图标的边框颜色 * @param [options.clustering.borderOpacity = 0.6] - 内置样式时,圆形图标边框的透明度 * @param [options.clustering.getImage] - 自定义聚合的图标样式,例如:getImage:function(count) { return image} * @param [options.stopPropagation = false] - 当前类中事件是否停止冒泡, false时:事件冒泡到map中。 */ declare class GraphicLayer extends BaseGraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; hasEdit?: boolean; isAutoEditing?: boolean; isContinued?: boolean; isRestorePositions?: boolean; data?: any | object[]; clustering: { enabled?: boolean; pixelRange?: number; clampToGround?: boolean; radius?: number; fontColor?: string; color?: string; opacity?: number; borderWidth?: number; borderColor?: string; borderOpacity?: number; getImage?: (...params: any[]) => any; }; stopPropagation?: boolean; }); /** * 是否聚合(点数据时) */ clustering: boolean; /** * 当加载Entity类型数据的内部Cesium容器 {@link BaseEntity} */ readonly dataSource: Cesium.CustomDataSource; /** * 当加载普通 primitive类型数据的内部Cesium容器 {@link BasePrimitive} */ primitiveCollection: Cesium.PrimitiveCollection; /** * 当加载 DivGraphic 数据的内部DOM容器 {@link DivGraphic} */ readonly container: Element; /** * 当加载 DivGraphic 数据的DIV是否可以鼠标交互,为false时可以穿透操作及缩放地图,但无法进行鼠标交互及触发相关事件。 */ pointerEvents: boolean; /** * 是否可以调整图层顺序(在同类型图层间) */ readonly hasZIndex: boolean; /** * 图层顺序,数字大的在上面。(当hasZIndex为true时) */ zIndex: number; /** * 图层内的Graphic矢量数据个数 */ readonly length: number; /** * 图层内的Graphic集合对象 */ readonly graphics: BaseGraphic[]; /** * 是否自动激活编辑(true时,单击后自动激活编辑) */ readonly hasEdit: boolean; /** * 是否正在编辑状态 */ readonly isEditing: boolean; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; /** * 将图层数据导出为GeoJSON格式规范对象。 * @param [options] - 参数对象: * @param [options.noAlt] - 不导出高度值 * @returns GeoJSON格式规范对象 */ toGeoJSON(options?: { noAlt?: boolean; }): any; /** * 加载转换GeoJSON格式规范数据为Graphic后加载到图层中。 * @param geojson - GeoJSON格式规范数据 * @param [options] - 加载控制参数,包含: * @param [options.clear = false] - 是否清除图层已有数据 * @param [options.flyTo = false] - 是否加载完成后进行飞行到数据区域 * @param [options.style] - 可以设置指定style样式 * @returns 转换后的Graphic对象数组 */ loadGeoJSON(geojson: string | any, options?: { clear?: boolean; flyTo?: boolean; style?: any; }): BaseGraphic[]; /** * 添加Graphic矢量数据 * @param graphic - 矢量数据 * @returns 添加后的Graphic对象 */ addGraphic(graphic: BaseGraphic | BaseGraphic[]): BaseGraphic | BaseGraphic[]; /** * 移除Graphic矢量数据 * @param graphic - 矢量数据 * @param [hasDestory = false] - 是否释放矢量对象 * @returns 当前对象本身,可以链式调用 */ removeGraphic(graphic: BaseGraphic, hasDestory?: boolean): this; /** * 根据id或uuid取矢量数据对象 * @param id - 矢量数据id或uuid * @returns 矢量数据对象 */ getGraphicById(id: string | number): BaseGraphic; /** * 根据 指定属性 获取 单个矢量数据对象(多个匹配时取首个) * @param attrName - 属性名称值(如id、name等) * @param attrVal - 属性值 * @returns 矢量数据对象 */ getGraphicByAttr(attrName: any | string | number, attrVal: string): BaseGraphic; /** * 根据 指定属性 获取 矢量数据对象 数组 * @param attrName - 属性名称值(如id、name等) * @param attrVal - 属性值 * @returns 矢量数据对象 */ getGraphicsByAttr(attrName: any | string | number, attrVal: string): BaseGraphic[]; /** * 遍历所有矢量数据并将其作为参数传递给回调函数 * @param method - 回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ eachGraphic(method: (...params: any[]) => any, context: any): this; /** * 获取图层内 所有矢量数据 * @returns 矢量数据数组 */ getGraphics(): BaseGraphic[]; /** * 清除图层内所有矢量数据 * @param [hasDestory = false] - 是否释放矢量对象 * @returns 无 */ clear(hasDestory?: boolean): void; /** * 异步计算更新坐标进行贴地(或贴模型) * @param [options = {}] - 参数对象: * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param options.callback - 异步计算高度完成后 的回调方法 * @param options.endItem - 异步计算高度完成后 的回调方法 * @returns 当前对象本身,可以链式调用 */ clampToGround(options?: { has3dtiles?: boolean; objectsToExclude?: object[]; callback: (...params: any[]) => any; endItem: (...params: any[]) => any; }): this; /** * 开始绘制矢量数据,绘制的数据会加载在当前图层。 * @param options - Graphic构造参数,包含: * @param options.type - 类型 * @param [options.其他] - 按type支持 {@link GraphicType} 类的构造方法参数 * @param [options.success] - 绘制创建完成的回调方法,同drawCreated事件,例如: success: function (graphic){ } * @returns 创建完成的矢量数据对象 */ startDraw(options: { type: GraphicType; 其他?: any; success?: (...params: any[]) => any; }): BaseGraphic; /** * 停止绘制,如有未完成的绘制会自动删除 * @returns 当前对象本身,可以链式调用 */ stopDraw(): this; /** * 完成绘制和编辑,如有未完成的绘制会自动完成。 * 在移动端需要调用此方法来类似PC端双击结束。 * @returns 当前对象本身,可以链式调用 */ endDraw(): this; /** * 激活编辑,绑定相关处理,同 hasEdit=true * @returns 当前对象本身,可以链式调用 */ activateEdit(): this; /** * 释放编辑,解除绑定相关事件,同 hasEdit=false * @returns 当前对象本身,可以链式调用 */ disableEdit(): this; /** * 激活编辑指定的矢量数据 * @param graphic - 需要激活编辑的矢量数据 * @param [event] - 内部使用,传递事件 * @returns 当前对象本身,可以链式调用 */ startEditing(graphic: BaseGraphic, event?: any): this; /** * 停止编辑,释放正在编辑的对象。 * @param [graphic] - 需要停止编辑的矢量数据,默认为上一次正在编辑的对象 * @returns 当前对象本身,可以链式调用 */ stopEditing(graphic?: BaseGraphic): this; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } /** * 经纬网 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.lineStyle] - 线的样式 * @param [options.labelStyle] - 文本的样式 * @param [options.numLines = 10] - 网格数 */ declare class GraticuleLayer extends BaseLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; lineStyle?: PolylinePrimitive.StyleOptions; labelStyle?: LabelEntity.StyleOptions; numLines?: number; }); /** * 对象添加到地图前创建一些对象的钩子方法, * 只会调用一次 * @returns 无 */ _mountedHook(): void; } declare namespace LodGraphicLayer { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.addGraphic, function (event) { * console.log('添加了矢量数据', event) * }) * @property 通用 - 支持的父类的事件类型 * @property addGraphic - 添加矢量数据时 * @property removeGraphic - 移除矢量数据时 */ type EventType = { 通用: BaseGraphicLayer.EventType; addGraphic: string; removeGraphic: string; }; } /** * 矢量数据LOD分层分块加载类 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.IdField = 'id'] - 数据中唯一标识的属性字段名称 * @param options.queryGridData - 获取网格内对应数据的的外部处理回调方法 * @param options.createGraphic - 根据数据创建矢量对象的外部处理回调方法 * @param options.updateGraphic - 根据数据更新矢量对象的外部处理回调方法,一般动态数据时可以用 * @param options.debuggerTileInfo - 是否开启测试显示瓦片信息 * @param [options.minimumLevel = 0] - 图层所支持的最低层级,当地图小于该级别时,平台不去请求服务数据。【影响效率的重要参数】 * @param [options.maximumLevel] - 图层所支持的最大层级,当地图大于该级别时,平台不去请求服务数据。 * @param options.rectangle - 瓦片数据的矩形区域范围 * @param options.rectangle.xmin - 最小经度值, -180 至 180 * @param options.rectangle.xmax - 最大纬度值, -180 至 180 * @param options.rectangle.ymin - 最小纬度值, -90 至 90 * @param options.rectangle.ymax - 最大纬度值, -90 至 90 * @param options.bbox - bbox规范的瓦片数据的矩形区域范围,与rectangle二选一即可。 * @param options.clustering - 设置聚合相关参数: * @param [options.clustering.enabled = false] - 是否开启聚合 * @param [options.clustering.pixelRange = 20] - 多少像素矩形范围内聚合 * @param [options.clustering.clampToGround = true] - 是否贴地 * @param [options.clustering.radius = 28] - 圆形图标的整体半径大小(单位:像素) * @param [options.clustering.radiusIn = radius-5] - 圆形图标的内圆半径大小(单位:像素) * @param [options.clustering.fontColor = '#ffffff'] - 数字的颜色 * @param [options.clustering.color = 'rgba(181, 226, 140, 0.6)'] - 圆形图标的背景颜色,默认自动处理 * @param [options.clustering.colorIn = 'rgba(110, 204, 57, 0.5)'] - 圆形图标的内圆背景颜色,默认自动处理 * @param [options.symbol] - 矢量数据的style样式,为Function时是完全自定义的回调处理 symbol(attr, style, feature) * @param options.symbol.styleOptions - 点数据时的Style样式,可以附加 model {@link ModelEntity.StyleOptions} 或 point {@link PointEntity.StyleOptions} * @param options.symbol.styleOptions - 线数据时的Style样式,可以附加 corridor {@link CorridorEntity.StyleOptions} * @param options.symbol.styleOptions - 面数据时的Style样式 * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [options.symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, styleOpt){ return { color: "#ff0000" }; } */ declare class LodGraphicLayer extends GraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; IdField?: string; queryGridData: (...params: any[]) => any; createGraphic: (...params: any[]) => any; updateGraphic: (...params: any[]) => any; debuggerTileInfo: boolean; minimumLevel?: number; maximumLevel?: number; rectangle: { xmin: number; xmax: number; ymin: number; ymax: number; }; bbox: Number[]; clustering: { enabled?: boolean; pixelRange?: number; clampToGround?: boolean; radius?: number; radiusIn?: number; fontColor?: string; color?: string; colorIn?: string; }; symbol?: { styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleOptions: PolygonEntity.StyleOptions; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }; }); /** * 根据LOD分块信息去请求对应的Tile瓦块内的数据 * @param grid - 瓦片信息对象 * @param callback - 数据获取完成后调用该回调方法。如:callback(grid, arrdata) * @returns 无 */ queryGridData(grid: any, callback: (...params: any[]) => any): void; /** * 根据 attr属性 创建 矢量对象 * @param grid - 瓦片信息对象 * @param attr - 数据的属性信息 * @returns 矢量对象 */ createGraphic(grid: any, attr: any): Graphic; /** * 根据 attr属性 更新 矢量对象,主要是属性是动态变化的场景下使用。 * @param graphic - 矢量对象 * @param attr - 数据的属性信息 * @returns 无 */ updateGraphic(graphic: Graphic, attr: any): void; /** * 清除图层内所有矢量数据 * @param [hasDestory = false] - 是否释放矢量对象 * @returns 无 */ clear(hasDestory?: boolean): void; /** * 重新加载数据 * @returns 无 */ reload(): void; } /** * gltf小模型图层 * @example * //方式1:单个模型时,直接按下面传入position即可 * let gltfLayer = new mars3d.layer.ModelLayer({ * name: '上海浦东', * url: 'http://data.mars3d.cn/gltf/mars/shanghai/scene.gltf', * style: { scale: 520, heading: 215 }, //style同标绘的model类型 * position: [121.507762, 31.233975, 200], * }) * map.addLayer(gltfLayer) * * //方式2:多个模型时,可以传入data属性构造 * let gltfLayer = new mars3d.layer.ModelLayer({ * name: '骨骼动画', * data: [ * { * url: 'http://data.mars3d.cn/gltf/mars/fengche.gltf', * position: [117.170624, 31.840666, 278.66], * style: { scale: 200, heading: 270 }, * }, * { * url: 'http://data.mars3d.cn/gltf/mars/firedrill/xiaofangyuan-run.gltf', * position: [117.184442, 31.842172, 33.92], * style: { scale: 300 }, * }, * ], * }) * map.addLayer(gltfLayer) * * * //方式3: 多个同属性(url和style完全相同)模型时,可以直接简化,传入positions属性。 * let gltfLayer = new mars3d.layer.ModelLayer({ * name: '风力发电机', * url: 'http://data.mars3d.cn/gltf/mars/fengche.gltf', * style: { scale: 40, heading: 135, minimumPixelSize: 30, clampToGround: true }, * positions: [ * { lng: 112.227630577, lat: 39.0613382363999, alt: 1815 }, * { lng: 112.229302206, lat: 39.0579481036999, alt: 1827 }, * { lng: 112.226596341, lat: 39.0584773033999, alt: 1849 }, * ], * }) * map.addLayer(gltfLayer) * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - 【方式1】模型的url地址 * @param options.position - 模型所在位置坐标 * @param options.style - 模型的样式配置 * @param options.data - 【方式2】多个模型时,可以传入data数组构造: * @param options.data.url - 模型的url地址 * @param options.data.position - 模型所在位置坐标 * @param options.data.style - 模型的样式配置 * @param options.positions - 【方式3】多个同属性(url和style完全相同)模型时,可以直接简化,传入positions属性。 * @param [options.hasEdit = false] - 是否可编辑 * @param [options.isAutoEditing = true] - 完成标绘时是否自动启动编辑(需要hasEdit:true时) * @param [options.isContinued = false] - 是否连续标绘 */ declare class ModelLayer extends GraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url: string; position: LatLngPoint | Cesium.Cartesian3; style: any; data: { url: string; position: LatLngPoint | Cesium.Cartesian3; style: any; }[]; positions: LatLngPointp[] | Cesium.Cartesian3[]; hasEdit?: boolean; isAutoEditing?: boolean; isContinued?: boolean; }); /** * 加载gltf模型数据的内部Cesium容器 */ readonly layer: Cesium.CustomDataSource; } /** * OSM在线 建筑物模型 * @param options - 参数对象, 构造参数建议从{@link http://mars3d.cn/example/g20_3dtiles_edit.html|模型编辑页面}设置后保存参数后拷贝json参数即可。参数包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.style] - 模型样式, 使用{@link https://github.com/CesiumGS/3d-tiles/tree/master/specification/Styling|3D Tiles Styling language}. * @param [options.highlight] - 鼠标移入或单击(type:'click')后的对应高亮的部分样式 * @param [options.highlight.type] - 鼠标移入高亮 或 单击高亮(type:'click') * @param [options.highlight.color = '#FFFF00'] - 颜色,支持rgba字符串 * @param [options.highlight.opacity = 1.0] - 透明度 */ declare class OsmBuildingsLayer extends TilesetLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; style?: any | Cesium.Cesium3DTileStyle; highlight?: { type?: string; color?: string; opacity?: number; }; }); } declare namespace TilesetLayer { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.load, function (event) { * console.log('矢量数据对象加载完成', event) * }) * @property 通用 - 支持的父类的事件类型 * @property initialTilesLoaded - 3dtiles模型,模型瓦片初始化完成 该回调只执行一次 * @property allTilesLoaded - 3dtiles模型 * @property loadBefore - 完成加载,但未做任何其他处理前 * @property load - 完成加载,执行所有内部处理后 */ type EventType = { 通用: BaseGraphicLayer.EventType; initialTilesLoaded: string; allTilesLoaded: string; loadBefore: string; load: string; }; } /** * 3dtiles 三维模型图层。 * @param options - 参数对象, 构造参数建议从{@link http://mars3d.cn/example/g20_3dtiles_edit.html|模型编辑页面}设置后保存参数后拷贝json参数即可。参数包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - tileset的主JSON文件的 url * @param [options.maximumScreenSpaceError = 16] - 用于驱动细化细节级别的最大屏幕空间错误。数值加大,能让最终成像变模糊 * @param [options.maximumMemoryUsage = 512] - 数据集可以使用的最大内存量(以MB计)。这个参数默认是512,也即是当几何体和纹理资源大于512MB的时候,Cesium就会淘汰掉当前帧中没有visited的所有块,这个值其实很小,也是cesium为了避免资源占用过高的一个保障,不过上述我们也估算过最差情况下,没有做纹理crn压缩的情况下,这个值很容易被超过,导致很多人误以为cesium的淘汰没有效果。这个值如果设置的过小,导致cesium几乎每帧都在尝试淘汰数据,增加了遍历的时间,也同时增加了崩溃的风险。这个值如果设置的过大,cesium的淘汰机制失效,那么容易导致显存超过显卡内存,也会导致崩溃。 这个值应该处于最差视角下资源占用 和 显存最大量之间。结论:这个参数要根据当前显卡显存来配置,如果我们场景只显示这一个模型数据,这个可以设置到显存的50 % 左右,比如我的显存是6G,这个可以设置到3000左右。那么既保证不超过显存限制,又可以最大利用显存缓存,配合crn压缩之后,这个几乎可以保证你第二次查看模型同一位置的时候,看不到加载过程,非常棒。 * @param [options.shadows = ShadowMode.ENABLED] - 确定tileset是否投射或接收来自光源的阴影。 * @param [options.cullWithChildrenBounds = true] - 优化选择。是否使用子绑定卷的并集来筛选贴图。 * @param [options.cullRequestsWhileMoving = true] - 优化选择。不要要求贴图,当他们回来的时候可能不会使用,因为相机的运动。这个优化只适用于固定瓷砖组。 * @param [options.cullRequestsWhileMovingMultiplier = 60.0] - 优化选择。在移动时选择请求时使用的倍增器。越大的选择性越强,越小的选择性越弱。值越小能够更快的剔除。 * @param [options.preloadWhenHidden = false] - 当true时,tileset.show是false,也去预加载数据。 * @param [options.preloadFlightDestinations = true] - 优化选择。当摄像机在飞行时,在摄像机的飞行目的地预加载贴图。 * @param [options.preferLeaves = false] - 优化选择。最好先加载上叶子节点数据。这个参数默认是false,同等条件下,叶子节点会优先加载。但是Cesium的tile加载优先级有很多考虑条件,这个只是其中之一,如果skipLevelOfDetail=false,这个参数几乎无意义。所以要配合skipLevelOfDetail=true来使用,此时设置preferLeaves=true。这样我们就能最快的看见符合当前视觉精度的块,对于提升大数据以及网络环境不好的前提下有一点点改善意义。 * @param [options.dynamicScreenSpaceError = false] - 优化选择。减少远离摄像头的贴图的屏幕空间误差。true时会在真正的全屏加载完之后才清晰化模型. * @param [options.dynamicScreenSpaceErrorDensity = 0.00278] - 密度用来调整动态画面空间误差,类似于雾密度。 * @param [options.dynamicScreenSpaceErrorFactor = 4.0] - 用于增加计算的动态屏幕空间误差的因素。 * @param [options.dynamicScreenSpaceErrorHeightFalloff = 0.25] - 瓷砖密度开始下降时的高度之比。 * @param [options.progressiveResolutionHeightFraction = 0.3] - 优化选择。如果在(0.0,0.5)之间,在屏幕空间或以上的瓷砖错误降低屏幕分辨率 <code>progressiveResolutionHeightFraction*screenHeight</code> 将优先。这可以帮助得到一个快速层的瓷砖下来,而全分辨率的瓷砖继续加载。 * @param [options.foveatedScreenSpaceError = true] - 优化选择。通过暂时提高屏幕边缘的贴图的屏幕空间误差,优先加载屏幕中央的贴图。一旦所有由{@link cesium3dtilesset#foveatedConeSize}确定的屏幕中央的贴图被加载,屏幕空间错误就会恢复正常。 * @param [options.foveatedConeSize = 0.1] - 优化选择。当{@link cesium3dtilesset#foveatedScreenSpaceError}为true时使用,以控制决定哪些贴图被延迟的锥大小。装在这个圆锥体里的瓷砖会立即被装入。锥外的贴图有可能被延迟,这取决于它们在锥外的距离和它们的屏幕空间误差。这是由{@link Cesium3DTileset#foveatedInterpolationCallback}和{@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}控制的。设置为0.0意味着圆锥将是由相机位置和它的视图方向形成的线。将此设置为1.0意味着圆锥将包含相机的整个视场,禁用此效果。 * @param [options.foveatedMinimumScreenSpaceErrorRelaxation = 0.0] - 优化选择。当{@link cesium3dtilesset#foveatedScreenSpaceError}为true时使用,以控制中心锥形以外的贴图的初始屏幕空间误差松弛。屏幕空间错误将基于所提供的{@link Cesium3DTileset#foveatedInterpolationCallback}从tileset值开始直到{@link Cesium3DTileset#maximumScreenSpaceError}。 * @param [options.foveatedInterpolationCallback = Math.lerp] - 优化选择。当{@link cesium3dtilesset#foveatedScreenSpaceError}为true时使用,以控制中心锥形以外的贴图的初始屏幕空间误差松弛。优化选择。当{@link Cesium3DTileset#foveatedScreenSpaceError}为true时使用,以控制凸出圆锥外的贴图的屏幕空间误差提高多少,插值在{@link Cesium3DTileset#foveatedminimumscreenspaceerror}和{@link Cesium3DTileset#maximumScreenSpaceError}之间。 * @param [options.foveatedTimeDelay = 0.2] - 优化选择。当{@link cesium3dtilesset#foveatedScreenSpaceError}为true时使用,以控制中心锥形以外的贴图的初始屏幕空间误差松弛。优化选择。优化选择。当{@link cesium3dtilesset#foveatedScreenSpaceError}为true时使用,以控制在延迟tile开始加载前摄像机停止移动后等待多长时间(秒)。这个时间延迟阻止了在相机移动时请求屏幕边缘的贴图。将此设置为0.0将立即请求任何给定视图中的所有贴图。 * @param [options.skipLevelOfDetail = false] - 优化选择。确定在遍历过程中是否应应用跳过详细信息的级别。是Cesium在1.5x 引入的一个优化参数,这个参数在金字塔数据加载中,可以跳过一些级别,这样整体的效率会高一些,数据占用也会小一些。但是带来的异常是:1) 加载过程中闪烁,看起来像是透过去了,数据载入完成后正常。2,有些异常的面片,这个还是因为两级LOD之间数据差异较大,导致的。当这个参数设置false,两级之间的变化更平滑,不会跳跃穿透,但是清晰的数据需要更长,而且还有个致命问题,一旦某一个tile数据无法请求到或者失败,导致一直不清晰。所以我们建议:对于网络条件好,并且数据总量较小的情况下,可以设置false,提升数据显示质量。 * @param [options.baseScreenSpaceError = 1024] - 当skipLevelOfDetail为true时,跳过详细级别之前必须达到的屏幕空间错误。 * @param [options.skipScreenSpaceErrorFactor = 16] - 当skipLevelOfDetail = true时,一个定义要跳过的最小屏幕空间错误的乘法器。与skipLevels一起使用,以决定加载哪些贴图。 * @param [options.skipLevels = 1] - 当skipLevelOfDetail是true,一个常量定义了加载tiles时要跳过的最小级别数。当它为0时,不会跳过任何级别。与skipScreenSpaceErrorFactor一起使用,以决定加载哪些贴图。 * @param [options.immediatelyLoadDesiredLevelOfDetail = false] - 当skipLevelOfDetail为true时,只有满足最大屏幕空间错误的tiles才会被下载。跳过因素将被忽略,并且只加载所需的块。 * @param [options.loadSiblings = false] - 当skipLevelOfDetail = true时,判断遍历过程中是否总是下载可见块的兄弟块。如果为true则不会在已加载完模型后,自动从中心开始超清化模型。 * @param [options.clippingPlanes] - {@link ClippingPlaneCollection}用于选择性地禁用tile集的渲染。 * @param [options.classificationType] - 确定地形、3D贴图或两者都将被这个贴图集分类。有关限制和限制的详细信息,请参阅{@link cesium3dtilesset #classificationType}。 * @param [options.pointCloudShading] - 基于几何误差和光照构造一个{@link PointCloudShading}对象来控制点衰减的选项。 * @param [options.imageBasedLightingFactor = new Cartesian2(1.0, 1.0)] - 缩放来自地球、天空、大气和星星天空盒的漫反射和高光图像照明。 * @param [options.lightColor] - 光的颜色当遮光模型。当undefined场景的浅色被使用代替。 * @param [options.luminanceAtZenith = 0.2] - 太阳在天顶的亮度,单位是千坎德拉每平方米,用于这个模型的程序环境地图。 * @param [options.sphericalHarmonicCoefficients] - 三阶球面调和系数用于基于图像的漫射色彩照明。 * @param [options.specularEnvironmentMaps] - 一个KTX文件的URL,该文件包含高光照明的立方体映射和复杂的高光mipmaps。 * @param [options.backFaceCulling = true] - 是否剔除面向背面的几何图形。当为真时,背面剔除由glTF材质的双面属性决定;当为false时,禁用背面剔除。 * @param [options.debugHeatmapTilePropertyName] - 是否剔除面向背面的几何图形。当为真时,背面剔除由glTF材质的双面属性决定;作为热图着色的tile变量。所有渲染的贴图都将相对于其他指定的变量值着色。 * @param [options.pickPrimitive] - 要在拾取过程中呈现的原语,而不是tile集合。 * @param [options.position] - 模型新的中心点位置(移动模型) * @param options.position.lng - 经度值, 180 - 180 * @param options.position.lat - 纬度值, -90 - 90 * @param options.position.alt - 高度值(单位:米) * @param [options.rotation] - 模型的旋转方向 * @param options.rotation.x - X方向,角度值0-360 * @param options.rotation.y - Y方向,角度值0-360 * @param options.rotation.z - 四周方向,角度值0-360 * @param [options.scale = 1] - 缩放比例 * @param [options.axis = ''] - 轴方向 * @param [options.modelMatrix] - 模型的矩阵位置,内部无坐标位置的模型使用,此时position和rotation等参数均无效。 * @param [options.updateMatrix] - 外部自定义修复模型矩阵位置 * @param [options.chinaCRS] - 标识模型的国内坐标系(用于自动纠偏或加偏) * @param [options.style] - 模型样式, 使用{@link https://github.com/CesiumGS/3d-tiles/tree/master/specification/Styling|3D Tiles Styling language}. * @param [options.marsJzwStyle = false] - 开启或设置建筑物特效样式。 * @param [options.highlight] - 高亮及其样式配置 * @param [options.highlight.type] - 鼠标移入高亮 或 单击高亮(type:'click') * @param [options.highlight.color = '#FFFF00'] - 颜色,支持rgba字符串 * @param [options.highlight.opacity = 1.0] - 透明度 * @param [options.highlight.outlineEffect = false] - 默认为修改矢量对象本身的style高亮,true时采用{@link OutlineEffect}方式高亮。 * @param [options.highlight.其他] - outlineEffect:true时对应的参数信息 * @param [options.clampToGround] - 是否贴地,true时自动调用贴地计算,但此属性只适合标准的与地形数据匹配的模型,并不精确,建议通过模型编辑页面调试给具体高度值。 */ declare class TilesetLayer extends BaseGraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url: Resource | string; maximumScreenSpaceError?: number; maximumMemoryUsage?: number; shadows?: ShadowMode; cullWithChildrenBounds?: boolean; cullRequestsWhileMoving?: boolean; cullRequestsWhileMovingMultiplier?: number; preloadWhenHidden?: boolean; preloadFlightDestinations?: boolean; preferLeaves?: boolean; dynamicScreenSpaceError?: boolean; dynamicScreenSpaceErrorDensity?: number; dynamicScreenSpaceErrorFactor?: number; dynamicScreenSpaceErrorHeightFalloff?: number; progressiveResolutionHeightFraction?: number; foveatedScreenSpaceError?: boolean; foveatedConeSize?: number; foveatedMinimumScreenSpaceErrorRelaxation?: number; foveatedInterpolationCallback?: Cesium3DTileset.foveatedInterpolationCallback; foveatedTimeDelay?: number; skipLevelOfDetail?: boolean; baseScreenSpaceError?: number; skipScreenSpaceErrorFactor?: number; skipLevels?: number; immediatelyLoadDesiredLevelOfDetail?: boolean; loadSiblings?: boolean; clippingPlanes?: ClippingPlaneCollection; classificationType?: ClassificationType; pointCloudShading?: any; imageBasedLightingFactor?: Cartesian2; lightColor?: Cartesian3; luminanceAtZenith?: number; sphericalHarmonicCoefficients?: Cartesian3[]; specularEnvironmentMaps?: string; backFaceCulling?: boolean; debugHeatmapTilePropertyName?: string; pickPrimitive?: any; position?: { lng: number; lat: number; alt: number; }; rotation?: { x: number; y: number; z: number; }; scale?: number; axis?: string | Cesium.Axis; modelMatrix?: Cesium.Matrix4; updateMatrix?: (...params: any[]) => any; chinaCRS?: ChinaCRS; style?: any | Cesium.Cesium3DTileStyle | ((...params: any[]) => any); marsJzwStyle?: boolean | string; highlight?: { type?: string; color?: string; opacity?: number; outlineEffect?: boolean; 其他?: OutlineEffect.Options; }; clampToGround?: boolean; }); /** * 原始的旋转角度,示例:{ x: 0, y: 0, z: 0 } */ readonly orginRotation: any; /** * 模型对应的 Cesium3DTileset对象 */ readonly tileset: Cesium.Cesium3DTileset; /** * 鼠标移入或单击(type:'click')后的对应高亮的部分样式,空值时不高亮 */ readonly highlight: any; /** * 开启或设置建筑物特效样式。 */ marsJzwStyle: boolean | any; /** * 模型样式, * 使用{@link https://github.com/CesiumGS/3d-tiles/tree/master/specification/Styling|3D Tiles Styling language}. */ style: any | Cesium.Cesium3DTileStyle | ((...params: any[]) => any); /** * 模型原始的中心点坐标 */ readonly orginCenterPoint: LatLngPoint; /** * 模型原始的中心点坐标 (笛卡尔坐标) */ readonly orginCenterPosition: Cesium.Cartesian3; /** * 模型当前中心点坐标 (笛卡尔坐标) */ readonly position: Cesium.Cartesian3; /** * 模型当前中心点坐标 */ center: LatLngPoint; /** * 调整修改模型高度 */ height: LatLngPoint; /** * 旋转方向,示例:{ x: 0, y: 0, z: 0 } */ rotation: any; /** * X轴上的旋转方向 */ rotation_x: number; /** * Y轴上的旋转方向 */ rotation_y: number; /** * Z轴上的旋转方向 */ rotation_z: number; /** * 轴方向 */ axis: string | Cesium.Axis; /** * 缩放比例 */ scale: number; /** * 模型自动贴地计算及处理, * 因为模型在设计或生产时,模型的视角中心位置不一定在0,0,0点,此方法不是唯一准确的。 * @param [addHeight = 1] - 计算完成的贴地高度基础上增加的高度值。 * @returns 无 */ clampToGround(addHeight?: number): void; /** * 重新计算当前矩阵(需要是否存在世界矩阵时) * @returns 计算完成的矩阵 */ updateMatrix(): Cesium.Matrix4 | undefined; /** * 重新计算当前矩阵,普通方式, 此种方式[x,y不能多次更改] * @returns 计算完成的矩阵 */ updateMatrix2(): Cesium.Matrix4; /** * 获取构件节点位置,现对于原始矩阵变化后的新位置 * @param position - 原始位置 * @returns 新位置 */ getPositionByOrginMatrix(position: Cesium.Cartesian3): Cesium.Cartesian3; /** * 设置透明度 * @param value - 透明度 * @returns 无 */ setOpacity(value: number): void; /** * 设置自定义Shader到Feature上 * @param customShader - Shader代码 * @returns 当前图层本身图层 */ setCustomShader(customShader: string): TilesetLayer; /** * 设置属性信息到Feature上 * @param idField - 数据中唯一标识的属性字段名称 * @param properties - 属性值数组 * @returns 当前图层本身图层 */ setProperties(idField: string, properties: object[]): TilesetLayer; /** * 高亮对象。 * @param [highlightStyle] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @returns 无 */ openHighlight(highlightStyle?: any): void; /** * 清除已选中的高亮 * @returns 无 */ closeHighlight(): void; /** * 绑定鼠标单击对象后的弹窗。 * @param content - 弹窗内容html字符串,或者回调方法。 * @param options - 控制参数 * @returns 当前对象本身,可以链式调用 */ bindPopup(content: string | any[] | ((...params: any[]) => any), options: Popup.StyleOptions): this; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } /** * WFS图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - WFS服务地址 * @param options.layer - 图层名称(命名空间:图层名称),多个图层名称用逗号隔开 * @param [options.parameters] - 要在URL中 传递给WFS服务GetFeature请求的其他参数。 * @param [options.headers] - 将被添加到HTTP请求头。 * @param [options.proxy] - 加载资源时使用的代理。 * @param [options.IdField = 'id'] - 数据中唯一标识的属性字段名称 * @param options.debuggerTileInfo - 是否开启测试显示瓦片信息 * @param [options.minimumLevel = 0] - 图层所支持的最低层级,当地图小于该级别时,平台不去请求服务数据。【影响效率的重要参数】 * @param [options.maximumLevel] - 图层所支持的最大层级,当地图大于该级别时,平台不去请求服务数据。 * @param options.rectangle - 瓦片数据的矩形区域范围 * @param options.rectangle.xmin - 最小经度值, -180 至 180 * @param options.rectangle.xmax - 最大纬度值, -180 至 180 * @param options.rectangle.ymin - 最小纬度值, -90 至 90 * @param options.rectangle.ymax - 最大纬度值, -90 至 90 * @param options.bbox - bbox规范的瓦片数据的矩形区域范围,与rectangle二选一即可。 * @param options.debuggerTileInfo - 是否开启测试显示瓦片信息 * @param [options.buildings] - 标识当前图层为建筑物白膜类型数据 * @param [options.buildings.bottomHeight] - 建筑物底部高度(如:0) 属性字段名称(如:{bottomHeight}) * @param [options.buildings.cloumn = 1] - 层数,楼的实际高度 = height*cloumn * @param [options.buildings.height = 3.5] - 层高的 固定层高数值(如:10) 或 属性字段名称(如:{height}) * @param options.clustering - 设置聚合相关参数[entity点类型时]: * @param [options.clustering.enabled = false] - 是否开启聚合 * @param [options.clustering.pixelRange = 20] - 多少像素矩形范围内聚合 * @param [options.clustering.clampToGround = true] - 是否贴地 * @param [options.clustering.radius = 28] - 圆形图标的整体半径大小(单位:像素) * @param [options.clustering.radiusIn = radius-5] - 圆形图标的内圆半径大小(单位:像素) * @param [options.clustering.fontColor = '#ffffff'] - 数字的颜色 * @param [options.clustering.color = 'rgba(181, 226, 140, 0.6)'] - 圆形图标的背景颜色,默认自动处理 * @param [options.clustering.colorIn = 'rgba(110, 204, 57, 0.5)'] - 圆形图标的内圆背景颜色,默认自动处理 * @param [options.symbol] - 矢量数据的style样式,为Function时是完全自定义的回调处理 symbol(attr, style, feature) * @param [options.symbol.type] - 标识数据类型,默认是根据数据生成 point、polyline、polygon * @param options.symbol.styleOptions - Style样式,每种不同类型数据都有不同的样式,具体见各矢量数据的style参数。{@link GraphicType} * @param [options.symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [options.symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [options.symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, styleOpt){ return { color: "#ff0000" }; } */ declare class WfsLayer extends LodGraphicLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url: string; layer: string; parameters?: any; headers?: any; proxy?: Cesium.Proxy; IdField?: string; debuggerTileInfo: boolean; minimumLevel?: number; maximumLevel?: number; rectangle: { xmin: number; xmax: number; ymin: number; ymax: number; }; bbox: Number[]; debuggerTileInfo: boolean; buildings?: { bottomHeight?: string; cloumn?: string; height?: string | number; }; clustering: { enabled?: boolean; pixelRange?: number; clampToGround?: boolean; radius?: number; radiusIn?: number; fontColor?: string; color?: string; colorIn?: string; }; symbol?: { type?: GraphicType; styleOptions: any; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }; }); } /** * 图层组,可以用于将多个图层组合起来方便控制(比如将 卫星底图 和 文字注记层 放在一起控制管理),或用于 图层管理 的图层分组节点(虚拟节点)。 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.opacity = 1] - 透明度,取值范围:0.0-1.0 * @param [options.center] - 图层自定义定位视角 * @param [options.layers] - 子图层数组,每个子图层的配置见按各类型图层配置即可。 */ declare class GroupLayer extends BaseGraphicLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; opacity?: number; center?: any; layers?: object[]; }); /** * 子图层对象数组 */ readonly arrLayer: BaseLayer[]; /** * 是否空组 ,空组目前就图层管理用于图层分组节点(虚拟节点)。 */ readonly hasEmptyGroup: boolean; /** * 是否有子图层 */ readonly hasChildLayer: boolean; /** * 子图层的个数 */ readonly length: Int; /** * 是否可以调整透明度 */ readonly hasOpacity: boolean; /** * 是否可以调整图层顺序(在同类型图层间) */ readonly hasZIndex: boolean; /** * 图层顺序,数字大的在上面。(当hasZIndex为true时) */ zIndex: number; /** * 添加子图层,并绑定关联关系。 * @param childlayer - 子图层对象 * @returns 当前对象本身,可以链式调用 */ addLayer(childlayer: BaseLayer): this; /** * 移除子图层,并解除关联关系。 * @param childlayer - 子图层对象 * @returns 当前对象本身,可以链式调用 */ removeLayer(childlayer: BaseLayer): this; /** * 遍历每一个子图层并将其作为参数传递给回调函数 * @param method - 回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ eachLayer(method: (...params: any[]) => any, context: any): this; /** * 获取所有子图层对象 * @returns } 所有子图层对象 */ getLayers(): BaseLayer[]; /** * 根据ID或取图层 * @param id - 图层id或uuid * @returns 图层对象 */ getLayerById(id: string | number): BaseLayer; /** * 根据id或name属性获取图层 * @param name - 图层id或uuid或name值 * @returns 图层对象 */ getLayer(name: string | number): BaseLayer; /** * 是否有同名的子图层,一般用于新增时判断 * @param name - 图层名称 * @param [excludedLayer = null] - 可以指定不进行判断的图层,比如当前图层本身 * @returns 是否同名 */ hasLayer(name: string, excludedLayer?: BaseLayer): boolean; } /** * 地形服务图层,一个地图中只会生效一个地形服务图层(单选) * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示(多个地形服务时,请只设置一个TerrainLayer图层的show为tue) * @param options.terrain - 地形服务配置 * @param [options.terrain.type = 'xyz'] - 地形类型 * @param options.terrain.url - 地形服务地址 * @param [options.terrain.requestVertexNormals = true] - 是否应该从服务器请求额外的光照信息,如果可用,以每个顶点法线的形式。 * @param [options.terrain.requestWaterMask = false] - 是否应该向服务器请求每个瓦的水掩膜(如果有的话)。 * @param [options.terrain.requestMetadata = true] - 是否应该从服务器请求每个块元数据(如果可用)。 */ declare class TerrainLayer extends BaseLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; terrain: { type?: TerrainType; url: string | Cesium.Resource; requestVertexNormals?: boolean; requestWaterMask?: boolean; requestMetadata?: boolean; }; }); } /** * AraGIS生成的金字塔瓦片数据 * @example * let tileLayer = new mars3d.layer.ArcGisCacheLayer({ * url: 'http://data.mars3d.cn/tile/hf/guihua/_alllayers/{z}/{y}/{x}.png', * minimumLevel: 1, * maximumLevel: 17, * minimumTerrainLevel: 1, * // "maximumTerrainLevel": 17, //如果需要大于maximumTerrainLevel层时不显示瓦片,则取消注释 * rectangle: { xmin: 116.846, xmax: 117.642, ymin: 31.533, ymax: 32.185 }, // 控制切片如果在矩形坐标内才显示,如果不在矩形坐标内不显示 * }) * map.addLayer(tileLayer) * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.upperCase] - url请求的瓦片图片名称是否大写。 */ declare class ArcGisCacheLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; upperCase?: boolean; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } declare namespace ArcGisLayer { /** * ArcGIS服务图层支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.loadConfig, function (event) { * console.log('loadConfig', event) * }) * @property loadConfig - 加载metadata配置信息完成事件 * @property click - 鼠标单击事件【enablePickFeatures:true时,支持单击获取对应的矢量对象】 */ type EventType = { loadConfig: string; click: string; }; } /** * ArcGIS标准服务图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - ArcGIS MapServer服务的网址。 * @param [options.layers] - 要显示的图层的逗号分隔列表,如果应显示所有图层,则未定义。 * @param [options.layerDefs] - 可以对动态服务加条件筛选数据,示例:"{\"0\":\"用地编号 = 'R'\"}",具体可以参阅arcgis官方帮助文档理解layerDefs参数。 * @param [options.maxTileLevel] - 指定在小于此层级时用瓦片加载,大于该层级用动态服务.可以在瓦片服务类型时,同时使用瓦片和动态服务。 * @param [options.wkid] - 当非标准EPSG标号时,可以指定wkid值。 * @param [options.token] - 用于通过ArcGIS MapServer服务进行身份验证的ArcGIS令牌。 * @param [options.tileDiscardPolicy] - 于确定图块是否为 无效,应将其丢弃。如果未指定此值,则为默认 {@link DiscardMissingTileImagePolicy} 用于平铺的地图服务器,并且{@link NeverTileDiscardPolicy} 用于非平铺地图服务器。在前一种情况下, 我们要求最大图块级别的图块0,0并检查像素(0,0),(200,20),(20,200), (80,110)和(160,130)。如果所有这些像素都是透明的,则丢弃检查为 禁用,并且不会丢弃任何图块。如果它们中的任何一种具有不透明的颜色, 在这些像素位置具有相同值的图块将被丢弃。的最终结果 对于标准ArcGIS Server,这些默认值应该是正确的图块丢弃。确保 不会丢弃任何图块,为此构造并传递 {@link NeverTileDiscardPolicy} 参数。 * @param [options.usePreCachedTilesIfAvailable = true] - 如果为true,则表示优先使用服务的瓦片图片,没有瓦片时再使用动态服务。如果为false,则将忽略所有瓦片,直接使用动态服务。 * @param [options.maxLength = 5000] - 单击获取到的数据,最大数据长度。大数据解析很卡,可以设定阀值屏蔽大数据,避免卡顿。 * @param [options.highlight] - 鼠标单击高亮显示对应的矢量数据 及其样式 * @param [options.highlight.type] - 构造成的矢量数据类型。 * @param [options.highlight.其他] - style样式,每种不同类型数据都有不同的样式,具体见各{@link GraphicType}矢量数据的style参数。 */ declare class ArcGisLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url: Cesium.Resource | string; layers?: string; layerDefs?: string; maxTileLevel?: number; wkid?: number; token?: string; tileDiscardPolicy?: TileDiscardPolicy; usePreCachedTilesIfAvailable?: boolean; maxLength?: number; highlight?: { type?: GraphicType; 其他?: any; }; }); /** * 绑定鼠标单击对象后的弹窗。 * @param content - 弹窗内容html字符串,或者回调方法。 * @param options - 控制参数 * @returns 当前对象本身,可以链式调用 */ bindPopup(content: string | ((...params: any[]) => any), options: Popup.StyleOptions): this; /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 百度地图 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.layer] - 图层类型,以及以下内容:<br /> * <ul> * <li><code>vec</code>: 电子图层</li> * <li><code>img_d</code>: 卫星影像</li> * <li><code>img_z</code>: 影像注记</li> * <li><code>custom</code>: 自定义样式图层</li> * <li><code>time</code>: 实时路况信息</li> * <li><code>streetview</code>: 街景覆盖图层</li> * </ul> * @param [options.bigfont] - 当layer为vec或img_z时,来标识使用是否大写字体。 * @param [options.style] - 当layer为custom时,标识的样式,可选值:dark,midnight,grayscale,hardedge,light,redalert,googlelite,grassgreen,pink,darkgreen,bluish * @param [options.url = null] - 当未指定layer类型时,可以传入外部指定url的服务地址,常用于离线服务。 */ declare class BaiduLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; layer?: string; bigfont?: boolean; style?: string; url?: string; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } declare namespace BaseTileLayer { /** * 栅格Tile瓦片图层 通用构造参数 * @property [id = uuid()] - 图层id标识 * @property [pid = -1] - 图层父级的id,一般图层管理中使用 * @property [name = '未命名'] - 图层名称 * @property [show = true] - 图层是否显示 * @property [center] - 图层自定义定位视角 {@link Map#setCameraView} * @property center.lng - 经度值, 180 - 180 * @property center.lat - 纬度值, -90 - 90 * @property center.alt - 高度值 * @property center.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0-360 * @property center.pitch - 俯仰角度值,绕纬度线旋转角度, 0-360 * @property center.roll - 翻滚角度值,绕经度线旋转角度, 0-360 * @property [flyTo] - 加载完成数据后是否自动飞行定位到数据所在的区域。 * @property [minimumLevel = 0] - 瓦片所支持的最低层级,如果数据没有第0层,该参数必须配置,当地图小于该级别时,平台不去请求服务数据。 * @property [maximumLevel] - 瓦片所支持的最大层级,大于该层级时会显示上一层拉伸后的瓦片,当地图大于该级别时,平台不去请求服务数据。 * @property [minimumTerrainLevel] - 展示影像图层的最小地形细节级别,小于该级别时,平台不显示影像数据。 * @property [maximumTerrainLevel] - 展示影像图层的最大地形细节级别,大于该级别时,平台不显示影像数据。 * @property rectangle - 瓦片数据的矩形区域范围 * @property rectangle.xmin - 最小经度值, -180 至 180 * @property rectangle.xmax - 最大纬度值, -180 至 180 * @property rectangle.ymin - 最小纬度值, -90 至 90 * @property rectangle.ymax - 最大纬度值, -90 至 90 * @property bbox - bbox规范的瓦片数据的矩形区域范围,与rectangle二选一即可。 * @property [crs = CRS.EPSG:3857] - 瓦片数据的坐标系信息,默认为墨卡托投影 * @property [chinaCRS] - 标识瓦片的国内坐标系(用于自动纠偏或加偏),自动将瓦片转为map对应的chinaCRS类型坐标系。 * @property [subdomains = 'abc'] - URL模板中用于 {s} 占位符的子域。 如果此参数是单个字符串,则字符串中的每个字符都是一个子域。如果是 一个数组,数组中的每个元素都是一个子域。 * @property [customTags] - 允许替换网址模板中的自定义关键字。该对象必须具有字符串作为键,并且必须具有值。 * @property [tileWidth = 256] - 图像图块的像素宽度。 * @property [tileHeight = 256] - 图像图块的像素高度。 * @property [hasAlphaChannel = true] - 如果此图像提供者提供的图像为真 包括一个Alpha通道;否则为假。如果此属性为false,则为Alpha通道,如果 目前,将被忽略。如果此属性为true,则任何没有Alpha通道的图像都将 它们的alpha随处可见。当此属性为false时,内存使用情况 和纹理上传时间可能会减少。 * @property [enablePickFeatures = true] - 如果为true,则 {@link UrlTemplateImageryProvider#pickFeatures} 请求 pickFeaturesUrl 并尝试解释响应中包含的功能。 * 如果为 false{@link UrlTemplateImageryProvider#pickFeatures} 会立即返回未定义(表示没有可拾取的内容) 功能)而无需与服务器通信。如果您知道数据,则将此属性设置为false 源不支持选择功能,或者您不希望该提供程序的功能可供选择。注意 可以通过修改 {@link UriTemplateImageryProvider#enablePickFeatures}来动态覆盖 属性。 * @property [getFeatureInfoFormats] - 在某处获取功能信息的格式 调用 {@link UrlTemplateImageryProvider#pickFeatures} 的特定位置。如果这 参数未指定,功能选择已禁用。 * @property [popup] - 当pickFeatures有效返回时,图层支持popup弹窗,绑定的弹窗值(如wms动态服务),支持:'all'、数组、字符串模板,当为数组时支持: * @property popup.field - 字段名称 * @property popup.name - 显示的对应自定义名称 * @property [popup.type] - 默认为label文本,也可以支持:'button'按钮,'html' html内容。 * @property [popup.callback] - 当type为'button'按钮时,单击后触发的事件。 * @property [popup.html] - 当type为'html'时,对于拼接的html内容。 * @property [popup.format] - 使用window的外部格式化js方法,格式化字符串值。 * @property [popup.unit] - 追加的计量单位值。 * @property [popupOptions] - popup弹窗时的配置参数 * @property [opacity = 1.0] - 透明度,取值范围:0.0-1.0。 * @property [alpha = 1.0] - 同opacity。 * @property [nightAlpha = 1.0] - 当 enableLighting 为 true 时 ,在地球的夜晚区域的透明度,取值范围:0.0-1.0。 * @property [dayAlpha = 1.0] - 当 enableLighting 为 true 时,在地球的白天区域的透明度,取值范围:0.0-1.0。 * @property [brightness = 1.0] - 亮度,取值范围:0.0-1.0。 * @property [contrast = 1.0] - 对比度。 1.0使用未修改的图像颜色,小于1.0会降低对比度,而大于1.0则会提高对比度。 * @property [hue = 0.0] - 色调。 0.0 时未修改的图像颜色。 * @property [saturation = 1.0] - 饱和度。 1.0使用未修改的图像颜色,小于1.0会降低饱和度,而大于1.0则会增加饱和度。 * @property [gamma = 1.0] - 伽马校正值。 1.0使用未修改的图像颜色。 * @property [maximumAnisotropy = maximum supported] - 使用的最大各向异性水平 用于纹理过滤。如果未指定此参数,则支持最大各向异性 将使用WebGL堆栈。较大的值可使影像在水平方向上看起来更好 视图。 * @property [cutoutRectangle] - 制图矩形,用于裁剪此ImageryLayer的一部分。 * @property [colorToAlpha] - 用作Alpha的颜色。 * @property [colorToAlphaThreshold = 0.004] - 颜色到Alpha的阈值。 * @property [proxy] - 加载资源时要使用的代理服务url。 * @property [templateValues] - 一个对象,用于替换Url中的模板值的键/值对 * @property [queryParameters] - 一个对象,其中包含在检索资源时将发送的查询参数。比如:queryParameters: {'access_token': '123-435-456-000'}, * @property [headers] - 一个对象,将发送的其他HTTP标头。比如:headers: { 'X-My-Header': 'valueOfHeader' }, * @property [zIndex] - 控制图层的叠加层次,默认按加载的顺序进行叠加,但也可以自定义叠加顺序,数字大的在上面。 */ type ConstructorOptions = { id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: { lng: number; lat: number; alt: number; heading: number; pitch: number; roll: number; }; flyTo?: boolean; minimumLevel?: number; maximumLevel?: number; minimumTerrainLevel?: number; maximumTerrainLevel?: number; rectangle: { xmin: number; xmax: number; ymin: number; ymax: number; }; bbox: Number[]; crs?: CRS; chinaCRS?: ChinaCRS; subdomains?: string | String[]; customTags?: any; tileWidth?: number; tileHeight?: number; hasAlphaChannel?: boolean; enablePickFeatures?: boolean; getFeatureInfoFormats?: GetFeatureInfoFormat[]; popup?: { field: string; name: string; type?: string; callback?: string; html?: string; format?: string; unit?: string; }; popupOptions?: Popup.StyleOptions; opacity?: number; alpha?: number | ((...params: any[]) => any); nightAlpha?: number | ((...params: any[]) => any); dayAlpha?: number | ((...params: any[]) => any); brightness?: number | ((...params: any[]) => any); contrast?: number | ((...params: any[]) => any); hue?: number | ((...params: any[]) => any); saturation?: number | ((...params: any[]) => any); gamma?: number | ((...params: any[]) => any); maximumAnisotropy?: number; cutoutRectangle?: Cesium.Rectangle; colorToAlpha?: Cesium.Color; colorToAlphaThreshold?: number; proxy?: string; templateValues?: any; queryParameters?: any; headers?: any; zIndex?: number; }; /** * 当前栅格瓦片图层支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.addTile, function (event) { * console.log('addTile', event) * }) * @property add - 添加对象 * @property remove - 移除对象 * @property show - 显示了对象 * @property hide - 隐藏了对象 * @property load - 瓦片图层初始化完成 * @property addTile - 栅格瓦片图层,开始加载瓦片 * @property addTileSuccess - 栅格瓦片图层,加载瓦片完成 * @property addTileError - 栅格瓦片图层,加载瓦片出错了 * @property click - 鼠标单击事件【WMS等动态服务enablePickFeatures:true时,支持单击获取对应的矢量对象】 * @property popupOpen - 当存在popup时,popup弹窗打开后 * @property popupClose - 当存在popup时,popup弹窗关闭 */ type EventType = { add: string; remove: string; show: string; hide: string; load: string; addTile: string; addTileSuccess: string; addTileError: string; click: string; popupOpen: string; popupClose: string; }; } /** * 栅格Tile瓦片图层 基类 * @param options - 描述初始化构造参数选项的对象 */ declare class BaseTileLayer extends BaseLayer { constructor(options: BaseTileLayer.ConstructorOptions); /** * 瓦片图层对应的内部ImageryLayer对象 */ readonly layer: Cesium.ImageryLayer; /** * 瓦片图层对应的内部ImageryProvider对象 */ readonly imageryProvider: Cesium.XXXImageryProvider; /** * 透明度,同opacity。从0.0到1.0。 */ alpha: number; /** * 亮度,取值范围:0.0-1.0。 */ brightness: number; /** * 对比度。 1.0使用未修改的图像颜色,小于1.0会降低对比度,而大于1.0则会提高对比度。 */ contrast: number; /** * 色调。 0.0 时未修改的图像颜色。 */ hue: number; /** * 饱和度。 1.0使用未修改的图像颜色,小于1.0会降低饱和度,而大于1.0则会增加饱和度。 */ saturation: number; /** * 伽马校正值。 1.0使用未修改的图像颜色。 */ gamma: number; /** * 是否可以调整图层顺序(在同类型图层间) */ readonly hasZIndex: boolean; /** * 图层顺序,数字大的在上面。(当hasZIndex为true时) */ zIndex: number; /** * 瓦片数据范围 */ rectangle: Cesium.Rectangle; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; /** * 重新加载图层 * @returns 无 */ reload(): void; /** * 设置透明度 * @param value - 透明度 * @returns 无 */ setOpacity(value: number): void; /** * 绑定鼠标移入或单击后的 对象高亮 * @param [options] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @param [options.type] - 事件类型,默认为鼠标移入高亮,也可以指定'click'单击高亮. * @returns 无 */ bindHighlight(options?: { type?: string; }): void; /** * 解绑鼠标移入或单击后的高亮处理 * @returns 无 */ unbindHighlight(): void; /** * 高亮对象。 * @param [highlightStyle] - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @returns 无 */ openHighlight(highlightStyle?: any): void; /** * 清除已选中的高亮 * @returns 无 */ closeHighlight(): void; /** * 透明度,取值范围:0.0-1.0 */ opacity: number; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } /** * 微软bing地图 * @property [options.key = mars3d.Token.bing] - 您的应用程序的Bing Maps密钥,可以在{@link https://www.bingmapsportal.com/}中创建 * @property [mapStyle = Cesium.BingMapsStyle.AERIAL] - 要加载的必应地图图像的类型。 * @property [tileProtocol] - 加载图块时要使用的协议,例如' http'或' https'。 默认情况下,将使用与页面相同的协议来加载图块。 * @property [culture = 'zh-Hans'] - 请求Bing Maps图像时要使用的区域性标记。不支持所有文化。请参阅 {@link http://msdn.microsoft.com/en-us/library/hh441729.aspx}了解有关支持的文化的信息。 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url = 'https://dev.virtualearth.net'] - 托管影像图像的Bing Maps服务器的网址。 * @param [options.tileDiscardPolicy] - 于确定图块是否为无效,应将其丢弃。如果未指定此值,则为默认 {@link DiscardMissingTileImagePolicy} 用于平铺的地图服务器,并且{@link NeverTileDiscardPolicy} 用于非平铺地图服务器。在前一种情况下, 我们要求最大图块级别的图块0,0并检查像素(0,0),(200,20),(20,200), (80,110)和(160,130)。如果所有这些像素都是透明的,则丢弃检查为 禁用,并且不会丢弃任何图块。如果它们中的任何一种具有不透明的颜色, 在这些像素位置具有相同值的图块将被丢弃。的最终结果 对于标准ArcGIS Server,这些默认值应该是正确的图块丢弃。确保 不会丢弃任何图块,为此构造并传递 {@link NeverTileDiscardPolicy} 参数。 */ declare class BingLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url?: Cesium.Resource | string; tileDiscardPolicy?: TileDiscardPolicy; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; /** * 要加载的必应地图图像的类型。 */ mapStyle?: Cesium.BingMapsStyle; /** * 加载图块时要使用的协议,例如' http'或' https'。 默认情况下,将使用与页面相同的协议来加载图块。 */ tileProtocol?: string; /** * 请求Bing Maps图像时要使用的区域性标记。不支持所有文化。请参阅 {@link http://msdn.microsoft.com/en-us/library/hh441729.aspx}了解有关支持的文化的信息。 */ culture?: string; } /** * 空白图层,目前主要在Lod矢量数据加载作为事件触发使用。 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的相关参数 */ declare class EmptyTileLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; }); /** * 判断级别是否在当前图层的最大最小层级范围内 * @param level - 判断的级别 * @returns 是否在限定的范围内 */ isInRange(level: number): boolean; /** * 判断所有瓦片 是否都在最大最小层级范围外,用于判断清除数据 * @param level - 判断的级别 * @returns 是否都在范围外 */ isAllOutRange(level: number): boolean; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 高德 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.layer] - 图层类型,以及以下内容:<br /> * <ul> * <li><code>vec</code>: 电子图层</li> * <li><code>img_d</code>: 卫星影像</li> * <li><code>img_z</code>: 影像注记</li> * <li><code>time</code>: 实时路况信息</li> * </ul> * @param [options.url = null] - 当未指定layer类型时,可以传入外部指定url的服务地址,常用于离线服务。 * @param [options.bigfont] - 当layer为vec时,来标识使用是否大写字体。 */ declare class GaodeLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; layer?: string; url?: string; bigfont?: boolean; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * GoogleEarth Enterprise企业版本 影像服务 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - 承载瓦片服务的谷歌地球企业服务器的url */ declare class GeeLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url: Cesium.Resource | string; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 谷歌 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.layer] - 图层类型,以及以下内容:<br /> * <ul> * <li><code>vec</code>: 电子图层</li> * <li><code>img_d</code>: 卫星影像</li> * <li><code>img_z</code>: 影像注记</li> * <li><code>ter</code>: 地形渲染图</li> * </ul> * @param [options.chinaCRS = 'GCJ02'] - 可以加ChinaCRS.WGS84标识切换到无偏底图(仅layer:img_d 时有效) */ declare class GoogleLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; layer?: string; chinaCRS?: ChinaCRS; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 网格线 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.cells = 2] - 网格单元格的数量。 * @param [options.color = rgba(255,255,255,1)] - 绘制网格线的颜色。 * @param [options.glowColor = color.withAlpha(0.3)] - 为网格线绘制渲染线发光效果的颜色。 * @param [options.glowWidth = 3] - 用于渲染线发光效果的线的宽度。 * @param [options.backgroundColor = 'rgba(0,0,0,0)'] - 背景填充颜色。 * @param [options.canvasSize = 256] - 用于渲染的画布的大小。 */ declare class GridLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; cells?: number; color?: string; glowColor?: string; glowWidth?: number; backgroundColor?: string; canvasSize?: number; }); /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 单张图片图层 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - 图片url地址 * @param options.rectangle - 瓦片数据的矩形区域范围 * @param options.rectangle.xmin - 最小经度值, -180 至 180 * @param options.rectangle.xmax - 最大纬度值, -180 至 180 * @param options.rectangle.ymin - 最小纬度值, -90 至 90 * @param options.rectangle.ymax - 最大纬度值, -90 至 90 * * @param options.bbox - bbox规范的瓦片数据的矩形区域范围,与rectangle二选一即可。 */ declare class ImageLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url: Cesium.Resource | string; rectangle: { xmin: number; xmax: number; ymin: number; ymax: number; }; bbox: Number[]; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * cesium ion资源地图,官网: {@link https://cesium.com/ion/signin/} * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.assetId - ION服务 assetId * @param [options.accessToken = mars3d.Token.ion] - ION服务 token令牌 * @param [options.server = Ion.defaultServer] - Cesium ion API服务器的资源。 */ declare class IonLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; assetId: number; accessToken?: string; server?: string | Resource; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * Mapbox地图服务 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url = 'https://api.mapbox.com/styles/v1/'] - Mapbox服务器网址。 * @param [options.username = 'marsgis'] - 地图帐户的用户名。 * @param options.styleId - Mapbox样式ID。 * @param [options.accessToken = mars3d.Token.mapbox] - 图像的Token公共访问令牌。 * @param [options.tilesize = 512] - 图像块的大小。 * @param [options.scaleFactor = true] - 确定贴图是否以 @2x 比例因子渲染。 */ declare class MapboxLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url?: Cesium.Resource | string; username?: string; styleId: string; accessToken?: string; tilesize?: number; scaleFactor?: boolean; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * OSM开源地图 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 */ declare class OsmLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 天地图 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.layer] - 图层类型,以及以下内容:<br /> * <ul> * <li><code>vec_d</code>: 电子图层</li> * <li><code>vec_z</code>: 电子注记</li> * <li><code>img_d</code>: 卫星影像</li> * <li><code>img_z</code>: 影像注记</li> * <li><code>ter_d</code>: 地形渲染图</li> * <li><code>ter_z</code>: 地形渲染图注记</li> * </ul> * @param [options.key = mars3d.Token.tiandituArr] - 天地图服务Token,可以自行注册官网: {@link https://console.tianditu.gov.cn/api/key} * @param [options.crs = 'EPSG3857'] - 标识不同坐标系。 */ declare class TdtLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; layer?: string; key?: String[]; crs?: CRS; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 腾讯 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.layer] - 图层类型,以及以下内容:<br /> * <ul> * <li><code>vec</code>: 电子图层</li> * <li><code>img_d</code>: 卫星影像</li> * <li><code>img_z</code>: 影像注记</li> * <li><code>custom</code>: 地形渲染图</li> * </ul> * @param [options.style] - 当layer为custom时,标识的样式,可选值:灰白地图:3,暗色地图:4 */ declare class TencentLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; layer?: string; style?: string; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 瓦片信息,一般用于测试 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.color = rgba(255,0,0,1)] - 画瓦片边框线和标签的颜色 */ declare class TileInfoLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; color?: string; }); /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * TileMapService 提供由MapTiler,GDAL2Tiles等生成的切片图像 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url = '.'] - 服务地址 * @param [options.fileExtension = 'png'] - 服务器上图像的文件扩展名。 * @param [options.flipXY] - gdal2tiles.py的旧版本将tilemapresource.xml中的X和Y值翻转了。指定此选项将执行相同的操作,从而允许加载这些不正确的图块集。 */ declare class TmsLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url?: Resource | string | Promise<Resource> | Promise<String>; fileExtension?: string; flipXY?: boolean; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * WMS服务 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - WMS服务的URL。URL支持相同的关键字 {@link XyzLayer}. * @param options.layers - 要包含的图层,用逗号分隔。 * @param [options.parameters = WebMapServiceImageryProvider.DefaultParameters] - 要在URL中 传递给WMS服务GetMap请求的其他参数。 * @param [options.getFeatureInfoParameters = WebMapServiceImageryProvider.GetFeatureInfoDefaultParameters] - 要在GetFeatureInfo URL中传递给WMS服务器的其他参数。 * @param [options.crs] - CRS规范,用于WMS规范>= 1.3.0。 * @param [options.srs] - SRS规范,与WMS规范1.1.0或1.1.1一起使用 * @param [options.clock] - 一个时钟实例,用于确定时间维度的值。指定' times '时需要。 * @param [options.times] - TimeIntervalCollection 的数据属性是一个包含时间动态维度及其值的对象。 * @param [options.maxLength = 5000] - 单击获取到的数据,最大数据长度。大数据解析很卡,可以设定阀值屏蔽大数据,避免卡顿。 * @param [options.highlight] - 鼠标单击高亮显示对应的矢量数据 及其样式 * @param [options.highlight.type] - 构造成的矢量数据类型。 * @param [options.highlight.其他] - style样式,每种不同类型数据都有不同的样式,具体见各{@link GraphicType}矢量数据的style参数。 */ declare class WmsLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url: Cesium.Resource | string; layers: string; parameters?: any; getFeatureInfoParameters?: any; crs?: string; srs?: string; clock?: Cesium.Clock; times?: Cesium.TimeIntervalCollection; maxLength?: number; highlight?: { type?: GraphicType; 其他?: any; }; }); /** * 绑定鼠标单击对象后的弹窗。 * @param content - 弹窗内容html字符串,或者回调方法。 * @param options - 控制参数 * @returns 当前对象本身,可以链式调用 */ bindPopup(content: string | ((...params: any[]) => any), options: Popup.StyleOptions): this; /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; } /** * WMTS服务 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - WMTS GetTile操作(用于kvp编码的请求)或tile-URL模板(用于RESTful请求)的基本URL。tile-URL模板应该包含以下变量:&#123;style&#125;, &#123;TileMatrixSet&#125;, &#123;TileMatrix&#125;, &#123;TileRow&#125;, &#123;TileCol&#125; 前两个是可选的,如果实际值是硬编码的或者服务器不需要。 &#123;s&#125;关键字可用于指定子域。 * @param [options.format = 'image/jpeg'] - 要从服务器检索的瓦片图像的MIME类型。 * @param options.layer - WMTS请求的层名。 * @param options.style - WMTS请求的样式名称。 * @param options.tileMatrixSetID - 用于WMTS请求的TileMatrixSet的标识符。 * @param [options.tileMatrixLabels] - 瓦片矩阵中用于WMTS请求的标识符列表,每个瓦片矩阵级别一个。 * @param [options.clock] - 一个时钟实例,用于确定时间维度的值。指定' times '时需要。 * @param [options.times] - TimeIntervalCollection 的数据属性是一个包含时间动态维度及其值的对象。 * @param [options.enablePickFeatures = false] - 如果为true,则请求 pickFeaturesUrl 并尝试解释响应中包含的功能。 * @param [options.pickFeaturesUrl] - enablePickFeatures为true时,用于单击查看矢量对象功能的对应wms服务url。 * @param [options.pickFeatures] - 外部自定义单击请求对应矢量数据的处理。与pickFeaturesUrl二选一 * @param [options.highlight] - 鼠标单击高亮显示对应的矢量数据 及其样式。需要enablePickFeatures等参数有效配置。 * @param [options.highlight.type] - 构造成的矢量数据类型。 * @param [options.highlight.其他] - style样式,每种不同类型数据都有不同的样式,具体见各{@link GraphicType}矢量数据的style参数。 */ declare class WmtsLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url: Cesium.Resource | string; format?: string; layer: string; style: string; tileMatrixSetID: string; tileMatrixLabels?: String[]; clock?: Cesium.Clock; times?: Cesium.TimeIntervalCollection; enablePickFeatures?: boolean; pickFeaturesUrl?: Cesium.Resource | string; pickFeatures?: (...params: any[]) => any; highlight?: { type?: GraphicType; 其他?: any; }; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; } /** * 标准xyz金字塔 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param options.url - 用于请求瓦片图块的URL模板。它具有以下关键字: * <ul> * <li><code>{z}</code>: 切片方案中切片的级别。零级是四叉树金字塔的根。</li> * <li><code>{x}</code>:切片方案中的图块X坐标,其中0是最西端的图块。</li> * <li><code>{y}</code>: 切片方案中的图块Y坐标,其中0是最北的图块。</li> * <li><code>{s}</code>:可用的子域之一,用于克服浏览器对每个主机的并发请求数的限制。</li> * <li><code>{reverseX}</code>: 切片方案中的图块X坐标,其中0是最东的图块。</li> * <li><code>{reverseY}</code>:切片方案中的图块Y坐标,其中0是最南端的图块。</li> * <li><code>{reverseZ}</code>:在切片方案中切片的级别,其中级别0是四叉树金字塔的最大级别。为了使用reverseZ,必须定义maximumLevel。</li> * <li><code>{westDegrees}</code>: 瓦片图块在测地角度上的西边缘。</li> * <li><code>{southDegrees}</code>:瓦片图块在测地角度上的南边缘。</li> * <li><code>{eastDegrees}</code>:以大地测量度表示的图块的东边缘。</li> * <li><code>{northDegrees}</code>: 瓦片图块在测地角度上的北边缘。</li> * <li><code>{westProjected}</code>:图块方案的墨卡托投影坐标中图块的西边缘。</li> * <li><code>{southProjected}</code>: 图块方案的墨卡托投影坐标中图块的南边缘。</li> * <li><code>{eastProjected}</code>: :图块方案的墨卡托投影坐标中图块的东边缘。</li> * <li><code>{northProjected}</code>:图块方案的墨卡托投影坐标中图块的北边缘。</li> * <li><code>{width}</code>:每个图块的宽度(以像素为单位)。</li> * <li><code>{height}</code>: 每个图块的高度(以像素为单位)。</li> * </ul> * @param [options.urlSchemeZeroPadding] - 为每个图块坐标获取URL方案零填充。格式为' 000',其中每个坐标将在左侧用零填充,以匹配传递的零字符串的宽度。例如设置: * urlSchemeZeroPadding:{'{x}':'0000'}将导致'x'值为12,以在生成的URL中返回{x}的字符串'0012'。传递的对象具有以下关键字: * <ul> * <li> <code>{z}</code>: 切片方案中图块级别的零填充。</li> * <li> <code>{x}</code>: 切片方案中图块X坐标的零填充。</li> * <li> <code>{y}</code>: 切片方案中图块Y坐标的零填充。</li> * <li> <code>{reverseX}</code>: 在平铺方案中图块reverseX坐标的零填充。</li> * <li> <code>{reverseY}</code>: 在切片方案中,图块反向Y坐标的零填充。</li> * <li> <code>{reverseZ}</code>: 在切片方案中,图块的reverseZ坐标的零填充。</li> * </ul> * @param [options.pickFeaturesUrl] - 用于选择功能的URL模板。如果未指定此属性, * {@link Cesium.UrlTemplateImageryProvider#pickFeatures} 会立即返回undefined,表示没有 功能选择。 * 网址模板支持 <code>url</code>参数支持的所有关键字参数,以及以下内容: * <ul> * <li><code>{i}</code>: 所选位置的像素列(水平坐标),其中最西端的像素为0。</li> * <li><code>{j}</code>: 所选位置的像素行(垂直坐标),其中最北端的像素为0。</li> * <li><code>{reverseI}</code>: 所选位置的像素列(水平坐标),其中最东端的像素为0。</li> * <li><code>{reverseJ}</code>: 所选位置的像素行(垂直坐标),其中最南端的像素为0。</li> * <li><code>{longitudeDegrees}</code>: 所选位置的经度(以度为单位)。</li> * <li><code>{latitudeDegrees}</code>: 所选位置的纬度(以度为单位)。</li> * <li><code>{longitudeProjected}</code>:在平铺方案的投影坐标中所拾取位置的经度。</li> * <li><code>{latitudeProjected}</code>: 在平铺方案的投影坐标中所拾取位置的纬度。</li> * <li><code>{format}</code>: 获取功能信息的格式,如 {@link GetFeatureInfoFormat}中所指定。</li> * </ul> */ declare class XyzLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; url: Cesium.Resource | string; urlSchemeZeroPadding?: any; pickFeaturesUrl?: Cesium.Resource | string; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): any; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; } /** * 键盘漫游控制类 */ declare class KeyboardRoam extends BaseControl { /** * 平移步长 (米) */ moveStep: number; /** * 相机原地旋转步长,值越大步长越小。 */ dirStep: number; /** * 相机围绕目标点旋转速率,0.3 - 2.0 */ rotateStep: number; /** * 最小仰角 0 - 1 */ minPitch: number; /** * 最大仰角 0 - 1 */ maxPitch: number; /** * 最低高度(单位:米) */ minHeight: number; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; /** * 开始自动向前平移镜头,不改变相机朝向 * @returns 无 */ startMoveForward(): void; /** * 停止自动向前平移镜头,不改变相机朝向 * @returns 无 */ stopMoveForward(): void; /** * 开始自动向后平移镜头,不改变相机朝向 * @returns 无 */ startMoveBackward(): void; /** * 停止自动向后平移镜头,不改变相机朝向 * @returns 无 */ stopMoveBackward(): void; /** * 开始自动向右平移镜头,不改变相机朝向 * @returns 无 */ startMoveRight(): void; /** * 停止自动向右平移镜头,不改变相机朝向 * @returns 无 */ stopMoveRight(): void; /** * 开始自动向左平移镜头,不改变相机朝向 * @returns 无 */ startMoveLeft(): void; /** * 停止自动向左平移镜头,不改变相机朝向 * @returns 无 */ stopMoveLeft(): void; /** * 相对于屏幕中心点 转动 * @param type - 旋转的方向 * @returns 无 */ moveCamera(type: MoveType): void; /** * 相对于相机本身 转动 * @param type - 旋转的方向 * @returns 无 */ rotateCamera(type: MoveType): void; /** * 相机旋转的类型 * @property ENLARGE - 向屏幕中心靠近 * @property NARROW - 向屏幕中心远离 * @property LEFT_ROTATE - 相机原地左旋转 * @property RIGHT_ROTATE - 相机原地右旋转 * @property TOP_ROTATE - 相机原地上旋转 * @property BOTTOM_ROTATE - 相机原地下旋转 */ static MoveType: { ENLARGE: Int; NARROW: Int; LEFT_ROTATE: Int; RIGHT_ROTATE: Int; TOP_ROTATE: Int; BOTTOM_ROTATE: Int; }; } /** * 地图鼠标事件 统一管理类 */ declare class MouseEvent { /** * 是否开启鼠标移动事件的拾取矢量数据 */ enabledMoveTarget: boolean; /** * 是否不拾取数据 */ noPickEntity: boolean; /** * 获取拾取到的Cesium选中对象 * @param pickedObject - scene.pick返回的对象 * @returns 获取拾取到的Cesium选中对象 */ getPicked(pickedObject: any): any | undefined; } declare namespace Map { /** * 场景参数 * @property center - 默认相机视角 * @property center.lng - 经度值, 180 - 180 * @property center.lat - 纬度值, -90 - 90 * @property center.alt - 高度值 * @property center.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0-360 * @property center.pitch - 俯仰角度值,绕纬度线旋转角度, 0-360 * @property center.roll - 翻滚角度值,绕经度线旋转角度, 0-360 * @property [extent] - 矩形范围 相机视角,与center二选一 * @property extent.xmin - 最小经度值, -180 至 180 * @property extent.xmax - 最大纬度值, -180 至 180 * @property extent.ymin - 最小纬度值, -90 至 90 * @property extent.ymax - 最大纬度值, -90 至 90 * @property [removeDblClick = false] - 是否移除Cesium默认的双击事件 * @property [ionToken = null] - Cesium Ion服务的 Token令牌 * @property [resolutionScale = 1.0] - 获取或设置渲染分辨率的缩放比例。小于1.0的值可以改善性能不佳的设备上的性能,而值大于1.0则将以更高的速度呈现分辨率,然后缩小比例,从而提高视觉保真度。例如,如果窗口小部件的尺寸为640x480,则将此值设置为0.5将导致场景以320x240渲染,然后在设置时按比例放大设置为2.0将导致场景以1280x960渲染,然后按比例缩小。 * * 以下是Cesium.Scene对象相关参数 * @property showSun - 是否显示太阳 * @property showMoon - 是否显示月亮 * @property showSkyBox - 是否显示天空盒 * @property showSkyAtmosphere - 是否显示地球大气层外光圈 * @property fog - 是否启用雾化效果 * @property fxaa - 是否开启快速抗锯齿 * @property highDynamicRange - 是否关闭高动态范围渲染(不关闭时地图会变暗) * @property backgroundColor - 空间背景色 ,css颜色值 * * 以下是Cesium.Viewer所支持的options【控件相关的写在另外的control属性中】 * @property [sceneMode = Cesium.SceneMode.SCENE3D] - 初始场景模式。 * @property [scene3DOnly = false] - 为 true 时,每个几何实例将仅以3D渲染以节省GPU内存。 * @property [shouldAnimate = true] - 是否开启时钟动画 * @property [shadows = false] - 是否启用日照阴影 * @property [useDefaultRenderLoop = true] - 如果此小部件应控制渲染循环,则为true,否则为false。 * @property [targetFrameRate] - 使用默认渲染循环时的目标帧速率。 * @property [useBrowserRecommendedResolution = true] - 如果为true,则以浏览器建议的分辨率渲染,并忽略 window.devicePixelRatio 。 * @property [automaticallyTrackDataSourceClocks = true] - 如果为true,则此小部件将自动跟踪新添加的数据源的时钟设置,并在数据源的时钟发生更改时进行更新。如果要独立配置时钟,请将其设置为false。 * @property [contextOptions] - WebGL创建属性 传递给 Cesium.Scene 的 options 。{@link Cesium.Scene}. * @property [orderIndependentTranslucency = true] - 如果为true,并且配置支持它,则使用顺序无关的半透明性。 * @property [terrainShadows = Cesium.ShadowMode.RECEIVE_ONLY] - 确定地形是否投射或接收来自光源的阴影。 * @property [mapMode2D = Cesium.MapMode2D.INFINITE_SCROLL] - 确定2D地图是可旋转的还是可以在水平方向无限滚动。 * @property [requestRenderMode = false] - 如果为真,渲染帧只会在需要时发生,这是由场景中的变化决定的。启用可以减少你的应用程序的CPU/GPU使用量,并且在移动设备上使用更少的电池,但是需要使用 {@link Scene#requestRender} 在这种模式下显式地渲染一个新帧。在许多情况下,在API的其他部分更改场景后,这是必要的。参见 {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}. * @property [maximumRenderTimeChange = 0.0] - 如果requestRenderMode为true,这个值定义了在请求渲染之前允许的模拟时间的最大变化。参见 {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}. * * 以下是Cesium.Globe对象相关参数 * @property globe - globe地球相关参数 * @property [globe.show = true] - 是否显示地球 * @property [globe.baseColor = '#546a53'] - 地球背景色 ,css颜色值 * @property [globe.depthTestAgainstTerrain = false] - 是否启用深度监测,可以开启来测试矢量对象是否在地形下面或被遮挡。 * @property [globe.showGroundAtmosphere = true] - 是否在地球上绘制的地面大气 * @property [globe.enableLighting = false] - 是否显示昼夜区域 * @property [globe.tileCacheSize = 100] - 地形图块缓存的大小,表示为图块数。任何其他只要不需要渲染,就会释放超出此数目的图块这个框架。较大的数字将消耗更多的内存,但显示细节更快例如,当缩小然后再放大时。 * @property [globe.terrainExaggeration = 1.0] - 地形夸张倍率,用于放大地形的标量。请注意,地形夸张不会修改其他相对于椭球的图元。 * @property [globe.terrainExaggerationRelativeHeight = 0.0] - 地形被夸大的高度。默认为0.0(相对于椭球表面缩放)。高于此高度的地形将向上缩放,低于此高度的地形将向下缩放。请注意,地形夸大不会修改任何其他图元,因为它们是相对于椭球体定位的。 * * 以下是Cesium.ScreenSpaceCameraController对象相关参数 * @property cameraController - 相机操作相关参数 * @property [cameraController.zoomFactor = 3.0] - 鼠标滚轮放大的步长参数 * @property [cameraController.constrainedAxis = true] - 为false时 解除在南北极区域鼠标操作限制 * @property [cameraController.minimumZoomDistance = 1.0] - 变焦时相机位置的最小量级(以米为单位),默认为1。该值是相机与地表(含地形)的相对距离。 * @property [cameraController.maximumZoomDistance = 50000000.0] - 变焦时相机位置的最大值(以米为单位)。该值是相机与地表(含地形)的相对距离。 * @property [cameraController.minimumCollisionTerrainHeight = 80000] - 低于此高度时绕鼠标键绕圈,大于时绕视图中心点绕圈。 * @property [cameraController.enableRotate = true] - 2D和3D视图下,是否允许用户旋转相机 * @property [cameraController.enableTranslate = true] - 2D和哥伦布视图下,是否允许用户平移地图 * @property [cameraController.enableTilt = true] - 3D和哥伦布视图下,是否允许用户倾斜相机 * @property [cameraController.enableZoom = true] - 是否允许 用户放大和缩小视图 * @property [cameraController.enableCollisionDetection = true] - 是否允许 地形相机的碰撞检测 * * 以下是Cesium.Clock时钟相关参数 * @property clock - 时钟相关参数 * @property [clock.currentTime = null] - 当前的时间 * @property [clock.multiplier = 1.0] - 当前的速度 */ type sceneOptions = { center: { lng: number; lat: number; alt: number; heading: number; pitch: number; roll: number; }; extent?: { xmin: number; xmax: number; ymin: number; ymax: number; }; removeDblClick?: boolean; ionToken?: string; resolutionScale?: number; showSun: boolean; showMoon: boolean; showSkyBox: boolean; showSkyAtmosphere: boolean; fog: boolean; fxaa: boolean; highDynamicRange: boolean; backgroundColor: string; sceneMode?: Cesium.SceneMode; scene3DOnly?: boolean; shouldAnimate?: boolean; shadows?: boolean; useDefaultRenderLoop?: boolean; targetFrameRate?: number; useBrowserRecommendedResolution?: boolean; automaticallyTrackDataSourceClocks?: boolean; contextOptions?: any; orderIndependentTranslucency?: boolean; terrainShadows?: Cesium.ShadowMode; mapMode2D?: Cesium.MapMode2D; requestRenderMode?: boolean; maximumRenderTimeChange?: number; globe: { show?: boolean; baseColor?: string; depthTestAgainstTerrain?: boolean; showGroundAtmosphere?: boolean; enableLighting?: boolean; tileCacheSize?: number; terrainExaggeration?: number; terrainExaggerationRelativeHeight?: number; }; cameraController: { zoomFactor?: number; constrainedAxis?: boolean; minimumZoomDistance?: number; maximumZoomDistance?: number; minimumCollisionTerrainHeight?: number; enableRotate?: boolean; enableTranslate?: boolean; enableTilt?: boolean; enableZoom?: boolean; enableCollisionDetection?: boolean; }; clock: { currentTime?: string | Cesium.JulianDate; multiplier?: number; }; }; /** * 控件参数 * * 以下是mars3d.control定义的控件 * @property [defaultContextMenu = true] - 是否绑定默认的地图右键菜单 * @property [mouseDownView = false] - 鼠标滚轮缩放美化样式 {@link MouseDownView} * @property [locationBar] - 鼠标提示控件, {@link LocationBar} * @property [locationBar.fps] - 是否显示实时FPS帧率 * @property [locationBar.format] - 显示内容的格式化html展示的内容格式化字符串。 支持以下模版配置:【鼠标所在位置】 经度:{lng}, 纬度:{lat}, 海拔:{alt}米, 【相机的】 方向角度:{heading}, 俯仰角度:{pitch}, 视高:{cameraHeight}米, 【地图的】 层级:{level}, * @property [compass] - 导航球控件 {@link Compass} * @property [distanceLegend] - 比例尺控件 {@link DistanceLegend} * * 以下是Cesium.Viewer所支持的控件相关的options * @property [infoBox = true] - 是否显示 点击要素之后显示的信息 * @property [selectionIndicator = true] - 选择模型时,是否显示绿色框 * @property [animation = true] - 是否创建 左下角仪表动画面板 * @property [timeline = true] - 是否创建 下侧时间线控件面板 * @property [baseLayerPicker = true] - 是否显示 basemaps底图切换按钮 * @property [fullscreenButton = true] - 是否显示 全屏按钮 * @property [vrButton = false] - 是否显示 右下角vr虚拟现实按钮 * @property [geocoder = true] - 是否显示 地名查找控件按钮 * @property [homeButton = true] - 是否显示 视角复位按钮 * @property [sceneModePicker = true] - 是否显示 二三维视图切换按钮 * @property [projectionPicker = false] - 是否显示 用于在透视和正投影之间进行切换按钮 * @property [navigationHelpButton = true] - 是否显示 帮助按钮 * @property [navigationInstructionsInitiallyVisible = true] - 在用户明确单击按钮之前是否自动显示navigationHelpButton * @property [showRenderLoopErrors = true] - 如果为true,则在发生渲染循环错误时,此小部件将自动向包含错误的用户显示HTML面板。 */ type controlOptions = { defaultContextMenu?: boolean; mouseDownView?: boolean; locationBar?: { fps?: boolean; format?: string | ((...params: any[]) => any); }; compass?: any; distanceLegend?: any; infoBox?: boolean; selectionIndicator?: boolean; animation?: boolean; timeline?: boolean; baseLayerPicker?: boolean; fullscreenButton?: boolean; vrButton?: boolean; geocoder?: boolean | GeocoderService[]; homeButton?: boolean; sceneModePicker?: boolean; projectionPicker?: boolean; navigationHelpButton?: boolean; navigationInstructionsInitiallyVisible?: boolean; showRenderLoopErrors?: boolean; }; /** * 地形服务配置 * @property type - 地形类型 * @property url - 地形服务地址 * @property [show = false] - 是否启用显示地形 * @property [requestVertexNormals = false] - 是否应该从服务器请求额外的光照信息,如果可用,以每个顶点法线的形式。 * @property [requestWaterMask = false] - 是否应该向服务器请求每个瓦的水掩膜(如果有的话)。 * @property [requestMetadata = true] - 是否应该从服务器请求每个块元数据(如果可用)。 */ type terrainOptions = { type: TerrainType; url: string | Cesium.Resource; show?: boolean; requestVertexNormals?: boolean; requestWaterMask?: boolean; requestMetadata?: boolean; }; /** * 底图图层配置 * @property type - 图层类型 * @property [通用参数] - 与BaseTileLayer类构造参数相同 * @property [其他参数] - 每种不同type都有自己的不同属性,具体参考{@link LayerType}找到type对应的图层类,查看其构造参数 */ type basemapOptions = { type: string; 通用参数?: BaseTileLayer.ConstructorOptions; 其他参数?: any; }; /** * 可以叠加显示的图层配置 * @property type - 图层类型 * @property [id] - 图层id标识 * @property [pid = -1] - 图层父级的id,一般图层管理中使用 * @property [name = '未命名'] - 图层名称 * @property [show = true] - 图层是否显示 * @property [center] - 图层自定义定位视角,默认根据数据情况自动定位。 * @property [popup] - 当图层支持popup弹窗时,绑定的值 * @property [popupOptions] - popup弹窗时的配置参数 * @property [tooltip] - 当图层支持tooltip弹窗时,绑定的值 * @property [tooltipOptions] - tooltip弹窗时的配置参数 * @property [其他参数] - 每种type都有自己的不同属性,具体参考{@link LayerType}找到type对应的图层类,查看其构造参数 */ type layerOptions = { type: string; id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; popup?: any; popupOptions?: Popup.StyleOptions; tooltip?: any; tooltipOptions?: Tooltip.StyleOptions; 其他参数?: any; }; /** * Map支持的{@link EventType}事件类型 * @example * //绑定监听事件 * map.on(mars3d.EventType.click, function (event) { * console.log('单击了地图对象', event) * }) * @property addLayer - 添加图层 * @property removeLayer - 移除图层 * @property cameraMoveStart - 相机开启移动前 场景事件 * @property cameraMoveEnd - 相机移动完成后 场景事件 * @property cameraChanged - 相机位置完成 场景事件 * @property preUpdate - 场景更新前 场景事件 * @property postUpdate - 场景更新后 场景事件 * @property preRender - 场景渲染前 场景事件 * @property postRender - 场景渲染后 场景事件 * @property morphStart - 场景模式(2D/3D/哥伦布)变换前 场景事件 * @property morphComplete - 完成场景模式(2D/3D/哥伦布)变换 场景事件 * @property clockTick - 时钟跳动 场景事件 * @property renderError - 场景渲染失败(需要刷新页面) * @property click - 左键单击 鼠标事件 * @property clickGraphic - 左键单击到矢量或模型数据时 鼠标事件 * @property clickTileGraphic - 左键单击到wms或arcgis瓦片服务的对应矢量数据时 * @property clickMap - 左键单击地图空白(未单击到矢量或模型数据)时 鼠标事件 * @property dblClick - 左键双击 鼠标事件 * @property leftDown - 左键鼠标按下 鼠标事件 * @property leftUp - 左键鼠标按下后释放 鼠标事件 * @property mouseMove - 鼠标移动 鼠标事件 * @property mouseMoveTarget - 鼠标移动(拾取目标,并延迟处理) 鼠标事件 * @property wheel - 鼠标滚轮滚动 鼠标事件 * @property rightClick - 右键单击 鼠标事件 * @property rightDown - 右键鼠标按下 鼠标事件 * @property rightUp - 右键鼠标按下后释放 鼠标事件 * @property middleClick - 中键单击 鼠标事件 * @property middleDown - 中键鼠标按下 鼠标事件 * @property middleUp - 中键鼠标按下后释放 鼠标事件 * @property pinchStart - 在触摸屏上两指缩放开始 鼠标事件 * @property pinchEnd - 在触摸屏上两指缩放结束 鼠标事件 * @property pinchMove - 在触摸屏上两指移动 鼠标事件 * @property mouseDown - 鼠标按下 [左中右3键都触发] 鼠标事件 * @property mouseUp - 鼠标按下后释放 [左中右3键都触发] 鼠标事件 * @property mouseOver - 鼠标移入 鼠标事件 * @property mouseOut - 鼠标移出 鼠标事件 * @property keydown - 按键按下 键盘事件 * @property keyup - 按键按下后释放 键盘事件 * @property popupOpen - popup弹窗打开后 * @property popupClose - popup弹窗关闭 * @property tooltipOpen - tooltip弹窗打开后 * @property tooltipClose - tooltip弹窗关闭 */ type EventType = { addLayer: string; removeLayer: string; cameraMoveStart: string; cameraMoveEnd: string; cameraChanged: string; preUpdate: string; postUpdate: string; preRender: string; postRender: string; morphStart: string; morphComplete: string; clockTick: string; renderError: string; click: string; clickGraphic: string; clickTileGraphic: string; clickMap: string; dblClick: string; leftDown: string; leftUp: string; mouseMove: string; mouseMoveTarget: string; wheel: string; rightClick: string; rightDown: string; rightUp: string; middleClick: string; middleDown: string; middleUp: string; pinchStart: string; pinchEnd: string; pinchMove: string; mouseDown: string; mouseUp: string; mouseOver: string; mouseOut: string; keydown: string; keyup: string; popupOpen: string; popupClose: string; tooltipOpen: string; tooltipClose: string; }; } /** * 地图类 ,这是构造三维地球的一切的开始起点。 * @param id - 地图div容器的id 或 已构造好的Viewer对象 * @param [options = {}] - 参数对象: * @param options.scene - 场景参数 * @param options.control - 控件参数 * @param options.terrain - 地形服务配置 * @param options.basemaps - 底图图层配置 * @param options.layers - 可以叠加显示的图层配置 * @param [options.templateValues] - 图层中统一的url模版,。比如可以将服务url前缀统一使用模板,方便修改或动态配置。 * @param [options.chinaCRS = ChinaCRS.WGS84] - 标识当前三维场景的国内坐标系(用于部分图层内对比判断来自动纠偏或加偏) * @param [options.lang] - 使用的语言(如中文、英文等)。 */ declare class Map extends BaseClass { constructor(id: string | Cesium.Viewer, options?: { scene: Map.sceneOptions; control: Map.controlOptions; terrain: Map.terrainOptions; basemaps: Map.basemapOptions[]; layers: Map.layerOptions[]; templateValues?: any; chinaCRS?: ChinaCRS; lang?: LangType; }); /** * 地图对应的Cesium原生的Viewer对象 */ readonly viewer: Cesium.Viewer; /** * 获取地图DOM容器。 */ readonly container: Element; /** * 获取场景。 */ readonly scene: Cesium.Scene; /** * 获取相机 */ readonly camera: Cesium.Camera; /** * 获取Canvas画布 */ readonly canvas: HTMLCanvasElement; /** * 获取将在地球上渲染的ImageryLayer图像图层的集合 */ readonly imageryLayers: Cesium.ImageryLayerCollection; /** * 获取要可视化的 DataSource 实例集。 */ readonly dataSources: Cesium.DataSourceCollection; /** * 获取未绑定到特定数据源的实体的集合。这是 dataSourceDisplay.defaultDataSource.entities 的快捷方式。 */ readonly entities: Cesium.EntityCollection; /** * 获取时钟。 */ readonly clock: Cesium.Clock; /** * 获取 CesiumWidget */ readonly cesiumWidget: Cesium.CesiumWidget; /** * 获取或设置相机当前正在跟踪的Entity实例。 */ trackedEntity: Cesium.Entity; /** * 获取或设置当前的地形服务 */ terrainProvider: Cesium.TerrainProvider; /** * 是否开启地形 */ hasTerrain: boolean; /** * 获取或设置当前显示的底图,设置时可以传入图层id或name */ basemap: string | number | BaseTileLayer; /** * 是否只拾取模型上的点 */ onlyPickModelPosition: boolean; /** * 获取鼠标事件控制器 */ readonly mouseEvent: MouseEvent; /** * 获取键盘漫游控制器 */ readonly keyboardRoam: KeyboardRoam; /** * 获取config.json预先传入的构造完成的控件对象 */ readonly controls: KeyboardRoam; /** * 默认绑定的图层,简单场景时快捷方便使用 */ readonly graphicLayer: GraphicLayer; /** * 获取当前地图层级(概略),一般为0-21层 */ readonly level: Int; /** * 是否固定光照, * true:可避免gltf、3dtiles模型随时间存在亮度不一致。 */ fixedLight: boolean; /** * 使用的语言(如中文、英文等)。 */ readonly lang: LangType; /** * 设置Scene场景参数 * @param options - 参数 * @returns 当前对象本身,可以链式调用 */ setSceneOptions(options: Map.sceneOptions): this; /** * 获取地图的配置参数,即new Map传入的参数。 * @returns 地图的配置参数 */ getOptions(): any; /** * 获取平台内置的右键菜单 * @returns 右键菜单 */ getDefaultContextMenu(): object[]; /** * 取地图屏幕中心点坐标 * @returns 屏幕中心点坐标 */ getCenter(): LatLngPoint; /** * 提取地球当前视域边界,示例:{ xmin: 70, xmax: 140, ymin: 0, ymax: 55, height: 0, } * @param [options = {}] - 参数对象: * @param [options.formatNum = false] - 是否格式化小数位,只保留6位小数 * @returns 当前视域边界 */ getExtent(options?: { formatNum?: boolean; }): any; /** * 截图,导出地图场景图片 * @param [options = {}] - 参数对象: * @param [options.download = true] - 是否自动下载图片 * @param [options.filename = '场景出图_' + width + 'x' + height] - 图片名称 * @param [options.width = canvas.width] - 图片的高度像素值 * @param [options.height = canvas.height] - 图片的高度像素值 * @param [options.type = 'image/jpeg'] - 图片格式 * @param [options.encoderOptions = 0.92] - 在指定图片格式为 image/jpeg 或 image/webp的情况下,可以从 0 到 1 的区间内选择图片的质量。如果超出取值范围,将会使用默认值 0.92。其他参数会被忽略。 * @param [options.callback] - 截图完成后的回调方法 * @returns 无 */ expImage(options?: { download?: boolean; filename?: string; width?: number; height?: number; type?: string; encoderOptions?: number; callback?: (...params: any[]) => any; }): void; /** * 设置鼠标状态为“+”号效果,比如标绘时切换 * @param val - 是否“+”号效果 * @returns 无 */ setCursor(val: boolean): void; /** * 获取坐标位置的3dtiles模型对象 * @param positions - 坐标 或 坐标数组 * @returns 3dtiles模型对象 */ pick3DTileset(positions: Cesium.Cartesian3 | Cesium.Cartesian3[]): Cesium.Cesium3DTileset; /** * 重新设置basemps底图图层,对options.basemaps重新赋值 * @param arr - 底图图层配置 * @returns 图层数组 */ setBasemapsOptions(arr: Map.basemapOptions[]): BaseLayer[]; /** * 重新设置layers图层,对options.layers重新赋值 * @param arr - 可以叠加显示的图层配置 * @returns 图层数组 */ setLayersOptions(arr: Map.layerOptions[]): BaseLayer[]; /** * 获取图层ID值,按顺序取值。 * 没有id的图层,会自动使用本方法进行id赋值处理 * @returns 图层ID */ getNextLayerId(): Int; /** * 添加图层到地图上 * @param layer - 图层对象 * @param showVal - 如果传值,覆盖图层的show属性 * @returns 当前对象本身,可以链式调用 */ addLayer(layer: BaseLayer, showVal: boolean): this; /** * 移除图层 * @param layer - 需要移除的图层 * @param hasDestory - 是否释放 * @returns 当前对象本身,可以链式调用 */ removeLayer(layer: BaseLayer, hasDestory: boolean): this; /** * 是否有指定的图层存在(就是已经addLayer的图层) * @param layer - 指定的图层或图层ID * @returns 是否存在 */ hasLayer(layer: BaseLayer | string): boolean; /** * 遍历每一个图层并将其作为参数传递给回调函数 * @param method - 回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ eachLayer(method: (...params: any[]) => any, context: any): this; /** * 根据ID或取图层 * @param id - 图层id或uuid * @returns 图层对象 */ getLayerById(id: string | number): BaseLayer; /** * 根据指定属性获取图层 * @param key - 图层值(如id、name值) 或 配置的图层参数对象 * @param [attrName = 'id'] - 属性名称 * @returns 图层对象 */ getLayer(key: any | string | number, attrName?: string): BaseLayer; /** * 获取所有图层 * @param options - 参数对象,包括以下: * @param [options.basemaps = false] - 是否包含basemps中配置的所有图层 * @param [options.layers = false] - 是否包含layers中配置的所有图层 * @param [options.filter = false] - 是否排除layers和baseps的图层 * @returns 图层数组 */ getLayers(options: { basemaps?: boolean; layers?: boolean; filter?: boolean; }): BaseLayer[]; /** * 获取所有basemps底图图层 * @param [removeEmptyGroup = false] - 是否移除 空图层组 * @returns 图层数组 */ getBasemaps(removeEmptyGroup?: boolean): BaseLayer[]; /** * 获取所有瓦片图层,可以用于卷帘对比 * @returns 图层数组 */ getTileLayers(): BaseLayer[]; /** * 添加控件到地图上 * @param control - 控件对象 * @param enabledVal - 如果传值,覆盖控件的enabled属性 * @returns 当前对象本身,可以链式调用 */ addControl(control: BaseControl, enabledVal: boolean): this; /** * 移除控件 * @param control - 需要移除的控件 * @param hasDestory - 是否释放 * @returns 当前对象本身,可以链式调用 */ removeControl(control: BaseControl, hasDestory: boolean): this; /** * 是否有指定的控件存在(就是已经addControl的控件) * @param control - 指定的控件或控件ID * @returns 是否存在 */ hasControl(control: BaseLayer | string): boolean; /** * 遍历每一个控件并将其作为参数传递给回调函数 * @param method - 回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ eachControl(method: (...params: any[]) => any, context: any): this; /** * 根据指定属性获取控件 * @param key - 属性值(如id、name值) * @param [attrName = 'id'] - 属性名称 * @returns 控件对象 */ getControl(key: any | string | number, attrName?: string): BaseControl; /** * 添加特效对象到地图上 * @param item - 特效对象 * @returns 当前对象本身,可以链式调用 */ addEffect(item: BaseEffect): this; /** * 移除特效对象 * @param item - 需要移除的特效对象 * @param hasDestory - 是否释放 * @returns 当前对象本身,可以链式调用 */ removeEffect(item: BaseEffect, hasDestory: boolean): this; /** * 根据指定属性获取Thing对象 * @param key - 属性值(如id、name值) * @param [attrName = 'id'] - 属性名称 * @returns Thing对象 */ getEffect(key: string | any, attrName?: string): BaseEffect; /** * 添加Thing对象到地图上 * @param item - Thing对象 * @returns 当前对象本身,可以链式调用 */ addThing(item: BaseThing): this; /** * 移除Thing对象 * @param item - 需要移除的Thing对象 * @param hasDestory - 是否释放 * @returns 当前对象本身,可以链式调用 */ removeThing(item: BaseThing, hasDestory: boolean): this; /** * 是否有指定的Thing对象存在(就是已经addThing的图层) * @param thing - 指定的Thing对象或Thing对象ID * @returns 是否存在 */ hasThing(thing: BaseThing | string): boolean; /** * 遍历每一个Thing对象并将其作为参数传递给回调函数 * @param method - 回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ eachThing(method: (...params: any[]) => any, context: any): this; /** * 根据指定属性获取Thing对象 * @param key - 属性值(如id、name值) * @param [attrName = 'id'] - 属性名称 * @returns Thing对象 */ getThing(key: string | any, attrName?: string): BaseThing; /** * 根据设置的lang参数,获取当前key对应语言的文本内容。 * @param key - 文本key * @returns lang参数指定的对应文本内容 */ getLangText(key: string): void; /** * 放大地图 * @param [relativeAmount = 2] - 相对量 * @returns 当前对象本身,可以链式调用 */ zoomIn(relativeAmount?: number): this; /** * 缩小地图 * @param [relativeAmount = 2] - 相对量 * @returns 当前对象本身,可以链式调用 */ zoomOut(relativeAmount?: number): this; /** * 设置鼠标操作习惯方式。 * 默认为中键旋转,右键拉伸远近。传`rightTilt:true`可以设置为右键旋转,中键拉伸远近。 * @param [rightTilt = false] - 是否右键旋转 * @returns 无 */ changeMouseModel(rightTilt?: boolean): void; /** * 设置鼠标操作限定的Pitch范围 * @param max - 最大值(角度值) * @param [min = -90] - 最小值(角度值) * @returns 无 */ setPitchRange(max: number, min?: number): void; /** * 设置相机pitch值,保持地图中心位置不变。 * @param pitch - 俯仰角度值, 0至360 * @param [options] - 具有以下属性的对象: * @param [options.heading] - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param [options.duration] - 飞行持续时间(秒)。如果省略,内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @returns 无 */ setPitch(pitch: number, options?: { heading?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; }): void; /** * 清除鼠标操作限定的Pitch范围 * @returns 无 */ clearPitchRange(): void; /** * 停止视角定位等操作 * @returns 当前对象本身,可以链式调用 */ cancelFlight(): this; /** * 获取当前相机视角参数, * 示例:{"lat":30.526361,"lng":116.335987,"alt":45187,"heading":0,"pitch":-45} * @param [options = {}] - 参数对象: * @param [options.simplify = true] - 是否简化,false时保留角度1位小数位 * @returns 当前相机视角参数 */ getCameraView(options?: { simplify?: boolean; }): any; /** * 将相机本身定位至指定位置 * @param cameraView - 飞行参数 * @param cameraView.lng - 经度值, 180 - 180 * @param cameraView.lat - 纬度值, -90 - 90 * @param cameraView.alt - 高度值 * @param cameraView.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0-360 * @param cameraView.pitch - 俯仰角度值,绕纬度线旋转角度, 0-360 * @param cameraView.roll - 翻滚角度值,绕经度线旋转角度, 0-360 * @param [options = {}] - 参数对象: * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ setCameraView(cameraView: { lng: number; lat: number; alt: number; heading: number; pitch: number; roll: number; }, options?: { duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): void; /** * 将相机本身定位至指定位置,同 setCameraView 方法 * 为了兼容老版本用户习惯和center参数名称一致而用的别名方法。 * @param cameraView - 飞行参数,同 setCameraView 方法 * @param [options = {}] - 参数对象,同 setCameraView 方法 * @returns 无 */ centerAt(cameraView: any, options?: any): void; /** * 飞行到默认视角, * 一般为config.json中的center参数配置的视角。 * @param [options = {}] - 参数对象: * @param [options.duration = null] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @returns 无 */ flyHome(options?: { duration?: number; }): void; /** * 定位到多个相机视角位置,按数组顺序播放 * @param arr - 视角参数数组,每个对象包含: * @param arr.lng - 经度值, -180 至 180 * @param arr.lat - 纬度值, -90 至 90 * @param arr.alt - 高度值 * @param arr.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param arr.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param arr.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [arr.duration = null] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [arr.stop = 1] - 该步骤飞行结束的停留时间(单位:秒)。 * @param [arr.onStart] - 该步骤飞行开始前的回调方法 * @param [arr.onEnd] - 该步骤飞行开始结束后的回调方法 * @param [options = {}] - 参数对象: * @param [options.complete] - 全部飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction = Cesium.EasingFunction.LINEAR_NONE] - 控制在飞行过程中如何插值时间。 * @returns 无 */ setCameraViewList(arr: { lng: number; lat: number; alt: number; heading: number; pitch: number; roll: number; duration?: number; stop?: number; onStart?: (...params: any[]) => any; onEnd?: (...params: any[]) => any; }[], options?: { complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): void; /** * 飞行至Cesium相关矢量对象处,是Cesium本身的flyTo方法。 * * 将相机移至提供的一个或多个实体或数据源。如果数据源仍在加载过程中,或者可视化仍在加载中,此方法在执行飞行之前等待数据准备就绪。 * 偏移量是在以边界球中心为中心的局部东北向上参考框中的航向/俯仰/范围。航向角和俯仰角是在局部的东西向北参考系中定义的。航向是从y轴到x轴的角度。间距是从xy平面开始的旋转。正螺距角度在平面上方。负俯仰角在平面下方。范围是到中心的距离。如果范围是零,则将计算范围以使整个边界球都可见。 * * 在2D模式下,必须有一个俯视图。摄像机将被放置在目标上方并向下看。上方的高度目标将是范围。航向将根据偏移量确定。如果标题不能根据偏移量确定,航向将为北。 * @param target - 需要定位的Cesium内部对象。您还可以传递一个: Cesium.Entity|Cesium.Entity[]|Cesium.EntityCollection|Cesium.DataSource|Cesium.ImageryLayer|Cesium.Cesium3DTileset|Cesium.TimeDynamicPointCloud|Promise.<Entity|Entity[]|Cesium.EntityCollection|Cesium.DataSource|Cesium.ImageryLayer|Cesium.Cesium3DTileset|Cesium.TimeDynamicPointCloud> * @param [options] - 具有以下属性的对象: * @param [options.duration = 3.0] - 飞行持续时间(秒)。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.offset] - 在局部东北朝上的参考框中,距目标的偏移量为中心。 * @returns 如果飞行成功则解析为true的承诺,如果当前未在场景中可视化目标或取消飞行,则为false的Promise。 //TODO:清理实体提及 */ flyTo(target: any, options?: { duration?: number; maximumHeight?: number; offset?: HeadingPitchRange; }): Promise<Boolean>; /** * 飞行定位到 Graphic矢量对象 处 * @param graphic - 矢量对象 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.minHeight] - 定位时相机的最小高度值,用于控制避免异常数据 * @param [options.maxHeight] - 定位时相机的最大高度值,用于控制避免异常数据 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyToGraphic(graphic: BaseGraphic, options?: { radius: number; scale?: number; minHeight?: number; maxHeight?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): void; /** * 定位至坐标数组 * @param positions - 坐标数组 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.minHeight] - 定位时相机的最小高度值,用于控制避免异常数据 * @param [options.maxHeight] - 定位时相机的最大高度值,用于控制避免异常数据 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyToPositions(positions: Cesium.Cartesian3[], options?: { radius: number; scale?: number; minHeight?: number; maxHeight?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): void; /** * 相机飞行定位至矩形区域 * @param extent - 飞行参数, Object时可以传入: * @param extent.xmin - 最小经度值, -180 至 180 * @param extent.xmax - 最大纬度值, -180 至 180 * @param extent.ymin - 最小纬度值, -90 至 90 * @param extent.ymax - 最大纬度值, -90 至 90 * @param [extent.height = 0] - 矩形高度值 * @param [options = {}] - 参数对象: * @param [options.scale] - 缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.minHeight] - 定位时相机的最小高度值,用于控制避免异常数据 * @param [options.maxHeight] - 定位时相机的最大高度值,用于控制避免异常数据 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyToExtent(extent: { xmin: number; xmax: number; ymin: number; ymax: number; height?: number; }, options?: { scale?: number; minHeight?: number; maxHeight?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): void; /** * 定位至目标点(非相机位置) * @param point - 目标点位置(视角中心点) * @param [options = {}] - 具有以下属性的对象: * @param options.radius - 相机距离目标点的距离(单位:米) * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行持续时间(秒)。如果省略,内部会根据飞行距离计算出理想的飞行时间。 * @param [options.clampToGround] - 是否贴地对象,true时异步计算实际高度值后进行定位。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 表示飞行完成后摄像机将位于的参考帧的变换矩阵。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机的飞行角度高于该值,请在飞行过程中调整俯仰角度以向下看,并将地球保持在视口中。 * @param [options.flyOverLongitude] - 地球上2点之间总是有两种方式。此选项会迫使相机选择战斗方向以在该经度上飞行。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyToPoint(point: LatLngPoint | Cesium.Cartesian3, options?: { radius: number; heading: number; pitch: number; roll: number; duration?: number; clampToGround?: boolean; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; easingFunction?: EasingFunction.Callback; }): void; /** * 是否在调用了openFlyAnimation正在进行开场动画 * @returns 是否在开场动画 */ isFlyAnimation(): boolean; /** * 执行开场动画,动画播放地球飞行定位到指定区域 * @param [options = {}] - 参数对象: * @param [options.center = getCameraView()] - 飞行到的指定区域视角参数 * @param [options.callback = null] - 飞行结束的回调方法 * @returns 无 */ openFlyAnimation(options?: { center?: any; callback?: (...params: any[]) => any; }): void; /** * 执行旋转地球动画 * @param [options = {}] - 参数对象: * @param [options.duration = 10] - 动画时长(单位:秒) * @param [options.center = getCameraView()] - 飞行到的指定区域视角参数 * @param [options.callback = null] - 飞行结束的回调方法 * @returns 无 */ rotateAnimation(options?: { duration?: number; center?: any; callback?: (...params: any[]) => any; }): void; /** * 清除已高亮的矢量对象 * @returns 无 */ closeHighlight(): void; /** * 高亮矢量对象 * @param graphic - 矢量对象 * @param highlightStyle - 高亮的样式,具体见各{@link GraphicType}矢量数据的style参数。 * @param [event] - 鼠标事件对象 * @returns 无 */ openHighlight(graphic: BaseGraphic, highlightStyle: any, event?: any): void; /** * 打开Popup弹窗 * @param position - 矢量对象 或 显示的位置 * @param content - 弹窗内容html字符串,或者 回调方法 或者矢量对象/图层。 * @param options - 配置参数 * @returns 当前对象本身,可以链式调用 */ openPopup(position: LatLngPoint | Cesium.Cartesian3, content: string | ((...params: any[]) => any) | BaseGraphic | BaseGraphicLayer, options: Popup.StyleOptions): this; /** * 关闭Popup弹窗 * @returns 当前对象本身,可以链式调用 */ closePopup(): this; /** * 打开Tooltip弹窗 * @param [position] - 矢量对象 或 显示的位置 * @param content - 弹窗内容html字符串,或者 回调方法 * @param options - 配置参数 * @returns 当前对象本身,可以链式调用 */ openTooltip(position?: LatLngPoint | Cesium.Cartesian3, content: string | ((...params: any[]) => any), options: Tooltip.StyleOptions): this; /** * 关闭Tooltip弹窗 * @returns 当前对象本身,可以链式调用 */ closeTooltip(): this; /** * 获取绑定的右键菜单数组 * @returns 右键菜单数组 */ getContextMenu(): object[]; /** * 绑定地图的默认右键菜单 * @example * //内置的默认右键菜单获取方法 * var defaultContextmenuItems =map.getDefaultContextMenu() * map.bindContextMenu(defaultContextmenuItems) * @param content - 右键菜单配置数组,数组中每一项包括: * @param [content.text] - 菜单文字 * @param [content.iconCls] - 小图标css * @param [content.show] - 菜单项是否显示的回调方法 * @param [content.callback] - 菜单项单击后的回调方法 * @param [content.children] - 当有二级子菜单时,配置数组。 * @param [options = {}] - 控制参数 * @param [options.offsetX] - 用于非规则对象时,横向偏移的px像素值 * @param [options.offsetY] - 用于非规则对象时,垂直方向偏移的px像素值 * @returns 当前对象本身,可以链式调用 */ bindContextMenu(content: { text?: string; iconCls?: string; show?: ((...params: any[]) => any) | boolean; callback?: (...params: any[]) => any; children?: object[]; }[], options?: { offsetX?: number; offsetY?: number; }): this; /** * 解除绑定的右键菜单 * @returns 当前对象本身,可以链式调用 */ unbindContextMenu(): this; /** * 打开右键菜单 * @param [position] - 显示的位置 * @returns 当前对象本身,可以链式调用 */ openContextMenu(position?: Cesium.Cartesian3): this; /** * 关闭右键菜单 * @returns 当前对象本身,可以链式调用 */ closeContextMenu(): this; /** * 显示小提示窗,一般用于鼠标操作的提示。 * @param position - 显示的屏幕坐标位置 或 笛卡尔坐标位置 * @param message - 显示的内容 * @returns 当前对象本身,可以链式调用 */ openSmallTooltip(position: Cesium.Cartesian2 | Cesium.Cartesian3, message: any): this; /** * 关闭小提示窗 * @returns 当前对象本身,可以链式调用 */ closeSmallTooltip(): this; /** * 销毁地图 * @returns 无 */ destroy(): void; /** * 绑定指定类型事件监听器 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ on(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): this; /** * 解除绑定指定类型事件监听器 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 当前对象本身,可以链式调用 */ off(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): this; } /** * 材质属性(Entity使用) 基础类 * @param options - 参数对象 */ declare class BaseMaterialProperty { constructor(options: any); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 圆形扫描效果 材质属性 * @param options - 参数对象,包括以下: * @param options.image - 背景图片URL * @param [options.color = new Cesium.Color(1, 0, 0, 0.5))] - 颜色 */ declare class CircleScanMaterialProperty extends BaseMaterialProperty { constructor(options: { image: string; color?: string | Cesium.Color; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; /** * 颜色 */ color: Cesium.Color; /** * 背景图片URL */ image: string; } /** * 圆形扩散波纹效果 材质属性 * @param options - 参数对象,包括以下: * @param [options.color = Cesium.Color.YELLOW] - 颜色 * @param [options.speed = 10] - 速度 * @param [options.count = 1] - 圆圈个数 * @param [options.gradient = 0.1] - 透明度的幂方(0-1),0表示无虚化效果,1表示虚化成均匀渐变 */ declare class CircleWaveMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: string | Cesium.Color; speed?: number; count?: number; gradient?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; /** * 颜色 */ color: Cesium.Color; /** * 速度 */ speed: number; /** * 圆圈个数 */ count: number; /** * 透明度的幂方(0-1),0表示无虚化效果,1表示虚化成均匀渐变 */ gradient: number; /** * 颜色 */ color: Cesium.Color; /** * 线的背景颜色 */ bgColor: Cesium.Color; /** * 速度 */ speed: number; /** * 颜色 */ color: Cesium.Color; /** * 速度 */ speed: number; /** * 基础颜色 */ baseWaterColor: Cesium.Color; /** * 从水中混合到非水域时使用的rgba颜色对象。 */ blendColor: Cesium.Color; /** * 单一通道纹理用来指示水域的面积。 */ specularMap: string; /** * 水正常扰动的法线图。 */ normalMap: string; } /** * 球体: 电弧球体效果 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @param [options.speed = 5.0] - 速度,值越大越快 */ declare class EllipsoidElectricMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: Cesium.Color; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 球体: 波纹球体效果 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @param [options.speed = 5.0] - 速度,值越大越快 */ declare class EllipsoidWaveMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: Cesium.Color; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 通用:图片 材质2 材质属性, 没有加载完成前的白色闪烁,但也不支持纯白色的图片 * @param options - 参数对象,包括以下: * @param options.image - 背景图片URL * @param [options.opacity = 1] - 透明度 */ declare class Image2MaterialProperty extends BaseMaterialProperty { constructor(options: { image: string; opacity?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; /** * 透明度,0-1 */ opacity: number; /** * 背景图片URL */ image: string; } /** * 线状: 闪烁线 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @param [options.speed = 2] - 速度,值越大越快 */ declare class LineFlickerMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: Cesium.Color; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 线状 流动效果 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @param [options.speed = 2] - 速度,值越大越快 * @param [options.percent = 0.04] - 比例 * @param [options.alpha = 0.1] - 透明程度 0.0-1.0 */ declare class LineFlowColorMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: Cesium.Color; speed?: number; percent?: number; alpha?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 线状 流动效果 材质 * @param options - 参数对象,包括以下: * @param options.image - 背景图片URL * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 背景图片颜色 * @param [options.repeat = new Cesium.Cartesian2(1.0, 1.0)] - 横纵方向重复次数 * @param [options.axisY = false] - 是否Y轴朝上 * @param [options.speed = 10] - 速度,建议取值范围1-100 * @param [options.hasImage2 = false] - 是否有2张图片的混合模式 * @param [options.image2] - 第2张背景图片URL地址 * @param [options.color2 = new Cesium.Color(1, 1, 1)] - 第2张背景图片颜色 */ declare class LineFlowMaterialProperty extends BaseMaterialProperty { constructor(options: { image: string; color?: string | Cesium.Color; repeat?: Cesium.Cartesian2; axisY?: boolean; speed?: number; hasImage2?: boolean; image2?: string; color2?: string | Cesium.Color; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 线状: 轨迹线 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @param [options.speed = 5.0] - 速度,值越大越快 */ declare class LineTrailMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: Cesium.Color; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 线状 OD线效果 材质 * @param options - 参数对象,包括以下: * @param [options.color = 随机色] - 运动对象的颜色 * @param [options.bgColor] - 线的背景颜色 * @param [options.speed = 20 + 10 * Math.random()] - 速度 * @param [options.startTime = Math.random] - 开始的时间系数 * @param [options.bidirectional = 0] - 运行形式:0 正向运动 1 反向运动 2 双向运动 */ declare class ODLineMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: string | Cesium.Color; bgColor?: string | Cesium.Color; speed?: number; startTime?: number; bidirectional?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 面状: 渐变面 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1.0, 1.0, 0.0, 0.5)] - 颜色 * @param [options.alphaPower = 1.5] - 透明度系数 * @param [options.diffusePower = 1.6] - 漫射系数 */ declare class PolyGradientMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: string | Cesium.Color; alphaPower?: number; diffusePower?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 圆形: 雷达线(圆+旋转半径线) 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @param [options.speed = 5.0] - 速度,值越大越快 */ declare class RadarLineMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: Cesium.Color; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 圆形: 雷达线(圆+旋转半径线) 材质 * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 颜色 * @param [options.speed = 5.0] - 速度,值越大越快 */ declare class RadarWaveMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: Cesium.Color; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 矩形面: 轮播图 材质 * @param options - 参数对象,包括以下: * @param options.image - 图片URL * @param [options.color = Cesium.Color.WHITE] - 颜色和透明度 * @param [options.speed = 1] - 速度,值越大越快 * @param [options.pure = false] - 是否纯色 */ declare class RectSlideMaterialProperty extends BaseMaterialProperty { constructor(options: { image: string; color?: Cesium.Color; speed?: number; pure?: boolean; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 面状: 用于面状对象的 扫描线放大效果 材质属性 * @param options - 参数对象,包括以下: * @param [options.color = Cesium.Color.YELLOW] - 颜色 * @param [options.speed = 10] - 速度 */ declare class ScanLineMaterialProperty extends BaseMaterialProperty { constructor(options: { color?: string | Cesium.Color; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 文字贴图 entity材质 * @param options - 参数对象,包括以下: * @param [options.text] - 文本内容 * @param [options.font_family = "楷体"] - 字体 ,可选项:微软雅黑,宋体,楷体,隶书,黑体, * @param [options.font_size = 30] - 字体大小 * @param [options.font_weight = "normal"] - 是否加粗 ,可选项:bold (解释:是),normal (解释:否), * @param [options.font_style = "normal"] - 是否斜体 ,可选项:italic (解释:是),normal (解释:否), * @param [options.font = '30px normal normal 楷体'] - 上叙4个属性的一次性指定CSS字体的属性。 * @param [options.fill = true] - 是否填充 * @param [options.color = "#ffff00"] - 文本颜色 * @param [options.stroke = true] - 是否描边文本。 * @param [options.strokeColor = new Cesium.Color(1.0, 1.0, 1.0, 0.8)] - 描边的颜色。 * @param [options.strokeWidth = 2] - 描边的宽度。 * @param [options.backgroundColor = new Cesium.Color(1.0, 1.0, 1.0, 0.1)] - 画布的背景色。 * @param [options.outlineWidth] - 边框的宽度。 * @param [options.outlineColor = fillColor] - 矩形边框的颜色。 * @param [options.padding = 10] - 要在文本周围添加的填充的像素大小。 * @param [options.textBaseline = 'top'] - 文本的基线。 * @param [options.onCustomCanvas] - 支持对生成后的Canvas做自定义处理。 */ declare class TextMaterialProperty extends Image2MaterialProperty { constructor(options: { text?: string; font_family?: string; font_size?: number; font_weight?: string; font_style?: string; font?: string; fill?: boolean; color?: string; stroke?: boolean; strokeColor?: Color; strokeWidth?: number; backgroundColor?: Color; outlineWidth?: number; outlineColor?: Cesium.Color; padding?: number; textBaseline?: string; onCustomCanvas?: (...params: any[]) => any; }); /** * 文本内容 */ text: string; /** * 文本样式 */ textStyles: any; } /** * 墙体: 走马灯围墙 材质 * @param options - 参数对象,包括以下: * @param options.image - 背景图片URL * @param [options.color = new Cesium.Color(1, 0, 0, 1.0)] - 背景图片颜色 * @param [options.count = 1] - 数量 * @param [options.speed = 5.0] - 速度 */ declare class WallScrollMaterialProperty extends BaseMaterialProperty { constructor(options: { image: string; color?: string | Cesium.Color; count?: number; speed?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 水面效果材质 * @param options - 参数对象,包括以下: * @param [options.baseWaterColor = new Cesium.Color(0.2, 0.3, 0.6, 1.0)] - 基础颜色 * @param [options.blendColor = new Cesium.Color(0.0, 1.0, 0.699, 1.0)] - 从水中混合到非水域时使用的rgba颜色对象。 * @param [options.specularMap] - 单一通道纹理用来指示水域的面积。 * @param [options.normalMap] - 水正常扰动的法线图。 * @param [options.frequency = 100] - 控制波数的数字。 * @param [options.animationSpeed = 0.01] - 控制水的动画速度的数字。 * @param [options.amplitude = 10] - 控制水波振幅的数字。 * @param [options.specularIntensity = 0.5] - 控制镜面反射强度的数字。 * @param [options.fadeFactor = 1.0] - fadeFactor */ declare class WaterMaterialProperty extends BaseMaterialProperty { constructor(options: { baseWaterColor?: string | Cesium.Color; blendColor?: string | Cesium.Color; specularMap?: string; normalMap?: string; frequency?: number; animationSpeed?: number; amplitude?: number; specularIntensity?: number; fadeFactor?: number; }); /** * 获取 材质名称 * @param [time] - 检索值的时间。 * @returns 材质名称 */ getType(time?: Cesium.JulianDate): string; /** * 获取所提供时间的属性值。 * @param [time] - 检索值的时间。 * @param [result] - 用于存储值的对象,如果省略,则创建并返回一个新的实例。 * @returns 修改的result参数或一个新的实例(如果没有提供result参数)。 */ getValue(time?: Cesium.JulianDate, result?: any): any; /** * 将此属性与提供的属性进行比较并返回, 如果两者相等返回true,否则为false * @param [other] - 比较的对象 * @returns 两者是同一个对象 */ equals(other?: Cesium.Property): boolean; } /** * 圆锥 波纹扩散效果 材质 * @example * var primitive = new mars3d.graphic.CylinderPrimitive({ * position: [116.328775, 30.954602, 5000], * style: { * topRadius: 0.0, * bottomRadius: 1500.0, * length: 10000.0, * material: new mars3d.material.CylinderWaveMaterial({ * color: 'rgba(255,0,0,0.7)', * repeat: 30.0, * }), * faceForward: false, * closed: true, * }, * }) * graphicLayer.addGraphic(primitive) * @param options - 参数对象,包括以下: * @param [options.color = new Cesium.Color(2, 1, 0.0, 0.8)] - 颜色 * @param [options.repeat = 30] - 圈数量 * @param [options.frameRate = 60] - 每秒刷新次数 */ declare class CylinderWaveMaterial extends Cesium.Material { constructor(options: { color?: string | Cesium.Color; repeat?: number; frameRate?: number; }); } /** * 文字贴图 primitive材质 * @example * var primitive = new mars3d.graphic.WallPrimitive({ * positions: [ * [121.479343, 29.791419, 25], * [121.479197, 29.791474, 25], * ], * style: { * diffHeight: 5, * material: new mars3d.material.TextMaterial({ * text: "火星科技", * fillColor: "#3388cc", * outlineWidth: 4, * }), * }, * }) * graphicLayer.addGraphic(primitive) * @param options - 参数对象,包括以下: * @param [options.text] - 文本内容 * @param [options.font_family = "楷体"] - 字体 ,可选项:微软雅黑,宋体,楷体,隶书,黑体, * @param [options.font_size = 30] - 字体大小 * @param [options.font_weight = "normal"] - 是否加粗 ,可选项:bold (解释:是),normal (解释:否), * @param [options.font_style = "normal"] - 是否斜体 ,可选项:italic (解释:是),normal (解释:否), * @param [options.font = '30px normal normal 楷体'] - 上叙4个属性的一次性指定CSS字体的属性。 * @param [options.fill = true] - 是否填充 * @param [options.fillColor = new Cesium.Color(1.0, 1.0, 0.0, 1.0)] - 填充颜色。 * @param [options.stroke = true] - 是否描边文本。 * @param [options.strokeColor = new Cesium.Color(1.0, 1.0, 1.0, 0.8)] - 描边的颜色。 * @param [options.strokeWidth = 2] - 描边的宽度。 * @param [options.backgroundColor = new Cesium.Color(1.0, 1.0, 1.0, 0.1)] - 画布的背景色。 * @param [options.outlineWidth] - 边框的宽度。 * @param [options.outlineColor = fillColor] - 矩形边框的颜色。 * @param [options.padding = 10] - 要在文本周围添加的填充的像素大小。 * @param [options.textBaseline = 'top'] - 文本的基线。 */ declare class TextMaterial extends Cesium.Material { constructor(options: { text?: string; font_family?: string; font_size?: number; font_weight?: string; font_style?: string; font?: string; fill?: boolean; fillColor?: Color; stroke?: boolean; strokeColor?: Color; strokeWidth?: number; backgroundColor?: Color; outlineWidth?: number; outlineColor?: Cesium.Color; padding?: number; textBaseline?: string; }); } declare namespace CanvasWindLayer { /** * Canvas风场图层, data数据结构 * @property [rows] - 行总数 * @property [cols] - 列总数 * @property [xmin] - 最小经度(度数,-180-180) * @property [xmax] - 最大经度(度数,-180-180) * @property [ymin] - 最小纬度(度数,-90-90) * @property [ymax] - 最大纬度(度数,-90-90) * @property [udata] - U值一维数组, 数组长度应该是 rows*cols 。也支持按rows行cols列构建好的二维数组。 * @property [vdata] - V值一维数组, 数组长度应该是 rows*cols 。也支持按rows行cols列构建好的二维数组。 */ type DataOptions = { rows?: number; cols?: number; xmin?: number; xmax?: number; ymin?: number; ymax?: number; udata?: Number[] | any[][]; vdata?: Number[] | any[][]; }; } /** * Canvas风场图层, * 基于Canvas绘制,【需要引入 mars3d-wind 插件库】 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.center] - 图层自定义定位视角 * @param [options.data] - 风场数据 * @param [options.speedRate = 50] - 风前进速率,意思是将当前风场横向纵向分成100份,再乘以风速就能得到移动位置,无论地图缩放到哪一级别都是一样的速度,可以用该数值控制线流动的快慢,值越大,越慢, * @param [options.particlesNumber = 20000] - 初始粒子总数 * @param [options.maxAge = 120] - 每个粒子的最大生存周期 * @param [options.frameRate = 10] - 每秒刷新次数,因为requestAnimationFrame固定每秒60次的渲染,所以如果不想这么快,就把该数值调小一些 * @param [options.color = '#ffffff'] - 线颜色 * @param [options.lineWidth = 1] - 线宽度 * @param [options.fixedHeight = 0] - 点的固定的海拔高度 * @param [options.reverseY = false] - 是否翻转纬度数组顺序,正常数据是从北往南的(纬度从大到小),如果反向时请传reverseY为true * @param [options.pointerEvents = false] - 图层是否可以进行鼠标交互,为false时可以穿透操作及缩放地图 */ declare class CanvasWindLayer extends BaseLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; data?: CanvasWindLayer.DataOptions; speedRate?: number; particlesNumber?: number; maxAge?: number; frameRate?: number; color?: string; lineWidth?: number; fixedHeight?: number; reverseY?: boolean; pointerEvents?: boolean; }); /** * 线颜色 */ color: string; /** * 线宽度 */ lineWidth: number; /** * 点的固定的海拔高度 */ fixedHeight: number; /** * 是否翻转纬度数组顺序,正常数据是从北往南的(纬度从大到小),如果反向时请传reverseY为true */ reverseY: boolean; /** * 图层对应的Canvas对象 */ readonly canvas: HTMLCanvasElement; /** * 图层对应的Canvas对象 */ readonly layer: HTMLCanvasElement; /** * Canvas对象宽度(单位:像素) */ readonly canvasWidth: number; /** * Canvas对象高度(单位:像素) */ readonly canvasHeight: number; /** * 图层是否可以鼠标交互,为false时可以穿透操作及缩放地图 */ pointerEvents: boolean; /** * 风前进速率,意思是将当前风场横向纵向分成100份,再乘以风速就能得到移动位置,无论地图缩放到哪一级别都是一样的速度,可以用该数值控制线流动的快慢,值越大,越慢, */ speedRate: number; /** * 初始粒子总数 */ particlesNumber: number; /** * 每个粒子的最大生存周期 */ maxAge: number; /** * 风场数据,数据结构见类的构造方法说明 */ data: CanvasWindLayer.DataOptions; /** * 重绘,根据现有参数重新生成风场 * @returns 无 */ redraw(): void; /** * 清除数据 * @returns 无 */ clear(): void; /** * 显示隐藏状态 */ show: boolean; } /** * 风场相关 静态方法,【需要引入 mars3d-wind 插件库】 */ declare module "WindUtil" { /** * 风速风向 转 U值 * @param speed - 风速 * @param direction - 风向 * @returns U值 */ function getU(speed: number, direction: number): number; /** * 风速风向 转 V值 * @param speed - 风速 * @param direction - 风向 * @returns V值 */ function getV(speed: number, direction: number): number; /** * UV值 转 风速, 风速是uv分量的平方和 * @param u - U值 * @param v - V值 * @returns 风速 */ function getSpeed(u: number, v: number): number; /** * UV 转 风向 * @param u - U值 * @param v - V值 * @returns 风向 */ function getDirection(u: number, v: number): number; } /** * Echarts图层, * 【需要引入 echarts 库 和 mars3d-echarts 插件库】 * @param options - 参数对象,包括以下: * @param [options.Echarts本身] - 支持Echarts本身所有Options参数,具体查阅 [Echarts配置项手册]{@link https://echarts.apache.org/zh/option.html} * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.center] - 图层自定义定位视角 * @param [options.depthTest = true] - 是否进行计算深度判断,在地球背面或被遮挡时不显示(大数据时,需要关闭) * @param [options.fixedHeight = 0] - 点的固定的海拔高度 * @param [options.clampToGround = false] - 点是否贴地 * @param [options.pointerEvents = false] - 图层是否可以进行鼠标交互,为false时可以穿透操作及缩放地图 */ declare class EchartsLayer extends BaseLayer { constructor(options: { Echarts本身?: any; id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; depthTest?: boolean; fixedHeight?: number; clampToGround?: boolean; pointerEvents?: boolean; }); /** * echarts对象,是echarts.init方法返回的 echartsInstance 实例 */ readonly layer: HTMLCanvasElement; /** * 改变图层canvas容器尺寸,在容器大小发生改变时需要手动调用。 * @returns 无 */ resize(): void; /** * 设置图表实例的配置项以及数据, * 万能接口,所有参数和数据的修改都可以通过 setOption 完成, * ECharts 会合并新的参数和数据,然后刷新图表。 * 如果开启动画的话,ECharts 找到两组数据之间的差异然后通过合适的动画去表现数据的变化。 * @param option - 图表的配置项和数据,具体见 [Echarts配置项手册]{@link https://echarts.apache.org/zh/option.html}。 * @param [notMerge = false] - 是否不跟之前设置的 option 进行合并。默认为 false。即表示合并。合并的规则,详见 组件合并模式。如果为 true,表示所有组件都会被删除,然后根据新 option 创建所有新组件。 * @param [lazyUpdate = false] - 在设置完 option 后是否不立即更新图表,默认为 false,即同步立即更新。如果为 true,则会在下一个 animation frame 中,才更新图表。 * @returns 无 */ setEchartsOption(option: any, notMerge?: boolean, lazyUpdate?: boolean): void; } /** * 热力图图层,基于heatmap.js库渲染。 * 【需要引入 heatmap.js 库 和 mars3d-heatmap 插件库】 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.center] - 图层自定义定位视角 * @param [options.positions] - 坐标位置数组,有热力值时,传入LatLngPoint数组,热力值为value字段。示例:[{lat:31.123,lng:103.568,value:1.2},{lat:31.233,lng:103.938,value:2.3}] * @param [options.heatStyle] - heatmap热力图本身configObject参数,详情也可查阅 [heatmap文档]{@link https://www.patrick-wied.at/static/heatmapjs/docs.html} * @param [options.heatStyle.maxOpacity = 0.8] - 最大不透明度,取值范围0.0-1.0。 * @param [options.heatStyle.minOpacity = 0.1] - 最小不透明度,取值范围0.0-1.0。 * @param [options.heatStyle.blur = 0.85] - 将应用于所有数据点的模糊因子。模糊因子越高,渐变将越平滑 * @param [options.heatStyle.radius = 25] - 每个数据点将具有的半径(如果未在数据点本身上指定) * @param [options.heatStyle.gradient] - 色带,表示渐变的对象,示例:{ 0.4: 'blue', 0.6: 'green',0.8: 'yellow',0.9: 'red' } * @param [options.style] - 矢量对象样式参数,还包括: * @param [options.style.父类] - 父类支持的样式 * @param [options.style.opacity = 1] - 透明度 * @param [options.style.arc = false] - 是否显示曲面热力图 * @param [options.style.arcRadiusScale = 1.5] - 曲面热力图时,radius扩大比例 * @param [options.style.arcBlurScale = 1.5] - 曲面热力图时,blur扩大比例 * @param [options.maxCanvasSize = 5000] - Canvas最大尺寸(单位:像素),调大精度更高,但过大容易内存溢出 * @param [options.minCanvasSize = 700] - Canvas最小尺寸(单位:像素) * @param [options.delayTime = 2] - 显示数据时的过渡动画时长(单位:秒) */ declare class HeatLayer extends BaseLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; positions?: LatLngPoint[] | any[][] | String[] | Cesium.Cartesian3[]; heatStyle?: { maxOpacity?: number; minOpacity?: number; blur?: number; radius?: number; gradient?: any; }; style?: { 父类?: RectanglePrimitive.StyleOptions; opacity?: boolean; arc?: boolean; arcRadiusScale?: boolean; arcBlurScale?: boolean; }; maxCanvasSize?: number; minCanvasSize?: number; delayTime?: number; }); /** * 矢量数据图层 */ readonly layer: GraphicLayer; /** * heatmap热力图本身configObject参数,详情也可查阅 [heatmap文档]{@link https://www.patrick-wied.at/static/heatmapjs/docs.html} */ heatStyle: any; /** * 矩形的样式参数 */ style: RectanglePrimitive.StyleOptions; /** * 数据位置坐标数组 (笛卡尔坐标), 赋值时可以传入LatLngPoint数组对象 */ positions: Cesium.Cartesian3[] | LatLngPoint[]; /** * 位置坐标(数组对象),示例 [ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] */ readonly coordinates: any[][]; /** * 坐标数据对应的矩形边界 */ readonly rectangle: Cesium.Rectangle; /** * 添加新的坐标点 * @param item - 坐标点(含热力值) * @returns 无 */ addPosition(item: Cesium.Cartesian3 | LatLngPoint): void; /** * 清除矢量对象 * @returns 无 */ clear(): void; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } /** * MapV图层 * 【需要引入 heatmap.js 库 和 mars3d-heatmap 插件库】 * @param options - 图层参数,包括: * @param [options.mapV本身] - 支持mapv本身所有drawOptions图层样式参数,具体查阅 [mapv库drawOptions文档]{@link https://github.com/huiyan-fe/mapv/wiki/%E7%B1%BB%E5%8F%82%E8%80%83} ,也可以 [在线编辑图层样式]{@link https://mapv.baidu.com/editor/} * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.center] - 图层自定义定位视角 * @param [options.depthTest = true] - 是否进行计算深度判断,在地球背面或被遮挡时不显示(大数据时,需要关闭) * @param [options.fixedHeight = 0] - 点的固定的海拔高度 * @param [options.clampToGround = false] - 点是否贴地 * @param [options.pointerEvents = false] - 图层是否可以进行鼠标交互,为false时可以穿透操作及缩放地图 * @param dataSet - MapV数据集,可以参考[ MapV数据集对象说明]{@link https://github.com/huiyan-fe/mapv/blob/master/src/data/DataSet.md} */ declare class MapVLayer extends BaseLayer { constructor(options: { mapV本身?: any; id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; depthTest?: boolean; fixedHeight?: number; clampToGround?: boolean; pointerEvents?: boolean; }, dataSet: mapv.DataSet); /** * 图层对应的Canvas对象 */ readonly canvas: HTMLCanvasElement; /** * 新增mapv数据 * @param dataSet - MapV数据集,可以参考[ MapV数据集对象说明]{@link https://github.com/huiyan-fe/mapv/blob/master/src/data/DataSet.md} * @returns 无 */ addData(dataSet: mapv.DataSet): void; /** * 更新mapv数据 * @param dataSet - MapV数据集,可以参考[ MapV数据集对象说明]{@link https://github.com/huiyan-fe/mapv/blob/master/src/data/DataSet.md} * @returns 无 */ updateData(dataSet: mapv.DataSet): void; /** * 获取数据 * @returns MapV数据集,可以参考[ MapV数据集对象说明]{@link https://github.com/huiyan-fe/mapv/blob/master/src/data/DataSet.md} */ getData(): mapv.DataSet; /** * 删除指定数据 * @param data - 数据 * @returns 无 */ removeData(data: mapv.DataSet): void; /** * 删除所有数据 * @returns 无 */ removeAllData(): void; /** * 重绘图层 * @returns 无 */ draw(): void; /** * 改变图层canvas容器尺寸 * @returns 无 */ resize(): void; /** * 从地图上移除,同map.removeThing * @param destroy - 是否调用destroy释放 * @returns 无 */ remove(destroy: boolean): void; } /** * 卫星TLE和SGP4相关算法类 * @param tle1 - 卫星两行轨道数(TLE) 的tle1,每行69个字符, 示例:'1 39150U 13018A 18309.20646405 .00000034 00000-0 12253-4 0 9993' * @param tle2 - 卫星两行轨道数(TLE) 的tle2,每行69个字符, 示例:'2 39150 97.9189 29.2064 0018076 220.9170 139.0692 14.76532215297913' * @param [name] - 卫星名称 */ declare class Tle { constructor(tle1: string, tle2: string, name?: string); /** * COSPAR国际代号,国际空间研究委员会制定. */ readonly cospar: string; /** * NORAD 空间目录号,北美空防司令部制定。 * tle1的第3-7列 */ readonly norad: number; /** * 卫星类别(U表示不保密,可供公众使用的;C 表示保密,仅限NORAD使用;S表示保密的,仅限NORAD使用), * tle1的第8列 */ readonly classification: string; /** * 返回发射年份(最后两位数字),这是COSPAR id的一部分(国际指示器), * tle1的第10–11列 */ readonly intDesignatorYear: number; /** * 返回当年的发射顺序编号,这是COSPAR id的一部分(国际指示器), * tle1的第12–14列 */ readonly intDesignatorLaunchNumber: number; /** * 发射卫星个数(A表示是第一个,如果一次发射多颗卫星,使用26个英文字母排序;如果超过了26个编号,则使用两位字母,如AA、AB、AC编号),这是COSPAR id的一部分(国际指示器), * tle1的第15–17列 */ readonly intDesignatorPieceOfLaunch: string; /** * TLE历时(年份后两位), * tle1的第19–20列 */ readonly epochYear: number; /** * TLE历时 (用十进制小数表示一年中的第几日和日中的小数部分), * tle1的第21–32列 */ readonly epochDay: number; /** * 平均运动的一阶时间导数,用来计算每一天平均运动的变化带来的轨道漂移,提供给轨道计算软件预测卫星的位置。两行式轨道数据使用这个数据校准卫星的位置。 * tle1的第34–43列 */ readonly firstTimeDerivative: number; /** * 平均运动的二阶时间导数,用来计算每一天平均运动的变化带来的轨道漂移,提供给轨道计算软件预测卫星的位置。 * tle1的第45–52列 */ readonly secondTimeDerivative: number; /** * BSTAR阻力系数,用于大气阻力对卫星运动的影响。 * tle1的第45–52列 */ readonly bstarDrag: number; /** * 美国空军空间指挥中心内部使用的为1;美国空军空间指挥中心以外公开使用标识为0。 * tle1的第63列 */ readonly orbitModel: number; /** * 星历编号,TLE数据按新发现卫星的先后顺序的编号, * tle1的第65–68列 */ readonly tleSetNumber: number; /** * 校验和,指这一行的所有非数字字符,按照“字母、空格、句点、正号= 0;负号=1”的规则换算成0和1后,将这一行中原来的全部数字加起来,以10为模计算后所得的和。校验和可以检查出90%的数据存储或传送错误。按十进制加起来的个位数字的校验和,用于精确纠正误差。 * tle1的第69列 */ readonly checksum1: number; /** * 轨道的交角是指天体的轨道面和地球赤道面之间的夹度,用0~90°来表示顺行轨道(从地球北极上空看是逆时针运行);用90~180°表示逆行轨道(从地球北极上空看是顺时针运行)。 * tle2的第09–16列 */ readonly inclination: number; /** * 升交点赤经,升交点赤经是指卫星由南到北穿过地球赤道平面时,与地球赤道平面的交点。 * tle2的第18–25列 */ readonly rightAscension: number; /** * 轨道偏心率,轨道离心率是指卫星椭圆轨道的中心点到地球的球心点的距离(c)除以卫星轨道半长轴(a)得到的一个0(圆型)到1(抛物线)之间的小数值。 * tle2的第27–33列 */ readonly eccentricity: number; /** * 近地点幅角, * tle2的第35–42列 */ readonly perigee: number; /** * 平近点角, * tle2的第44–51列 */ readonly meanAnomaly: number; /** * 每天绕地球公转圈数(平均运动), * tle2的第53–63列 */ readonly meanMotion: number; /** * 卫星的运行周期(单位:分钟) */ readonly period: number; /** * 发射以来飞行的圈数, * tle2的第64–68列 */ readonly revNumberAtEpoch: number; /** * 校验和, * tle2的第69列 */ readonly checksum2: number; /** * 获取卫星指定时间所在的 ECEF坐标 * @param datetime - 指定的时间 * @returns ECEF(地心地固坐标系) 坐标 */ getEcfPosition(datetime: Date | Cesium.JulianDate | number): Cesium.Cartesian3 | undefined; /** * 获取卫星指定时间所在的 ECI惯性坐标 * @param datetime - 指定的时间 * @returns ECI(地心惯性坐标系)坐标 */ getEciPosition(datetime: Date | Cesium.JulianDate | number): Cesium.Cartesian3 | undefined; /** * 获取卫星指定时间所在的 ECI惯性坐标和地理坐标 * @param datetime - 指定的时间 * @returns ECI惯性坐标和地理坐标等信息 */ getEciPositionAndGeodetic(datetime: Date | Cesium.JulianDate | number): any | undefined; /** * 获取卫星指定时间 所在的位置坐标(经纬度) * @param datetime - 指定的时间 * @returns 卫星当前经纬度位置 */ getPoint(datetime: Date | Cesium.JulianDate | number): LatLngPoint | undefined; /** * 获取 地面地点 对卫星的 天文观测值 * @param point - 地面地点经纬度坐标 * @param datetime - 指定的时间 * @returns 观测值 */ getLookAngles(point: LatLngPoint, datetime: Date | Cesium.JulianDate | number): Tle.LookAngles; /** * 计算卫星指定时间所在的 经纬度位置 * @param tle1 - 卫星TLE的第一行 * @param tle2 - 卫星TLE的第二行 * @param datetime - 指定的时间 * @returns 卫星当前经纬度位置 */ static getPoint(tle1: string, tle2: string, datetime: Date | Cesium.JulianDate | number): LatLngPoint | undefined; /** * 获取卫星指定时间所在的 ECEF坐标 * @param tle1 - 卫星TLE的第一行 * @param tle2 - 卫星TLE的第二行 * @param datetime - 指定的时间 * @returns ECEF(地心地固坐标系) 坐标 */ static getEcfPosition(tle1: string, tle2: string, datetime: Date | Cesium.JulianDate | number): Cesium.Cartesian3 | undefined; /** * 获取 格林尼治恒星时(GMST)时间 * @param datetime - 时间对象 * @returns 格林尼治恒星时(GMST)时间 */ static gstime(datetime: Date | Cesium.JulianDate): number; /** * ECI惯性系坐标 转换为 经纬度坐标 * @param positionEci - ECI(地心惯性坐标系) 坐标 * @param datetime - 指定时间, Number时请传入格林尼治恒星时(GMST)时间 * @returns 经纬度坐标 */ static eciToGeodetic(positionEci: Cesium.Cartesian3, datetime: Date | Cesium.JulianDate | number): LatLngPoint; /** * ECI坐标 转换为 ECEF坐标 * @param positionEci - ECI(地心惯性坐标系)坐标 * @param datetime - 指定时间, Number时请传入格林尼治恒星时(GMST)时间 * @returns ECEF(地心地固坐标系) 坐标 */ static eciToEcf(positionEci: Cesium.Cartesian3, datetime: Date | Cesium.JulianDate | number): Cesium.Cartesian3; /** * ECEF坐标 转换为 ECI坐标 * @param positionEcf - ECEF(地心地固坐标系) 坐标 * @param datetime - 指定时间, Number时请传入格林尼治恒星时(GMST)时间 * @returns ECI(地心惯性坐标系)坐标 */ static ecfToEci(positionEcf: Cesium.Cartesian3, datetime: Date | Cesium.JulianDate | number): Cesium.Cartesian3; } declare namespace Tle { /** * 从地面上某点的天文观测角度等值。 * @property position - 卫星的当前位置 * @property range - 与卫星的距离,单位:米 * @property azimuth - 方位角,角度值 * @property elevation - 仰角,角度值 */ type LookAngles = { position: Cesium.Cartesian3; range: number; azimuth: number; elevation: number; }; } declare namespace CamberRadar { /** * 双曲面拱形雷达 支持的样式信息 * @property [color = "#00FF00"] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = true] - 是否边线 * @property [outlineColor = new Cesium.Color(1.0, 0.0, 0.0)] - 边线颜色 * @property startRadius - 内曲面半径 (单位:米) * @property radius - 外曲面半径 (单位:米) * @property [startFovH = Cesium.Math.toRadians(-50)] - 左横截面角度(弧度值) * @property [endFovH = Cesium.Math.toRadians(50)] - 右横截面角度(弧度值) * @property [startFovV = Cesium.Math.toRadians(5)] - 垂直起始角度(弧度值) * @property [endFovV = Cesium.Math.toRadians(85)] - 垂直结束角度(弧度值) * @property [segmentH = 60] - 垂直方向(类似经度线)分割数 * @property [segmentV = 20] - 水平方向(类似纬度线)分割数 * @property [heading = 0] - 方向角 (度数值,0-360度) * @property [pitch = 0] - 俯仰角(度数值,0-360度) * @property [roll = 0] - 翻滚角(度数值,0-360度) */ type StyleOptions = { color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; startRadius: number; radius: number; startFovH?: number; endFovH?: number; startFovV?: number; endFovV?: number; segmentH?: number; segmentV?: number; subSegmentH?: number; subSegmentV?: number; heading?: number; pitch?: number; roll?: number; }; } /** * 双曲面拱形雷达, * 【需要引入 mars3d-space 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 */ declare class CamberRadar extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: CamberRadar.StyleOptions; attr?: any; }); /** * 内曲面半径 (单位:米) */ startRadius: number; /** * 外曲面半径 (单位:米) */ radius: number; /** * 左横截面角度(弧度值) */ startFovV: number; /** * 右横截面角度(弧度值) */ endFovV: number; /** * 垂直起始角度(弧度值) */ startFovH: number; /** * 垂直结束角度(弧度值) */ endFovH: number; } declare namespace ConicSensor { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.postUpdate, function (event) { * console.log('对象更新了', event) * }) * @property preUpdate - 更新前 * @property postUpdate - 更新后 */ type EventType = { preUpdate: string; postUpdate: string; }; /** * 圆锥体(单目标雷达) 支持的样式信息 * @property [angle = 85] - 夹角,半场角度,取值范围 0.1-89.9 * @property [length = 100] - 半径长度(米) * @property [heading = 0] - 方向角 (角度值 0-360) * @property [pitch = 0] - 俯仰角(角度值 0-360) * @property [roll = 0] - 翻滚角(角度值 0-360) * @property [color = Cesium.Color.YELLOW] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否显示边线 * @property [outlineColor = color] - 边线颜色 * @property [topShow = true] - 是否显示顶 * @property [topOutlineShow = true] - 是否显示顶边线 * @property [shadowShow = false] - 是否显示地面投影 * @property [rayEllipsoid = false] - 是否求交地球计算动态length */ type StyleOptions = { angle?: number; length?: number; heading?: number; pitch?: number; roll?: number; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; topShow?: boolean; topOutlineShow?: boolean; shadowShow?: boolean; rayEllipsoid?: boolean; }; } /** * 圆锥体(单目标雷达), * 【需要引入 mars3d-space 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.lookAt] - 椎体方向追踪的目标(椎体方向跟随变化,位置不变) * @param [options.fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @param [options.revers = false] - 是否反转朝向 */ declare class ConicSensor extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: ConicSensor.StyleOptions; attr?: any; lookAt?: Cesium.Cartesian3 | Cesium.PositionProperty; fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame; revers?: boolean; }); /** * 椎体方向追踪的目标(椎体方向跟随变化,位置不变) */ lookAt: Cesium.Cartesian3 | Cesium.PositionProperty; /** * 颜色 */ color: Cesium.Color; /** * 边线颜色 */ outlineColor: Cesium.Color; /** * 是否显示边线 */ outline: boolean; /** * 是否显示顶 */ topShow: boolean; /** * 是否显示顶边线 */ topOutlineShow: boolean; /** * 夹角,半场角度,取值范围 0.1-89.9 */ angle: number; /** * 半径长度(米) */ length: number; /** * 四周方向角,0-360度角度值 */ heading: number; /** * 四周方向角,弧度值 */ readonly headingRadians: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右摆动的角度,0-360度角度值 */ roll: number; /** * 是否显示地面投影 */ shadowShow: boolean; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly matrix: Cesium.Matrix4; /** * 获取视锥体射出length半径长度后的点坐标 */ readonly rayPosition: Cesium.Cartesian3; /** * 是否反向 */ readonly reverse: boolean; /** * 是否与地球相交,当rayEllipsoid:true时才有效。 */ readonly intersectEllipsoid: boolean; /** * 获取射线向地面与地球的的大概距离 * @returns 距离值,单位:米 */ getRayEarthLength(): number; /** * 获取射线向地面与地球的4个交点坐标 * @returns 坐标数组 */ getRayEarthPositions(): Cesium.Cartesian3[]; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } declare namespace RectSensor { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.postUpdate, function (event) { * console.log('对象更新了', event) * }) * @property preUpdate - 更新前 * @property postUpdate - 更新后 */ type EventType = { preUpdate: string; postUpdate: string; }; /** * 四棱锥体 支持的样式信息 * @property [angle1 = 5] - 夹角1,半场角度,取值范围 0.1-89.9 * @property [angle2 = 5] - 夹角2,半场角度,取值范围 0.1-89.9 * @property [angle = 5] - 夹角1和夹角2相同时,可以传入angle一个属性 * @property [length = 100] - 半径长度(米) * @property [heading = 0] - 方向角 (角度值 0-360) * @property [pitch = 0] - 俯仰角(角度值 0-360) * @property [roll = 0] - 翻滚角(角度值 0-360) * @property [color = Cesium.Color.YELLOW] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否显示边线 * @property [outlineColor = color] - 边线颜色 * @property [topShow = true] - 是否显示顶 * @property [topOutlineShow = true] - 是否显示顶边线 * @property [topSteps = 8] - 顶边线数量 * @property [rayEllipsoid = false] - 是否求交地球计算动态length */ type StyleOptions = { angle1?: number; angle2?: number; angle?: number; length?: number; heading?: number; pitch?: number; roll?: number; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; topShow?: boolean; topOutlineShow?: boolean; topSteps?: number; rayEllipsoid?: boolean; }; } /** * 四棱锥体, * 【需要引入 mars3d-space 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.lookAt] - 椎体方向追踪的目标(椎体方向跟随变化,位置不变) * @param [options.fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @param [options.revers = false] - 是否反转朝向 */ declare class RectSensor extends mars3d.graphic.BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: RectSensor.StyleOptions; attr?: any; lookAt?: Cesium.Cartesian3 | Cesium.PositionProperty; fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame; revers?: boolean; }); /** * 椎体方向追踪的目标(椎体方向跟随变化,位置不变) */ lookAt: Cesium.Cartesian3 | Cesium.PositionProperty; /** * 颜色 */ color: Cesium.Color; /** * 边线颜色 */ outlineColor: Cesium.Color; /** * 是否显示边线 */ outline: boolean; /** * 是否显示顶 */ topShow: boolean; /** * 是否显示顶边线 */ topOutlineShow: boolean; /** * 夹角(angle1和angle2相同),半场角度,取值范围 0.1-89.9 */ angle: number; /** * 夹角1,半场角度,取值范围 0.1-89.9 */ angle1: number; /** * 夹角2,半场角度,取值范围 0.1-89.9 */ angle2: number; /** * 半径长度(米) */ length: number; /** * 四周方向角,0-360度角度值 */ heading: number; /** * 四周方向角,弧度值 */ readonly headingRadians: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右摆动的角度,0-360度角度值 */ roll: number; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly matrix: Cesium.Matrix4; /** * 获取视锥体射出length半径长度后的点坐标 */ readonly rayPosition: Cesium.Cartesian3; /** * 是否反向 */ readonly reverse: boolean; /** * 是否与地球相交,当rayEllipsoid:true时才有效。 */ readonly intersectEllipsoid: boolean; /** * 获取射线向地面与地球的的大概距离 * @returns 距离值,单位:米 */ getRayEarthLength(): number; /** * 获取射线向地面与地球的4个交点坐标 * @returns 坐标数组 */ getRayEarthPositions(): Cesium.Cartesian3[]; } declare namespace Satellite { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * graphic.on(mars3d.EventType.change, function (event) { * console.log('卫星位置发送了变化', event) * }) * @property change - 卫星位置变化了 */ type EventType = { change: string; }; } /** * 卫星综合体 对象类【统一管理卫星模型、轨道、视锥体】, * 【需要引入 mars3d-space 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.tle1 - 卫星两行轨道数(TLE) 的tle1, 示例:'1 39150U 13018A 18309.20646405 .00000034 00000-0 12253-4 0 9993' * @param options.tle2 - 卫星两行轨道数(TLE) 的tle2, 示例:'2 39150 97.9189 29.2064 0018076 220.9170 139.0692 14.76532215297913' * @param [options.period] - 卫星运行周期(单位:分钟), 未传值时自动在tle2中解析 * @param options.position - 当没有tle时,自定义传入动态坐标位置(含时序的点集合) * @param [options.orientation] - 当没有tle时,自定义传入实体方向 * @param [options.model] - 设置是否显示 gltf卫星模型 和对应的样式,属性还包含: * @param [options.model.autoHeading = true] - heading是否自动为轨道的方向 * @param [options.cone] - 设置是否显示 卫星视锥体 和对应的样式 * @param [options.label] - 设置是否显示 文本 和对应的样式 * @param [options.billboard] - 设置是否显示 图标点 和对应的样式 * @param [options.point] - 设置是否显示 像素点 和对应的样式 * @param [options.path] - 设置是否显示 卫星轨迹路线 和对应的样式,属性还包含: * @param [options.path.closure = false] - 是否闭合轨道圆 * @param [options.shadingLine] - 设置是否显示 星下轨迹 和对应的样式 * @param [options.fixedFrameTransform] - 参考系 * @param [options.frameRate = 50] - 多少帧刷新1次,控制效率,如果卡顿就把该数值调大一些。 */ declare class Satellite extends BaseGraphic { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; tle1: string; tle2: string; period?: number; position: Cesium.SampledPositionProperty; orientation?: Cesium.Property; model?: { autoHeading?: boolean; }; cone?: SatelliteSensor.StyleOptions; label?: LabelEntity.StyleOptions; billboard?: BillboardEntity.StyleOptions; point?: PointEntity.StyleOptions; path?: { closure?: boolean; }; shadingLine?: BillboardEntity.StyleOptions; fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame; frameRate?: number; }); /** * 加载Entity数据的内部Cesium容器 */ readonly dataSource: Cesium.CustomDataSource; /** * 卫星TLE算法类对象 */ readonly tle: Tle; /** * 圆锥的角度或者四棱锥的第一个角度,半场角度,取值范围 0.1-89.9 */ angle1: number; /** * 四棱锥的第二个角度,半场角度,取值范围 0.1-89.9 */ angle2: number; /** * 四周方向角,0-360度角度值 */ heading: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右摆动的角度,0-360度角度值 */ roll: number; /** * 是否显示视锥体 */ coneShow: boolean; /** * 当前时间的卫星位置坐标 (笛卡尔坐标) */ position: Cesium.Cartesian3; /** * 获取当前时间转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly modelMatrix: Cesium.Matrix4; /** * 获取卫星方向 中心射线与地球相交点 */ readonly groundPosition: Cesium.Cartesian3; /** * 获取当前已计算的轨道的开始时间和结束时间,格式为{start:'2021-01-01 00:00:00',end:'2021-01-01 12:01:02'} */ readonly timeRange: any; /** * 卫星凝视的目标(卫星方向一直朝向这个目标所在位置) */ lookAt: Cesium.Cartesian3 | Cesium.PositionProperty; /** * 是否显示3个方向轴,用于对比测试 */ debugAxis: boolean; /** * 显示3个方向轴时的对应轴长度,用于对比测试 */ debugAxisLength: number; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 无 */ setOptions(options: any): void; /** * 单击轨迹连线上的点后,求该点对应的时间 * @param position - 轨迹连线上的某点 * @param [arr] - 轨迹的原始数组,默认为内部记录的轨迹 * @returns 对应的时间 */ getPointTime(position: Cesium.Cartesian3, arr?: object[]): Date; /** * 更新角度 * @param [newangle] - 新角度值 * @param [newangle.heading = 0] - 方向角 (度数值,0-360度),如 model.autoHeading 为true,传入值无效 * @param [newangle.pitch = 0] - 俯仰角(度数值,0-360度) * @param [newangle.roll = 0] - 翻滚角(度数值,0-360度) * @returns 无 */ updateOrientation(newangle?: { heading?: number; pitch?: number; roll?: number; }): void; /** * 定位到卫星当前所在位置 * @param [options = {}] - 具有以下属性的对象: * @param [options.scale = 1.5] - 视角离卫星距离的缩放比例,计算公式:视角距离 = scale*卫星当前高度 * @param options.heading - 方向角度值,绕垂直于地心的轴旋转角度, 0至360 * @param options.pitch - 俯仰角度值,绕纬度线旋转角度, 0至360 * @param options.roll - 翻滚角度值,绕经度线旋转角度, 0至360 * @param [options.duration] - 飞行持续时间(秒)。如果省略,内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 表示飞行完成后摄像机将位于的参考帧的变换矩阵。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机的飞行角度高于该值,请在飞行过程中调整俯仰角度以向下看,并将地球保持在视口中。 * @param [options.flyOverLongitude] - 地球上2点之间总是有两种方式。此选项会迫使相机选择战斗方向以在该经度上飞行。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 无 */ flyTo(options?: { scale?: number; heading: number; pitch: number; roll: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; easingFunction?: EasingFunction.Callback; }): void; /** * 对象的id标识 */ id: string | number; } declare namespace SatelliteSensor { /** * 卫星视锥综合体(圆锥或四凌锥) 支持的样式信息 * @property [sensorType = SatelliteSensor.Type.Rect] - 视锥类型 * @property [angle1 = 5] - 圆锥的角度或者四棱锥的第一个角度,半场角度,取值范围 0.1-89.9 * @property [angle2 = 5] - 四棱锥的第二个角度,半场角度,取值范围 0.1-89.9 * @property [angle = 5] - 夹角1和夹角2相同时,可以传入angle一个属性 * @property [length] - 指定的半径长度(米),默认与地球进行相交运算 * @property [heading = 0] - 方向角 (角度值 0-360) * @property [pitch = 0] - 俯仰角(角度值 0-360) * @property [roll = 0] - 翻滚角(角度值 0-360) * @property [color = Cesium.Color.YELLOW] - 颜色 * @property [opacity = 1.0] - 透明度, 取值范围:0.0-1.0 * @property [outline = false] - 是否显示边线 * @property [outlineColor = color] - 边线颜色 * @property [rayEllipsoid = false] - 是否求交地球计算 */ type StyleOptions = { sensorType?: SatelliteSensor.Type; angle1?: number; angle2?: number; angle?: number; length?: number; heading?: number; pitch?: number; roll?: number; color?: string | Cesium.Color; opacity?: number; outline?: boolean; outlineColor?: string | Cesium.Color; rayEllipsoid?: boolean; }; /** * 视锥体类型 */ enum Type { Conic, Rect } } /** * 卫星视锥综合体(圆锥或四凌锥), * 【需要引入 mars3d-space 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 支持所有Graphic通用参数 * @param options.position - 坐标位置 * @param options.style - 样式信息 * @param [options.attr] - 附件的属性信息,可以任意附加属性,导出geojson或json时会自动处理导出。 * @param [options.lookAt] - 椎体方向追踪的目标(椎体方向跟随变化,位置不变) * @param [options.trackedEntity] - 椎体跟随的卫星(椎体位置跟随变化,方向不变) * @param [options.autoHeading] - 是否自动追踪trackedEntity目标的heading方向 * @param [options.fixedFrameTransform] - 参考系 * @param [options.revers = false] - 是否反转朝向 */ declare class SatelliteSensor extends BasePointPrimitive { constructor(options: { 通用参数?: BaseGraphic.ConstructorOptions; position: LatLngPoint | Cesium.Cartesian3; style: SatelliteSensor.StyleOptions; attr?: any; lookAt?: Cesium.Cartesian3 | Cesium.PositionProperty; trackedEntity?: Cesium.Entity; autoHeading?: boolean; fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame; revers?: boolean; }); /** * 椎体类型 */ sensorType: SatelliteSensor.Type; /** * 颜色 */ color: Cesium.Color; /** * 边线颜色 */ outlineColor: Cesium.Color; /** * 夹角(angle1和angle2相同),半场角度,取值范围 0.1-89.9 */ angle: number; /** * 圆锥的角度或者四棱锥的第一个角度,半场角度,取值范围 0.1-89.9 */ angle1: number; /** * 四棱锥的第二个角度,半场角度,取值范围 0.1-89.9 */ angle2: number; /** * 四周方向角,0-360度角度值 */ heading: number; /** * 俯仰角,上下摇摆的角度,0-360度角度值 */ pitch: number; /** * 滚转角,左右摆动的角度,0-360度角度值 */ roll: number; /** * 是否显示边线 */ outline: boolean; /** * 椎体跟随的卫星(椎体位置跟随变化,方向不变) */ trackedEntity: Cesium.Entity | ModelEntity; /** * 椎体方向追踪的目标(椎体方向跟随变化,位置不变) */ lookAt: Cesium.Entity; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly matrix: Cesium.Matrix4; /** * 获取视锥体方向中心射线与地球相交点 */ readonly groundPosition: Cesium.Cartesian3; /** * 是否求交地球计算 */ rayEllipsoid: boolean; /** * 与地球相交的类型:0不想交,1完全相交,2部分相交。 * 仅当rayEllipsoid:true时才有效。 */ readonly intersectEllipsoid: number; /** * 导出成像区坐标 * @returns 成像区坐标,经、纬度坐标数组 */ getAreaCoords(): any[][]; /** * 位置坐标 (笛卡尔坐标), 赋值时可以传入LatLngPoint对象 */ position: Cesium.Cartesian3; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } /** * 超图S3M三维模型图层, * 【需要引入 mars3d-supermap 插件库】 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param options.url - supermap的S3M服务地址,示例:"url": "http://www.supermapol.com/realspace/services/3D-Olympic/rest/realspace" * @param [options.layername] - 指定图层名称,未指定时,打开iserver场景服务下所有图层 * @param [options.sceneName] - 工作空间中有多个场景,需要指定场景名称;设置为undefined,默认打开第一个 * @param [options.s3mOptions] - [S3M支持的参数]{@link http://support.supermap.com.cn:8090/webgl/docs/Documentation/S3MTilesLayer.html?classFilter=S3MTilesLayer} ,示例: {"selectEnabled":false}, * @param [options.position] - 模型新的中心点位置(移动模型) * @param options.position.alt - 获取或设置底部高程。(单位:米) * @param [options.center] - 图层自定义定位视角 * @param [options.flyTo] - 加载完成数据后是否自动飞行定位到数据所在的区域。 */ declare class S3MLayer extends BaseLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; url: string; layername?: string; sceneName?: string; s3mOptions?: any; position?: { alt: number; }; center?: any; flyTo?: boolean; }); /** * 模型对应的supermap图层组 */ readonly layer: Cesium.S3MTilesLayer[]; /** * 设置S3M图层本身支持的参数 */ s3mOptions: any; /** * 设置透明度 * @param value - 透明度 * @returns 无 */ setOpacity(value: number): void; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } /** * 超图影像瓦片服务图层, * 【需要引入 mars3d-supermap 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.transparent = true] - 设置请求的地图服务的参数是否为transparent。 * @param [options.tileFormat] - 影像图片格式,默认为png。 * @param [options.cacheKey] - 影像的三维缓存密钥。 * @param [options.transparentBackColor] - 设置影像透明色。 * @param [options.transparentBackColorTolerance] - 去黑边,设置影像透明色容限,取值范围为0.0~1.0。0.0表示完全透明,1.0表示完全不透明。 */ declare class SmImgLayer extends BaseTileLayer { constructor(options: { 通用参数?: BaseTileLayer.ConstructorOptions; transparent?: boolean; tileFormat?: string; cacheKey?: string; transparentBackColor?: string | Cesium.Color; transparentBackColorTolerance?: number; }); /** * 创建用于图层的 ImageryProvider对象 * @param options - Provider参数,同图层构造参数。 * @returns ImageryProvider类 */ static createImageryProvider(options: any): Cesium.SuperMapImageryProvider; /** * 创建瓦片图层对应的ImageryProvider对象 * @param [options = {}] - 参数对象,具体每类瓦片图层都不一样。 * @returns 创建完成的 ImageryProvider 对象 */ _createImageryProvider(options?: any): Cesium.UrlTemplateImageryProvider | any; /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; } /** * 超图MVT矢量瓦片图层, * 【需要引入 mars3d-supermap 插件库】 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.center] - 图层自定义定位视角 * @param options.url - 适用于通过SuperMap桌面软件生成mvt数据,经iServer发布为rest风格的地图服务,只需提供服务地址。 * @param options.url - 服务地址,适用于第三方发布的WMTS服务。 * @param options.layer - 图层名称,适用于第三方发布的WMTS服务。 * @param [options.canvasWidth] - 用来绘制矢量的纹理边长。默认是512,越大越精细,越小性能越高。 * @param [options.format = 'mvt'] - 适用于第三方发布的WMTS服务。 * @param [options.mapboxStyle] - 使用的mapBox风格。 * @param [options.其他] - 参考[supermap官方API]{@link http://support.supermap.com.cn:8090/webgl/docs/Documentation/Scene.html#addVectorTilesLayer} */ declare class SmMvtLayer extends BaseLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; url: string; url: string; layer: string; canvasWidth?: number; format?: string; mapboxStyle?: any; 其他?: any; }); /** * 对应的supermap图层 */ readonly layer: Cesium.VectorTilesLayer; /** * 设置透明度 * @param value - 透明度 * @returns 无 */ setOpacity(value: number): void; /** * 飞行定位至图层数据所在的视角 * @param [options = {}] - 参数对象: * @param options.radius - 点状数据时,相机距离目标点的距离(单位:米) * @param [options.scale = 1.8] - 线面数据时,缩放比例,可以控制视角比矩形略大一些,这样效果更友好。 * @param [options.duration] - 飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.complete] - 飞行完成后要执行的函数。 * @param [options.cancel] - 飞行取消时要执行的函数。 * @param [options.endTransform] - 变换矩阵表示飞行结束时相机所处的参照系。 * @param [options.maximumHeight] - 飞行高峰时的最大高度。 * @param [options.pitchAdjustHeight] - 如果相机飞得比这个值高,在飞行过程中调整俯仰以向下看,并保持地球在视口。 * @param [options.flyOverLongitude] - 地球上的两点之间总有两条路。这个选项迫使相机选择战斗方向飞过那个经度。 * @param [options.flyOverLongitudeWeight] - 仅在通过flyOverLongitude指定的lon上空飞行,只要该方式的时间不超过flyOverLongitudeWeight的短途时间。 * @param [options.convert = true] - 是否将目的地从世界坐标转换为场景坐标(仅在不使用3D时相关)。 * @param [options.easingFunction] - 控制在飞行过程中如何插值时间。 * @returns 当前对象本身,可以链式调用 */ flyTo(options?: { radius: number; scale?: number; duration?: number; complete?: Cesium.Camera.FlightCompleteCallback; cancel?: Cesium.Camera.FlightCancelledCallback; endTransform?: Matrix4; maximumHeight?: number; pitchAdjustHeight?: number; flyOverLongitude?: number; flyOverLongitudeWeight?: number; convert?: boolean; easingFunction?: Cesium.EasingFunction.Callback; }): this; } /** * 天地图 三维地名服务图层 * 【需要引入 mars3d-tdt 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url = 'https://t{s}.tianditu.gov.cn/mapservice/GetTiles'] - 天地图服务地址 * @param [options.subdomains = '01234567'] - 服务负载子域 * @param [options.key = mars3d.Token.tianditu] - 天地图服务token令牌 */ declare class TdtDmLayer extends BaseLayer { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url?: string; subdomains?: string; key?: string; }); /** * 对象添加到地图上的创建钩子方法, * 每次add时都会调用 * @returns 无 */ _addedHook(): void; /** * 对象从地图上移除的创建钩子方法, * 每次remove时都会调用 * @returns 无 */ _removedHook(): void; } /** * 天地图 地形服务 * 【需要引入 mars3d-tdt 插件库】 * @param options - 参数对象,包括以下: * @param [options.通用参数] - 包含父类支持的所有参数 * @param [options.url = 'https://t{s}.tianditu.gov.cn/DataServer'] - 天地图服务地址 * @param [options.subdomains = '01234567'] - 服务负载子域 * @param [options.key = mars3d.Token.tianditu] - 天地图服务token令牌 */ declare class TdtTerrainProvider extends Cesium.GeoTerrainProvider { constructor(options: { 通用参数?: BaseGraphicLayer.ConstructorOptions; url?: string; subdomains?: string; key?: string; }); } /** * widget基础类, * 需要继承后使用,不用手动实例化,框架内部自动实例化及相关处理。 * 【需要引入 mars3d-widget 插件库】 * @example * //使用示例 * class MyWidget extends mars3d.widget.BaseWidget { * //外部资源配置 * get resources() { * return [ * 'js/test.js', //当前同目录下 * './lib/dom2img/dom-to-image.js', //主页面相同目录下 * ] * } * //弹窗配置 * get view() { * return { * type: 'window', * url: 'view.html', * windowOptions: { width: 250 }, * } * } * //初始化[仅执行1次] * create() {} * //每个窗口创建完成后调用 * winCreateOK(opt, result) { * this.viewWindow = result * } * //打开激活 * activate() {} * //关闭释放 * disable() { * this.viewWindow = null * } * } * * //注册到widget管理器中。 * mars3d.widget.bindClass(MyWidget) * @param map - 地图对象 * @param options - 配置参数 */ declare class BaseWidget extends BaseClass { constructor(map: Map, options: widget.WidgetOptions); /** * 获取当前地图 */ readonly map: Map; /** * 获取当前配置参数 */ readonly options: widget.WidgetOptions; /** * 获取当前配置参数,别名,同options */ readonly config: widget.WidgetOptions; /** * 获取当前widget的目录路径 */ readonly path: string; /** * 是否激活状态 */ readonly isActivate: boolean; /** * 是否已创建 */ readonly isCreate: boolean; /** * 该模块依赖的外部js、css资源文件,会在实例化之前加入的页面中。 * 默认引用是当前widget所在同path目录的资源, * 相当于html主页面的资源 或 外部资源 请 以 “/” 或 “.” 或 “http” 开始的url */ readonly resources: String[]; /** * 定义关联的view弹窗或页面配置信息,目前支持3种类型, * (1)type:'window',iframe模式弹窗 ,参考_example示例, 独立的html子页面,比较自由,简单粗暴、无任何限制;可以每个页面用不同的UI和第三方插件不用考虑冲突问题;任何水平的开发人员均容易快速开发。 * (2)type:'divwindow',div元素模式弹窗 参考_example_divwin示例,可直接互相访问,这种模式弊端是易引起模块间id命名冲突,在css和html中命名时需注意。 * (3)type:'append',任意html元素 参考_example_append示例,任意div节点,比较自由。 * 为空时表示当前模块无关联的view页面, * 其中url地址规则,参考resources说明 */ readonly view: any | object[]; /** * 激活widget,同 mars3d.widget.activate方法 * @returns 无 */ activateBase(): void; /** * 构造方法完成后的钩子方法,子类继承后按需使用 * @returns 无 */ init(): void; /** * 模块初始化,仅首次初始化执行1次 * @param [endfun] - 当create内存在异步时,可以异步后调用下endfun * @returns 无 */ create(endfun?: (...params: any[]) => any): void; /** * 遍历所有view配置 * @param callback - 回调方法 * @param [index] - 当有多个view时,可以指定单个操作的view的index * @returns callback执行的返回结果 */ eachView(callback: (...params: any[]) => any, index?: number): any; /** * 更新窗口大小或位置,改变了主页面尺寸后需要调用(内部已自动调用)。 * @returns 无 */ indexResize(): void; /** * 每个view窗口或页面创建完成后调用的钩子方法 * @param opt - 对应的view配置 * @param result - 得到iframe页的窗口对象 或 view的html内容 * @returns 无 */ winCreateOK(opt: any, result: any | string): void; /** * 窗口最大化后触发后 的钩子方法 * @returns 无 */ winFull(): void; /** * 窗口最小化后触发 的钩子方法 * @returns 无 */ winMin(): void; /** * 窗口还原后触发 的钩子方法 * @returns 无 */ winRestore(): void; /** * 激活模块之前 的钩子方法 * @returns 无 */ beforeActivate(): void; /** * 激活模块【类内部实现方法】 * @returns 无 */ activate(): void; /** * 释放插件,同 mars3d.widget.disable方法 * @returns 无 */ disableBase(): void; /** * 释放模块前 * @returns 无 */ beforeDisable(): void; /** * 释放模块【类内部实现方法】 * @returns 无 */ disable(): void; /** * 还原配置为初始状态 * @returns 无 */ resetConfig(): void; /** * 设置view弹窗的显示和隐藏,基于修改css实现 * @param show - 是否显示 * @param [index] - 当有多个view时,可以指定单个操作的view的index * @returns 无 */ setViewShow(show: boolean, index?: number): void; /** * 设置view弹窗的css * @param style - css值 * @param [index] - 当有多个view时,可以指定单个操作的view的index * @returns 无 */ setViewCss(style: any, index?: number): void; /** * 读取html页面的内容 * @param url - html页面的url * @param callback - 读取完成后的回调方法 * @returns 无 */ getHtml(url: string, callback: (...params: any[]) => any): void; } /** * 事件类型 枚举(所有事件统一的入口) */ declare const enum EventType { /** * 添加对象 */ add = "add", /** * 移除对象 */ remove = "remove", /** * 添加矢量数据时[图层上监听时使用] */ addGraphic = "addGraphic", /** * 移除矢量数据时[图层上监听时使用] */ removeGraphic = "removeGraphic", /** * 添加图层[map上监听时使用] */ addLayer = "addLayer", /** * 移除图层[map上监听时使用] */ removeLayer = "removeLayer", /** * 更新了对象 */ update = "update", /** * 更新了style对象 */ updateStyle = "updateStyle", /** * 更新了attr对象 */ updateAttr = "updateAttr", /** * 显示了对象 */ show = "show", /** * 隐藏了对象 */ hide = "hide", /** * 开始 */ start = "start", /** * 变化了 */ change = "change", /** * 多个数据异步分析时,完成其中一个时的回调事件 */ endItem = "endItem", /** * 多个数据异步分析时,完成所有的回调事件 */ end = "end", /** * 完成 */ stop = "stop", /** * 完成加载,但未做任何其他处理前 */ loadBefore = "loadBefore", /** * 完成加载,执行所有内部处理后 */ load = "load", /** * 出错了 */ error = "error", /** * 完成加载配置信息 */ loadConfig = "loadConfig", /** * popup弹窗打开后 */ popupOpen = "popupOpen", /** * popup弹窗关闭 */ popupClose = "popupClose", /** * tooltip弹窗打开后 */ tooltipOpen = "tooltipOpen", /** * tooltip弹窗关闭 */ tooltipClose = "tooltipClose", /** * 左键单击 鼠标事件 */ click = "click", /** * 左键单击到矢量或模型数据时 鼠标事件 */ clickGraphic = "clickGraphic", /** * 左键单击到wms或arcgis瓦片服务的对应矢量数据时 */ clickTileGraphic = "clickTileGraphic", /** * 左键单击地图空白(未单击到矢量或模型数据)时 鼠标事件 */ clickMap = "clickMap", /** * 左键双击 鼠标事件 */ dblClick = "dblClick", /** * 左键鼠标按下 鼠标事件 */ leftDown = "leftDown", /** * 左键鼠标按下后释放 鼠标事件 */ leftUp = "leftUp", /** * 鼠标移动 鼠标事件 */ mouseMove = "mouseMove", /** * 鼠标移动(拾取目标,并延迟处理) 鼠标事件 */ mouseMoveTarget = "mouseMoveTarget", /** * 鼠标滚轮滚动 鼠标事件 */ wheel = "wheel", /** * 右键单击 鼠标事件 */ rightClick = "rightClick", /** * 右键鼠标按下 鼠标事件 */ rightDown = "rightDown", /** * 右键鼠标按下后释放 鼠标事件 */ rightUp = "rightUp", /** * 中键单击 鼠标事件 */ middleClick = "middleClick", /** * 中键鼠标按下 鼠标事件 */ middleDown = "middleDown", /** * 中键鼠标按下后释放 鼠标事件 */ middleUp = "middleUp", /** * 在触摸屏上两指缩放开始 鼠标事件 */ pinchStart = "pinchStart", /** * 在触摸屏上两指缩放结束 鼠标事件 */ pinchEnd = "pinchEnd", /** * 在触摸屏上两指移动 鼠标事件 */ pinchMove = "pinchMove", /** * 鼠标按下 [左中右3键都触发] 鼠标事件 */ mouseDown = "mouseDown", /** * 鼠标按下后释放 [左中右3键都触发] 鼠标事件 */ mouseUp = "mouseUp", /** * 鼠标移入 鼠标事件 */ mouseOver = "mouseOver", /** * 鼠标移出 鼠标事件 */ mouseOut = "mouseOut", /** * 按键按下 键盘事件 */ keydown = "keydown", /** * 按键按下后释放 键盘事件 */ keyup = "keyup", /** * 开始绘制 标绘事件 */ drawStart = "drawStart", /** * 正在移动鼠标中,绘制过程中鼠标移动了点 标绘事件 */ drawMouseMove = "drawMouseMove", /** * 绘制过程中增加了点 标绘事件 */ drawAddPoint = "drawAddPoint", /** * 绘制过程中删除了最后一个点 标绘事件 */ drawRemovePoint = "drawRemovePoint", /** * 创建完成 标绘事件 */ drawCreated = "drawCreated", /** * 开始编辑 标绘事件 */ editStart = "editStart", /** * 移动鼠标按下左键(LEFT_DOWN)标绘事件 */ editMouseDown = "editMouseDown", /** * 正在移动鼠标中,正在编辑拖拽修改点中(MOUSE_MOVE) 标绘事件 */ editMouseMove = "editMouseMove", /** * 编辑修改了点(LEFT_UP)标绘事件 */ editMovePoint = "editMovePoint", /** * 编辑删除了点 标绘事件 */ editRemovePoint = "editRemovePoint", /** * 图上编辑修改了相关style属性 标绘事件 */ editStyle = "editStyle", /** * 停止编辑 标绘事件 */ editStop = "editStop", /** * 标绘事件 */ move = "move", /** * 3dtiles模型,模型瓦片初始化完成 * 该回调只执行一次 */ initialTilesLoaded = "initialTilesLoaded", /** * 3dtiles模型,当前批次模型加载完成 * 该回调会执行多次,视角变化后重新加载一次完成后都会回调 */ allTilesLoaded = "allTilesLoaded", /** * 栅格瓦片图层,添加单个瓦片,开始加载瓦片(请求前) */ addTile = "addTile", /** * 栅格瓦片图层,添加单个瓦片 加载瓦片完成 */ addTileSuccess = "addTileSuccess", /** * 栅格瓦片图层,添加单个瓦片 加载瓦片出错了 */ addTileError = "addTileError", /** * 栅格瓦片图层,移除单个瓦片 */ removeTile = "removeTile", /** * 相机开启移动前 场景事件 */ cameraMoveStart = "cameraMoveStart", /** * 相机移动完成后 场景事件 */ cameraMoveEnd = "cameraMoveEnd", /** * 相机位置完成 场景事件 */ cameraChanged = "cameraChanged", /** * 场景更新前 场景事件 */ preUpdate = "preUpdate", /** * 场景更新后 场景事件 */ postUpdate = "postUpdate", /** * 场景渲染前 场景事件 */ preRender = "preRender", /** * 场景渲染后 场景事件 */ postRender = "postRender", /** * 场景渲染失败(需要刷新页面) */ renderError = "renderError", /** * 场景模式(2D/3D/哥伦布)变换前 场景事件 */ morphStart = "morphStart", /** * 完成场景模式(2D/3D/哥伦布)变换 场景事件 */ morphComplete = "morphComplete", /** * 时钟跳动 场景事件 */ clockTick = "clockTick" } /** * widget模块化框架,公共处理类 * 【需要引入 mars3d-widget 插件库】 */ declare module "widget" { /** * 初始化widget管理器,在构造完成map后调用一次即可。 * @example * let widgetCfg ={ * "version": "20210803", * "defaultOptions": { * "style": "dark", * "windowOptions": { * "skin": "layer-mars-dialog animation-scale-up", * "position": { * "top": 50, * "right": 10 * }, * "maxmin": false, * "resize": true * }, * "autoReset": false, * "autoDisable": true, * "disableOther": true * }, * "openAtStart": [ * { * "name": "放大缩小按钮", * "uri": "widgets/toolButton/zoom.js" * } * ], * "widgets": [ * { * "name": "模板-div弹窗", * "uri": "widgets/_example_divwin/widget.js" * }, * { * "name": "模板-append模板", * "uri": "widgets/_example_append/widget.js" * } * ] * } * mars3d.widget.init(map, widgetCfg, './') * @param map - 地图对象 * @param [widgetcfg = {}] - 全局配置(一般存放在widget.json),包括: * @param [widgetcfg.defaultOptions] - 所有widget的默认参数值,可以系统内所有widget相同配置统一在此处传入,额外的个性化的再配置到各widget中。 * @param [widgetcfg.openAtStart] - 默认自启动并不可释放的插件,其中autoDisable和openAtStart固定,设置无效。 * @param [widgetcfg.widgets] - 所有插件配置,传入后后续激活时,只用传入uri即可。 * @param [widgetcfg.version] - 加载资源时,附加的参数,主要为了清理浏览器缓存,可选值:"time"(实时时间戳)或固定的字符串值,每次发布新版本换下固定值。 * @param [widgetcfg.debugger] - 是否显示插件测试栏,true时会在地图下侧显示所有插件测试按钮,方便测试。 * @param [_basePath = ''] - widgets目录所在的主路径(统一前缀), 如果widgets目录不在主页面一起或存在路由时,可以传入自定义主目录,值为 widgets目录相对于当前html页面的相对路径。 * @returns 无 */ function init(map: Map, widgetcfg?: { defaultOptions?: widget.WidgetOptions; openAtStart?: widget.WidgetOptions[]; widgets?: widget.WidgetOptions[]; version?: string; debugger?: boolean; }, _basePath?: string): void; /** * 获取默认init时中传入配置的 windowOptions 参数 * @returns windowOptions参数默认值 */ function getDefWindowOptions(): any; /** * 激活指定 widget模块 * @example * //常用方式,直接使用uri * mars3d.widget.activate("widgets/bookmark/widget.js"); * * //使用对象,可以传入更多参数,具体参数参看配置项手册,。 * mars3d.widget.activate({ * name:"视角书签" * uri: "widgets/bookmark/widget.js", * autoDisable: true, * testdata:'测试数据1987', //传数据进widget内部,widget内部使用this.config.testdata获取到传的数据 * }); * @param item - 指widget模块的uri 或 指模块的配置参数,当有配置参数时,参数优先级是: * 【activate方法传入的配置 > init方法传入的配置(widget.json) > widget.js内部配置的】 * @param [item.map] - 当单页面简单场景没有init时,也可以传入map来使用单个widget * @param [noDisableOther = false] - 不释放其他已激活的widget * @returns 指widget模块对象 */ function activate(item: { map?: Map; }, noDisableOther?: boolean): widget.WidgetOptions; /** * 获取指定的widget配置信息 * @param uri - widget的uri 或 id * @returns widget配置信息 */ function getWidget(uri: string): widget.WidgetOptions; /** * 获取指定的widget 对应的实例化对象 * @param uri - widget的uri 或 id * @returns widget对应的实例化对象 */ function getClass(uri: string): BaseWidget; /** * 获取widget的当前激活状态 * @param uri - widget的uri 或 id * @returns 是否激活 */ function isActivate(uri: string): boolean; /** * 释放指定的widget * @param uri - widget的uri 或 id * @returns 是否成功调用了释放 */ function disable(uri: string): boolean; /** * 关闭释放所有widget * @param [nodisable] - 指定不释放的widget的uri或id 或 传true值强制释放所有widget(默认autoDisable为false的widet不会释放) * @param [group] - 指定强制释放的group名(默认autoDisable为false的widet不会释放),传入group值后会强制释放所有同group组的widget * @returns 无 */ function disableAll(nodisable?: string | boolean, group?: string): void; /** * 关闭释放同组widget * @param group - 指定强制释放的group名 * @param [nodisable] - 指定不释放的widget的uri或id * @returns 无 */ function disableGroup(group: string, nodisable?: string): void; /** * 遍历所有widget * @param method - 回调方法 * @returns 无 */ function eachWidget(method: (...params: any[]) => any): void; /** * 绑定类到当前对应js的widget中。 * @param _class - 定义的BaseWidget子类 * @returns 实例化后的对象 */ function bindClass(_class: BaseWidget): any; /** * 移除Widget测试栏(当有开启debugger时) * @returns 无 */ function removeDebugeBar(): void; /** * 获取配置的version配置参数,用于附加清除浏览器缓存 * @returns 配置的version参数 */ function getCacheVersion(): string; /** * 获取init方法传入的主目录配置参数 * @returns 主目录配置参数 */ function getBasePath(): string; /** * 销毁对象 * @returns 无 */ function destroy(): void; /** * 绑定指定类型事件监听器 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 无 */ function on(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): void; /** * 解除绑定指定类型事件监听器 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 无 */ function off(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): void; /** * 触发指定类型的事件。 * @param type - 事件类型 * @param data - 传输的数据或对象,可在事件回调方法中event对象中获取进行使用 * @param [propagate = null] - 将事件传播给父类 (用addEventParent设置) * @returns 无 */ function fire(type: EventType, data: any, propagate?: BaseClass): void; /** * 绑定一次性执行的指定类型事件监听器 * 与on类似,监听器只会被触发一次,然后被删除。 * @param types - 事件类型 * @param fn - 绑定的监听器回调方法 * @param context - 侦听器的上下文(this关键字将指向的对象)。 * @returns 无 */ function once(types: EventType | EventType[], fn: (...params: any[]) => any, context: any): void; /** * 是否有绑定指定的事件 * @param type - 事件类型 * @param [propagate = null] - 是否判断指定的父类 (用addEventParent设置的) * @returns 是否存在 */ function listens(type: EventType, propagate?: BaseClass): boolean; } /** * 风场图层,基于粒子实现, * 【需要引入 mars3d-wind 插件库】 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 图层id标识 * @param [options.pid = -1] - 图层父级的id,一般图层管理中使用 * @param [options.name = '未命名'] - 图层名称 * @param [options.show = true] - 图层是否显示 * @param [options.center] - 图层自定义定位视角 * @param [options.maxParticles = 4096] - 初始粒子总数 * @param [options.particleHeight = 100] - 粒子的高度 * @param [options.fadeOpacity = 0.996] - 消失不透明度 * @param [options.dropRate = 0.003] - 下降率 * @param [options.dropRateBump = 0.01] - 下降速度 * @param [options.speedFactor = 0.5] - 速度系数 * @param [options.lineWidth = 2.0] - 线宽度 */ declare class WindLayer extends BaseLayer { constructor(options: { id?: string | number; pid?: string | number; name?: string; show?: boolean; center?: any; maxParticles?: number; particleHeight?: number; fadeOpacity?: number; dropRate?: number; dropRateBump?: number; speedFactor?: number; lineWidth?: number; }); /** * 存放风场粒子对象的容器 */ readonly layer: Cesium.PrimitiveCollection; /** * 设置 风场数据 * @param data - 风场数据 * @returns 无 */ setData(data: any): void; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; } /** * 百度 POI查询 工具类 , * 参考文档: https://lbsyun.baidu.com/index.php?title=webapi/guide/webservice-placeapi * @param options - 参数对象,包括以下: * @param [options.key = mars3d.Token.baiduArr] - 百度KEY,实际项目中请使用自己申请的百度KEY,因为我们的key不保证长期有效。 * @param [options.city = '全国'] - 限定查询的区域,支持城市及对应百度编码(Citycode)(指定的区域的返回结果加权,可能返回其他城市高权重结果。若要对返回结果区域严格限制,请使用city_limit参数) * @param [options.headers = {}] - 将被添加到HTTP请求头。 * @param [options.proxy] - 加载资源时使用的代理。 */ declare class BaiduPOI { constructor(options: { key?: String[]; city?: string; headers?: any; proxy?: Cesium.Proxy; }); /** * 百度key数组,内部轮询使用 */ keys: String[]; /** * 轮询取单个key进行使用 */ readonly key: string; /** * 根据经纬度坐标获取地址,逆地理编码 * @param queryOptions - 查询参数 * @param [queryOptions.location = null] - 经纬度坐标 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ getAddress(queryOptions: { location?: LatLngPoint; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 搜索提示查询 * @param queryOptions - 查询参数 * @param queryOptions.text - 输入建议关键字(支持拼音) * @param [queryOptions.location = null] - 传入location参数后,返回结果将以距离进行排序 * @param [queryOptions.city = null] - 可以重新限定查询的区域,默认为类构造时传入的city * @param [queryOptions.citylimit = false] - 取值为"true",仅返回city中指定城市检索结果 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ autoTip(queryOptions: { text: string; location?: LatLngPoint; city?: string; citylimit?: boolean; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 关键字搜索 * @param queryOptions - 查询参数 * @param queryOptions.text - 检索关键字。支持多个关键字并集检索,不同关键字间以空格符号分隔,最多支持10个关键字检索。 * @param [queryOptions.types = ''] - 检索分类偏好,与text组合进行检索,多个分类以","分隔(POI分类),如果需要严格按分类检索,请通过text参数设置 * @param [queryOptions.location = null] - 圆形区域检索中心点,不支持多个点 * @param queryOptions.location.lat - 纬度 * @param queryOptions.location.lng - 经度 * @param [queryOptions.radius = null] - 圆形区域检索半径,单位为米。(增加区域内数据召回权重,如需严格限制召回数据在区域内,请搭配使用radiuslimit参数),当半径过大,超过中心点所在城市边界时,会变为城市范围检索,检索范围为中心点所在城市 * @param [queryOptions.radiuslimit = false] - 是否严格限定召回结果在设置检索半径范围内。true(是),false(否)。设置为true时会影响返回结果中total准确性及每页召回poi数量, 设置为false时可能会召回检索半径外的poi。 * @param [queryOptions.city = null] - 可以重新限定查询的区域,默认为类构造时传入的city * @param [queryOptions.citylimit = false] - 取值为"true",仅返回city中指定城市检索结果 * @param [queryOptions.page = 0] - 分页页码,默认为0, 0代表第一页,1代表第二页,以此类推。常与 count 搭配使用,仅当返回结果为poi时可以翻页。 * @param [queryOptions.count = 20] - 单次召回POI数量,最大返回20条。多关键字检索时,返回的记录数为关键字个数*count。多关键词检索时,单页返回总数=关键词数量*count * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ queryText(queryOptions: { text: string; types?: string; location?: { lat: number; lng: number; }; radius?: number; radiuslimit?: boolean; city?: string; citylimit?: boolean; page?: number; count?: number; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 周边搜索(圆形搜索) * @param queryOptions - 查询参数 * @param queryOptions.text - 检索关键字。支持多个关键字并集检索,不同关键字间以空格符号分隔,最多支持10个关键字检索。 * @param [queryOptions.types = ''] - 检索分类偏好,与text组合进行检索,多个分类以","分隔(POI分类),如果需要严格按分类检索,请通过text参数设置 * @param [queryOptions.location = null] - 圆形区域检索中心点,取值范围:0-50000。规则:大于50000按默认值,单位:米 * @param [queryOptions.radius = 3000] - 圆形区域检索半径,单位为米。(增加区域内数据召回权重,如需严格限制召回数据在区域内,请搭配使用radiuslimit参数),当半径过大,超过中心点所在城市边界时,会变为城市范围检索,检索范围为中心点所在城市 * @param [queryOptions.limit = false] - 是否严格限定召回结果在设置检索半径范围内。true(是),false(否)。设置为true时会影响返回结果中total准确性及每页召回poi数量, 设置为false时可能会召回检索半径外的poi。 * @param [queryOptions.count = 20] - 单次召回POI数量,最大返回25条。多关键字检索时,返回的记录数为关键字个数*count。多关键词检索时,单页返回总数=关键词数量*count * @param [queryOptions.page = 0] - 分页页码,默认为0, 0代表第一页,1代表第二页,以此类推。常与 count 搭配使用,仅当返回结果为poi时可以翻页。 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ queryCircle(queryOptions: { text: string; types?: string; location?: LatLngPoint; radius?: number; limit?: boolean; count?: number; page?: number; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; } /** * 高德 POI查询 工具类, * 参考文档: https://lbs.amap.com/api/webservice/guide/api/search * @param options - 参数对象,包括以下: * @param [options.key = mars3d.Token.gaodeArr] - 百度KEY,在实际项目中请使用自己申请的高德KEY,因为我们的key不保证长期有效。 * @param [options.headers = {}] - 将被添加到HTTP请求头。 * @param [options.proxy] - 加载资源时使用的代理。 */ declare class GaodePOI { constructor(options: { key?: String[]; headers?: any; proxy?: Cesium.Proxy; }); /** * 高德key数组,内部轮询使用 */ keys: String[]; /** * 轮询取单个key进行使用 */ readonly key: string; /** * 根据经纬度坐标获取地址,逆地理编码 * @param queryOptions - 查询参数 * @param [queryOptions.location = null] - 经纬度坐标 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ getAddress(queryOptions: { location?: LatLngPoint; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 高德搜索提示 * @param queryOptions - 查询参数 * @param queryOptions.text - 输入建议关键字(支持拼音) * @param [queryOptions.location = null] - 建议使用location参数,可在此location附近优先返回搜索关键词信息,在请求参数city不为空时生效 * @param [queryOptions.city = null] - 可以重新限定查询的区域,默认为类构造时传入的city * @param [queryOptions.citylimit = false] - 取值为"true",仅返回city中指定城市检索结果 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ autoTip(queryOptions: { text: string; location?: LatLngPoint; city?: string; citylimit?: boolean; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 按限定区域搜索 * @param queryOptions - 查询参数 * @param queryOptions.text - 检索关键字。支持多个关键字并集检索,不同关键字间以空格符号分隔,最多支持10个关键字检索。 * @param [queryOptions.types = ''] - 检索分类偏好,与text组合进行检索,多个分类以","分隔(POI分类),如果需要严格按分类检索,请通过text参数设置 * @param [queryOptions.graphic] - 限定的搜索区域 * @param [queryOptions.limit = false] - 取值为"true",严格返回限定区域内检索结果 * @param [queryOptions.page = 0] - 分页页码,默认为0, 0代表第一页,1代表第二页,以此类推。常与 count 搭配使用,仅当返回结果为poi时可以翻页。 * @param [queryOptions.count = 20] - 单次召回POI数量,默认为10条记录,最大返回20条。多关键字检索时,返回的记录数为关键字个数*count。多关键词检索时,单页返回总数=关键词数量*count * @param [queryOptions.error] - 查询失败的回调方法 * @param [queryOptions.success] - 查询完成的回调方法 * @returns 当前对象本身,可以链式调用 */ query(queryOptions: { text: string; types?: string; graphic?: BaseGraphic; limit?: boolean; page?: number; count?: number; error?: (...params: any[]) => any; success?: (...params: any[]) => any; }): this; /** * 关键字搜索 * @param queryOptions - 查询参数 * @param queryOptions.text - 检索关键字。支持多个关键字并集检索,不同关键字间以空格符号分隔,最多支持10个关键字检索。 * @param [queryOptions.types = ''] - 检索分类偏好,与text组合进行检索,多个分类以","分隔(POI分类),如果需要严格按分类检索,请通过text参数设置 * @param [queryOptions.city = null] - 可以重新限定查询的区域,默认为类构造时传入的city * @param [queryOptions.citylimit = false] - 取值为"true",仅返回city中指定城市检索结果 * @param [queryOptions.count = 20] - 单次召回POI数量,最大返回25条。多关键字检索时,返回的记录数为关键字个数*count。多关键词检索时,单页返回总数=关键词数量*count * @param [queryOptions.page = 0] - 分页页码,默认为0, 0代表第一页,1代表第二页,以此类推。常与 count 搭配使用,仅当返回结果为poi时可以翻页。 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ queryText(queryOptions: { text: string; types?: string; city?: string; citylimit?: boolean; count?: number; page?: number; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 周边搜索(圆形搜索) * @param queryOptions - 查询参数 * @param queryOptions.text - 检索关键字。支持多个关键字并集检索,不同关键字间以空格符号分隔,最多支持10个关键字检索。 * @param [queryOptions.types = ''] - 检索分类偏好,与text组合进行检索,多个分类以","分隔(POI分类),如果需要严格按分类检索,请通过text参数设置 * @param [queryOptions.location = null] - 圆形区域检索中心点,取值范围:0-50000。规则:大于50000按默认值,单位:米 * @param [queryOptions.radius = 3000] - 圆形区域检索半径,单位为米。(增加区域内数据召回权重,如需严格限制召回数据在区域内,请搭配使用radiuslimit参数),当半径过大,超过中心点所在城市边界时,会变为城市范围检索,检索范围为中心点所在城市 * @param [queryOptions.limit = false] - 是否严格限定召回结果在设置检索半径范围内。true(是),false(否)。设置为true时会影响返回结果中total准确性及每页召回poi数量, 设置为false时可能会召回检索半径外的poi。 * @param [queryOptions.count = 20] - 单次召回POI数量,最大返回25条。多关键字检索时,返回的记录数为关键字个数*count。多关键词检索时,单页返回总数=关键词数量*count * @param [queryOptions.page = 0] - 分页页码,默认为0, 0代表第一页,1代表第二页,以此类推。常与 count 搭配使用,仅当返回结果为poi时可以翻页。 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ queryCircle(queryOptions: { text: string; types?: string; location?: LatLngPoint; radius?: number; limit?: boolean; count?: number; page?: number; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 多边形搜索 * @param queryOptions - 查询参数 * @param queryOptions.text - 检索关键字。支持多个关键字并集检索,不同关键字间以空格符号分隔,最多支持10个关键字检索。 * @param [queryOptions.types = ''] - 检索分类偏好,与text组合进行检索,多个分类以","分隔(POI分类),如果需要严格按分类检索,请通过text参数设置 * @param queryOptions.polygon - 经纬度数组,经纬度小数点后不得超过6位。多边形为矩形时,可传入左上右下两顶点坐标对;其他情况下首尾坐标对需相同。 * @param [queryOptions.limit = false] - 是否严格限定召回结果在设置检索的多边形或矩形范围内。true(是),false(否)。设置为true时会影响返回结果中total准确性及每页召回poi数量, 设置为false时可能会召回检索半径外的poi。 * @param [queryOptions.count = 20] - 单次召回POI数量,最大返回25条。多关键字检索时,返回的记录数为关键字个数*count。多关键词检索时,单页返回总数=关键词数量*count * @param [queryOptions.page = 0] - 分页页码,默认为0, 0代表第一页,1代表第二页,以此类推。常与 count 搭配使用,仅当返回结果为poi时可以翻页。 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ queryPolygon(queryOptions: { text: string; types?: string; polygon: any[][]; limit?: boolean; count?: number; page?: number; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; } /** * 高德 路径规划 工具类, * 参考文档:https://lbs.amap.com/api/webservice/guide/api/direction * @param options - 参数对象,包括以下: * @param [options.key = mars3d.Token.gaodeArr] - 百度KEY,在实际项目中请使用自己申请的高德KEY,因为我们的key不保证长期有效。 * @param [options.headers = {}] - 将被添加到HTTP请求头。 * @param [options.proxy] - 加载资源时使用的代理。 */ declare class GaodeRoute { constructor(options: { key?: String[]; headers?: any; proxy?: Cesium.Proxy; }); /** * 高德key数组,内部轮询使用 */ keys: String[]; /** * 轮询取单个key进行使用 */ readonly key: string; /** * 按指定类别自动查询 * @param queryOptions - 查询参数 * @param queryOptions.type - 类型 * @param queryOptions.points - 按起点、终点 顺序的坐标数组,如[[117.500244, 40.417801],[117.500244, 40.417801]] * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ query(queryOptions: { type: GaodeRoute.RouteType; points: any[][]; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 按指定类别自动查询(多个路线数组,递归处理) * @param queryOptions - 查询参数 * @param queryOptions.type - 类型 * @param queryOptions.points - 多条,按起点终点 顺序的坐标数组,如[ * [ [117.500244, 40.417801],[117.500244, 40.417801] ], * [ [117.500244, 40.417801],[117.500244, 40.417801] ] * ] * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 无 */ queryArr(queryOptions: { type: GaodeRoute.RouteType; points: any[][]; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): void; /** * 计算结果中的最短距离的导航路径 * @param data - queryArr返回的结果数组 * @returns 返回路线数据和index顺序 */ getShortestPath(data: object[]): any; /** * 步行路径规划 (单个查询) * @param queryOptions - 查询参数 * @param queryOptions.points - 按起点、终点 顺序的坐标数组,如[[117.500244, 40.417801],[117.500244, 40.417801]] * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 无 */ queryWalking(queryOptions: { points: any[][]; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): void; /** * 骑行路径查询 (单个查询) * @param queryOptions - 查询参数 * @param queryOptions.points - 按起点、终点 顺序的坐标数组,如[[117.500244, 40.417801],[117.500244, 40.417801]] * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 无 */ queryBicycling(queryOptions: { points: any[][]; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): void; /** * 驾车路径规划查询 * @param queryOptions - 查询参数 * @param queryOptions.points - 按起点、途经点、终点 顺序的坐标数组,如[[117.500244, 40.417801],[117.500244, 40.417801]] * @param queryOptions.avoidpolygons - 区域避让数组(支持多个),支持32个避让区域,每个区域最多可有16个顶点。避让区域不能超过81平方公里,否则避让区域会失效。 * @param [queryOptions.extensions = 'base'] - 返回结果控制,可选值:core/all base:返回基本信息;all:返回全部信息 * @param [queryOptions.strategy = 0] - 驾车选择策略,参考高德官网说明,默认为0:速度优先,不考虑当时路况,此路线不一定距离最短 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 无 */ queryDriving(queryOptions: { points: any[][]; avoidpolygons: any[][]; extensions?: string; strategy?: string; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): void; } declare namespace GaodeRoute { /** * 路径规划方式 */ enum RouteType { Walking, Bicycling, Driving } } declare namespace QueryArcServer { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * layer.on(mars3d.EventType.load, function (event) { * console.log('矢量数据对象加载完成', event) * }) * @property click - 左键单击 鼠标事件 * @property load - 完成加载,执行所有内部处理后 */ type EventType = { click: string; load: string; }; } /** * ArcGIS WFS矢量服务查询类 * @param options - 参数对象,包括以下: * @param options.url - ArcGIS服务地址, 示例:'http://server.mars3d.cn/arcgis/rest/services/mars/hefei/MapServer/37', * * @param [options.pageSize = 10] - 每页条数 * * @param [options.headers = {}] - 将被添加到HTTP请求头。 * @param [options.proxy] - 加载资源时使用的代理。 * @param [options.图层参数] - layer属性获取的图层对应的构造参数,参考{@link GeoJsonLayer} */ declare class QueryArcServer extends BaseClass { constructor(options: { url: string; pageSize?: number; headers?: any; proxy?: Cesium.Proxy; 图层参数?: any; }); /** * ArcGIS服务地址 */ url: string; /** * 分页的 每页条数 */ pageSize: number; /** * 总记录数 */ readonly allCount: number; /** * 总页数 */ readonly allPage: number; /** * 页码,当前第几页 */ readonly pageIndex: number; /** * 用于显示查询结果的GeoJsonLayer图层,图层参数在当前类构造方法中传入 */ readonly layer: GeoJsonLayer; /** * 首页,查看第1页数据 * @returns 无 */ showFirstPage(): void; /** * 上一页 * @returns 无 */ showPretPage(): void; /** * 下一页 * @returns 无 */ showNextPage(): void; /** * 跳转到指定页 * @param pageIndex - 指定页 * @returns 无 */ showPage(pageIndex: number): void; /** * 按指定类别自动查询 * @param queryOptions - 查询参数 * @param [queryOptions.text] - 检索关键字。 * @param [queryOptions.column] - 检索关键字的字段名称。 * @param [queryOptions.like = true] - 检索关键字时,是否模糊匹配,false时精确查询。 * @param [queryOptions.where] - 自定义的检索条件,与text二选一 * @param [queryOptions.graphic] - 限定的搜索区域 * @param [queryOptions.page = true] - 是否分页查询,false时不分页,一次性查询返回 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ query(queryOptions: { text?: string; column?: string; like?: boolean; where?: string; graphic?: BaseGraphic; page?: boolean; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 清除 * @returns 无 */ clear(): void; } /** * GeoServer WFS服务查询类 * @param options - 参数对象,包括以下: * @param options.layer - 图层名称(命名空间:图层名称),多个图层名称用逗号隔开 * @param [options.headers = {}] - 将被添加到HTTP请求头。 * @param [options.proxy] - 加载资源时使用的代理。 * @param [options.图层参数] - layer属性获取的图层对应的构造参数,参考{@link GeoJsonLayer} */ declare class QueryGeoServer extends BaseClass { constructor(options: { layer: string; headers?: any; proxy?: Cesium.Proxy; 图层参数?: any; }); /** * 用于显示查询结果的GeoJsonLayer图层,图层参数在当前类构造方法中传入 */ readonly layer: GeoJsonLayer; /** * 按指定类别自动查询 * @param queryOptions - 查询参数 * @param [queryOptions.text] - 检索关键字。 * @param [queryOptions.column] - 检索关键字的属性名称(PropertyName)。 * @param [queryOptions.like = true] - 检索关键字时,是否模糊匹配,false时精确查询。 * @param [queryOptions.graphic] - 限定的搜索区域 * @param [queryOptions.geoColumn = 'the_geom'] - 搜索区域的属性名称(PropertyName)。 * @param [queryOptions.maxFeatures = 1000] - 最多返回结果个数 * @param [queryOptions.success] - 查询完成的回调方法 * @param [queryOptions.error] - 查询失败的回调方法 * @returns 当前对象本身,可以链式调用 */ query(queryOptions: { text?: string; column?: string; like?: boolean; graphic?: BaseGraphic; geoColumn?: string; maxFeatures?: number; success?: (...params: any[]) => any; error?: (...params: any[]) => any; }): this; /** * 清除 * @returns 无 */ clear(): void; } declare namespace Measure { /** * @example * //绑定监听事件 * thing.on(mars3d.EventType.change, function (event) { * console.log('发送了变化', event) * }) * @property remove - 移除对象 * @property change - 测量值变化了 * @property start - 异步测量中,开始测量 * @property end - 异步测量中,完成了测量后 * @property 其他 - 支持的父类的事件类型 */ type EventType = { remove: string; change: string; start: string; end: string; 其他: GraphicLayer.EventType; }; } /** * 图上量算 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.hasEdit = false] - 是否可编辑 * @param [options.isAutoEditing = true] - 完成测量时是否自动启动编辑(需要hasEdit:true时) * @param [options.isContinued = false] - 是否连续测量 * @param [options.label] - 测量结果文本的样式 * @param [options.polygon] - 体积测量时,面的样式 * @param [options.polygonJzmStyle] - 体积测量时,基准面的样式 * @param [options.heightLabel = true] - 体积测量时,是否显示各边界点高度值文本 * @param [options.labelHeight] - 体积测量时,各边界点高度结果文本的样式 * @param [options.offsetLabel = false] - 体积测量时,是否显示各边界点高度差文本 */ declare class Measure extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; hasEdit?: boolean; isAutoEditing?: boolean; isContinued?: boolean; label?: LabelEntity.StyleOptions; polygon?: PolygonEntity.StyleOptions; polygonJzmStyle?: PolygonEntity.StyleOptions; heightLabel?: boolean; labelHeight?: LabelEntity.StyleOptions; offsetLabel?: boolean; }); /** * 对应的矢量图层 */ readonly graphicLayer: GraphicLayer; /** * 图层内的Graphic集合对象 */ readonly graphics: BaseGraphic[]; /** * 测量 空间长度 * @param opts - 控制参数 * @param [opts.style] - 路线的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatDistance}可选值:auto、m、km、mile、zhang 。auto时根据距离值自动选用k或km * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.showAddText = true] - 是否显示每一段的增加部分距离,如(+10.1km) * @returns 长度测量控制类 对象 */ distance(opts: { style?: PolylineEntity.StyleOptions; unit?: string; }): MeasureDistance; /** * 测量 贴地长度 * @param opts - 控制参数 * @param [opts.style] - 路线的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatDistance}可选值:auto、m、km、mile、zhang 。auto时根据距离值自动选用k或km * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.showAddText = true] - 是否显示每一段的增加部分距离,如(+10.1km) * @param [options.splitNum = 100] - 插值数,将线段分割的个数 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @returns 贴地长度测量控制类 对象 */ distanceSurface(opts: { style?: PolylineEntity.StyleOptions; unit?: string; }): MeasureDistanceSurface; /** * 剖面分析,测量线插值点的高程数据 * @param opts - 控制参数 * @param [opts.style] - 路线的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatDistance}可选值:auto、m、km、mile、zhang 。auto时根据距离值自动选用k或km * @param [options.maxPointNum = 9999] - 绘制时,最多允许点的个数 * @param [options.addHeight = 0] - 在draw绘制时,在绘制点的基础上增加的高度值 * @param [options.splitNum = 200] - 插值数,将线段分割的个数 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @returns 剖面分析控制类 对象 */ section(opts: { style?: PolylineEntity.StyleOptions; unit?: string; }): MeasureDistanceSection; /** * 面积测量(水平面) * @param opts - 控制参数 * @param [opts.style] - 面的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatArea}可选值:auto、m、km、mu、ha 。auto时根据面积值自动选用k或km * @returns 面积测量控制类 对象 */ area(opts: { style?: PolygonEntity.StyleOptions; unit?: string; }): MeasureArea; /** * 贴地面积测量 * @param opts - 控制参数 * @param [opts.style] - 面的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatArea}可选值:auto、m、km、mu、ha 。auto时根据面积值自动选用k或km * @param [options.splitNum = 10] - 插值数,将面分割的网格数 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @returns 面积测量控制类 对象 */ areaSurface(opts: { style?: PolygonEntity.StyleOptions; unit?: string; }): MeasureArea; /** * 体积测量(方量分析) * @param opts - 控制参数 * @param [opts.style] - 路线的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatArea}可选值:auto、m、km、mu、ha 。auto时根据面积值自动选用k或km * @param [options.splitNum = 10] - 插值数,将面分割的网格数 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.minHeight] - 可以指定最低高度(单位:米) * @param [options.maxHeight] - 可以指定最高高度(单位:米) * @param [options.height] - 可以指定基准面高度(单位:米),默认是绘制后的最低高度值 * @returns 体积测量控制类 对象 */ volume(opts: { style?: PolygonEntity.StyleOptions; unit?: string; }): MeasureVolume; /** * 高度测量 * @param opts - 控制参数 * @param [opts.style] - 路线的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatDistance}可选值:auto、m、km、mile、zhang 。auto时根据距离值自动选用k或km * @returns 高度测量控制类 对象 */ height(opts: { style?: PolylineEntity.StyleOptions; unit?: string; }): MeasureHeight; /** * 三角高度测量, * 包括水平距离、空间距离、高度差。 * @param opts - 控制参数 * @param [opts.style] - 路线的样式 * @param [opts.unit = 'auto'] - 计量单位,{@link MeasureUtil#formatDistance}可选值:auto、m、km、mile、zhang 。auto时根据距离值自动选用k或km * @returns 三角高度测量控制类 对象 */ heightTriangle(opts: { style?: PolylineEntity.StyleOptions; unit?: string; }): MeasureHeightTriangle; /** * 角度测量 * @param opts - 控制参数 * @param [opts.style] - 路线的样式,默认为箭头线 * @returns 角度测量控制类 对象 */ angle(opts: { style?: PolylineEntity.StyleOptions; }): MeasureAngle; /** * 坐标测量 * @param opts - 控制参数 * @param [opts.style] - 点的样式 * @returns 坐标测量控制类 对象 */ point(opts: { style?: PointEntity.StyleOptions; }): MeasurePoint; /** * 取消并停止绘制,如有未完成的绘制会自动删除 * @returns 当前对象本身,可以链式调用 */ stopDraw(): this; /** * 完成绘制和编辑,如有未完成的绘制会自动完成。 * 在移动端需要调用此方法来类似PC端双击结束。 * @returns 无 */ endDraw(): void; /** * 清除测量 * @returns 无 */ clear(): void; /** * 更新量测结果的单位 * @param unit - 计量单位,{@link MeasureUtil#formatDistance}{@link MeasureUtil#formatArea} 可选值:auto、m、km、mile、zhang 等。auto时根据距离值自动选用k或km * @returns 无 */ updateUnit(unit: string): void; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } declare namespace Shadows { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.change, function (event) { * console.log('时间发送了变化', event) * }) * @property change - 变化了 */ type EventType = { change: string; }; } /** * 日照分析 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 */ declare class Shadows extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; }); /** * 设置时间 */ time: Date; /** * 是否在播放 */ readonly isStart: boolean; /** * 倍速,控制速率 */ multiplier: number; /** * 开始播放日照分析效果 * @param startDate - 开始时间 * @param endDate - 结束时间 * @param [currentTime = startDate] - 当前所在时间 * @returns 无 */ start(startDate: Date, endDate: Date, currentTime?: Date): void; /** * 暂停 * @returns 无 */ pause(): void; /** * 继续 * @returns 无 */ proceed(): void; /** * 停止 * @returns 无 */ stop(): void; /** * 清除分析 * @returns 无 */ clear(): void; } declare namespace Sightline { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.end, function (event) { * console.log('分析完成', event) * }) * @property start - 开始分析 * @property end - 完成分析 */ type EventType = { start: string; end: string; }; } /** * 通视分析 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.visibleColor = new Cesium.Color(0, 1, 0, 1)] - 可视区域颜色 * @param [options.hiddenColor = new Cesium.Color(1, 0, 0, 1)] - 不可视区域颜色 * @param [options.depthFailColor] - 当线位于地形或被遮挡时的区域颜色 */ declare class Sightline extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; visibleColor?: Cesium.Color; hiddenColor?: Cesium.Color; depthFailColor?: Cesium.Color; }); /** * 可视区域颜色 */ visibleColor: Cesium.Color; /** * 不可视区域颜色 */ hiddenColor: Cesium.Color; /** * 当线位于地形或被遮挡时的区域颜色 */ depthFailColor: Cesium.Color; /** * 添加通视分析 * @param origin - 起点(视点位置) * @param target - 终点(目标点位置) * @param [options = {}] - 控制参数,包括: * @param [options.offsetHeight = 0] - 在起点增加的高度值,比如加上人的身高 * @returns 分析结果 */ add(origin: Cesium.Cartesian3, target: Cesium.Cartesian3, options?: { offsetHeight?: number; }): any; /** * 添加通视分析,插值异步分析 * @param origin - 起点 * @param target - 终点(目标点) * @param [options = {}] - 控制参数,包括: * @param [options.offsetHeight = 0] - 在起点增加的高度值,比如加上人的身高 * @param [options.splitNum = 50] - 插值数,等比分割的个数 * @param [options.minDistance] - 插值时的最小间隔(单位:米),优先级高于splitNum * @returns 无, 分析结果在end事件中返回 */ addAsync(origin: Cesium.Cartesian3, target: Cesium.Cartesian3, options?: { offsetHeight?: number; splitNum?: number; minDistance?: number; }): void; /** * 清除分析 * @returns 无 */ clear(): void; } /** * 天际线 描边 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.color = new Cesium.Color(1.0, 0.0, 0.0)] - 边际线颜色 * @param [options.width = 2] - 天际线宽度 */ declare class Skyline extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; color?: Cesium.Color; width?: number; }); /** * 边际线颜色 */ color: Cesium.Color; /** * 天际线宽度 */ width: number; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } /** * 地下模式类 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.alpha = 0.5] - 透明度 0.0-1.0 * @param [options.color = Cesium.Color.BLAC] - 当相机在地下或球体是半透明时,渲染球体背面的颜色 */ declare class Underground extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; alpha?: number; color?: Color; }); /** * 控制球体透明度的Cesium内部对象 */ readonly translucency: Cesium.GlobeTranslucency; /** * 透明度 */ alpha: number; /** * 当相机在地下或球体是半透明时,渲染球体背面的颜色,将根据相机的距离与地球颜色混合。 * 禁用地下着色时,可以设置为undefined。 */ color: Cesium.Color; /** * 获取或设置将color与Globe颜色混合的远近距离。 * alpha将插值在{@link Cesium.NearFarScalar#nearValue}和{@linkCesium.NearFarScalar#farValue}之间, * 同时摄像机距离在指定的{@link Cesium.NearFarScalar#near}和{@link Cesium.NearFarScalar#far}的上下边界内。 * 在这些范围之外,alpha仍然被限制在最近的范围内。如果未定义,地下颜色将不会与地球颜色混合。 * 当相机在椭球上方时,距离计算从椭球上最近的点而不是相机的位置。 */ colorAlphaByDistance: Cesium.NearFarScalar; } declare namespace ViewShed3D { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.end, function (event) { * console.log('分析完成', event) * }) * @property drawStart - 开始绘制 * @property drawAddPoint - 绘制过程中增加了点 * @property drawMouseMove - 正在移动鼠标中,绘制过程中鼠标移动了点 * @property drawCreated - 完成绘制 * @property end - 完成分析 */ type EventType = { drawStart: string; drawAddPoint: string; drawMouseMove: string; drawCreated: string; end: string; }; } /** * 可视域分析 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.position] - 视点位置,未传入值时自动激活鼠标绘制 * @param [options.cameraPosition] - 相机位置 * @param [options.horizontalAngle = 120] - 水平张角(度数),取值范围 0-120 * @param [options.verticalAngle = 90] - 垂直张角(度数),取值范围 0-90 * @param [options.visibleAreaColor = new Cesium.Color(0, 1, 0, 1)] - 可视区域颜色 * @param [options.hiddenAreaColor = new Cesium.Color(1, 0, 0, 1)] - 不可视区域颜色 * @param [options.alpha = 0.5] - 混合系数 0.0-1.0 * @param [options.offsetHeight = 1.5] - 在起点增加的高度值,比如加上人的身高 * @param [options.showFrustum = true] - 是否显示视椎体框线 */ declare class ViewShed3D extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; position?: LatLngPoint | Cesium.Cartesian3; cameraPosition?: LatLngPoint | Cesium.Cartesian3; horizontalAngle?: number; verticalAngle?: number; visibleAreaColor?: Cesium.Color; hiddenAreaColor?: Cesium.Color; alpha?: number; offsetHeight?: number; showFrustum?: boolean; }); /** * 水平张角(度数),取值范围 0-120 */ horizontalAngle: number; /** * 垂直张角(度数),取值范围 0-90 */ verticalAngle: number; /** * 可视距离(单位:米) */ distance: number; /** * 可视区域颜色 */ visibleAreaColor: Cesium.Color; /** * 不可视区域颜色 */ hiddenAreaColor: Cesium.Color; /** * 混合系数 0-1 */ alpha: number; /** * 是否显示视椎体框线 */ showFrustum: boolean; /** * 相机位置(笛卡尔坐标) */ readonly cameraPosition: Cesium.Cartesian3; /** * 相机位置 */ cameraPoint: LatLngPoint; /** * 视点位置 (笛卡尔坐标) */ readonly position: Cesium.Cartesian3; /** * 视点位置 */ readonly point: LatLngPoint; } declare namespace CameraHistory { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.change, function (event) { * console.log('记录发送了变化', event) * }) * @property change - 变化了 */ type EventType = { change: string; }; } /** * 相机视角记录及处理类,含 上一视图 下一视图 等 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.maxCacheCount = 99] - 保留的历史记录最多个数 * @param [options.limit] - 限定视角范围参数,包括以下: * @param options.limit.position - 中心点坐标 * @param options.limit.radius - 半径(单位:米) * @param [options.limit.debugExtent] - 是否显示限定范围的边界 */ declare class CameraHistory extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; maxCacheCount?: number; limit?: { position: Cesium.Cartesian3; radius: number; debugExtent?: boolean; }; }); /** * 是否显示限定范围的边界 */ debugExtent: boolean; /** * 切换到 下一视角 * @returns 是否成功切换 */ goNext(): boolean; /** * 切换到 上一视角 * @returns 是否成功切换 */ goLast(): boolean; /** * 回到当前视角(记录的最后一个视角) * @returns 是否成功切换 */ goNow(): boolean; /** * 回到记录的第一个视角 * @returns 是否成功切换 */ goFirst(): boolean; } /** * 第一人称贴地漫游, * 键盘漫游时,先单击地图激活后 按 W前进、 S后退、A左移、D右移 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.speed = 1.5] - 速度 * @param [options.rotateSpeed = -5] - 旋转速度 * @param [options.height = 10] - 高度 * @param [options.maxPitch = 88] - 最大pitch角度(度数值) */ declare class FirstPersonRoam extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; speed?: number; rotateSpeed?: number; height?: number; maxPitch?: number; }); /** * 速度 */ speed: number; /** * 旋转速度 */ rotateSpeed: number; /** * 高度(单位:米) */ height: number; /** * 最大pitch角度(度数值) */ maxPitch: number; /** * 开始自动前进漫游 * @returns 无 */ startAutoForward(): void; /** * 停止自动前进漫游 * @returns 无 */ stopAutoForward(): void; } declare namespace RotateOut { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.stop, function (event) { * console.log('停止了旋转', event) * }) * @property start - 开始旋转 * @property change - 变化了角度 * @property stop - 停止了旋转 */ type EventType = { start: string; change: string; stop: string; }; } /** * 相机位置不动,对外四周旋转 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.direction = false] - 旋转方向, true逆时针,false顺时针 * @param [options.time = 60] - 飞行一周所需时间(单位 秒),控制速度 * @param [options.autoStopAngle] - 自动停止的角度值(0-360度),未设置时不自动停止 */ declare class RotateOut extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; direction?: boolean; time?: number; autoStopAngle?: number; }); /** * 是否在旋转中 */ readonly isStart: boolean; /** * 开始旋转 * @returns 无 */ start(): void; /** * 停止旋转 * @returns 无 */ stop(): void; } declare namespace RotatePoint { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.stop, function (event) { * console.log('停止了旋转', event) * }) * @property start - 开始旋转 * @property change - 变化了角度 * @property stop - 停止了旋转 */ type EventType = { start: string; change: string; stop: string; }; } /** * 相机绕 固定中心点 旋转 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.direction = false] - 旋转方向, true逆时针,false顺时针 * @param [options.time = 60] - 飞行一周所需时间(单位 秒),控制速度 * @param [options.autoStopAngle] - 自动停止的角度值(0-360度),未设置时不自动停止 * @param [options.distance] - 可以指定旋转时相机到中心点的距离,默认不改变相对距离。 */ declare class RotatePoint extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; direction?: boolean; time?: number; autoStopAngle?: number; distance?: number; }); /** * 是否在旋转中 */ readonly isStart: boolean; /** * 开始旋转 * @param point - 旋转的中心点 * @returns 无 */ start(point: LatLngPoint | Cesium.Cartesian3): void; /** * 停止旋转 * @returns 无 */ stop(): void; } /** * 街景视角模式控制, * 1、右键拖拽,以相机视角为中心进行旋转; * 2、中键拖拽,可以升高或降低相机高度; * 3、左键双击,飞行定位到该点; * 4、右键双击,围绕该点旋转。 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.rotateSpeed = 30] - 右键拖拽时,旋转速度,正负控制方向。 * @param [options.heightStep = 0.2] - 中键拖拽时,高度移动比例,控制升高或降低相机高度的速度 * @param [options.moveStep = 0.1] - 双击定位到点时,距离目标点的距离的移动比例 0.0-1.0 * @param [options.moveDuration] - 双击定位到点时,飞行时间(单位:秒)。如果省略,SDK内部会根据飞行距离计算出理想的飞行时间。 * @param [options.rotatePoint] - 右键双击,围绕该点旋转时的参考,具体同{@link RotatePoint}类的构造参数。 */ declare class StreetView extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; rotateSpeed?: number; heightStep?: number; moveStep?: number; moveDuration?: number; rotatePoint?: any; }); /** * 右键拖拽时,旋转速度,正负控制方向。 */ rotateSpeed: number; /** * 中键拖拽时,高度移动比例,控制升高或降低相机高度的速度 */ heightStep: number; /** * 双击定位到点时,距离目标点的距离的移动比例 0.0-1.0 */ moveStep: number; } /** * 等高线 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.positions] - 坐标位置数组,只显示单个区域【单个区域场景时使用】 * @param [options.contourShow = true] - 是否显示等高线 * @param [options.spacing = 100.0] - 等高线 间隔(单位:米) * @param [options.width = 1.5] - 等高线 线宽(单位:像素) * @param [options.color = Cesium.Color.RED] - 等高线 颜色 * @param [options.shadingType = 'none'] - 地表渲染效果,可选值: 无nono, 高程 elevation, 坡度slope, 坡向aspect * @param [options.colorScheme] - 地表渲染配色方案,默认值为: * { * elevation: { * step: [0.0, 0.045, 0.1, 0.15, 0.37, 0.54, 1.0], * color: ['#000000', '#2747E0', '#D33B7D', '#D33038', '#FF9742', '#FF9742', '#ffd700'], * }, * slope: { * step: [0.0, 0.29, 0.5, Math.sqrt(2) / 2, 0.87, 0.91, 1.0], * color: ['#000000', '#2747E0', '#D33B7D', '#D33038', '#FF9742', '#FF9742', '#ffd700'], * }, * aspect: { * step: [0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 1.0], * color: ['#000000', '#2747E0', '#D33B7D', '#D33038', '#FF9742', '#FF9742', '#ffd700'], * }, * } * @param [options.showElseArea = true] - 是否显示区域外的地图 * @param [options.minHeight = -414.0] - 地表渲染配色方案中的 最低海拔高度 * @param [options.maxHeight = 8777] - 地表渲染配色方案中的 最高海拔高度 */ declare class ContourLine extends TerrainEditBase { constructor(options: { id?: string | number; enabled?: boolean; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; contourShow?: boolean; spacing?: number; width?: number; color?: Cesium.Color; shadingType?: string; colorScheme?: any; showElseArea?: boolean; minHeight?: number; maxHeight?: number; }); /** * 是否显示等高线 */ contourShow: boolean; /** * 地表渲染效果,可选值: 无nono, 高程 elevation, 坡度slope, 坡向aspect */ shadingType: string; /** * 等高线 线宽(单位:像素) */ width: number; /** * 等高线 间隔(单位:米) */ spacing: number; /** * 等高线 颜色 */ color: Cesium.Color; /** * 清除数据 * @returns 无 */ clear(): void; } declare namespace FloodByGraphic { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.end, function (event) { * console.log('分析完成', event) * }) * @property start - 开始分析 * @property change - 变化了 * @property end - 完成分析 */ type EventType = { start: string; change: string; end: string; }; } /** * 淹没分析, * 基于polygon矢量面抬高模拟,只支持单个区域 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.positions] - 区域位置,坐标位置数组 * @param [options.style] - 淹没区域的样式 * @param [options.speed] - 淹没速度 * @param [options.minHeight] - 淹没起始的海拔高度(单位:米) * @param [options.maxHeight] - 淹没结束的海拔高度(单位:米) * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准),未设置时根据坐标自动判断(判断可能不准确) */ declare class FloodByGraphic extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; style?: PolygonEntity.StyleOptions; speed?: number; minHeight?: number; maxHeight?: number; has3dtiles?: boolean; }); /** * 淹没区域 坐标位置数组 */ positions: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; /** * 淹没平面高度(单位:米) */ height: number; /** * 淹没速度 */ speed: number; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; /** * 开始播放淹没动画效果 * @returns 无 */ start(): void; /** * 停止播放淹没动画效果 * @returns 无 */ stop(): void; /** * 重新开始播放淹没动画效果 * @returns 无 */ restart(): void; /** * 清除分析 * @returns 无 */ clear(): void; /** * 销毁当前对象 * @param [noDel = false] - false:会自动delete释放所有属性,true:不delete绑定的变量 * @returns 无 */ destroy(noDel?: boolean): void; } declare namespace FloodByMaterial { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.end, function (event) { * console.log('分析完成', event) * }) * @property start - 开始分析 * @property change - 变化了 * @property end - 完成分析 */ type EventType = { start: string; change: string; end: string; }; } /** * 淹没分析 , * 基于地球材质,可以多个区域 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [positions] - 坐标位置数组,只显示单个区域【单个区域场景时使用】 * @param [options.speed] - 淹没速度 * @param [options.minHeight] - 淹没起始的海拔高度(单位:米) * @param [options.maxHeight] - 淹没结束的海拔高度(单位:米) * @param [options.showElseArea = true] - 是否显示区域外的地图 */ declare class FloodByMaterial extends TerrainEditBase { constructor(options: { id?: string | number; enabled?: boolean; speed?: number; minHeight?: number; maxHeight?: number; showElseArea?: boolean; }, positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]); /** * 淹没高度(单位:米) */ height: number; /** * 淹没速度 */ speed: number; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; /** * 开始播放淹没动画效果 * @returns 无 */ start(): void; /** * 暂停播放淹没动画效果 * @returns 无 */ stop(): void; /** * 重新开始播放淹没动画效果 * @returns 无 */ restart(): void; /** * 清除分析 * @returns 无 */ clear(): void; } declare namespace Slope { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.change, function (event) { * console.log('发送了变化', event) * }) * @property endItem - 多个数据异步分析时,完成其中一个时的回调事件 * @property end - 多个数据异步分析时,完成所有的回调事件 */ type EventType = { endItem: string; end: string; }; } /** * 坡度坡向分析 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [options.positions] - 分析区域 坐标位置数组 * @param [options.arrow] - 箭头线的样式,包括以下: * @param [options.arrow.show = true] - 是否显示箭头线 * @param [options.arrow.scale = 0.3] - 箭头长度的比例(网格大小),根据绘制区域的大小和插值数来计算实际长度值。 * @param [options.arrow.color = Cesium.Color.YELLOW] - 颜色 * @param [options.arrow.length = 40] - 分析单个点时,箭头长度值 * @param [options.point] - 点的样式,包括以下: * @param [options.point.show = true] - 是否显示点 * @param [options.point.pixelSize = 9] - 像素大小 * @param [options.point.color = Cesium.Color.RED.withAlpha(0.5)] - 颜色 * @param [options.tooltip] - 可以指定绑定tooltip * @param [options.tooltipOptions] - tooltip弹窗时的配置参数 * @param [options.popup] - 可以指定绑定popup * @param [options.popupOptions] - popup弹窗时的配置参数 */ declare class Slope extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; arrow?: { show?: boolean; scale?: number; color?: Cesium.Color; length?: number; }; point?: { show?: boolean; pixelSize?: number; color?: Cesium.Color; }; tooltip?: (...params: any[]) => any; tooltipOptions?: Tooltip.StyleOptions; popup?: (...params: any[]) => any; popupOptions?: Popup.StyleOptions; }); /** * 添加计算的 位置 * @param positions - 坐标数组 或 单个坐标 * @param [options = {}] - 控制参数,包括: * @param [options.splitNum = 8] - 插值数,横纵等比分割的网格个数 * @param [options.radius = 2] - 取样分析,点周边半径(单位:米) * @param [options.count = 4] - 取样分析,点周边象限内点的数量,共计算 count*4 个点 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @returns 无,计算结果在 end事件中返回 */ add(positions: any[][] | LatLngPoint[] | Cesium.Cartesian3[] | LatLngPoint | Cesium.Cartesian3, options?: { splitNum?: number; radius?: number; count?: number; has3dtiles?: boolean; }): void; /** * 计算两点之间的坡度 * @param c1 - 点1 * @param c2 - 点2 * @returns 坡度值 */ getSlope(c1: Cesium.Cartesian3, c2: Cesium.Cartesian3): number; /** * 清除分析 * @returns 无 */ clear(): void; } /** * 地形开挖, * 基于地球材质,可以多个区域开挖。 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [positions] - 坐标位置数组,只显示单个区域【单个区域场景时使用】 * @param [options.clipOutSide = false] - 是否外切开挖 * @param [options.image] - 开挖区域的井墙面贴图URL。未传入该值时,不显示开挖区域的井。 * @param [options.imageBottom] - 当显示开挖区域的井时,井底面贴图URL * @param [options.diffHeight] - 当显示开挖区域的井时,设置所有区域的挖掘深度(单位:米) * @param [splitNum = 30] - 当显示开挖区域的井时,井墙面每两点之间插值个数 */ declare class TerrainClip extends TerrainEditBase { constructor(options: { id?: string | number; enabled?: boolean; clipOutSide?: boolean; image?: string; imageBottom?: string; diffHeight?: number; }, positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[], splitNum?: number); /** * 是否外切开挖 */ clipOutSide: boolean; /** * 设置所有区域的挖掘深度(单位:米) */ diffHeight: number; /** * 清除开挖 * @returns 无 */ clear(): void; } /** * 地形开挖、淹没等分析 基础类 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [positions] - 坐标位置数组,只显示单个区域【单个区域场景时使用】 */ declare class TerrainEditBase extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; }, positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]); /** * 区域 列表 */ readonly list: object[]; /** * 是否显示区域外的地图 */ showElseArea: boolean; /** * 坐标位置数组,只显示单个区域【单个区域场景时使用】 */ positions: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; /** * 已添加的区域个数 */ readonly length: Int; /** * 清除所有区域 * @returns 无 */ clear(): void; /** * 根据id获取区域对象 * @param id - id值 * @returns 区域对象 */ getAreaById(id: number): any; /** * 隐藏单个区域 * @param id - 区域id值 * @returns 无 */ hideArea(id: number): void; /** * 显示单个区域 * @param id - 区域id值 * @returns 无 */ showArea(id: number): void; /** * 移除单个区域 * @param item - 区域的id值,或 addArea返回的区域对象 * @returns 无 */ removeArea(item: number | any): void; /** * 添加单个区域 * @param positions - 坐标位置数组 * @param [options = {}] - 控制的参数 * @param [options.diffHeight] - 开挖深度(地形开挖时,可以控制单个区域的开挖深度) * @returns 添加区域的记录对象 */ addArea(positions: String[] | any[][] | LatLngPoint[] | Cesium.Cartesian3[], options?: { diffHeight?: any; }): any; } /** * 地形开挖 , * 基于clippingPlanes接口,只支持单个开挖。 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param [positions] - 开挖区域的 坐标位置数组 * @param [options.clipOutSide = false] - 是否外切开挖 * @param [options.image] - 开挖区域的井墙面贴图URL。未传入该值时,不显示开挖区域的井。 * @param [options.imageBottom] - 当显示开挖区域的井时,井底面贴图URL * @param [options.diffHeight] - 当显示开挖区域的井时,设置区域的挖掘深度(单位:米) * @param [splitNum = 30] - 当显示开挖区域的井时,井墙面每两点之间插值个数 */ declare class TerrainPlanClip extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; clipOutSide?: boolean; image?: string; imageBottom?: string; diffHeight?: number; }, positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[], splitNum?: number); /** * 开挖区域的 坐标位置数组 */ positions: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; /** * 设置所有区域的挖掘深度(单位:米) */ diffHeight: number; /** * 是否外切开挖 */ clipOutSide: boolean; /** * 清除开挖 * @returns 无 */ clear(): void; } /** * 限高分析 * @param options - 参数对象,包括以下: * @param [options.positions] - 限高区域坐标数组 * @param [options.height] - 限高高度(单位米),相对于bottomHeight模型地面的海拔高度的相对高度。 * @param [options.bottomHeight] - 模型地面的海拔高度(单位米) */ declare class LimitHeight extends BaseThing { constructor(options: { positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; height?: number; bottomHeight?: number; }); /** * 矢量数据图层 */ readonly layer: GraphicLayer; /** * 分析区域坐标数组 */ positions: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; /** * 限高高度(单位米),相对于bottomHeight模型地面的海拔高度的相对高度。 */ height: number; /** * 模型地面的海拔高度(单位:米) */ bottomHeight: number; /** * 清除限高分析 * @returns 无 */ clear(): void; } /** * Gltf模型剖切, * 基于clippingPlanes接口,只支持单个开挖。 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param options.graphic - 需要裁剪的对象(gltf模型) * @param [options.positions] - 裁剪区域坐标数组(按面或线裁剪) * @param [options.height] - 当有裁剪区域挖时,底面的高度(单位米),未设置时不显示底面。 * @param [options.type] - 裁剪类型(按方向类型正方向单面裁剪) * @param [options.distance = 0] - 裁剪的距离 * @param [options.clipOutSide = false] - 是否外裁剪 * @param [options.edgeWidth = 0] - 裁剪区域边线宽度,0时不显示 * @param [options.edgeColor = Cesium.Color.WHITE] - 裁剪区域边线颜色 */ declare class ModelPlanClip extends TilesetPlanClip { constructor(options: { id?: string | number; enabled?: boolean; graphic: ModelEntity; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; height?: number; type?: TilesetPlanClip.Type; distance?: number; clipOutSide?: boolean; edgeWidth?: number; edgeColor?: Cesium.Color; }); /** * 需要裁剪的对象(gltf模型) */ graphic: ModelEntity; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly matrix: Cesium.Matrix4; } declare namespace ModelPlanClip { /** * 裁剪模型 类型 枚举 同{@link TilesetPlanClip.Type} */ enum Type { } } /** * 3dtiles模型裁剪 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param options.layer - 需要裁剪的对象(3dtiles图层) * @param [options.positions] - 坐标位置数组,只裁剪单个区域【单个区域场景时使用】 * @param [options.clipOutSide = false] - 是否外裁剪 */ declare class TilesetClip extends TilesetEditBase { constructor(options: { id?: string | number; enabled?: boolean; layer: TilesetLayer; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; clipOutSide?: boolean; }); /** * 是否外裁剪 */ clipOutSide: boolean; } /** * 3dtiles模型分析(裁剪、压平、淹没) 基础类 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param options.layer - 需要模型分析的对象(3dtiles图层) * @param [options.positions] - 坐标位置数组,只分析的单个区域【单个区域场景时使用】 */ declare class TilesetEditBase extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; layer: TilesetLayer; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; }); /** * 区域 列表 */ readonly list: object[]; /** * 需要分析的模型(3dtiles图层) */ layer: TilesetLayer; /** * 需要分析的模型 对应的 Cesium3DTileset 对象 */ tileset: Cesium.Cesium3DTileset; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly matrix: Cesium.Matrix4; /** * 坐标位置数组,只显示单个区域【单个区域场景时使用】 */ positions: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; /** * 已添加的区域个数 */ readonly length: Int; /** * 清除分析 * @returns 无 */ clear(): void; /** * 根据id获取区域对象 * @param id - id值 * @returns 区域对象 */ getAreaById(id: number): any; /** * 隐藏单个区域 * @param id - 区域id值 * @returns 无 */ hideArea(id: number): void; /** * 显示单个区域 * @param id - 区域id值 * @returns 无 */ showArea(id: number): void; /** * 移除单个区域 * @param item - 区域的id,或 addArea返回的区域对象 * @returns 无 */ removeArea(item: number | any): void; /** * 添加区域 * @param positions - 坐标位置数组 * @returns 添加区域的记录对象 */ addArea(positions: String[] | any[][] | LatLngPoint[] | Cesium.Cartesian3[]): any; } /** * 3dtiles模型压平 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param options.layer - 需要压平的对象(3dtiles图层) * @param [options.positions] - 坐标位置数组,只压平单个区域【单个区域场景时使用】 * @param [options.height] - 压平高度 (单位:米),基于压平区域最低点高度的偏移量 */ declare class TilesetFlat extends TilesetEditBase { constructor(options: { id?: string | number; enabled?: boolean; layer: TilesetLayer; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; height?: number; }); /** * 压平高度 (单位:米),基于压平区域最低点高度的偏移量 */ height: number; } declare namespace TilesetFlood { /** * 当前类支持的{@link EventType}事件类型 * @example * //绑定监听事件 * thing.on(mars3d.EventType.end, function (event) { * console.log('分析完成', event) * }) * @property start - 开始分析 * @property change - 变化了 * @property end - 完成分析 */ type EventType = { start: string; change: string; end: string; }; } /** * 3dtiles模型淹没分析 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param options.layer - 需要裁剪的对象(3dtiles图层) * @param [options.positions] - 坐标位置数组,只淹没单个区域【单个区域场景时使用】 * @param [options.speed] - 淹没速度,米/秒(默认刷新频率为55Hz) * @param [options.minHeight] - 淹没起始的海拔高度(单位:米) * @param [options.maxHeight] - 淹没结束的海拔高度(单位:米) * @param [options.color = new Cesium.Color(0.15, 0.7, 0.95, 0.5)] - 淹没颜色 * @param [options.floodAll] - 是否对整个模型进行分析 */ declare class TilesetFlood extends TilesetEditBase { constructor(options: { id?: string | number; enabled?: boolean; layer: TilesetLayer; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; speed?: number; minHeight?: number; maxHeight?: number; color?: Cesium.Color; floodAll?: boolean; }); /** * 淹没速度,米/秒(默认刷新频率为55Hz) */ speed: number; /** * 是否对整个模型进行分析 */ floodAll: boolean; /** * 淹没高度(单位:米) */ height: number; /** * 淹没颜色 */ color: Cesium.Color; /** * 重新赋值参数,同构造方法参数一致。 * @param options - 参数,与类的构造方法参数相同 * @returns 当前对象本身,可以链式调用 */ setOptions(options: any): this; /** * 开始播放淹没动画效果 * @returns 无 */ start(): void; /** * 暂停播放淹没动画效果 * @returns 无 */ stop(): void; /** * 重新开始播放淹没动画效果 * @returns 无 */ restart(): void; /** * 清除分析 * @returns 无 */ clear(): void; } /** * 3dtiles模型裁剪, * 基于clippingPlanes接口,只支持单个开挖。 * @param options - 参数对象,包括以下: * @param [options.id = uuid()] - 对象的id标识 * @param [options.enabled = true] - 对象的启用状态 * @param options.layer - 需要裁剪的对象(3dtiles图层) * @param [options.positions] - 裁剪区域坐标数组(按面或线裁剪) * @param [options.height] - 当有裁剪区域挖时,底面的高度(单位米),未设置时不显示底面。 * @param [options.type] - 裁剪类型(按方向类型正方向单面裁剪) * @param [options.distance = 0] - 裁剪的距离 * @param [options.clipOutSide = false] - 是否外裁剪 * @param [options.edgeWidth = 0] - 裁剪区域边线宽度,0时不显示 * @param [options.edgeColor = Cesium.Color.WHITE] - 裁剪区域边线颜色 */ declare class TilesetPlanClip extends BaseThing { constructor(options: { id?: string | number; enabled?: boolean; layer: TilesetLayer; positions?: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; height?: number; type?: TilesetPlanClip.Type; distance?: number; clipOutSide?: boolean; edgeWidth?: number; edgeColor?: Cesium.Color; }); /** * 需要裁剪的对象(3dtiles图层) */ layer: TilesetLayer; /** * 裁剪面集合 */ readonly planes: Cesium.ClippingPlaneCollection; /** * 获取当前转换计算模型矩阵。如果方向或位置未定义,则返回undefined。 */ readonly matrix: Cesium.Matrix4; /** * 更新最后一个面的 裁剪距离 (单位:米) */ distance: number; /** * 裁剪类型(按方向类型正方向单面裁剪) */ type: TilesetPlanClip.Type; /** * 裁剪区域坐标数组(按面或线裁剪) */ positions: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[]; /** * 是否外裁剪 */ clipOutSide: boolean; /** * 清除裁剪面 * @returns 无 */ clear(): void; /** * 更新所有面的 裁剪距离 (单位:米) * @param val - 裁剪距离 (单位:米) * @returns 无 */ updateAllDistance(val: number): void; } declare namespace TilesetPlanClip { /** * 裁剪模型 类型 枚举 */ enum Type { Z, ZR, X, XR, Y, YR } } /** * DOM操作 相关静态方法类 */ declare module "DomUtil" { /** * 创建一个tagName的HTML元素,将其class设置为className,并可选择将其添加到container元素中 * @param tagName - 元素类型,比如 div * @param className - 附加的class样式名 * @param container - 添加到指定的父节点(可选) * @returns 创建好的DOM元素 */ function create(tagName: string, className: string, container: HTMLElement): HTMLElement; /** * 创建svg元素 * @param width - 宽度 * @param height - 高度 * @param path - url路径 * @param container - 添加到指定的父节点(可选) * @returns 创建的svg元素 */ function createSvg(width: number, height: number, path: string, container: HTMLElement): SVGElement; /** * 创建Video元素 * @param url - url地址 * @param type - 视频类型 * @param className - 样式名称 * @param container - 添加到指定的父节点(可选) * @returns 创建的Video元素 */ function createVideo(url: string, type: string, className: string, container: HTMLElement): HTMLElement; /** * 返回给定DOM id的元素,或者返回元素本身 * @param id - dom的id * @returns DOM元素 */ function get(id: string): HTMLElement | any; /** * 将HTML字符串解析为DOM * @param domStr - HTML字符串 * @param withWrapper - 是否返回DIV父节点 * @param className - 指定加上的样式名称 * @returns 解析后的DOM元素 */ function parseDom(domStr: string, withWrapper: boolean, className: string): HTMLDivElement | NodeListOf<ChildNode>; /** * 从其父元素中移除元素 * @param el - DOM元素或元素ID * @returns 无 */ function remove(el: HTMLElement | string): void; /** * 删除所有子元素 * @param el - DOM元素 * @returns 无 */ function empty(el: HTMLElement): void; /** * 返回元素上某个样式属性的值 * @param el - 指定的DOM元素 * @param style - 样式名称 * @returns 样式的值 */ function getStyle(el: HTMLElement, style: string): string | null; /** * 判断元素是否有指定class样式 * @param el - DOM元素 * @param name - class样式名称 * @returns 包含返回`true`,不包含返回`false` */ function hasClass(el: HTMLElement, name: string): boolean; /** * 在元素上添加指定的name的calss样式 * @param el - DOM元素 * @param name - class样式名称 * @returns 无 */ function addClass(el: HTMLElement, name: string): void; /** * 在元素上移除指定的name的calss样式 * @param el - DOM元素 * @param name - class样式名称 * @returns 无 */ function removeClass(el: HTMLElement, name: string): void; /** * 在元素上赋值设置指定的name的calss样式 * @param el - DOM元素 * @param name - class样式名称 * @returns 无 */ function setClass(el: HTMLElement, name: string): void; /** * 获取dom元素上的class样式名称 * @param el - DOM元素 * @returns class样式名称 */ function getClass(el: HTMLElement): string; /** * 进入全屏 * @param el - 指定DOM元素 * @returns 是否执行 */ function enterFullscreen(el: HTMLElement): boolean; /** * 退出全屏 * @returns 是否执行 */ function exitFullscreen(): boolean; } /** * 矢量数据标绘编辑相关常量 */ declare module "DrawUtil" { /** * 拖拽点分类 */ var PointType: number; /** * 拖拽点颜色 * @example * mars3d.DrawUtil.PointColor.Control = '#1c197d' //位置控制拖拽点 * mars3d.DrawUtil.PointColor.MoveAll = '#8c003a' //整体平移(如线面)拖拽点 * mars3d.DrawUtil.PointColor.MoveHeight = '#9500eb' //上下移动高度的拖拽点 * mars3d.DrawUtil.PointColor.EditAttr = '#f73163' //辅助修改属性(如半径)的拖拽点 * mars3d.DrawUtil.PointColor.AddMidPoint = 'rgba(4,194,201,0.3)' //增加新点,辅助拖拽点 */ var PointColor: Cesium.Color; /** * 设置编辑点的样式(color颜色除外) * @param value - 像素 * @returns 无 */ function setPointStyle(value: PointPrimitive.StyleOptions): void; } /** * 矢量数据 相关静态方法 */ declare module "GraphicUtil" { /** * 是否有指定类型矢量对象 * @param type - 矢量数据类型 * @returns 是否有指定类型 */ function hasType(type: string): boolean; /** * 判断该类型是否点状对象 * @param type - 矢量数据类型 * @returns 是否点状对象类型 */ function isPointType(type: string): boolean; /** * 注册矢量数据类 * @param type - 矢量数据类型 * @param graphicClass - 矢量数据类 * @returns 无 */ function register(type: string, graphicClass: BaseGraphic): void; /** * 根据 矢量数据类型 获取 矢量数据类 * @param type - 矢量数据类型 * @returns 矢量数据类 */ function getClass(type: string): BaseGraphic | undefined; /** * 根据类型和参数 创建Graphic工厂方法 * @param type - 数据类型 * @param options - 构造参数, 按type支持{@link GraphicType}类的构造方法参数 * @returns 创建完成的矢量数据对象 */ function create(type: any, options: any): BaseGraphic; /** * 通过标绘 创建Graphic工厂方法 * @param layer - 图层对象 * @param options - Graphic构造参数,包含: * @param options.type - 类型 * @param [options.其他] - 按type支持{@link GraphicType}类的构造方法参数 * @returns 创建完成的矢量数据对象 */ function fromDraw(layer: GraphicLayer, options: { type: GraphicType; 其他?: any; }): BaseGraphic; /** * 根据cesium的entity生成Graphic的工厂方法 * @param entity - cesium的entity对象 * @param options - Graphic构造参数,包含: * @param options.type - 类型 * @param options.style - 样式,按{@link GraphicType}对应的类的style配置 * @param [options.attr = null] - 属性 * @returns 创建完成的矢量数据对象 */ function fromEntity(entity: Cesium.Entity, options: { type: GraphicType; style: any; attr?: any; }): BaseEntity; } /** * 图层相关 静态方法 */ declare module "LayerUtil" { /** * 注册图层类 * @param type - 图层类型 * @param layerClass - 图层类 * @returns 无 */ function register(type: string, layerClass: BaseLayer): void; /** * 根据 图层类型 获取 图层类 * @param type - 图层类型 * @returns 图层类 */ function getClass(type: LayerType): BaseLayer | undefined; /** * 创建图层工厂方法 * @param options - 图层参数,包括: * @param options.type - 图层类型 * @param options.其他 - 具体见各{@link LayerType}对应的图层类的构造方法参数 * @param [templateValues = {}] - url模版 * @returns 创建完成的图层对象 */ function create(options: { type: LayerType; 其他: any; }, templateValues?: any): BaseLayer; /** * 注册ImageryProvider类 * @param type - Provider类型 * @param layerClass - ImageryProvider类 * @returns 无 */ function registerImageryProvider(type: string, layerClass: any): void; /** * 创建地图底图ImageryProvider的工厂方法 * @param options - Provider参数,具体见各Provider类的构造方法参数说明 * @returns ImageryProvider类 */ function createImageryProvider(options: any): any; /** * 获取baseLayerPicker使用的绑定图层列表配置, * 用于将config.json的配置basemaps数据转换为imageryProviderViewModels * @param arrLayer - basemaps配置 * @returns 转换后的 imageryProviderViewModels数组 和 显示图层的index(selectedIndex) */ function getImageryProviderViewModels(arrLayer: object[]): any; /** * 创建 无地形的 标准椭球体对象 * @returns 无地形 标准椭球体对象 */ function getNoTerrainProvider(): Cesium.EllipsoidTerrainProvider; /** * 注册TerrainProvider类 * @param type - Provider类型 * @param layerClass - TerrainProvider类 * @returns 无 */ function registerTerrainProvider(type: string, layerClass: any): void; /** * 创建地形对象的工厂方法 * @param options - 地形参数 * @param options.type - 地形类型 * @param options.url - 地形服务地址 * @param [options.proxy] - 加载资源时要使用的代理服务url。 * @param [options.templateValues] - 一个对象,用于替换Url中的模板值的键/值对 * @param [options.queryParameters] - 一个对象,其中包含在检索资源时将发送的查询参数。比如:queryParameters: {'access_token': '123-435-456-000'} * @param [options.headers] - 一个对象,将发送的其他HTTP标头。比如:headers: { 'X-My-Header': 'valueOfHeader' } * @param [options.requestVertexNormals = true] - 是否应该从服务器请求额外的光照信息,如果可用,以每个顶点法线的形式。 * @param [options.requestWaterMask = false] - 是否应该向服务器请求每个瓦的水掩膜(如果有的话)。 * @param [options.requestMetadata = true] - 是否应该从服务器请求每个块元数据(如果可用)。 * @param [templateValues = {}] - url模版 * @returns 地形对象 */ function createTerrainProvider(options: { type: TerrainType; url: string | Cesium.Resource; proxy?: string; templateValues?: any; queryParameters?: any; headers?: any; requestVertexNormals?: boolean; requestWaterMask?: boolean; requestMetadata?: boolean; }, templateValues?: any): Cesium.CesiumTerrainProvider; /** * 获取baseLayerPicker使用的绑定地形列表 * @param options - 地形参数,同{@link createTerrainProvider}方法参数 * @returns 地形列表 */ function getTerrainProviderViewModels(options: any): Cesium.ProviderViewModel[]; } /** * SDK内部统一调用console.* 打印日志的控制类,在外部可以按需开启和关闭。 */ declare module "Log" { /** * 是否 console.log 打印普通日志信息,可以按需关闭或开启 * @param val - 是否打印 * @returns 无 */ function hasInfo(val: boolean): void; /** * 是否 console.warn 打印警告日志信息,可以按需关闭或开启,但不建议关闭 * @param val - 是否打印 * @returns 无 */ function hasWarn(val: boolean): void; /** * 是否 console.error 打印错误日志信息,可以按需关闭或开启,但不建议关闭 * @param val - 是否打印 * @returns 无 */ function hasError(val: boolean): void; /** * console.log 打印普通日志信息,方便开发调试 * @param sources - 打印的日志内容 * @returns 无 */ function logInfo(sources: string | any): void; /** * console.warn 打印警告日志信息,方便开发调试 * @param sources - 打印的警告日志内容 * @returns 无 */ function logWarn(sources: string | any): void; /** * console.warn 打印错误日志信息,方便开发调试定位问题 * @param sources - 打印的错误日志内容 * @returns 无 */ function logError(sources: string | any): void; } /** * 矢量数据材质 */ declare module "MaterialUtil" { /** * 创建 材质属性(用于Entity) * @param type - 材质类型 * @param options - 创建参数,具体对照{@link MaterialType}的注释说明 * @returns 材质属性对象 */ function createMaterialProperty(type: MaterialType, options: any): BaseMaterialProperty; /** * 创建 材质(用于Primitive) * @param type - 材质类型 * @param options - 创建参数,具体对照{@link MaterialType}的注释说明 * @returns 材质对象 */ function createMaterial(type: MaterialType, options: any): Cesium.Material; /** * 将材质对象转为Josn简单对象,用于保存。 * @param material - 材质对象 * @param style - 附加到的目标对象 * @returns json简单对象 */ function toJSON(material: Cesium.Material | BaseMaterialProperty, style: any): any; } /** * 图上量算 的 常用静态方法 */ declare module "MeasureUtil" { /** * 求坐标数组的空间距离 * @param positions - 坐标数组 * @returns 距离(单位:米) */ function getDistance(positions: Cesium.Cartesian3[]): number; /** * 求坐标数组的 距离(地球表面弧度的), * 比如北京到纽约(不能穿过球心,是贴地表的线的距离) * @param positions - 坐标数组 * @returns 距离(单位:米) */ function getSurfaceDistance(positions: Cesium.Cartesian3[]): number; /** * 异步计算贴地距离中,每计算完成2个点之间的距离后 的回调方法 * @param options - 参数对象,具有以下属性: * @param options.index - 坐标数组的index顺序 * @param options.positions - 当前2个点之间的 贴地坐标数组 * @param options.distance - 当前2个点之间的 贴地距离 * @param options.arrDistance - 已计算完成从第0点到index点的 每一段的长度数组 * @param options.all_distance - 已计算完成从第0点到index点的 贴地距离 */ type getClampDistance_endItem = (options: { index: number; positions: Cesium.Cartesian3[]; distance: number; arrDistance: Number[]; all_distance: number; }) => void; /** * 异步计算贴地距离完成 的回调方法 * @param all_distance - 路线的全部距离,单位:米 * @param arrDistance - 每2个点间的 每一段的长度数组 */ type getClampDistance_callback = (all_distance: number, arrDistance: any[]) => void; /** * 异步计算贴地(地表或模型表面)距离,单位:米 * @param positions - 坐标数组 * @param options - 参数对象,具有以下属性: * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param [options.splitNum = 100] - 插值数,将线段分割的个数 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param options.endItem - 异步计算贴地距离中,每计算完成2个点之间的距离后 的回调方法 * @param options.callback - 异步计算贴地距离完成 的回调方法 * @returns 无 */ function getClampDistance(positions: Cesium.Cartesian3[], options: { scene: Cesium.Scene; splitNum?: number; has3dtiles?: boolean; endItem: getClampDistance_endItem; callback: getClampDistance_callback; }): void; /** * 计算面积(空间平面) * @param positions - 坐标数组 * @returns 面积,单位:平方米 */ function getArea(positions: Cesium.Cartesian3[]): number; /** * 计算三角形面积(空间平面) * @param pos1 - 三角形顶点坐标1 * @param pos2 - 三角形顶点坐标2 * @param pos3 - 三角形顶点坐标3 * @returns 面积,单位:平方米 */ function getTriangleArea(pos1: Cesium.Cartesian3, pos2: Cesium.Cartesian3, pos3: Cesium.Cartesian3): number; /** * 异步精确计算贴地面积完成 的回调方法 * @param area - 贴地面积,单位:平方米 * @param resultInter - 面内进行贴地(或贴模型)插值对象 */ type getClampArea_callback = (area: number, resultInter: any) => void; /** * 计算贴地面积 * @param positions - 坐标数组 * @param options - 参数对象,具有以下属性: * @param options.asyn - 是否进行异步精确计算 * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param [options.splitNum = 10] - 插值数,将面分割的网格数 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param options.callback - 异步计算贴地距离完成 的回调方法 * @returns 仅 asyn:false 时返回面积,单位:平方米 */ function getClampArea(positions: Cesium.Cartesian3[], options: { asyn: boolean; scene: Cesium.Scene; splitNum?: number; has3dtiles?: boolean; callback: getClampArea_callback; }): number | void; /** * 计算2点的角度值,角度已正北为0度,顺时针为正方向 * @param startPosition - 需要计算的点 * @param endPosition - 目标点,以该点为参考中心。 * @param [isNorthZero = false] - 是否正东为0时的角度(如方位角) * @returns 返回角度值,0-360度 */ function getAngle(startPosition: Cesium.Cartesian3, endPosition: Cesium.Cartesian3, isNorthZero?: boolean): number; /** * 异步计算中,每计算完成1个点的坡度坡向后 的回调方法 * @param event - 参数对象,具有以下属性: * @param event.index - 数组点中的index顺序 * @param event.data - 数据对象,具有以下属性: * @param event.data.position - 坐标位置 * @param event.data.slope - 度数法值【 α(坡度)=arc tan (高程差/水平距离)】 * @param event.data.slopeStr1 - 度数法值字符串 * @param event.data.slopeStr2 - 百分比法值字符串【 坡度 = (高程差/水平距离)x100%】 * @param event.data.direction - 坡向值(0-360度) */ type getSlope_endItem = (event: { index: number; data: { position: Cesium.Cartesian3; slope: number; slopeStr1: string; slopeStr2: string; direction: number; }; }) => void; /** * 异步计算完成所有点的坡度坡向后 的回调方法 * @param event - 参数对象,具有以下属性: * @param event.data - 数组对象,数组中每一个值,具有以下属性: * @param event.data.position - 坐标位置 * @param event.data.slope - 度数法值【 α(坡度)=arc tan (高程差/水平距离)】 * @param event.data.slopeStr1 - 度数法值字符串 * @param event.data.slopeStr2 - 百分比法值字符串【 坡度 = (高程差/水平距离)x100%】 * @param event.data.direction - 坡向值(0-360度) */ type getSlope_callback = (event: { data: { position: Cesium.Cartesian3; slope: number; slopeStr1: string; slopeStr2: string; direction: number; }[]; }) => void; /** * 异步计算点的坡度坡向 * @param options - 参数对象,具有以下属性: * @param options.map - Map地图对象 * @param options.positions - 坐标数组 * @param options.radius - 缓冲半径(影响坡度坡向的精度) * @param options.count - 缓冲的数量(影响坡度坡向的精度)会求周边(count*4)个点 * @param options.has3dtiles - 是否在3dtiles模型上分析(模型分析较慢,按需开启) * @param options.endItem - 异步计算中,每计算完成1个点的坡度坡向后 的回调方法 * @param options.callback - 异步计算完成所有点的坡度坡向后 的回调方法 * @returns 坡度坡向分析类对象,分析完成方法内部会自动释放 */ function getSlope(options: { map: Map; positions: Cesium.Cartesian3[]; radius: number; count: number; has3dtiles: boolean; endItem: getSlope_endItem; callback: getSlope_callback; }): Slope; /** * 格式化显示距离值, 可指定单位 * @param val - 距离值,米 * @param [unit = 'auto'] - 计量单位, 可选值:auto、m、km、mile、zhang 。auto时根据距离值自动选用k或km * @param lang - 使用的语言 * @returns 带单位的格式化距离值字符串,如:20.17 米 */ function formatDistance(val: number, unit?: string, lang: LangType): string; /** * 格式化显示面积值, 可指定单位 * @param val - 面积值,平方米 * @param [unit = 'auto'] - 计量单位,可选值:auto、m、km、mu、ha 。auto时根据面积值自动选用m或km * @param lang - 使用的语言 * @returns 带单位的格式化面积值字符串,如:20.21 平方公里 */ function formatArea(val: number, unit?: string, lang: LangType): string; /** * 格式化显示体积值, 可指定单位 * @param val - 体积值,立方米 * @param [unit = 'auto'] - 计量单位,当前无用,备用参数 * @param lang - 使用的语言 * @returns 带单位的格式化体积值字符串,如:20.21 方 */ function formatVolume(val: number, unit?: string, lang: LangType): string; } /** * 坐标点的转换 相关静态方法。 * 提供了cesium内部不同坐标系之间的坐标转换、提供了国内偏移坐标系与标准坐标的转换。 */ declare module "PointTrans" { /** * 经度/纬度 十进制 转为 度分秒格式 * @param value - 经度或纬度值 * @returns 度分秒对象,如: { degree:113, minute:24, second:40 } */ function degree2dms(value: number): any; /** * 经度/纬度 度分秒 转为 十进制 * @param degree - 度 * @param minute - 分 * @param second - 秒 * @returns 十进制 */ function dms2degree(degree: number, minute: number, second: number): number; /** * 根据经度值 获取CGCS2000投影坐标对应的 EPSG值 * @param lng - 经度值 * @param [fd6 = false] - 是否为6度分带, true:6度分带,false:3度分带 * @param [hasAddDH = true] - 横坐标前是否加带号 * @returns EPSG值 */ function getCGCS2000EPSGByLng(lng: number, fd6?: boolean, hasAddDH?: boolean): string | undefined; /** * 根据加带号的横坐标值 获取CGCS2000投影坐标对应的EPSG值 * @param x - 根据加带号的横坐标值 * @returns EPSG值 */ function getCGCS2000EPSGByX(x: number): string | undefined; /** * 使用proj4转换坐标(支持任意坐标系), * 坐标系 可以在 {@link http://epsg.io }进行查询,已经内置支持 EPSG:4326、EPSG:3857、EPSG:4490、EPSG:4491至4554 * @param arrdata - 原始坐标,示例:[39396641,3882123] * @param fromProjParams - 原始坐标的坐标系,如'EPSG:4527' * @param [toProjParams = 'EPSG:4326'] - 转为返回的结果坐标系 * @returns 返回结果坐标系的对应坐标,示例:[115.866936, 35.062583] */ function proj4Trans(arrdata: Number[], fromProjParams: string | CRS, toProjParams?: string | CRS): Number[]; /** * 使用proj4转换坐标数组(支持任意坐标系), * 坐标系 可以在 {@link http://epsg.io }进行查询,已经内置支持 EPSG:4326、EPSG:3857、EPSG:4490、EPSG:4491至4554 * @param coords - 原始坐标数组,示例:[[39396641,3882123],[39396623,3882134]] * @param fromProjParams - 原始坐标的坐标系,如'EPSG:4527' * @param [toProjParams = 'EPSG:4326'] - 转为返回的结果坐标系 * @returns 返回结果坐标系的对应坐标数组,示例:[[115.866936, 35.062583],[115.866923, 35.062565]] */ function proj4TransArr(coords: Number[], fromProjParams: string, toProjParams?: string): Number[]; /** * Cesium笛卡尔空间坐标 转 经纬度坐标 * 常用于转换geojson * @param cartesian - Cesium笛卡尔空间xyz坐标 * @param noAlt - 是否包含高度值 * @returns 经纬度坐标,示例:[123.123456,32.654321,198.7] */ function cartesian2lonlat(cartesian: Cesium.Cartesian3, noAlt: boolean): Number[]; /** * Cesium笛卡尔空间坐标数组 转 经纬度坐标数组 * 常用于转换geojson * @param positions - Cesium笛卡尔空间xyz坐标数组 * @param noAlt - 是否包含高度值 * @returns 经纬度坐标数组,示例:[ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] */ function cartesians2lonlats(positions: Cesium.Cartesian3[], noAlt: boolean): any[][]; /** * Cesium笛卡尔空间坐标 转 WebMercator投影平面坐标 * @param position - Cesium笛卡尔空间xyz坐标 * @returns 墨卡托投影平面坐标,示例:[13048882,3741659,20.1] */ function cartesian2mercator(position: Cesium.Cartesian3): Number[]; /** * Cesium笛卡尔空间坐标数组 转 WebMercator投影平面坐标数组 * @param positions - Cesium笛卡尔空间xyz坐标数组 * @returns WebMercator投影平面坐标数组,示例:[[13048882,3741659,20.1],[13048882,3741659,21.2] ] */ function cartesians2mercators(positions: Cesium.Cartesian3[]): any[][]; /** * 经纬度坐标 转 Cesium笛卡尔空间xyz坐标 * @param coord - 经纬度坐标,示例:[123.123456,32.654321,198.7] * @param [defHeight = 0] - 默认高度 * @returns Cesium笛卡尔空间xyz坐标 */ function lonlat2cartesian(coord: any[][], defHeight?: number): Cesium.Cartesian3; /** * 经纬度坐标数组 转 Cesium笛卡尔空间xyz坐标数组 * @param coords - 经纬度坐标数组,示例:[ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] * @param [defHeight = 0] - 默认高度 * @returns Cesium笛卡尔空间xyz坐标数组 */ function lonlats2cartesians(coords: any[][], defHeight?: number): Cesium.Cartesian3[]; /** * 经纬度地理坐标 转 投影平面坐标 * @param lnglat - 经纬度坐标,示例:[123.123456,32.654321,20.1] * @returns WebMercator投影平面坐标,示例:[13048882,3741659,20.1] */ function lonlat2mercator(lnglat: Number[]): Number[]; /** * 经纬度地理坐标数组 转 投影平面坐标数组 * @param arr - 经纬度坐标数组,示例:[ [123.123456,32.654321,20.1], [111.123456,22.654321,21.2] ] * @returns WebMercator投影平面坐标数组,示例:[[13048882,3741659,20.1],[13048882,3741659,21.2] ] */ function lonlats2mercators(arr: any[][]): any[][]; /** * 投影平面坐标 转 Cesium笛卡尔空间xyz坐标 * @param point - WebMercator投影平面坐标,示例:[13048882,3741659,20.1] * @param [height] - 赋值高度 * @returns Cesium笛卡尔空间xyz坐标 */ function mercator2cartesian(point: Number[], height?: number): Cesium.Cartesian3; /** * 投影平面坐标数组 转 Cesium笛卡尔空间xyz坐标数组 * @param arr - WebMercator投影平面坐标数组,示例:[[13048882,3741659,20.1],[13048882,3741659,21.2] ] * @param [height] - 赋值高度 * @returns Cesium笛卡尔空间xyz坐标数组 */ function mercators2cartesians(arr: Number[], height?: number): Cesium.Cartesian3; /** * 投影平面坐标 转 经纬度地理坐标 * @param point - WebMercator投影平面坐标,示例:[13048882,3741659,20.1] * @returns 经纬度坐标,示例:[123.123456,32.654321,20.1] */ function mercator2lonlat(point: Number[]): Number[]; /** * 投影平面坐标数组 转 经纬度地理坐标数组 * @param arr - WebMercator投影平面坐标数组,示例:[[13048882,3741659,20.1],[13048882,3741659,21.2] ] * @returns 经纬度坐标数组,示例:[ [123.123456,32.654321,20.1], [111.123456,22.654321,21.2] ] */ function mercators2lonlats(arr: any[][]): any[][]; /** * 经纬度坐标转换, * 百度坐标 (BD09) 转换为 国测局坐标 (GCJ02) * @param arrdata - 百度坐标 (BD09)坐标数据,示例:[117.225590,31.832916] * @returns 国测局坐标 (GCJ02)坐标数据,示例:[:117.22559,31.832917] */ function bd2gcj(arrdata: Number[]): Number[]; /** * 经纬度坐标转换, * 国测局坐标 (GCJ02) 转换为 百度坐标 (BD09) * @param arrdata - 高德谷歌等国测局坐标 (GCJ02) 坐标数据,示例:[117.225590,31.832916] * @returns 百度坐标 (BD09)坐标数据,示例:[117.232039,31.839177] */ function gcj2bd(arrdata: Number[]): Number[]; /** * 经纬度坐标转换, * 标准无偏坐标(WGS84) 转为 国测局坐标 (GCJ02) * @param arrdata - 标准无偏坐标(WGS84)坐标数据,示例:[117.220102, 31.834912] * @returns 国测局坐标 (GCJ02)坐标数据,示例:[117.225590,31.832916] */ function wgs2gcj(arrdata: Number[]): Number[]; /** * 经纬度坐标转换, * 国测局坐标 (GCJ02) 转换为 标准无偏坐标(WGS84) * @param arrdata - 国测局坐标 (GCJ02)坐标数据,示例:[117.225590,31.832916] * @returns 标准无偏坐标(WGS84)坐标数据,示例:[117.220102, 31.834912] */ function gcj2wgs(arrdata: Number[]): Number[]; /** * 经纬度坐标转换, * 百度坐标 (BD09) 转 标准无偏坐标(WGS84) * @param arrdata - 百度坐标 (BD09)坐标数据,示例:[117.232039,31.839177] * @returns 标准无偏坐标(WGS84)坐标数据,示例:[117.220102, 31.834912] */ function bd2wgs(arrdata: Number[]): Number[]; /** * 标准无偏坐标(WGS84) 转 百度坐标 (BD09) * @param arrdata - 标准无偏坐标(WGS84)坐标数据,示例:[117.220102, 31.834912] * @returns 百度坐标 (BD09)坐标数据,示例:[117.232039,31.839177] */ function wgs2bd(arrdata: Number[]): Number[]; /** * 【方式2】经纬度地理坐标 转 投影平面坐标 * @param arrdata - 经纬度坐标,示例:[117.220101,31.834907] * @returns WebMercator投影平面坐标,示例:[13048882.06,3741659.72] */ function jwd2mct(arrdata: Number[]): Number[]; /** * 【方式2】投影平面坐标 转 经纬度地理坐标 * @param arrdata - WebMercator投影平面坐标,示例:[13048882.06,3741659.72] * @returns 经纬度坐标数据,示例:[117.220101,31.834907] */ function mct2jwd(arrdata: Number[]): Number[]; } /** * 单个坐标或位置矩阵相关的处理 静态方法 */ declare module "PointUtil" { /** * 获取PointTrans中对应的坐标转换方法 * srcCoordType 转 dstCoordType 对应的方法名称 * @param srcCoordType - 原始的坐标系 * @param dstCoordType - 转换后的坐标系 * @returns PointTrans中对应的坐标转换方法 */ function getTransFun(srcCoordType: ChinaCRS, dstCoordType: ChinaCRS): (...params: any[]) => any; /** * 获取position的最终value值, * 因为cesium经常属性或绑定一层,通过该方法可以内部去判断是否有getValue或_value进行取最终value值。 * @param position - 各种位置属性对象 * @param [time = Cesium.JulianDate.now()] - 指定的时间值 * @returns 具体的Cartesian3对象坐标值 */ function getPositionValue(position: Cesium.XXXPositionProperty | Cesium.Cartesian3 | any, time?: Cesium.JulianDate): Cesium.Cartesian3; /** * 获取 坐标数组 中 最高高程值 * @param positions - 笛卡尔坐标数组 * @param [defaultVal = 0] - 默认高程值 * @returns 最高高程值 */ function getMaxHeight(positions: Cartesian3[], defaultVal?: number): number; /** * 获取 坐标数组 中 最低高程值 * @param positions - 笛卡尔坐标数组 * @param [defaultVal = 0] - 默认高程值 * @returns 最低高程值 */ function getMinHeight(positions: Cartesian3[], defaultVal?: number): number; /** * 对坐标(或坐标数组)增加 指定的海拔高度值 * @param positions - 笛卡尔坐标数组 * @param [addHeight = 0] - 增加的海拔高度值 * @returns 增加高度后的坐标(或坐标数组) */ function addPositionsHeight(positions: Cartesian3 | Cartesian3[], addHeight?: number): Cartesian3 | Cartesian3[]; /** * 对坐标(或坐标数组)赋值修改为 指定的海拔高度值 * @param positions - 笛卡尔坐标数组 * @param [height = 0] - 增加的海拔高度值 * @returns 增加高度后的坐标(或坐标数组) */ function setPositionsHeight(positions: Cartesian3 | Cartesian3[], height?: number): Cartesian3 | Cartesian3[]; /** * 异步计算贴地(或贴模型)高度完成 的回调方法 * @param newHeight - 计算完成的贴地(或贴模型)高度值 * @param cartOld - 原始点坐标对应的Cartographic经纬度值(弧度值) */ type getSurfaceHeight_callback = (newHeight: number | null, cartOld: Cesium.Cartographic) => void; /** * 获取 坐标 的 贴地(或贴模型)高度 * @example * var position = graphic.position * position = mars3d.PointUtil.getSurfaceHeight(map.scene, position, { * asyn: true, //是否异步求准确高度 * has3dtiles: true, //是否先求贴模型上(无模型时改为false,提高效率) * callback: function (newHeight, cartOld) { * console.log("原始高度为:" + cartOld.height.toFixed(2) + ",贴地高度:" + newHeight.toFixed(2)) * var positionNew = Cesium.Cartesian3.fromRadians(cartOld.longitude, cartOld.latitude, newHeight); * graphic.position =positionNew * } * }); * @param scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param position - 坐标 * @param [options = {}] - 参数对象: * @param options.asyn - 是否进行异步精确计算 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 仅 asyn:false 时返回高度值 */ function getSurfaceHeight(scene: Cesium.Scene, position: Cesium.Cartesian3, options?: { asyn: boolean; has3dtiles?: boolean; objectsToExclude?: object[]; callback: getSurfaceHeight_callback; }): number | void; /** * 获取 坐标 的 贴3dtiles模型高度 * @param scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param position - 坐标 * @param [options = {}] - 参数对象: * @param options.asyn - 是否进行异步精确计算 * @param [options.objectsToExclude = null] - 排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 仅 asyn:false 时返回高度值 */ function getSurface3DTilesHeight(scene: Cesium.Scene, position: Cesium.Cartesian3, options?: { asyn: boolean; objectsToExclude?: object[]; callback: getSurfaceHeight_callback; }): number | void; /** * 获取 坐标 的 贴地高度 * @example * var position = entity.position.getValue(); * position = mars3d.PointUtil.getSurfaceTerrainHeight(map.scene, position, { * asyn: true, //是否异步求准确高度 * callback: function (newHeight, cartOld) { * if (newHeight == null) return; * console.log("地面海拔:" + newHeight.toFixed(2)) * } * }); * @param scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param position - 坐标 * @param [options = {}] - 参数对象: * @param options.asyn - 是否进行异步精确计算 * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 仅 asyn:false 时返回高度值 */ function getSurfaceTerrainHeight(scene: Cesium.Scene, position: Cesium.Cartesian3, options?: { asyn: boolean; callback: getSurfaceHeight_callback; }): number | void; /** * 计算 贴地(或贴模型)高度 坐标 * (非精确计算,根据当前加载的地形和模型数据情况有关) * @param scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param position - 坐标 * @param [options = {}] - 参数对象,具有以下属性: * @param [options.relativeHeight = fasle] - 是否在地形上侧的高度,在对象具备Cesium.HeightReference.RELATIVE_TO_GROUND时,可以设置为ture * @param [options.maxHeight] - 可以限定最高高度,当计算的结果大于maxHeight时,原样返回,可以屏蔽计算误差的数据。 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象, * @returns 贴地坐标 */ function getSurfacePosition(scene: Cesium.Scene, position: Cesium.Cartesian3, options?: { relativeHeight?: boolean; maxHeight?: number; has3dtiles?: boolean; objectsToExclude?: object[]; }): Cesium.Cartesian3; /** * 获取 屏幕XY坐标 对应的 笛卡尔三维坐标 * @example * //Cesium原生鼠标单击事件 * var handler = new Cesium.ScreenSpaceEventHandler(map.scene.canvas); * handler.setInputAction(function (event) { * var cartesian = mars3d.PointUtil.getCurrentMousePosition(map.scene, event.position); * //继续写其他代码 * }, Cesium.ScreenSpaceEventType.LEFT_CLICK); * @param scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param position - 屏幕XY坐标(如鼠标所在位置) * @param noPickEntity - 排除的不拾取矢量对象,主要用于绘制中,排除对自己本身的拾取 * @returns 笛卡尔三维坐标 */ function getCurrentMousePosition(scene: Cesium.Scene, position: Cesium.Cartesian2, noPickEntity: any): Cesium.Cartesian3; /** * 求2点的中间点(贴地表) * @param mpt1 - 点1坐标 * @param mpt2 - 点2坐标 * @returns 2个点是否为重复的点 */ function getMidpoint(mpt1: Cesium.Cartesian3, mpt2: Cesium.Cartesian3): Cesium.Cartesian3; /** * 判断2个点是否为重复的点,比如标绘中的双击会偶尔产生2个重复点 * @param mpt1 - 点1坐标 * @param mpt2 - 点2坐标 * @returns 2个点是否为重复的点 */ function isRepeatPoint(mpt1: Cesium.Cartesian3, mpt2: Cesium.Cartesian3): boolean; /** * 获取 点point1 绕 点center 的地面法向量 旋转顺时针angle角度 后的 新坐标 * @param center - 中心点坐标 * @param point1 - 点坐标 * @param angle - 旋转角度,顺时针方向 0-360度 * @returns 计算得到的新坐标 */ function getRotateCenterPoint(center: Cesium.Cartesian3, point1: Cesium.Cartesian3, angle: number): Cesium.Cartesian3; /** * 求 p1指向p2方向线上,距离p1或p2指定长度的 新的点 * @param p1 - 起点坐标 * @param p2 - 终点坐标 * @param len - 指定的距离,addBS为false时:len为距离起点p1的距离,addBS为true时:len为距离终点p2的距离 * @param [addBS = false] - 标识len的参考目标 * @returns 计算得到的新坐标 */ function getOnLinePointByLen(p1: Cesium.Cartesian3, p2: Cesium.Cartesian3, len: number, addBS?: boolean): Cesium.Cartesian3; /** * 获取点的offest平移矩阵后点, * 已经弃用,建议用 getPositionByHprAndOffset 方法 * @param position - 中心点坐标 * @param offest - 偏移值 * @param offest.x - X轴方向偏移值,单位:米 * @param offest.y - Y轴方向偏移值,单位:米 * @param offest.z - Z轴方向偏移值,单位:米 * @param degree - 方向,0-360度 * @param [type = 'z'] - 轴方向,可选值:'x' 、 'y' 、 'z' * @param [fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @returns 计算得到的新坐标 */ function getTranslationPosition(position: Cesium.Cartesian3, offest: { x: number; y: number; z: number; }, degree: number, type?: string, fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame): Cesium.Cartesian3; /** * 根据 坐标位置、hpr方向、偏移距离,计算目标点坐标 * @param position - 坐标位置 * @param offest - 偏移距离值, xyz值的单位:米 * @param hpr - 方向值 * @param [ellipsoid = Cesium.Ellipsoid.WGS84] - 变换中使用固定坐标系的椭球。 * @param [fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @returns 目标点坐标 */ function getPositionByHprAndOffset(position: Cesium.Cartesian3, offest: Cesium.Cartesian3, hpr: Cesium.HeadingPitchRoll, ellipsoid?: Cesium.Ellipsoid, fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame): Cesium.Cartesian3; /** * 根据观察点的方向角度和距离,计算目标点坐标 * @param position - 观察点坐标 * @param angle - 方向角度 (正东方向为0,顺时针到360度) * @param radius - 半径距离 * @returns 目标点坐标 */ function getPositionByDirectionAndLen(position: Cesium.Cartesian3, angle: number, radius: number): Cesium.Cartesian3; /** * 根据观察点的hpr方向和距离,计算目标点坐标 * @param position - 观察点坐标 * @param hpr - 方向值 * @param radiusZ - 半径距离 * @returns 目标点坐标 */ function getPositionByHprAndLen(position: Cesium.Cartesian3, hpr: Cesium.HeadingPitchRoll, radiusZ: number): Cesium.Cartesian3; /** * 按观察点坐标和orientation方向,求观察点射向地球与地球的交点 * @param position - 观察点坐标 * @param orientation - HeadingPitchRoll方向 或 四元数实例 * @param reverse - 是否翻转射线方向 * @param [ellipsoid = Cesium.Ellipsoid.WGS84] - 变换中使用固定坐标系的椭球。 * @returns 射线与地球的交点 */ function getRayEarthPosition(position: Cesium.Cartesian3, orientation: Cesium.HeadingPitchRoll | Cesium.Quaternion, reverse: boolean, ellipsoid?: Cesium.Ellipsoid): Cesium.Cartesian3; /** * 按转换矩阵,求观察点射向地球与地球的交点 * @param matrix - 转换矩阵 * @param reverse - 是否翻转射线方向 * @param [ellipsoid = Cesium.Ellipsoid.WGS84] - 变换中使用固定坐标系的椭球。 * @returns 射线与地球的交点 */ function getRayEarthPositionByMatrix(matrix: Cesium.Matrix4, reverse: boolean, ellipsoid?: Cesium.Ellipsoid): Cesium.Cartesian3; /** * 根据 position位置 和 orientation四元数实例 求 Heading Pitch Roll方向 * @param position - 位置坐标 * @param orientation - 四元数实例 * @param [ellipsoid = Cesium.Ellipsoid.WGS84] - 变换中使用固定坐标系的椭球。 * @param [fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @returns Heading Pitch Roll方向 */ function getHeadingPitchRollByOrientation(position: Cesium.Cartesian3, orientation: Cesium.Quaternion, ellipsoid?: Cesium.Ellipsoid, fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame): Cesium.HeadingPitchRoll; /** * 根据matrix转换矩阵 求 Heading Pitch Roll角度 * @param matrix - 转换矩阵 * @param [ellipsoid = Cesium.Ellipsoid.WGS84] - 变换中使用固定坐标系的椭球。 * @param [fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @param [result] - 可以先实例化返回的 Heading Pitch Roll角度对象 * @returns Heading Pitch Roll角度 */ function getHeadingPitchRollByMatrix(matrix: Cesium.Matrix4, ellipsoid?: Cesium.Ellipsoid, fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame, result?: Cesium.HeadingPitchRoll): Cesium.HeadingPitchRoll; /** * 求 localStart点 到 localEnd点的 Heading Pitch Roll方向 * @param localStart - 起点坐标 * @param localEnd - 终点坐标 * @param [ellipsoid = Cesium.Ellipsoid.WGS84] - 变换中使用固定坐标系的椭球。 * @param [fixedFrameTransform = Cesium.Transforms.eastNorthUpToFixedFrame] - 参考系 * @returns Heading Pitch Roll方向 */ function getHeadingPitchRollForLine(localStart: Cesium.Cartesian3, localEnd: Cesium.Cartesian3, ellipsoid?: Cesium.Ellipsoid, fixedFrameTransform?: Cesium.Transforms.LocalFrameToFixedFrame): Cesium.HeadingPitchRoll; } /** * 多个点 或 线面数据 相关处理 静态方法 */ declare module "PolyUtil" { /** * 求坐标数组的中心点 * @param arr - 坐标数组 * @param height - 指定中心点的高度值,默认为所有点的最高高度 * @returns 中心点坐标 */ function centerOfMass(arr: any[][] | String[] | LatLngPoint[] | Cesium.Cartesian3[], height: number): Cesium.Cartesian3; /** * 缓冲分析,求指定 点线面geojson对象 按width半径的 缓冲面对象 * @param geojson - geojson格式对象 * @param width - 缓冲半径,单位:米 * @param [steps = 8] - 缓冲步幅 * @returns 缓冲面对象,geojson格式 */ function buffer(geojson: any, width: number, steps?: number): any; /** * 缓冲分析,坐标数组围合面,按width半径的 缓冲新的坐标 * @param points - 坐标数组 * @param width - 缓冲半径,单位:米 * @param [steps = 8] - 缓冲步幅 * @returns 缓冲后的新坐标数组 */ function bufferPoints(points: LatLngPoint[], width: number, steps?: number): LatLngPoint[]; /** * 求坐标数组的矩形范围内 按 splitNum网格数插值的 granularity值 * @param positions - 坐标数组 * @param [splitNum = 10] - splitNum网格数 * @returns granularity值 */ function getGranularity(positions: Cesium.Cartesian3[], splitNum?: Int): number; /** * 面内进行贴地(或贴模型)插值, 返回三角网等计算结果 的回调方法 * @param [options = {}] - 参数对象: * @param options.granularity - 面内按splitNum网格数插值的granularity值 * @param options.maxHeight - 面内最大高度 * @param options.minHeight - 面内最小高度 * @param options.list - 三角网对象数组,每个对象包含三角形的3个顶点(point1\point2\point3)相关值 */ type interPolygon_callback = (options?: { granularity: number; maxHeight: number; minHeight: number; list: object[]; }) => void; /** * 面内进行贴地(或贴模型)插值, 返回三角网等计算结果 * @param [options = {}] - 参数对象: * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param options.positions - 坐标数组 * @param options.callback - 异步计算高度完成后 的回调方法 * @param [options.splitNum = 10] - 插值数,横纵等比分割的网格个数 * @param [options.asyn = false] - 是否进行异步精确计算 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param [options.onlyPoint = false] - truea时,返回结果中只返回点,不返回三角网 * @returns 仅 asyn:false 时返回计算结果值 */ function interPolygon(options?: { scene: Cesium.Scene; positions: Cesium.Cartesian3[]; callback: interPolygon_callback; splitNum?: number; asyn?: boolean; has3dtiles?: boolean; objectsToExclude?: object[]; onlyPoint?: boolean; }): any | void; /** * 计算面内最大、最小高度值 * @param positions - 坐标数组 * @param scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param [options = {}] - 参数对象: * @param [options.splitNum = 10] - 插值数,横纵等比分割的网格个数 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @returns 计算面内最大、最小高度值对象,结果示例:{ maxHeight: 100, minHeight: 21 } */ function getHeightRange(positions: Cesium.Cartesian3[], scene: Cesium.Scene, options?: { splitNum?: number; has3dtiles?: boolean; objectsToExclude?: object[]; }): any; /** * 体积计算 * @param [options = {}] - 参数对象: * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param options.positions - 坐标数组 * @param options.callback - 异步计算高度完成后 的回调方法 * @param [options.splitNum = 10] - 插值数,横纵等比分割的网格个数 * @param [options.asyn = false] - 是否进行异步精确计算 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @returns 仅 asyn:false 时返回计算结果值 */ function computeVolume(options?: { scene: Cesium.Scene; positions: Cesium.Cartesian3[]; callback: VolumeResult; splitNum?: number; asyn?: boolean; has3dtiles?: boolean; objectsToExclude?: object[]; }): VolumeResult | void; /** * 面内进行贴地(或贴模型)插值, 返回三角网等计算结果 的回调方法 * @param [options = {}] - 参数对象: * @param options.granularity - 面内按splitNum网格数插值的granularity值 * @param options.maxHeight - 面内最大高度 * @param options.minHeight - 面内最小高度 * @param options.list - 三角网对象数组,每个对象包含三角形的3个顶点(point1\point2\point3)相关值 * @param options.totalArea - 总面积(横截面/投影底面),执行updateVolumeByMinHeight后赋值 * @param options.totalVolume - 总体积,执行updateVolumeByMinHeight后赋值 * @param options.digVolume - 挖方体积,执行updateVolume后赋值 * @param options.fillVolume - 填方体积,执行updateVolume后赋值 */ type VolumeResult = (options?: { granularity: number; maxHeight: number; minHeight: number; list: object[]; totalArea: number; totalVolume: number; digVolume: number; fillVolume: number; }) => void; /** * 根据 minHeight最低底面高度 计算(或重新计算)填挖方体积 * @param resultInter - 插值完的对象 * @returns 计算完成的填挖方体积 */ function updateVolumeByMinHeight(resultInter: interPolygon_callback): VolumeResult; /** * 根据 基准面高度 重新计算填挖方体积 * @param resultInter - 插值完的对象 * @param cutHeight - 基准面高度 * @returns 重新计算填挖方体积后的对象 */ function updateVolume(resultInter: VolumeResult, cutHeight: number): VolumeResult; /** * 获取 圆(或椭圆)边线上的坐标点数组 * @param [options] - 参数对象: * @param options.position - 圆的中心坐标 * @param options.radius - 如是圆时,半径(单位:米) * @param options.semiMajorAxis - 椭圆时的 长半轴半径(单位:米) * @param options.semiMinorAxis - 椭圆时的 短半轴半径(单位:米) * @param [options.count = 1] - 象限内点的数量,返回的总数为 count*4 * @param [options.rotation = 0] - 旋转的角度 * @returns 边线上的坐标点数组 */ function getEllipseOuterPositions(options?: { position: Cesium.Cartesian3; radius: number; semiMajorAxis: number; semiMinorAxis: number; count?: number; rotation?: number; }): Cesium.Cartesian3[]; /** * 格式化Rectangle矩形对象,返回经纬度值 * @param rectangle - 矩形对象 * @param [digits = 6] - 经纬度保留的小数位数 * @returns 返回经纬度值,示例: { xmin: 73.16895, xmax: 134.86816, ymin: 12.2023, ymax: 54.11485 } */ function formatRectangle(rectangle: Cesium.Rectangle, digits?: Int): any; /** * 获取 坐标数组 的 矩形边界值 * @param positions - 坐标数组 * @param [isFormat = false] - 是否格式化,格式化时示例: { xmin: 73.16895, xmax: 134.86816, ymin: 12.2023, ymax: 54.11485 } * @returns isFormat:true时,返回格式化对象,isFormat:false时返回Cesium.Rectangle对象 */ function getRectangle(positions: Cesium.Cartesian3[] | String[] | any[][] | LatLngPoint[], isFormat?: boolean): Cesium.Rectangle | any; /** * 获取坐标点数组的外接矩形的 4个顶点坐标点(数组) * @param positions - 坐标点数组 * @param [rotation = 0] - 旋转的角度,弧度值 * @returns 4个顶点坐标点 */ function getPositionsRectVertex(positions: Cesium.Cartesian3[], rotation?: number): Cesium.Cartesian3[]; /** * 获取矩形(含旋转角度)的边线上的4个顶点坐标点数组 * @param [options] - 参数对象: * @param options.rectangle - 矩形对象 * @param [options.rotation = 0] - 旋转的角度,弧度值 * @param [options.height = 0] - 坐标的高度 * @param [options.granularity = Cesium.Math.RADIANS_PER_DEGREE] - granularity值 * @param [options.ellipsoid = Cesium.Ellipsoid.WGS84] - 变换中使用固定坐标系的椭球。 * @returns 边线上的4个顶点坐标点数组 */ function getRectangleOuterPositions(options?: { rectangle: Cesium.Rectangle; rotation?: number; height?: number; granularity?: number; ellipsoid?: Cesium.Ellipsoid; }): Cesium.Cartesian3[]; /** * 根据传入中心点、高宽或角度,计算矩形面的顶点坐标。 * @param [options] - 参数对象: * @param options.center - 中心坐标 * @param [options.width] - 矩形的宽度,单位:米 * @param [options.height] - 矩形的高度,单位:米 * @param [options.rotation = 0] - 旋转的角度 * @param [options.originX = 0.5] - 中心点所在的位置x轴方向比例,取值范围:0.1-1.0 * @param [options.originY = 0.5] - 中心点所在的位置y轴方向比例,取值范围:0.1-1.0 * @returns 矩形面的顶点坐标数组 */ function getRectPositionsByCenter(options?: { center: Cesium.Cartesian3; width?: number; height?: number; rotation?: number; originX?: number; originY?: number; }): Cesium.Cartesian3[]; /** * 求贝塞尔曲线坐标 * @param positions - 坐标数组 * @param [closure = fasle] - 是否闭合曲线 * @returns 坐标数组 */ function getBezierCurve(positions: Cesium.Cartesian3[], closure?: boolean): Cesium.Cartesian3[]; /** * 对路线进行平面等比插值,高度:指定的固定height值 或 按贴地高度。 * @param [options = {}] - 参数对象: * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param options.positions - 坐标数组 * @param [options.splitNum = 100] - 插值数,等比分割的个数 * @param [options.minDistance = null] - 插值最小间隔(单位:米),优先级高于splitNum * @param [options.height = 0] - 坐标的高度 * @param [options.surfaceHeight = true] - 是否计算贴地高度 (非精确计算,根据当前加载的地形和模型数据情况有关) * @returns 插值后的路线坐标数组 */ function interPolyline(options?: { scene: Cesium.Scene; positions: Cesium.Cartesian3; splitNum?: number; minDistance?: number; height?: number; surfaceHeight?: boolean; }): Cesium.Cartesian3[]; /** * 对路线进行按空间等比插值,高度:高度值按各点的高度等比计算 * 比如:用于航线的插值运算 * @param positions - 坐标数组 * @param [options = {}] - 参数对象: * @param [options.splitNum] - 插值数,等比分割的个数,默认不插值 * @param [options.minDistance] - 插值时的最小间隔(单位:米),优先级高于splitNum * @returns 插值后的坐标对象 */ function interLine(positions: Cesium.Cartesian3[], options?: { splitNum?: number; minDistance?: number; }): Cesium.Cartesian3[]; /** * 面内进行贴地(或贴模型)插值, 返回三角网等计算结果 的回调方法 * @param raisedPositions - 计算完成后得到的贴地点数组 * @param noHeight - 是否计算贴地高度失败,true时标识计算失败了 * @param positions - 原始的坐标数组 */ type surfaceLineWork_callback = (raisedPositions: Cesium.Cartesian3[], noHeight: boolean, positions: Cesium.Cartesian3[]) => void; /** * 求路线的贴地线坐标(插值) * @param [options = {}] - 参数对象: * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param options.positions - 坐标数组 * @param [options.splitNum = 100] - 插值数,等比分割的个数 * @param [options.minDistance = null] - 插值最小间隔(单位:米),优先级高于splitNum * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param [options.offset = 0] - 可以按需增加偏移高度(单位:米),便于可视 * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 无 */ function computeSurfaceLine(options?: { scene: Cesium.Scene; positions: Cesium.Cartesian3; splitNum?: number; minDistance?: number; has3dtiles?: boolean; objectsToExclude?: object[]; offset?: number; callback: surfaceLineWork_callback; }): void; /** * 求 多个点 的的贴地新坐标(不插值) * @param [options = {}] - 参数对象: * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param options.positions - 坐标数组 * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param [options.offset = 0] - 可以按需增加偏移高度(单位:米),便于可视 * @param options.callback - 异步计算高度完成后 的回调方法 * @returns 无 */ function computeSurfacePoints(options?: { scene: Cesium.Scene; positions: Cesium.Cartesian3; has3dtiles?: boolean; objectsToExclude?: object[]; offset?: number; callback: surfaceLineWork_callback; }): void; /** * 异步分段分步计算贴地距离中,每计算完成2个点之间的距离后 的回调方法 * @param raisedPositions - 当前2个点之间的 贴地坐标数组 * @param noHeight - 是否计算贴地高度失败,true时标识计算失败了 * @param index - 坐标数组的index顺序 */ type computeStepSurfaceLine_endItem = (raisedPositions: Cesium.Cartesian3[], noHeight: boolean, index: number) => void; /** * 异步分段分步计算贴地距离中,每计算完成2个点之间的距离后 的回调方法 * @param arrStepPoints - 二维数组坐标集合,各分段2点之间的贴地点数组的集合 */ type computeStepSurfaceLine_end = (arrStepPoints: any[][]) => void; /** * 按2个坐标点分段分步来计算,求路线的贴地线坐标(插值) * @param [options = {}] - 参数对象: * @param options.scene - 三维地图场景对象,一般用map.scene或viewer.scene * @param options.positions - 坐标数组 * @param [options.splitNum = 100] - 插值数,等比分割的个数 * @param [options.minDistance = null] - 插值最小间隔(单位:米),优先级高于splitNum * @param [options.has3dtiles = auto] - 是否在3dtiles模型上分析(模型分析较慢,按需开启),默认内部根据点的位置自动判断(但可能不准) * @param [options.objectsToExclude = null] - 贴模型分析时,排除的不进行贴模型计算的模型对象,可以是: primitives, entities, 或 3D Tiles features * @param [options.offset = 0] - 可以按需增加偏移高度(单位:米),便于可视 * @param options.endItem - 异步计算高度完成后 的回调方法 * @param options.end - 异步计算高度完成后 的回调方法 * @param options.callback - 异步计算高度完成后 的回调方法(别名,同end) * @returns 无 */ function computeStepSurfaceLine(options?: { scene: Cesium.Scene; positions: Cesium.Cartesian3; splitNum?: number; minDistance?: number; has3dtiles?: boolean; objectsToExclude?: object[]; offset?: number; endItem: computeStepSurfaceLine_endItem; end: computeStepSurfaceLine_end; callback: computeStepSurfaceLine_end; }): void; /** * 计算2点间的 曲线链路的点集(空中曲线) * @param startPoint - 开始节点 * @param endPoint - 结束节点 * @param angularityFactor - 曲率 * @param numOfSingleLine - 点集数量 * @returns 曲线坐标数组 */ function getLinkedPointList(startPoint: Cesium.Cartesian3, endPoint: Cesium.Cartesian3, angularityFactor: number, numOfSingleLine: number): Cesium.Cartesian3[]; /** * 计算平行线 * @param positions - 原始线的坐标数组 * @param offset - 偏移的距离(单位米),正负决定方向 * @returns 平行线坐标数组 */ function getOffsetLine(positions: Cesium.Cartesian3[], offset: number): Cesium.Cartesian3[]; /** * 截取路线指定最大长度的新路线, * 在最后一个点往前截取maxDistance长度。 * 应用场景: 航迹的 “尾巴线” 的运算 * @param positions - 路线坐标 * @param maxDistance - 最大的截取长度 * @param [options = {}] - 参数对象: * @param [options.point = false] - 为true时 只返回计算的maxDistance处的坐标 * @returns 指定长度的坐标数组 ,options.point为true时,只返回数组的第1个点。 */ function sliceByMaxDistance(positions: Cesium.Cartesian3[], maxDistance: number, options?: { point?: boolean; }): Cesium.Cartesian3[] | Cesium.Cartesian3; /** * 求 坐标点 的 外包围凸体面(简化只保留边界线坐标) * @param coordinates - 经纬度坐标数组,示例:[ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] * @returns 经纬度坐标数组,示例:[ [123.123456,32.654321,198.7], [111.123456,22.654321,50.7] ] */ function convex(coordinates: any[][]): any[][]; } /** * 常用静态方法 */ declare module "Util" { /** * 判断对象是否为Number类型 * @param obj - 对象 * @returns 是否为Number类型 */ function isNumber(obj: any): boolean; /** * 判断对象是否为String类型 * @param obj - 对象 * @returns 是否为String类型 */ function isString(obj: any): boolean; /** * 判断对象是否为Boolean类型 * @param obj - 对象 * @returns 是否为Boolean类型 */ function isBoolean(obj: any): boolean; /** * 判断对象是否为Object类型 * @param obj - 对象 * @returns 是否为Object类型 */ function isObject(obj: any): boolean; /** * 判断对象是否为简单类型(包括:String\Boolean\Number\Array) * @param value - 对象 * @returns 是否为简单类型(包括:String\Boolean\Number\Array) */ function isSimpleType(value: any): boolean; /** * 格式化数字,返回指定小数位的数字 * @param num - 数字 * @param [digits = 0] - 小数位数 * @returns 返回digits指定小数位的数字 */ function formatNum(num: number, digits?: Int): number; /** * 按指定长度,对数字进行补零,返回指定长度的字符串 * @param numStr - 数字对象,示例:1234 * @param n - 指定长度,示例:8 * @returns 补零后的指定长度的字符串,示例:'00001234' */ function padLeft0(numStr: number | string, n: Int): string; /** * 根据空格分割字符串,并返回字符串数组(会自动去掉首位空格) * @param str - 字符串 * @returns 分割后的字符串数组 */ function splitWords(str: string): String[]; /** * 除去字符串首尾的空格 * @param str - 字符串 * @returns 除去首尾空格的字符串 */ function trim(str: string): string; /** * 获取字符串长度,区分中文和英文 * @param str - 字符串 * @returns 字符串长度 */ function getStrLength(str: string): number; /** * 根据数据和格式化字符串模板,返回字符串 * @example * var str = mars3d.Util.template("<div>名称:{name}</div>", { name:"火星科技", date:"2017-8-25"} ); * //str结果为 : "<div>名称:火星科技</div>" * @param str - 格式化字符串模版,属性字段为大括号,如 {name} * @param data - 数据对象 * @param toEmpty - 是否将模板中未匹配项转为空值 * @returns 返回字符串 */ function template(str: string, data: any, toEmpty: boolean): string; /** * 获取随机唯一uuid字符串,包含数字、大写字母、小写字母 * @param [prefix = 'M'] - 前缀 * @returns 字符串 */ function uuid(prefix?: string): string; /** * 获取Popup或Tooltip格式化Html字符串 * @example * //template可以是'all' ,返回数据的全部属性信息 * tiles3dLayer.bindPopup(function (event) { * var attr = event.graphic.attr * return mars3d.Util.getTemplateHtml({ title: '桥梁', template: 'all', attr: attr }) * }) * * //template可以是格式化字符串模板 * var html = mars3d.Util.getTemplateHtml({ title: '火星项目', template: "名称:{项目名称}<br />类型:{设施类型}<br />面积:{用地面积}亩<br />位置:{具体位置}", attr: item }) * * //可以是数组的template,按数组顺序构造,并转义字段名称 * // * var html = mars3d.Util.getTemplateHtml({ * title: '塔杆', * template: [ * { field: 'roadName', name: '所属线路' }, * { field: 'towerId', name: '杆塔编号' }, * { field: '杆塔型号', name: '杆塔型号' }, * { field: '杆塔性质', name: '杆塔性质' }, * { field: '杆塔类型', name: '杆塔类型' }, * { field: '设计单位', name: '设计单位' }, * { field: 'height', name: '海拔高度' }, * ], * attr: item, * }) * @param [options = {}] - 参数对象: * @param options.attr - 属性值 * @param options.template - 模版配置,支持:'all'、数组、字符串模板,当为数组时支持: * @param options.template.field - 字段名称 * @param options.template.name - 显示的对应自定义名称 * * @param [options.template.type] - 默认为label文本,也可以支持:'button'按钮,'html' html内容。 * @param [options.template.callback] - 当type为'button'按钮时,单击后触发的事件。 * @param [options.template.html] - 当type为'html'时,对于拼接的html内容。 * * @param [options.template.format] - 使用window上有效的格式化js方法名称或function回调方法,来格式化字符串值。 * @param [options.template.unit] - 追加的计量单位值。 * @param options.title - 标题 * @param [options.edit = false] - 是否返回编辑输入框 * @returns Html字符串 */ function getTemplateHtml(options?: { attr: any; template: { field: string; name: string; type?: string; callback?: string; html?: string; format?: string | ((...params: any[]) => any); unit?: string; }; title: string; edit?: boolean; }): string; /** * 获取Cesium对象值的最终value值, * 因为cesium经常属性或绑定一层,通过本方法可以内部去判断是否有getValue或_value进行取最终value值。 * @param obj - Cesium对象值 * @param [ClasName = null] - Cesium的类名,方便识别判断 * @param [time = Cesium.JulianDate.now()] - 如果具有时间属于时,取指定的时间的值 * @returns 最终value值 */ function getCesiumValue(obj: any, ClasName?: Class, time?: Class): any; /** * 获取Cesium颜色对象 * @param color - Cesium的类名,方便识别判断 * @param [defval] - 默认值 * @returns 颜色值 */ function getCesiumColor(color: string | Cesium.Color, defval?: Cesium.Color): Cesium.Color; /** * 根据配置信息获取Cesium颜色对象 * @param style - 配置信息 * @param style.color - 颜色值 * @param [style.opacity] - 透明度 * @param [style.randomColor] - 是否随机色 * @param [defval = Cesium.Color.YELLOW] - 默认值 * @returns 颜色值 */ function getColorByStyle(style: { color: string | Cesium.Color; opacity?: number; randomColor?: boolean; }, defval?: Cesium.Color): Cesium.Color; /** * 取属性值,简化Cesium内的属性,去掉getValue等,取最简的键值对。 * 方便popup、tooltip等构造方法使用 * @param attr - Cesium内的属性对象 * @param [options = {}] - 参数对象: * @param options.onlySimpleType - 是否只获取简易类型的对象 * @returns 最简的键值对属性对象 */ function getAttrVal(attr: any, options?: { onlySimpleType: boolean; }): any; /** * 合并对象,对二级子属性为Object的对象也会进行融合。 * @param [dest] - 目标对象 * @param sources - 需要融入合并的对象 * @returns 融合后的对象 */ function merge(dest?: any, sources: any): any; /** * 复制克隆对象 * @param obj - 原始对象 * @param [removeKeys = []] - 不复制的属性名 数组 * @param [level = 5] - 拷贝的层级最大深度,避免死循环 * @returns 克隆后的对象 */ function clone(obj: any, removeKeys?: String[], level?: Int): any; /** * 随机获取数组中的一个元素 * @param arr - 数组 * @returns 获取到的随机元素 */ function getArrayRandomOne(arr: any[]): any; /** * 移除数组中的指定对象 * @param arr - 数组 * @param val - 需要移除的数组元素对象 * @returns 对象是否移除成功 */ function removeArrayItem(arr: any[], val: any): boolean; /** * 根据属性 和symbol配置 取style样式信息 * @param symbol - symbol配置 * @param symbol.styleOptions - Style样式,每种不同类型数据都有不同的样式,具体见各矢量数据的style参数。{@link GraphicType} * @param [symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, styleOpt){ return { color: "#ff0000" }; } * @param [attr] - 数据属性对象 * @param [mergeStyle] - 需要合并到styleOptions的默认Style样式 * @returns style样式 */ function getSymbolStyle(symbol: { styleOptions: any; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }, attr?: any, mergeStyle?: any): any; /** * geojson格式 转 arcgis服务的json格式 * @param geojson - geojson格式 * @param [idAttr = 'OBJECTID'] - id字段名称 * @returns arcgis服务的json格式 */ function geojsonToArcGIS(geojson: any, idAttr?: string): any; /** * arcgis服务的json格式 转 geojson格式 * @param arcgis - arcgis服务的json格式 * @param [idAttr = 'OBJECTID'] - id字段名称 * @returns geojson格式 */ function arcgisToGeoJSON(arcgis: any, idAttr?: string): any; /** * 获取GeoJSON中的features数组集合(自动判断数据来源) * @param geojson - geojson对象 * @returns features数组集合 */ function getGeoJsonFeatures(geojson: any): object[]; /** * GeoJSON 转为 Graphic构造参数数组(用于创建{@link BaseGraphic}) * style有3种方式控制: 1.传type及style参数;2.传symbol参数;3.数据本身的feature.properties.style; * 优先级为:1>2>3 * @param geojson - geojson对象 * @param [options = {}] - 控制参数 * @param [option.type] - 转为指定的类型 * @param [options.style = {}] - Style样式,每种不同类型数据都有不同的样式,具体见各矢量数据的style参数。{@link GraphicType} * @param symbol - symbol配置,与style二选一 * @param [symbol.type] - 标识数据类型 * @param [symbol.merge] - 是否合并并覆盖json中已有的style,默认不合并,仅适用symbol配置。 * @param symbol.styleOptions - Style样式,每种不同类型数据都有不同的样式,具体见各矢量数据的style参数。{@link GraphicType} * @param [symbol.styleField] - 按 styleField 属性设置不同样式。 * @param [symbol.styleFieldOptions] - 按styleField值与对应style样式的键值对象。 * @param [symbol.callback] - 自定义判断处理返回style ,示例:callback: function (attr, styleOpt){ return { color: "#ff0000" }; } * @param [options.crs] - 原始数据的坐标系,如'EPSG:3857' (可以从 {@link http://epsg.io }查询) * @param [options.hasEdit] - 当需要编辑时可以传true值,指定为Entity类型 * @returns Graphic构造参数数组(用于创建{@link BaseGraphic}) */ function geoJsonToGraphics(geojson: any, options?: { style?: any; crs?: string; hasEdit?: boolean; }, symbol: { type?: GraphicType; merge?: boolean; styleOptions: any; styleField?: string; styleFieldOptions?: any; callback?: (...params: any[]) => any; }): object[]; /** * GeoJSON格式的Feature单个对象转为 Graphic构造参数(用于创建{@link BaseGraphic}) * @param feature - geojson单个Feature对象 * @param [options = {}] - 参数,包括: * @param [options.type] - 转为指定的类型 * @param [options.crs] - 原始数据的坐标系,如'EPSG:3857' (可以从 {@link http://epsg.io }查询) * @param [options.style = {}] - Style样式,每种不同类型数据都有不同的样式,具体见各矢量数据的style参数。{@link GraphicType} * @param [options.hasEdit] - 当需要编辑时可以传true值,指定为Entity类型 * @returns Graphic构造参数(用于创建{@link BaseGraphic}) */ function featureToGraphic(feature: any, options?: { type?: GraphicType; crs?: string; style?: any; hasEdit?: boolean; }): any; /** * 根据当前高度获取地图层级 * @param altitude - 高度值 * @returns 地图层级,通常为 0-21 */ function heightToZoom(altitude: number): Int; /** * 根据图层的config的配置信息,自动加上代理等配置返回Resource对象 * @param config - 图层的配置信息 * @param config.url - url地址 * @param [config.proxy] - 加载资源时要使用的代理服务url。 * @param [config.templateValues] - 一个对象,用于替换Url中的模板值的键/值对 * @param [config.queryParameters] - 一个对象,其中包含在检索资源时将发送的查询参数。比如:queryParameters: {'access_token': '123-435-456-000'} * @param [config.headers] - 一个对象,将发送的其他HTTP标头。比如:headers: { 'X-My-Header': 'valueOfHeader' } * @returns Resource对象 */ function getUrlResource(config: { url: string; proxy?: string; templateValues?: any; queryParameters?: any; headers?: any; }): Cesium.Resource; /** * 文字转base64图片 * @param text - 文字内容 * @param [textStyle = {}] - 参数对象: * @param [textStyle.font = '10px sans-serif'] - 使用的CSS字体。 * @param [textStyle.textBaseline = 'bottom'] - 文本的基线。 * @param [textStyle.fill = true] - 是否填充文本。 * @param [textStyle.fillColor = Cesium.Color.WHITE] - 填充颜色。 * @param [textStyle.stroke = false] - 是否描边文本。 * @param [textStyle.strokeWidth = 1] - 文本描边的宽度。 * @param [textStyle.strokeColor = Cesium.Color.BLACK] - 文本描边的颜色。 * @param [textStyle.backgroundColor = Cesium.Color.TRANSPARENT] - 画布的背景色。 * @param [textStyle.padding = 0] - 要在文本周围添加的填充的像素大小。 * @param [textStyle.outlineWidth] - 边框的宽度。 * @param [textStyle.outlineColor = fillColor] - 矩形边框的颜色。 * @returns canvas对象 */ function getTextImage(text: string, textStyle?: { font?: string; textBaseline?: string; fill?: boolean; fillColor?: Cesium.Color; stroke?: boolean; strokeWidth?: number; strokeColor?: Cesium.Color; backgroundColor?: Cesium.Color; padding?: number; outlineWidth?: number; outlineColor?: Cesium.Color; }): HTMLCanvasElement; /** * 获取用于EntityCluster聚合的圆形图标对象 * @param count - 数字 * @param [options = {}] - 参数对象: * @param [options.radius = 26] - 圆形图标的整体半径大小(单位:像素) * @param [options.color = 'rgba(181, 226, 140, 0.6)'] - 圆形图标的背景颜色 * @param [options.opacity = 0.5] - 圆形图标的透明度 * @param [options.borderWidth = 5] - 圆形图标的边框宽度(单位:像素),0不显示 * @param [options.borderColor = 'rgba(110, 204, 57, 0.5)'] - 圆形图标的边框背景颜色 * @param [options.borderOpacity = 0.6] - 圆形图标边框的透明度 * @param [options.fontColor = '#ffffff'] - 数字的颜色 * @returns base64图片对象,包含 data URI 的DOMString。 */ function getCircleImage(count: number, options?: { radius?: number; color?: string; opacity?: number; borderWidth?: number; borderColor?: string; borderOpacity?: number; fontColor?: string; }): DOMString; /** * 导出下载图片文件 * @param name - 图片文件名称,不需要后缀名 * @param base64 - 图片内容,base64格式 * @returns 无 */ function downloadBase64Image(name: string, base64: string): void; /** * 导出下载文本文件 * @param fileName - 文件完整名称,需要含后缀名 * @param string - 文本内容 * @returns 无 */ function downloadFile(fileName: string, string: string): void; /** * 获取浏览器类型及版本 * @returns 浏览器类型及版本,示例:{ type: 'Chrome', version: 71 } */ function getExplorerInfo(): any; /** * 检测当前浏览器是否支持WebGL * @returns 是否支持WebGL */ function webglreport(): boolean; /** * 执行检测浏览器不支持webgl后的alert错误提示弹窗 * @returns 无 */ function webglerror(): void; /** * 获取当前页面的url中的?传入参数对象集合 * @returns 参数名与参数值的键值对 */ function getRequest(): any; /** * 获取当前页面的url中的?传入的指定参数值 * @param name - 指定参数名称 * @returns 获取到的参数值 */ function getRequestByName(name: string): string; /** * 当前是否是PC电脑浏览器。 * @returns 是否是PC电脑浏览器。 */ function isPCBroswer(): boolean; /** * 执行alert弹窗 * @param msg - 弹窗内的内容 * @param title - 弹窗的标题 * @returns 无 */ function alert(msg: string, title: string): void; /** * 执行msg提示窗 * @param msg - 弹窗内的内容 * @returns 无 */ function msg(msg: string): void; /** * 将 时间 转化为指定格式的字符串 * @example * mars3d.Util.formatDate(date,"yyyy-MM-dd HH:mm:ss") ==> 2017-08-25 08:08:00 * mars3d.Util.formatDate(date,"yyyy-MM-dd HH:mm:ss.S") ==> 2017-08-25 08:08:00.423 * mars3d.Util.formatDate(date,"yyyy-M-d HH:mm:ss") ==> 2017-8-5 08:08:00 * @param date - 时间 * @param fmt - 格式模版,月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符; 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字). * @returns 指定格式的字符串 */ function formatDate(date: Date, fmt: string): string; /** * 根据设置的lang参数,获取当前key对应语言的文本内容。 * @param key - 文本key * @param langType - 使用的语言 * @returns lang参数指定的对应文本内容 */ function getLangText(key: string, langType: LangType): void; }
the_stack
import {Plural, Trans} from '@lingui/react' import {DataLink} from 'components/ui/DbLink' import {Action, ActionKey} from 'data/ACTIONS' import {Status} from 'data/STATUSES' import {Event, Events} from 'event' import {Analyser} from 'parser/core/Analyser' import {EventHook} from 'parser/core/Dispatcher' import {filter} from 'parser/core/filter' import {dependency} from 'parser/core/Injectable' import {Actors} from 'parser/core/modules/Actors' import Checklist, {Requirement, Rule} from 'parser/core/modules/Checklist' import {Data} from 'parser/core/modules/Data' import {Invulnerability} from 'parser/core/modules/Invulnerability' import {Statuses} from 'parser/core/modules/Statuses' import Suggestions, {SEVERITY, TieredSuggestion} from 'parser/core/modules/Suggestions' import React from 'react' import DISPLAY_ORDER from './DISPLAY_ORDER' import {fillActions} from './utilities' // Expected maximum time left to refresh TS - this is the slowest possible GCD for a full set of forms const TWIN_SNAKES_BUFFER = 6000 const TWIN_IGNORED_GCDS: ActionKey[] = [ 'FORM_SHIFT', 'MEDITATION', ] // Expected time unbuffed post-PB, maximum possible time (2.50s base GCD at GL4 is 2.00s, and we allow for 2 GCDs) // The extra second here is to allow for latency in status application after actually using PB const UNBALANCED_BUFFER = 5000 interface TwinState { casts: Array<Events['action']> start: number end?: number } export class TwinSnakes extends Analyser { static override handle = 'twinsnakes' @dependency private actors!: Actors @dependency private checklist!: Checklist @dependency private data!: Data @dependency private invulnerability!: Invulnerability @dependency private statuses!: Statuses @dependency private suggestions!: Suggestions private history: TwinState[] = [] private ignoredGcds: Array<Action['id']> = [] private twinSnake: TwinState | undefined private lastRefresh: number = this.parser.pull.timestamp private lastDrop: number = this.parser.pull.timestamp // Clipping the duration private earlySnakes: number = 0 // Fury used without TS active private failedFury: number = 0 // Antman used without TS active private failedAnts: number = 0 // Tracking when PB dropped intentionally for uptime adjustment // Initialising PB drop time to 0 because we aren't considering start-of-fight downtime and prefer to not undef it private unbalanced: number = 0 private unbalancedHistory: number[] = [] private unbalancedHook?: EventHook<Events['action']> private allowedDowntime: number = 0 private twinHook?: EventHook<Events['action']> override initialise() { this.ignoredGcds = fillActions(TWIN_IGNORED_GCDS, this.data) const playerFilter = filter<Event>().source(this.parser.actor.id) this.addEventHook(playerFilter.type('statusApply').status(this.data.statuses.TWIN_SNAKES.id), this.onGain) this.addEventHook(playerFilter.type('statusRemove').status(this.data.statuses.TWIN_SNAKES.id), this.onDrop) this.addEventHook(playerFilter.type('statusRemove').status(this.data.statuses.PERFECT_BALANCE.id), this.onUnbalanced) this.addEventHook('complete', this.onComplete) } private onCast(event: Events['action']): void { const action = this.data.getAction(event.action) // Only include GCDs if (action == null || !(action.onGcd ?? false)) { return } // Ignore FS and Meditation if (this.ignoredGcds.includes(action.id)) { return } // Check for actions used without TS up. In the case of TS, the window will be opened // by the gain hook, so this GCD won't count anyway. For anything else, there's no // window so no need to count them. if (this.twinSnake == null) { // Did Anatman refresh TS? if (action.id === this.data.actions.ANATMAN.id) { this.failedAnts++ } // Did FPF refresh TS? if (action.id === this.data.actions.FOUR_POINT_FURY.id) { this.failedFury++ } // Since TS isn't active, we always return early return } // Verify the window isn't closed, and count the GCDs: if (this.twinSnake.end != null) { // We still count TS in the GCD list of the window, just flag if it's early if (action.id === this.data.actions.TWIN_SNAKES.id) { const expected = this.data.statuses.TWIN_SNAKES.duration - TWIN_SNAKES_BUFFER if (event.timestamp - this.lastRefresh < expected) { this.earlySnakes++ } } this.twinSnake.casts.push(event) } } // Can be TS, FPF, or Antman - new window for TS as needed, otherwise just reset the GCD count private onGain(event: Events['statusApply']): void { // Check if existing window or not if (this.twinSnake == null) { this.twinSnake = {start: event.timestamp, casts: []} // Hook all GCDs so we can count GCDs in buff windows this.twinHook = this.addEventHook( filter<Event>() .source(this.parser.actor.id) .type('action'), this.onCast, ) } // We allow downtime post-PB if it's resolved at the 2nd GCD and that GCD is Twin // If they applied Twin on the first GCD, something has gone wrong, and it's not allowed anyway if (this.unbalancedHistory.length === 2) { const secondGcd = this.unbalancedHistory[1] const secondAction = this.data.getAction(secondGcd) // Sanity check that action exists and Twin dropped after PB did if (secondAction != null && this.lastDrop >= this.unbalanced) { const timeDelta = event.timestamp - this.lastDrop if (timeDelta <= UNBALANCED_BUFFER && secondAction.id === this.data.actions.TWIN_SNAKES.id) { this.allowedDowntime += timeDelta } } // Reset the array and cleanup in case user took forever to apply Twin this.unbalancedHistory = [] if (this.unbalancedHook != null) { this.removeEventHook(this.unbalancedHook) this.unbalancedHook = undefined } } // Set the time for Twin refresh this.lastRefresh = event.timestamp } private onDrop(event: Events['statusRemove']): void { // Only account for the drop here, not at end of fight cleanup this.lastDrop = event.timestamp this.stopAndSave(event.timestamp) } private onUnbalanced(event: Events['statusRemove']): void { // Reset our state tracking this.unbalanced = event.timestamp this.unbalancedHistory = [] // Hook any GCDs after PB drops, using Twin will remove this this.unbalancedHook = this.addEventHook( filter<Event>() .source(this.parser.actor.id) .type('action'), this.onUnbalancedCast, ) } private onUnbalancedCast(event: Events['action']): void { // Prune out non-GCDs const action = this.data.getAction(event.action) if (action?.onGcd == null) { return } // Push the GCD to history so we can use it in the onGain hook this.unbalancedHistory.push(event.action) // If we use Twin, we no longer need to capture GCDs if (action.id === this.data.actions.TWIN_SNAKES.id && this.unbalancedHook != null) { this.removeEventHook(this.unbalancedHook) this.unbalancedHook = undefined } } private stopAndSave(endTime: number = this.parser.currentEpochTimestamp): void { if (this.twinSnake != null) { this.twinSnake.end = endTime this.history.push(this.twinSnake) if (this.twinHook != null) { this.removeEventHook(this.twinHook) this.twinHook = undefined } } this.twinSnake = undefined } private onComplete() { // Close off the last window this.stopAndSave(this.parser.pull.timestamp + this.parser.pull.duration) // Calculate derped potency to early refreshes const lostTruePotency = this.earlySnakes * (this.data.actions.TRUE_STRIKE.potency - this.data.actions.TWIN_SNAKES.potency) this.checklist.add(new Rule({ name: <Trans id="mnk.twinsnakes.checklist.name">Keep Twin Snakes up</Trans>, description: <Trans id="mnk.twinsnakes.checklist.description">Twin Snakes is an easy 10% buff to your DPS.</Trans>, displayOrder: DISPLAY_ORDER.TWIN_SNAKES, requirements: [ new Requirement({ name: <Trans id="mnk.twinsnakes.checklist.requirement.name"><DataLink action="TWIN_SNAKES"/> uptime</Trans>, percent: () => this.getBuffUptimePercent(this.data.statuses.TWIN_SNAKES.id), }), ], })) this.suggestions.add(new TieredSuggestion({ icon: this.data.actions.TWIN_SNAKES.icon, content: <Trans id="mnk.twinsnakes.suggestions.early.content"> Avoid refreshing <DataLink action="TWIN_SNAKES"/> signficantly before its expiration as you're losing uses of the higher potency <DataLink action="TRUE_STRIKE"/>. </Trans>, tiers: { 1: SEVERITY.MEDIUM, 4: SEVERITY.MAJOR, }, value: this.earlySnakes, why: <Trans id="mnk.twinsnakes.suggestions.early.why"> {lostTruePotency} potency lost to <Plural value={this.earlySnakes} one="# early refresh" other="# early refreshes" />. </Trans>, })) this.suggestions.add(new TieredSuggestion({ icon: this.data.actions.FOUR_POINT_FURY.icon, content: <Trans id="mnk.twinsnakes.suggestions.toocalm.content"> Try to get <DataLink status="TWIN_SNAKES"/> up before using <DataLink action="FOUR_POINT_FURY"/> to take advantage of its free refresh. </Trans>, tiers: { 1: SEVERITY.MINOR, 2: SEVERITY.MEDIUM, }, value: this.failedFury, why: <Trans id="mnk.twinsnakes.suggestions.toocalm.why"> <Plural value={this.failedFury} one="# use" other="# uses" /> of <DataLink action="FOUR_POINT_FURY"/> failed to refresh <DataLink status="TWIN_SNAKES"/>. </Trans>, })) this.suggestions.add(new TieredSuggestion({ icon: this.data.actions.ANATMAN.icon, content: <Trans id="mnk.twinsnakes.suggestions.antman.content"> Try to get <DataLink status="TWIN_SNAKES"/> up before using <DataLink action="ANATMAN"/> to take advantage of its free refresh. </Trans>, tiers: { 1: SEVERITY.MINOR, 2: SEVERITY.MEDIUM, }, value: this.failedAnts, why: <Trans id="mnk.twinsnakes.suggestions.antman.why"> <Plural value={this.failedAnts} one="# use" other="# uses" /> of <DataLink action="ANATMAN"/> failed to refresh <DataLink status="TWIN_SNAKES"/>. </Trans>, })) } private getBuffUptimePercent(statusId: Status['id']): number { const status = this.data.getStatus(statusId) if (status == null) { return 0 } const statusUptime = this.statuses.getUptime(status, this.actors.current) const fightUptime = this.parser.currentDuration - this.invulnerability.getDuration({types: ['invulnerable']}) - this.allowedDowntime return (statusUptime / fightUptime) * 100 } }
the_stack
import './index.less'; import { ValueComponentProps, ValueComponent, VNode, mountComponent, createVNode } from 'jeact'; export interface PmSelectorOption { value: any; label: string; checked?: boolean; parent?: PmSelectorOption; children?: PmSelectorOption[]; } export interface PmSelectorComponentProps extends ValueComponentProps<any[]> { placeholder?: string; options?: any[]; valueField?: string; labelField?: string; childrenField?: string; cacheName?: string; url: string; psPlaceholder?: string; psOptions?: any[]; psValueField?: string; psLabelField?: string; psChildrenField?: string; psCacheName?: string; value?: any[]; psUrl: string; } export class PmSelectorComponent extends ValueComponent<any[]> { placeholder: string; valueField: string; labelField: string; childrenField: string; cacheName: string; value: any[]; private _options: any[] = []; get options(): any[] { return this._options; } set options(value: any[]) { this._options = value; this.convertedOptions = this.convert( value, this.valueField, this.labelField, this.childrenField, null, this.value, ); this.leafOptions = this.leafChildren(this.convertedOptions); this.loadCommonOption(); this.update(); } private _url: string; get url(): string { return this._url; } set url(value: string) { this._url = value; window['$'].get(value, (res) => { if (res && res.success) { this.options = res.result; } }); } convertedOptions: PmSelectorOption[] = []; readonly saveCommonMax = 10; open = false; commonOptions: PmSelectorOption[] = []; commonCheckedAll = false; selectedIndexes: number[] = []; leafOptions: PmSelectorOption[] = []; searchText = ''; searchOptions: PmSelectorOption[] = []; searchCheckedAll = false; showSearch = true; get columns(): PmSelectorOption[][] { let list = this.convertedOptions; const result = [list]; for (let i = 0; this.selectedIndexes[i] != null; i++) { const selectedIndex = this.selectedIndexes[i]; if ( list[selectedIndex] && list[selectedIndex].children && list[selectedIndex].children.length > 0 ) { list = list[selectedIndex].children; result.push(list); } else { break; } } return result; } // 获取被勾选的所有叶子节点 get checkedOptions(): PmSelectorOption[] { let checkedOptions = []; let options = this.convertedOptions; // 待搜索列表 while (options.length > 0) { // 新增放进待搜索列表 const currChecked = options.filter( (value) => (!value.children || !value.children.length) && value.checked, ); checkedOptions = checkedOptions.concat(currChecked); options = options .filter((value) => value.children && value.children.length) .flatMap((value) => value.children); // 搜索待搜索列表 } return checkedOptions; } // 用于界面展示 get checkedOptionStr(): string { return this.checkedOptions.map((value) => value.label).join(','); } constructor(args: PmSelectorComponentProps) { super(args); this.placeholder = args.psPlaceholder || args.placeholder; this.valueField = args.psValueField || args.valueField || 'value'; this.labelField = args.psLabelField || args.labelField || 'label'; this.childrenField = args.psChildrenField || args.childrenField || 'children'; this.cacheName = args.psCacheName || args.cacheName || 'commonOptions'; this.value = args.value || []; if (args.psOptions || args.options) { this.options = args.psOptions || args.options; } else if (args.psUrl || args.url) { this.url = args.psUrl || args.url; } } writeValue(value: string) { this.value = value ? value.split(',') : []; if (this.convertedOptions != null) { this.leafOptions.forEach((value1) => (value1.checked = this.value.includes(value1.value))); this.update(); } } // 组件声明周期hook,当组件创建后调用,此时尚未挂载DOM beforeMount() {} // 组件声明周期hook,当组件挂载DOM后调用 mounted() { document.addEventListener( 'click', (e: any) => { if (this.refs.popup) { const path = e.path || (e.composedPath && e.composedPath()); if ( !(this.refs.popup as HTMLElement).contains(e.target) && !path.includes(this.refs.popup) ) { this.closePopup(); } } if (this.refs.search) { const path = e.path || (e.composedPath && e.composedPath()); if ( !(this.refs.search as HTMLElement).contains(e.target) && !path.includes(this.refs.search) ) { this.closeSearchPopup(); } } }, true, ); } // 关闭搜索弹窗 closeSearchPopup() { this.showSearch = false; this.update(); } // 打开搜索弹窗 openSearchPopup = () => { this.showSearch = true; this.update(); }; // 勾选 checkOption(option: PmSelectorOption, checked: boolean) { option.checked = checked; this.checkChildren(option, checked); this.checkAll(option.parent); this.checkCommonOption(); this.checkSearchOption(); this.onChange(this.checkedOptions.map((value1) => value1.value)); this.update(); } commonCheckAll = (e: Event) => { const checked = e.target['checked']; this.commonOptions.forEach((value) => this.checkOption(value, checked)); this.update(); }; leafChildren(options: PmSelectorOption[]): PmSelectorOption[] { const childrenLeaf = options.flatMap((value) => this.leafChildren(value.children)); const leaf = options.filter((value) => !value.children || !value.children.length); return [...childrenLeaf, ...leaf]; } clear = () => { this.searchText = ''; this.commonCheckedAll = false; this.checkedOptions.forEach((value) => { value.checked = false; this.checkAll(value.parent); }); this.update(); this.onChange([]); }; searchChange = (e: Event) => { this.searchText = e.target['value']; this.searchOptions = this.leafOptions.filter((value) => { return value.label && value.label.includes(this.searchText); }); this.checkSearchOption(); this.update(); }; searchCheckAll = (e) => { const checked = e.target['checked']; this.searchOptions.forEach((value) => this.checkOption(value, checked)); this.update(); }; openPopup = (e: Event) => { e.stopPropagation(); this.open = true; this.update(); }; closePopup() { this.open = false; this.searchText = ''; this.update(); } // 格式化外部option为内部option convert( options: any[], valueField, labelField, childrenField, parent: PmSelectorOption, values?: any[], ): PmSelectorOption[] { return (options || []).map((option) => { const obj: PmSelectorOption = { value: option[valueField], label: option[labelField], checked: (values || []).includes(String(option[valueField])), parent, }; obj.children = this.convert( option[childrenField] || [], valueField, labelField, childrenField, obj, values, ); return obj; }); } optionChange(e: Event, option: PmSelectorOption) { const checked = e.target['checked']; this.checkOption(option, checked); this.update(); } // 判断父节点是否需要勾选(当子节点全选时) checkAll(option: PmSelectorOption) { if (!option) { return; } const check = option.children && option.children.length > 0 && option.children.every((value) => value.checked); if (check !== option.checked) { option.checked = check; this.checkAll(option.parent); } } // 设置option的check状态,并递归更新子节点,然后saveCommonOption checkChildren(option: PmSelectorOption, check: boolean) { option.checked = check; if (option.children && option.children.length > 0) { option.children.forEach((value) => { this.checkChildren(value, check); }); } else if (check) { // 如果是被选中的叶子节点 this.saveCommonOption(option); } } // 展开下一级菜单 nextLevel(level: number, index: number) { this.selectedIndexes = this.selectedIndexes.slice(0, level); this.selectedIndexes[level] = index; this.update(); } // 保存常用选择到localStorage中 saveCommonOption(option: PmSelectorOption) { if (this.commonOptions.includes(option)) { return; } this.commonOptions.unshift(option); if (this.commonOptions.length > this.saveCommonMax) { this.commonOptions = this.commonOptions.slice(0, this.saveCommonMax); } const commonOptions = this.commonOptions.map((value) => value.value); localStorage.setItem(this.cacheName, JSON.stringify(commonOptions)); } // 加载localStorage中的常用选择 loadCommonOption() { const commonOptions: string[] = JSON.parse(localStorage.getItem(this.cacheName)) || []; this.commonOptions = commonOptions .map((value) => this.leafOptions.find((value1) => value1.value === value)) .filter((value) => value); } // 更新常用选择全选状态 checkCommonOption() { this.commonCheckedAll = this.commonOptions && this.commonOptions.length && this.commonOptions.every((value) => value.checked); } // 更新搜索选择全选状态 checkSearchOption() { this.searchCheckedAll = this.searchOptions && this.searchOptions.length && this.searchOptions.every((value) => value.checked); } render() { const checkedOptions = this.checkedOptions; let popup: VNode; if (this.open) { popup = ( <div class="ps-popup" ref="popup"> {/*搜索栏*/} <div class="ps-search-bar"> <div class="ps-search-input" ref="search"> <input type="text" class="form-control input-sm" value={this.searchText} oninput={this.searchChange} onfocus={this.openSearchPopup} placeholder="请输入搜索关键字" /> {this.searchText && this.showSearch && ( <div class="ps-search-popup"> <label class="ps-label"> <input class="ps-checkbox" type="checkbox" checked={this.searchCheckedAll} onchange={this.searchCheckAll} /> 全选 </label> <div class="ps-label ps-search-options"> {this.searchOptions.map((value) => ( <label key={value.value} class="ps-label ps-search-option"> <input class="ps-checkbox" type="checkbox" checked={value.checked} onchange={(e) => this.optionChange(e, value)} /> <span dangerouslySetInnerHTML={value.label.replace(this.searchText, (str) => str.fontcolor('#1481db'), )} ></span> </label> ))} </div> </div> )} </div> <button class="btn btn-default btn-sm" type="button" onclick={this.clear}> 清空 </button> </div> {/*常用选择*/} <div class="ps-commonly-used"> <label class="ps-label"> <input class="ps-checkbox" type="checkbox" checked={this.commonCheckedAll} onchange={this.commonCheckAll} /> 常用选择 </label> <div class="ps-commonly-used-options"> {this.commonOptions.map((value) => ( <label key={value.value} class="ps-label ps-commonly-used-option"> <input class="ps-checkbox" type="checkbox" checked={value.checked} onchange={(e) => this.optionChange(e, value)} /> {value.label} </label> ))} </div> </div> {/*options*/} <div class="ps-options"> {this.columns.map( (value, level) => value && ( <div class="ps-column"> {value.map((value1, index) => ( <div class={[ 'ps-option', value1.children && value1.children.length > 0 ? 'ps-option-next' : '', index === this.selectedIndexes[level] ? 'ps-option-selected' : '', ].join(' ')} onclick={() => this.nextLevel(level, index)} > <input class="ps-checkbox" type="checkbox" onchange={(e) => this.optionChange(e, value1)} checked={value1.checked} /> <div class="ps-option-text" title={value1.label}> {value1.label} </div> </div> ))} </div> ), )} </div> {/*已选择计数*/} <div class="ps-selected-cnt"> <span class="ps-selected-label">已选择</span> {String(checkedOptions.length)}/{this.leafOptions.length} </div> {/*已选择option*/} <div class="ps-selected-tags"> {checkedOptions.map((value) => ( <div class="ps-selected-tag"> {value.label} <span class="ps-close" onclick={() => this.checkOption(value, false)}> × </span> </div> ))} </div> </div> ); } return ( <div class="ps-selector" ref="selector"> <div class="input-group"> <input type="text" class="form-control input-sm ps-input" value={this.checkedOptionStr} placeholder={this.placeholder} onclick={this.openPopup} aria-describedby="basic-addon2" readonly /> <span class="input-group-addon" id="basic-addon2"> {this.checkedOptions.length}项 </span> </div> {popup} </div> ); } } // 挂载为jquery插件 mountComponent({ name: 'pmSelector', componentType: PmSelectorComponent, props: [ 'psValueField', 'psLabelField', 'psChildrenField', 'psPlaceholder', 'psUrl', 'psCacheName', ], });
the_stack
export namespace Mail { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Rich (styled) text */ export interface RichText { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Represents an inline text attachment. This class is used mainly for make commands. */ export interface Attachment { /** * The file for the attachment */ fileName(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into paragraphs. */ export interface Paragraph { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into words. */ export interface Word { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into characters. */ export interface Character { /** * The color of the character. */ color(): any; /** * The name of the font of the character. */ font(): string; /** * The size in points of the character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This subdivides the text into chunks that all have the same attributes. */ export interface AttributeRun { /** * The color of the first character. */ color(): any; /** * The name of the font of the first character. */ font(): string; /** * The size in points of the first character. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A new email message */ export interface OutgoingMessage { /** * The sender of the message */ sender(): string; /** * The subject of the message */ subject(): string; /** * Controls whether the message window is shown on the screen. The default is false */ visible(): boolean; /** * The signature of the message */ messageSignature(): any; /** * The unique identifier of the message */ id(): number; /** * Does nothing at all (deprecated) */ htmlContent(): string; /** * Does nothing at all (deprecated) */ vcardPath(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * DEPRECATED - DO NOT USE */ export interface LdapServer { /** * Does nothing at all (deprecated) */ enabled(): boolean; /** * Does nothing at all (deprecated) */ name(): string; /** * Does nothing at all (deprecated) */ port(): number; /** * Does nothing at all (deprecated) */ scope(): any; /** * Does nothing at all (deprecated) */ searchBase(): string; /** * Does nothing at all (deprecated) */ hostName(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * DEPRECATED - DO NOT USE */ export interface OLDMessageEditor { /** * DEPRECATED - DO NOT USE */ OLDComposeMessage(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Represents the object responsible for managing a viewer window */ export interface MessageViewer { /** * The top level Drafts mailbox */ draftsMailbox(): any; /** * The top level In mailbox */ inbox(): any; /** * The top level Junk mailbox */ junkMailbox(): any; /** * The top level Out mailbox */ outbox(): any; /** * The top level Sent mailbox */ sentMailbox(): any; /** * The top level Trash mailbox */ trashMailbox(): any; /** * The column that is currently sorted in the viewer */ sortColumn(): any; /** * Whether the viewer is sorted ascending or not */ sortedAscending(): boolean; /** * Controls whether the list of mailboxes is visible or not */ mailboxListVisible(): boolean; /** * Controls whether the preview pane of the message viewer window is visible or not */ previewPaneIsVisible(): boolean; /** * List of columns that are visible. The subject column and the message status column will always be visible */ visibleColumns(): any; /** * The unique identifier of the message viewer */ id(): number; /** * List of messages currently being displayed in the viewer */ visibleMessages(): any; /** * List of messages currently selected */ selectedMessages(): any; /** * List of mailboxes currently selected in the list of mailboxes */ selectedMailboxes(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Email signatures */ export interface Signature { /** * Contents of email signature. If there is a version with fonts and/or styles, that will be returned over the plain text version */ content(): string; /** * Name of the signature */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An email message */ export interface Message { /** * The unique identifier of the message. */ id(): number; /** * All the headers of the message */ allHeaders(): string; /** * The background color of the message */ backgroundColor(): any; /** * The mailbox in which this message is filed */ mailbox(): any; /** * Contents of an email message */ content(): any; /** * The date a message was received */ dateReceived(): any; /** * The date a message was sent */ dateSent(): any; /** * Indicates whether the message is deleted or not */ deletedStatus(): boolean; /** * Indicates whether the message is flagged or not */ flaggedStatus(): boolean; /** * The flag on the message, or -1 if the message is not flagged */ flagIndex(): number; /** * Indicates whether the message has been marked junk or evaluated to be junk by the junk mail filter. */ junkMailStatus(): boolean; /** * Indicates whether the message is read or not */ readStatus(): boolean; /** * The unique message ID string */ messageId(): string; /** * Raw source of the message */ source(): string; /** * The address that replies should be sent to */ replyTo(): string; /** * The size (in bytes) of a message */ messageSize(): number; /** * The sender of the message */ sender(): string; /** * The subject of the message */ subject(): string; /** * Indicates whether the message was forwarded or not */ wasForwarded(): boolean; /** * Indicates whether the message was redirected or not */ wasRedirected(): boolean; /** * Indicates whether the message was replied to or not */ wasRepliedTo(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A Mail account for receiving messages (POP/IMAP). To create a new receiving account, use the 'pop account', 'imap account', and 'iCloud account' objects */ export interface Account { /** * The delivery account used when sending mail from this account */ deliveryAccount(): any; /** * The name of an account */ name(): string; /** * The unique identifier of the account */ id(): string; /** * Password for this account. Can be set, but not read via scripting */ password(): string; /** * Preferred authentication scheme for account */ authentication(): any; /** * The type of an account */ accountType(): any; /** * The list of email addresses configured for an account */ emailAddresses(): any; /** * The users full name configured for an account */ fullName(): string; /** * Number of days before junk messages are deleted (0 = delete on quit, -1 = never delete) */ emptyJunkMessagesFrequency(): number; /** * Does nothing at all (deprecated) */ emptySentMessagesFrequency(): number; /** * Number of days before messages in the trash are permanently deleted (0 = delete on quit, -1 = never delete) */ emptyTrashFrequency(): number; /** * Indicates whether the messages in the junk messages mailboxes will be deleted on quit */ emptyJunkMessagesOnQuit(): boolean; /** * Does nothing at all (deprecated) */ emptySentMessagesOnQuit(): boolean; /** * Indicates whether the messages in deleted messages mailboxes will be permanently deleted on quit */ emptyTrashOnQuit(): boolean; /** * Indicates whether the account is enabled or not */ enabled(): boolean; /** * The user name used to connect to an account */ userName(): string; /** * The directory where the account stores things on disk */ accountDirectory(): any; /** * The port used to connect to an account */ port(): number; /** * The host name used to connect to an account */ serverName(): string; /** * Does nothing at all (deprecated) */ includeWhenGettingNewMail(): boolean; /** * Indicates whether messages that are deleted will be moved to the trash mailbox */ moveDeletedMessagesToTrash(): boolean; /** * Indicates whether SSL is enabled for this receiving account */ usesSsl(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An IMAP email account */ export interface ImapAccount { /** * Indicates whether an IMAP mailbox is automatically compacted when you quit Mail or switch to another mailbox */ compactMailboxesWhenClosing(): boolean; /** * Message caching setting for this account */ messageCaching(): any; /** * Indicates whether drafts will be stored on the IMAP server */ storeDraftsOnServer(): boolean; /** * Indicates whether junk mail will be stored on the IMAP server */ storeJunkMailOnServer(): boolean; /** * Indicates whether sent messages will be stored on the IMAP server */ storeSentMessagesOnServer(): boolean; /** * Indicates whether deleted messages will be stored on the IMAP server */ storeDeletedMessagesOnServer(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An iCloud or MobileMe email account */ export interface ICloudAccount {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A POP email account */ export interface PopAccount { /** * If message size (in bytes) is over this amount, Mail will prompt you asking whether you want to download the message (-1 = do not prompt) */ bigMessageWarningSize(): number; /** * Number of days before messages that have been downloaded will be deleted from the server (0 = delete immediately after downloading) */ delayedMessageDeletionInterval(): number; /** * Indicates whether POP account deletes messages on the server after downloading */ deleteMailOnServer(): boolean; /** * Indicates whether messages will be deleted from the server when moved from your POP inbox */ deleteMessagesWhenMovedFromInbox(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An SMTP account (for sending email) */ export interface SmtpServer { /** * The name of an account */ name(): string; /** * Password for this account. Can be set, but not read via scripting */ password(): string; /** * The type of an account */ accountType(): any; /** * Preferred authentication scheme for account */ authentication(): any; /** * Indicates whether the account is enabled or not */ enabled(): boolean; /** * The user name used to connect to an account */ userName(): string; /** * The port used to connect to an account */ port(): number; /** * The host name used to connect to an account */ serverName(): string; /** * Indicates whether SSL is enabled for this receiving account */ usesSsl(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A mailbox that holds messages */ export interface Mailbox { /** * The name of a mailbox */ name(): string; /** * The number of unread messages in the mailbox */ unreadCount(): number; account(): any; container(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Class for message rules */ export interface Rule { /** * If rule matches, apply this color */ colorMessage(): any; /** * If rule matches, delete message */ deleteMessage(): boolean; /** * If rule matches, prepend this text to the forwarded message. Set to empty string to include no prepended text */ forwardText(): string; /** * If rule matches, forward message to this address, or multiple addresses, separated by commas. Set to empty string to disable this action */ forwardMessage(): string; /** * If rule matches, mark message as flagged */ markFlagged(): boolean; /** * If rule matches, mark message with the specified flag. Set to -1 to disable this action */ markFlagIndex(): number; /** * If rule matches, mark message as read */ markRead(): boolean; /** * If rule matches, play this sound (specify name of sound or path to sound) */ playSound(): string; /** * If rule matches, redirect message to this address or multiple addresses, separate by commas. Set to empty string to disable this action */ redirectMessage(): string; /** * If rule matches, reply to message and prepend with this text. Set to empty string to disable this action */ replyText(): string; /** * If rule matches, run this compiled AppleScript file. Set to empty string to disable this action */ runScript(): any; /** * Indicates whether all conditions must be met for rule to execute */ allConditionsMustBeMet(): boolean; /** * If rule matches, copy to this mailbox */ copyMessage(): any; /** * If rule matches, move to this mailbox */ moveMessage(): any; /** * Indicates whether the color will be used to highlight the text or background of a message in the message list */ highlightTextUsingColor(): boolean; /** * Indicates whether the rule is enabled */ enabled(): boolean; /** * Name of rule */ name(): string; /** * Indicates whether the rule has a copy action */ shouldCopyMessage(): boolean; /** * Indicates whether the rule has a move action */ shouldMoveMessage(): boolean; /** * If rule matches, stop rule evaluation for this message */ stopEvaluatingRules(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Class for conditions that can be attached to a single rule */ export interface RuleCondition { /** * Rule expression field */ expression(): string; /** * Rule header key */ header(): string; /** * Rule qualifier */ qualifier(): any; /** * Rule type */ ruleType(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An email recipient */ export interface Recipient { /** * The recipients email address */ address(): string; /** * The name used for display */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An email recipient in the Bcc: field */ export interface BccRecipient {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An email recipient in the Cc: field */ export interface CcRecipient {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An email recipient in the To: field */ export interface ToRecipient {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A mailbox that contains other mailboxes. */ export interface Container {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A header value for a message. E.g. To, Subject, From. */ export interface Header { /** * Contents of the header */ content(): string; /** * Name of the header value */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file attached to a received message. */ export interface MailAttachment { /** * Name of the attachment */ name(): string; /** * MIME type of the attachment E.g. text/plain. */ MIMEType(): string; /** * Approximate size in bytes. */ fileSize(): number; /** * Indicates whether the attachment has been downloaded. */ downloaded(): boolean; /** * The unique identifier of the attachment. */ id(): string; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * Mail's top level scripting object. */ export interface Application { /** * Indicates whether you will be included in the Bcc: field of messages which you are composing */ alwaysBccMyself(): boolean; /** * Indicates whether you will be included in the Cc: field of messages which you are composing */ alwaysCcMyself(): boolean; /** * List of messages that the user has selected */ selection(): any; /** * The build number of the application */ applicationVersion(): string; /** * The interval (in minutes) between automatic fetches of new mail, -1 means to use an automatically determined interval */ fetchInterval(): number; /** * Number of background activities currently running in Mail, according to the Activity window */ backgroundActivityCount(): number; /** * Indicates whether user can choose a signature directly in a new compose window */ chooseSignatureWhenComposing(): boolean; /** * Indicates whether quoted text should be colored */ colorQuotedText(): boolean; /** * Default format for messages being composed or message replies */ defaultMessageFormat(): any; /** * Indicates whether images and attachments in HTML messages should be downloaded and displayed */ downloadHtmlAttachments(): boolean; /** * The top level Drafts mailbox */ draftsMailbox(): any; /** * Indicates whether group addresses will be expanded when entered into the address fields of a new compose message */ expandGroupAddresses(): boolean; /** * Font for plain text messages, only used if 'use fixed width font' is set to true */ fixedWidthFont(): string; /** * Font size for plain text messages, only used if 'use fixed width font' is set to true */ fixedWidthFontSize(): any; /** * Returns the same thing as application version (deprecated) */ frameworkVersion(): string; /** * This always returns default, and setting it doesn't do anything (deprecated) */ headerDetail(): any; /** * The top level In mailbox */ inbox(): any; /** * Indicates whether all of the original message will be quoted or only the text you have selected (if any) */ includeAllOriginalMessageText(): boolean; /** * Indicates whether the text of the original message will be included in replies */ quoteOriginalMessage(): boolean; /** * Indicates whether spelling will be checked automatically in messages being composed */ checkSpellingWhileTyping(): boolean; /** * The top level Junk mailbox */ junkMailbox(): any; /** * Color for quoted text with one level of indentation */ levelOneQuotingColor(): any; /** * Color for quoted text with two levels of indentation */ levelTwoQuotingColor(): any; /** * Color for quoted text with three levels of indentation */ levelThreeQuotingColor(): any; /** * Font for messages (proportional font) */ messageFont(): string; /** * Font size for messages (proportional font) */ messageFontSize(): any; /** * Font for message list */ messageListFont(): string; /** * Font size for message list */ messageListFontSize(): any; /** * Name of new mail sound or 'None' if no sound is selected */ newMailSound(): string; /** * The top level Out mailbox */ outbox(): any; /** * Indicates whether sounds will be played for various things such as when a messages is sent or if no mail is found when manually checking for new mail or if there is a fetch error */ shouldPlayOtherMailSounds(): boolean; /** * Indicates whether replies will be in the same text format as the message to which you are replying */ sameReplyFormat(): boolean; /** * Name of current selected signature (or 'randomly', 'sequentially', or 'none') */ selectedSignature(): string; /** * The top level Sent mailbox */ sentMailbox(): any; /** * Indicates whether mail will automatically be fetched at a specific interval */ fetchesAutomatically(): boolean; /** * Indicates whether messages in conversations should be highlighted in the Mail viewer window when not grouped */ highlightSelectedConversation(): boolean; /** * The top level Trash mailbox */ trashMailbox(): any; /** * This always returns true, and setting it doesn't do anything (deprecated) */ useAddressCompletion(): boolean; /** * Should fixed-width font be used for plain text messages? */ useFixedWidthFont(): boolean; /** * The user's primary email address */ primaryEmail(): string; /** * Indicates whether to log socket activity for the specified hosts */ hostsToLogActivityOn(): any; /** * Indicates whether to log socket activity for the specified ports */ portsToLogActivityOn(): any; /** * Indicates whether all socket activity will be logged */ logAllSocketActivity(): boolean; memoryStatistics(): any; /** * Ignored - Mail always uses the Keychain to store passwords */ useKeychain(): boolean; } // Records // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface DuplicateOptionalParameter { /** * The location for the new copy or copies. */ to?: any; /** * Properties to set in the new copy or copies right away. */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MoveOptionalParameter { /** * The new location for the object(s). */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CheckForNewMailOptionalParameter { /** * Specify the account that you wish to check for mail */ for?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ForwardOptionalParameter { /** * Whether the window for the forwarded message is shown. Default is to not show the window. */ openingWindow?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ImportMailMailboxOptionalParameter { /** * the mailbox or folder of mailboxes to import */ at: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PerformMailActionWithMessagesOptionalParameter { /** * If the script is being executed by the user selecting an item in the scripts menu, this argument will specify the mailboxes that are currently selected. Otherwise it will not be specified. */ inMailboxes?: any; /** * If the script is being executed by a rule action, this argument will be the rule being invoked. Otherwise it will not be specified. */ forRule?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RedirectOptionalParameter { /** * Whether the window for the redirected message is shown. Default is to not show the window. */ openingWindow?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ReplyOptionalParameter { /** * Whether the window for the reply message is shown. Default is to not show the window. */ openingWindow?: boolean; /** * Whether to reply to all recipients. Default is to reply to the sender only. */ replyToAll?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SynchronizeOptionalParameter { /** * The account to synchronize */ with: any; } } export interface Mail extends Mail.Application { // Functions /** * Delete an object. * @param directParameter The object(s) to delete. * */ delete(directParameter: any, ): void; /** * Copy an object. * @param directParameter The object(s) to copy. * @param option * */ duplicate(directParameter: any, option?: Mail.DuplicateOptionalParameter): void; /** * Move an object to a new location. * @param directParameter The object(s) to move. * @param option * */ move(directParameter: any, option?: Mail.MoveOptionalParameter): void; /** * Does nothing at all (deprecated) * @param directParameter the message to bounce * */ bounce(directParameter: Mail.Message, ): void; /** * Triggers a check for email. * @param option * */ checkForNewMail(option?: Mail.CheckForNewMailOptionalParameter): void; /** * Command to get the full name out of a fully specified email address. E.g. Calling this with "John Doe <jdoe@example.com>" as the direct object would return "John Doe" * @param directParameter fully formatted email address * @return the full name */ extractNameFrom(directParameter: string, ): string; /** * Command to get just the email address of a fully specified email address. E.g. Calling this with "John Doe <jdoe@example.com>" as the direct object would return "jdoe@example.com" * @param directParameter fully formatted email address * @return the email address */ extractAddressFrom(directParameter: string, ): string; /** * Creates a forwarded message. * @param directParameter the message to forward * @param option * @return the message to be forwarded */ forward(directParameter: Mail.Message, option?: Mail.ForwardOptionalParameter): Mail.OutgoingMessage; /** * Opens a mailto URL. * @param directParameter the mailto URL * */ getURL(directParameter: string, ): void; /** * Imports a mailbox created by Mail. * @param option * */ importMailMailbox(option?: Mail.ImportMailMailboxOptionalParameter): void; /** * Opens a mailto URL. * @param directParameter the mailto URL * */ mailto(directParameter: string, ): void; /** * Script handler invoked by rules and menus that execute AppleScripts. The direct parameter of this handler is a list of messages being acted upon. * @param directParameter the message being acted upon * @param option * */ performMailActionWithMessages(directParameter: {}, option?: Mail.PerformMailActionWithMessagesOptionalParameter): void; /** * Creates a redirected message. * @param directParameter the message to redirect * @param option * @return the redirected message */ redirect(directParameter: Mail.Message, option?: Mail.RedirectOptionalParameter): Mail.OutgoingMessage; /** * Creates a reply message. * @param directParameter the message to reply to * @param option * @return the reply message */ reply(directParameter: Mail.Message, option?: Mail.ReplyOptionalParameter): Mail.OutgoingMessage; /** * Sends a message. * @param directParameter the message to send * @return true if sending was successful, false if not */ send(directParameter: Mail.OutgoingMessage, ): boolean; /** * Command to trigger synchronizing of an IMAP account with the server. * @param option * */ synchronize(option?: Mail.SynchronizeOptionalParameter): void; }
the_stack
import * as React from 'react'; import * as renderer from 'react-test-renderer'; import { mount } from 'enzyme'; import { resetIds } from '@fluentui/utilities'; import { MessageBar } from './MessageBar'; import { MessageBarType } from './MessageBar.types'; import { isConformant } from '../../common/isConformant'; describe('MessageBar', () => { beforeEach(() => { resetIds(); }); afterEach(() => { if ((setTimeout as any).mock) { jest.useRealTimers(); } }); const noop = () => { /* no-op */ }; describe('snapshots', () => { beforeEach(() => { jest.useFakeTimers(); }); it('renders MessageBar correctly', () => { const component = renderer.create(<MessageBar>Message</MessageBar>); // The message is delay-rendered. Run timers to show it. jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a info MessageBar correctly', () => { const component = renderer.create(<MessageBar messageBarType={MessageBarType.info}>Message</MessageBar>); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a warning MessageBar correctly', () => { const component = renderer.create(<MessageBar messageBarType={MessageBarType.warning}>Message</MessageBar>); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a error MessageBar correctly', () => { const component = renderer.create(<MessageBar messageBarType={MessageBarType.error}>Message</MessageBar>); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a severeWarning MessageBar correctly', () => { const component = renderer.create(<MessageBar messageBarType={MessageBarType.severeWarning}>Message</MessageBar>); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a success MessageBar correctly', () => { const component = renderer.create(<MessageBar messageBarType={MessageBarType.success}>Message</MessageBar>); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a multiline MessageBar correctly', () => { const component = renderer.create(<MessageBar isMultiline={true}>Message</MessageBar>); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a multiline info MessageBar correctly', () => { const component = renderer.create( <MessageBar messageBarType={MessageBarType.info} isMultiline={true}> Message </MessageBar>, ); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a multiline warning MessageBar correctly', () => { const component = renderer.create( <MessageBar messageBarType={MessageBarType.warning} isMultiline={true}> Message </MessageBar>, ); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a multiline error MessageBar correctly', () => { const component = renderer.create( <MessageBar messageBarType={MessageBarType.error} isMultiline={true}> Message </MessageBar>, ); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a multiline severeWarning MessageBar correctly', () => { const component = renderer.create( <MessageBar messageBarType={MessageBarType.severeWarning} isMultiline={true}> Message </MessageBar>, ); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); it('renders a multiline success MessageBar correctly', () => { const component = renderer.create( <MessageBar messageBarType={MessageBarType.success} isMultiline={true}> Message </MessageBar>, ); jest.runOnlyPendingTimers(); const tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); }); isConformant({ Component: MessageBar, displayName: 'MessageBar', }); it('renders custom message bar icon correctly', () => { const wrapper = mount( <MessageBar messageBarType={MessageBarType.success} messageBarIconProps={{ iconName: 'AddFriend' }} />, ); const dismissIcon = wrapper.find('[data-icon-name="AddFriend"]'); expect(dismissIcon.exists()).toBe(true); }); it('can reflect props changes', () => { const wrapper = mount(<MessageBar messageBarType={MessageBarType.success} />); expect(wrapper.find('.ms-MessageBar--success').length).toEqual(1); wrapper.setProps({ messageBarType: MessageBarType.error }); expect(wrapper.find('.ms-MessageBar--success').length).toEqual(0); expect(wrapper.find('.ms-MessageBar--error').length).toEqual(1); }); it('delay renders message by default', () => { jest.useFakeTimers(); const wrapper = mount( <MessageBar> <span id="test">content</span> </MessageBar>, ); // message not rendered initially expect(wrapper.find('#test')).toHaveLength(0); // run timers to render jest.runOnlyPendingTimers(); // update recorded state of wrapper so .find() works wrapper.update(); // message is rendered expect(wrapper.find('#test')).toHaveLength(1); expect(wrapper.find('#test').text()).toBe('content'); }); it('can disable delayed rendering', () => { jest.useFakeTimers(); const wrapper = mount( <MessageBar delayedRender={false}> <span id="test">content</span> </MessageBar>, ); // message IS rendered initially expect(wrapper.find('#test')).toHaveLength(1); expect(wrapper.find('#test').text()).toBe('content'); }); it('respects updates to message', () => { jest.useFakeTimers(); const wrapper = mount( <MessageBar> <span id="test1">content 1</span> </MessageBar>, ); // run timers to render jest.runOnlyPendingTimers(); wrapper.update(); // check for first message expect(wrapper.find('#test1').text()).toBe('content 1'); // update message wrapper.setProps({ children: <span id="test2">content 2</span> }); wrapper.update(); expect(wrapper.find('#test1')).toHaveLength(0); expect(wrapper.find('#test2')).toHaveLength(1); expect(wrapper.find('#test2').text()).toBe('content 2'); }); describe('dismiss', () => { describe('single-line', () => { it('is present when onDismiss exists', () => { const wrapper = mount(<MessageBar onDismiss={noop} isMultiline={false} />); const dismissElement = wrapper.find('.ms-MessageBar-dismissal'); expect(dismissElement.exists()).toBe(true); }); it('is not present when onDismiss is missing', () => { const wrapper = mount(<MessageBar isMultiline={false} />); const dismissElement = wrapper.find('.ms-MessageBar-dismissal'); expect(dismissElement.exists()).toBe(false); }); it('has custom dismiss icon', () => { const wrapper = mount( <MessageBar onDismiss={noop} isMultiline={false} dismissIconProps={{ iconName: 'AddFriend' }} />, ); const dismissIcon = wrapper.find('[data-icon-name="AddFriend"]'); expect(dismissIcon.exists()).toBe(true); }); it('mixes in native props to the inner text element, except className', () => { const wrapper = mount( <MessageBar aria-live={'polite'} isMultiline={false} className={'sampleClassName'}> Message </MessageBar>, ); const innerText = wrapper.find('.ms-MessageBar-innerText'); expect(innerText.prop('aria-live')).toEqual('polite'); const singleLine = wrapper.find('.ms-MessageBar-singleline'); expect(singleLine.prop('className')).toContain('sampleClassName'); expect(innerText.prop('className')).not.toContain('sampleClassName'); }); }); describe('multi-line', () => { it('is present when onDismiss exists', () => { const wrapper = mount(<MessageBar onDismiss={noop} isMultiline={true} />); const dismissElement = wrapper.find('.ms-MessageBar-dismissal'); expect(dismissElement.exists()).toBe(true); }); it('is not present when onDismiss is missing', () => { const wrapper = mount(<MessageBar isMultiline={true} />); const dismissElement = wrapper.find('.ms-MessageBar-dismissal'); expect(dismissElement.exists()).toBe(false); }); it('mixes in native props to the inner text element', () => { const wrapper = mount( <MessageBar aria-live={'polite'} isMultiline={true}> Message </MessageBar>, ); const innerText = wrapper.find('.ms-MessageBar-innerText'); expect(innerText.prop('aria-live')).toEqual('polite'); }); }); }); describe('truncated', () => { it('is present when onDismiss exists', () => { const wrapper = mount(<MessageBar truncated={true} isMultiline={false} />); const expandElement = wrapper.find('.ms-MessageBar-expand'); expect(expandElement.exists()).toBe(true); }); it('is not present when truncated is missing', () => { const wrapper = mount(<MessageBar isMultiline={false} />); const expandElement = wrapper.find('.ms-MessageBar-expand'); expect(expandElement.exists()).toBe(false); }); }); describe('role attribute', () => { it('is present only once', () => { const wrapper = mount(<MessageBar />); const roleElements = wrapper.find('.ms-MessageBar [role]'); expect(roleElements.length).toBe(1); }); it('is present only once when custom role attribute exists', () => { const role = 'none'; const wrapper = mount(<MessageBar role={role} />); const roleElements = wrapper.find('.ms-MessageBar [role]'); expect(roleElements.length).toBe(1); expect(roleElements.prop('role')).toBe(role); }); it('uses correct default based on messageBarType', () => { const wrapper = mount(<MessageBar>content</MessageBar>); // Status messages for (const messageBarType of [MessageBarType.info, MessageBarType.success, MessageBarType.warning]) { const typeName = `MessageBarType.${MessageBarType[messageBarType]}`; wrapper.setProps({ messageBarType }); wrapper.update(); const roleElem = wrapper.find('[role]'); expect(roleElem).toHaveLength(1); // include the MessageBarType in the assertion so it's clearer what failed expect([typeName, roleElem.prop('role')]).toEqual([typeName, 'status']); expect([typeName, roleElem.prop('aria-live')]).toEqual([typeName, 'polite']); } // Alert messages for (const messageBarType of [MessageBarType.error, MessageBarType.blocked, MessageBarType.severeWarning]) { const typeName = `MessageBarType.${MessageBarType[messageBarType]}`; wrapper.setProps({ messageBarType }); wrapper.update(); const roleElem = wrapper.find('[role]'); expect(roleElem).toHaveLength(1); expect([typeName, roleElem.prop('role')]).toEqual([typeName, 'alert']); expect([typeName, roleElem.prop('aria-live')]).toEqual([typeName, 'assertive']); } }); }); });
the_stack
import * as React from "react"; import { ImageBackground, Animated } from "react-native"; import { Heroes } from "../../assets"; import { Colors, Shadows } from "../../components"; import { TestGroup } from "../../types"; import { FastImage } from "./FastImage"; //import { PhotoView } from "./PhotoView"; import { TestImage } from "./TestImage"; export function createImageTests(config: { title: string; name: string; props: any; }): TestGroup { const { title, name, props } = config; const startProps = props; const endProps = props; return { name: title, tests: [ { name: `${name} Move & Scale`, tests: [ { name: "Simple move", description: "The most basic form of a shared-element transition. The image should move smoothly without flickering from the start- to the end state, and back", start: <TestImage {...startProps} />, end: <TestImage {...endProps} end />, }, { name: "Move & scale", description: "Another basic form of a shared-element transition. The image should move & scale correctly without flickering from the start- to the end state, and back", start: <TestImage {...startProps} size="small" />, end: <TestImage {...endProps} end size="large" />, }, { name: "Full size", description: "When images are small they are stored with a lower resolution to optimize memory usage. When transitioning to a larger image, the higher resolution image should be used and you should not see a low-res/blurred image.", start: <TestImage {...startProps} size="small" />, end: <TestImage {...endProps} end size="max" />, }, ], }, { name: `${name} Resize-modes`, tests: [ { name: "Cover ➔ Contain", description: "Images may have different resize-mode props. The image should correctly transition from one resize mode to another", start: ( <TestImage {...startProps} size="small" resizeMode="cover" /> ), end: ( <TestImage {...endProps} end size="large" resizeMode="contain" /> ), }, { name: "Cover ➔ Stretch", description: "Images may have different resize-mode props. The image should correctly transition from one resize mode to another", start: ( <TestImage {...startProps} size="small" resizeMode="cover" /> ), end: ( <TestImage {...endProps} end size="large" resizeMode="stretch" /> ), }, { name: "Cover ➔ Center", description: "Images may have different resize-mode props. The image should correctly transition from one resize mode to another", start: ( <TestImage {...startProps} size="small" resizeMode="cover" /> ), end: ( <TestImage {...endProps} end size="large" resizeMode="center" /> ), }, { name: "Contain ➔ Stretch", description: "Images may have different resize-mode props. The image should correctly transition from one resize mode to another", start: ( <TestImage {...startProps} size="regular" resizeMode="contain" /> ), end: ( <TestImage {...endProps} end size="regular" resizeMode="stretch" /> ), }, { name: "Contain ➔ Center", description: "Images may have different resize-mode props. The image should correctly transition from one resize mode to another", start: ( <TestImage {...startProps} size="regular" resizeMode="contain" /> ), end: ( <TestImage {...endProps} end size="large" resizeMode="center" /> ), }, { name: "Stretch ➔ Center", description: "Images may have different resize-mode props. The image should correctly transition from one resize mode to another", start: ( <TestImage {...startProps} size="regular" resizeMode="stretch" /> ), end: ( <TestImage {...endProps} end size="large" resizeMode="center" /> ), }, ], }, { name: `${name} Styles`, tests: [ { name: "Opacity change", description: "The transition should use the start- and ending opacity of the image and create a smooth transition.", start: ( <TestImage {...startProps} size="regular" round style={{ opacity: 0.5 }} /> ), end: <TestImage {...endProps} end size="regular" round />, }, { name: "Border-radius change", description: "It's a common case that the border-radius of the start- and end image are not the same. The border-radius should correctly animate for the transition.", start: <TestImage {...startProps} size="regular" round />, end: <TestImage {...endProps} end size="regular" />, }, { name: "Border-radius some corners", description: "The border-radius should animate correct when only set for some corners.", start: ( <TestImage {...startProps} size="regular" style={{ borderTopLeftRadius: 20, borderTopRightRadius: 20 }} /> ), end: <TestImage {...endProps} end size="regular" />, }, { name: "Border-radius & contain", description: "It's a common case that the border-radius of the start- and end image are not the same. The border-radius should correctly animate for the transition.", start: ( <TestImage {...startProps} size="regular" round resizeMode="contain" /> ), end: <TestImage {...endProps} end size="regular" />, }, { name: "Border-radius & size", description: "It's a common case that the border-radius of the start- and end image are not the same. The border-radius should correctly animate for the transition.", start: <TestImage {...startProps} size="regular" round />, end: <TestImage {...endProps} end size="max" />, }, { name: "Border-radius & resizeMode", description: "It's a common case that the border-radius of the start- and end image are not the same. The border-radius should correctly animate for the transition.", start: ( <TestImage {...startProps} size="regular" round resizeMode="cover" /> ), end: ( <TestImage {...endProps} end size="regular" resizeMode="contain" /> ), }, { name: "Border ➔ No-border", description: "The transition should use the start- and ending opacity of the image and create a smooth transition.", start: ( <TestImage {...startProps} size="regular" round style={{ borderWidth: 5, borderColor: Colors.blue }} /> ), end: <TestImage {...endProps} end size="regular" round />, }, { name: "Border ➔ Other border", description: "The transition should use the start- and ending opacity of the image and create a smooth transition.", start: ( <TestImage {...startProps} size="regular" round style={{ borderWidth: 5, borderColor: Colors.blue }} /> ), end: ( <TestImage {...endProps} end size="regular" round style={{ borderWidth: 2, borderColor: Colors.yellow }} /> ), }, { name: "Shadow ➔ No shadow", description: "The transition should use the start- and ending opacity of the image and create a smooth transition.", start: ( <TestImage {...startProps} size="regular" round style={{ ...Shadows.elevation2, backgroundColor: "white" }} /> ), end: <TestImage {...endProps} end size="regular" round />, }, { name: "Resize-mode & Border & Radius", description: "Should look good", start: ( <TestImage {...startProps} size="regular" resizeMode="cover" round style={{ borderWidth: 2, borderColor: "green", }} /> ), end: ( <TestImage {...endProps} end size="large" resizeMode="contain" round style={{ borderWidth: 2, borderColor: "blue", }} /> ), }, ], }, { name: `${name} Fade`, description: 'When two images are distinctly different, the "fade" animation should create a smooth cross fade between the content', tests: [ { name: "Fade", start: ( <TestImage {...startProps} size="regular" resizeMode="cover" /> ), end: <TestImage {...endProps} end size="large" hero={Heroes[2]} />, animation: "fade", }, { name: "Fade != aspect-ratios", start: ( <TestImage {...startProps} size="regular" resizeMode="contain" /> ), end: ( <TestImage {...endProps} end size="large" hero={Heroes[8]} resizeMode="cover" /> ), animation: "fade", }, ], }, ], }; } export const ImageTests = createImageTests({ title: "Images", name: "Image", props: {}, }); export const ImageBackgroundTests = createImageTests({ title: "ImageBackground Component", name: "ImageBackground", props: { ImageComponent: ImageBackground, }, }); ImageTests.tests.push(ImageBackgroundTests); export const AnimatedImageTests = createImageTests({ title: "Animated.Image Component", name: "Animated.Image", props: { ImageComponent: Animated.Image, }, }); ImageTests.tests.push(AnimatedImageTests); export const FastImageTests = createImageTests({ title: "FastImage Component", name: "FastImage", props: { ImageComponent: FastImage, }, }); ImageTests.tests.push(FastImageTests); const oldTests: TestGroup = { name: "Other Image Components", tests: [ /*{ name: "react-native-photo-view", description: "TODO - This one doesnt work yet", start: <TestImage size="regular" resizeMode="cover" />, end: ( <TestImage end size="large" resizeMode="contain" ImageComponent={(props: any) => ( <PhotoView {...props} minimumZoomScale={0.5} maximumZoomScale={3} androidScaleType="center" /> )} /> ) },*/ { name: "react-native-image-pan-zoom", description: "react-native-image-pan-zoom offers zoom & panning abilities for Images. The underlying image should be correctly detected and you should not see any stretching", start: <TestImage size="small" resizeMode="cover" panZoom />, end: <TestImage end size="max" resizeMode="contain" panZoom />, }, ], }; ImageTests.tests.push(oldTests);
the_stack
import {isCancel} from 'cancel-token'; import * as path from 'path'; import {ForkOptions, LazyEdgeMap, NoKnownParserError, Options, ScannerTable} from '../core/analyzer'; import {CssCustomPropertyScanner} from '../css/css-custom-property-scanner'; import {CssParser} from '../css/css-parser'; import {HtmlCustomElementReferenceScanner} from '../html/html-element-reference-scanner'; import {HtmlImportScanner} from '../html/html-import-scanner'; import {HtmlParser} from '../html/html-parser'; import {HtmlScriptScanner} from '../html/html-script-scanner'; import {HtmlStyleScanner} from '../html/html-style-scanner'; import {ClassScanner} from '../javascript/class-scanner'; import {FunctionScanner} from '../javascript/function-scanner'; import {InlineHtmlDocumentScanner} from '../javascript/html-template-literal-scanner'; import {JavaScriptExportScanner} from '../javascript/javascript-export-scanner'; import {JavaScriptImportScanner} from '../javascript/javascript-import-scanner'; import {JavaScriptParser} from '../javascript/javascript-parser'; import {NamespaceScanner} from '../javascript/namespace-scanner'; import {JsonParser} from '../json/json-parser'; import {Result} from '../model/analysis'; import {Document, InlineDocInfo, LocationOffset, ScannedDocument, ScannedElement, ScannedImport, ScannedInlineDocument, Severity, Warning, WarningCarryingException} from '../model/model'; import {PackageRelativeUrl, ResolvedUrl} from '../model/url'; import {ParsedDocument, UnparsableParsedDocument} from '../parser/document'; import {Parser} from '../parser/parser'; import {BehaviorScanner} from '../polymer/behavior-scanner'; import {CssImportScanner} from '../polymer/css-import-scanner'; import {DomModuleScanner} from '../polymer/dom-module-scanner'; import {PolymerCoreFeatureScanner} from '../polymer/polymer-core-feature-scanner'; import {PolymerElementScanner} from '../polymer/polymer-element-scanner'; import {PseudoElementScanner} from '../polymer/pseudo-element-scanner'; import {scan} from '../scanning/scan'; import {Scanner} from '../scanning/scanner'; import {PackageUrlResolver} from '../url-loader/package-url-resolver'; import {UrlLoader} from '../url-loader/url-loader'; import {UrlResolver} from '../url-loader/url-resolver'; import {AnalysisCache} from './analysis-cache'; import {MinimalCancelToken} from './cancel-token'; import {LanguageAnalyzer} from './language-analyzer'; export const analyzerVersion: string = require('../../package.json').version; /** * An analysis of a set of files at a specific point-in-time with respect to * updates to those files. New files can be added to an existing context, but * updates to files will cause a fork of the context with new analysis results. * * All file contents and analysis results are consistent within a single * anaysis context. A context is forked via either the fileChanged or * clearCaches methods. * * For almost all purposes this is an entirely internal implementation detail. * An Analyzer instance has a reference to its current context, so it will * appear to be statefull with respect to file updates. */ export class AnalysisContext { readonly parsers = new Map<string, Parser<ParsedDocument>>([ ['html', new HtmlParser()], ['js', new JavaScriptParser()], ['mjs', new JavaScriptParser()], ['css', new CssParser()], ['json', new JsonParser()], ]); private readonly _languageAnalyzers = new Map<string, LanguageAnalyzer<{}>>([ // TODO(rictic): add typescript language analyzer back after investigating // https://github.com/Polymer/polymer-analyzer/issues/623 ]); /** A map from import url to urls that document lazily depends on. */ private readonly _lazyEdges: LazyEdgeMap|undefined; private readonly _scanners: ScannerTable; readonly loader: UrlLoader; readonly resolver: UrlResolver; private readonly _cache: AnalysisCache; /** Incremented each time we fork. Useful for debugging. */ private readonly _generation: number; /** * Resolves when the previous analysis has completed. * * Used to serialize analysis requests, not for correctness surprisingly * enough, but for performance, so that we can reuse AnalysisResults. */ private _analysisComplete: Promise<void>; static getDefaultScanners(options: Options) { return new Map<string, Scanner<ParsedDocument, {}|null|undefined, {}>[]>([ [ 'html', [ new HtmlImportScanner(options.lazyEdges), new HtmlScriptScanner(), new HtmlStyleScanner(), new DomModuleScanner(), new CssImportScanner(), new HtmlCustomElementReferenceScanner(), new PseudoElementScanner(), ] ], [ 'js', [ new PolymerElementScanner(), new PolymerCoreFeatureScanner(), new BehaviorScanner(), new NamespaceScanner(), new FunctionScanner(), new ClassScanner(), new JavaScriptImportScanner( {moduleResolution: options.moduleResolution}), new JavaScriptExportScanner(), new InlineHtmlDocumentScanner(), ] ], ['css', [new CssCustomPropertyScanner()]] ]); } constructor(options: Options, cache?: AnalysisCache, generation?: number) { this.loader = options.urlLoader; this.resolver = options.urlResolver || new PackageUrlResolver(); this.parsers = options.parsers || this.parsers; this._lazyEdges = options.lazyEdges; this._scanners = options.scanners || AnalysisContext.getDefaultScanners(options); this._cache = cache || new AnalysisCache(); this._generation = generation || 0; this._analysisComplete = Promise.resolve(); } /** * Returns a copy of this cache context with proper cache invalidation. */ filesChanged(urls: PackageRelativeUrl[]) { const newCache = this._cache.invalidate(this.resolveUserInputUrls(urls)); return this._fork(newCache); } /** * Implements Analyzer#analyze, see its docs. */ async analyze(urls: PackageRelativeUrl[], cancelToken: MinimalCancelToken): Promise<AnalysisContext> { const resolvedUrls = this.resolveUserInputUrls(urls); // 1. Await current analysis if there is one, so we can check to see if it // has all of the requested URLs. await this._analysisComplete; // 2. Check to see if we have all of the requested documents const hasAllDocuments = resolvedUrls.every( (url) => this._cache.analyzedDocuments.get(url) != null); if (hasAllDocuments) { // all requested URLs are present, return the existing context return this; } // 3. Some URLs are new, so fork, but don't invalidate anything const newCache = this._cache.invalidate([]); const newContext = this._fork(newCache); return newContext._analyze(resolvedUrls, cancelToken); } /** * Internal analysis method called when we know we need to fork. */ private async _analyze( resolvedUrls: ResolvedUrl[], cancelToken: MinimalCancelToken): Promise<AnalysisContext> { const analysisComplete = (async () => { // 1. Load and scan all root documents const maybeScannedDocuments = await Promise.all(resolvedUrls.map(async (url) => { try { const scannedResult = await this.scan(url, cancelToken); if (scannedResult.successful === true) { this._cache.failedDocuments.delete(url); return scannedResult.value; } else { this._cache.failedDocuments.set(url, scannedResult.error); return undefined; } } catch (e) { if (isCancel(e)) { return; } // This is a truly unexpected error. We should fail. throw e; } })); const scannedDocuments = maybeScannedDocuments.filter( (d) => d !== undefined) as ScannedDocument[]; // 2. Run per-document resolution const documents = scannedDocuments.map((d) => this.getDocument(d.url)); // TODO(justinfagnani): instead of the above steps, do: // 1. Load and run prescanners // 2. Run global analyzers (_languageAnalyzers now, but it doesn't need to // be separated by file type) // 3. Run per-document scanners and resolvers return documents; })(); this._analysisComplete = analysisComplete.then((_) => {}); await this._analysisComplete; return this; } /** * Gets an analyzed Document from the document cache. This is only useful for * Analyzer plugins. You almost certainly want to use `analyze()` instead. * * If a document has been analyzed, it returns the analyzed Document. If not * the scanned document cache is used and a new analyzed Document is returned. * If a file is in neither cache, it returns `undefined`. */ getDocument(resolvedUrl: ResolvedUrl): Document|Warning { const cachedWarning = this._cache.failedDocuments.get(resolvedUrl); if (cachedWarning) { return cachedWarning; } const cachedResult = this._cache.analyzedDocuments.get(resolvedUrl); if (cachedResult) { return cachedResult; } const scannedDocument = this._cache.scannedDocuments.get(resolvedUrl); if (!scannedDocument) { return makeRequestedWithoutLoadingWarning(resolvedUrl); } const extension = path.extname(resolvedUrl).substring(1); const languageAnalyzer = this._languageAnalyzers.get(extension); let analysisResult; if (languageAnalyzer) { analysisResult = languageAnalyzer.analyze(scannedDocument.url); } const document = new Document(scannedDocument, this, analysisResult); this._cache.analyzedDocuments.set(resolvedUrl, document); this._cache.analyzedDocumentPromises.getOrCompute( resolvedUrl, async () => document); document.resolve(); return document; } /** * This is only useful for Analyzer plugins. * * If a url has been scanned, returns the ScannedDocument. */ _getScannedDocument(resolvedUrl: ResolvedUrl): ScannedDocument|undefined { return this._cache.scannedDocuments.get(resolvedUrl); } /** * Clear all cached information from this analyzer instance. * * Note: if at all possible, instead tell the analyzer about the specific * files that changed rather than clearing caches like this. Caching provides * large performance gains. */ clearCaches(): AnalysisContext { return this._fork(new AnalysisCache()); } /** * Returns a copy of the context but with optional replacements of cache or * constructor options. * * Note: this feature is experimental. */ _fork(cache?: AnalysisCache, options?: ForkOptions): AnalysisContext { const contextOptions: Options = { lazyEdges: this._lazyEdges, parsers: this.parsers, scanners: this._scanners, urlLoader: this.loader, urlResolver: this.resolver, }; if (options && options.urlLoader) { contextOptions.urlLoader = options.urlLoader; } if (!cache) { cache = this._cache.invalidate([]); } const copy = new AnalysisContext(contextOptions, cache, this._generation + 1); return copy; } /** * Scans a file locally, that is for features that do not depend * on this files imports. Local features can be cached even when * imports are invalidated. This method does not trigger transitive * scanning, _scan() does that. * * TODO(justinfagnani): consider renaming this to something like * _preScan, since about the only useful things it can find are * imports, exports and other syntactic structures. */ private async _scanLocal( resolvedUrl: ResolvedUrl, cancelToken: MinimalCancelToken): Promise<Result<ScannedDocument, Warning>> { return this._cache.scannedDocumentPromises.getOrCompute( resolvedUrl, async () => { const parsedDocResult = await this._parse(resolvedUrl, cancelToken); if (parsedDocResult.successful === false) { this._cache.dependencyGraph.rejectDocument( resolvedUrl, new WarningCarryingException(parsedDocResult.error)); return parsedDocResult; } const parsedDoc = parsedDocResult.value; try { const scannedDocument = await this._scanDocument(parsedDoc); const imports = scannedDocument.getNestedFeatures().filter( (e) => e instanceof ScannedImport) as ScannedImport[]; // Update dependency graph const importUrls = filterOutUndefineds(imports.map( (i) => i.url === undefined ? undefined : this.resolver.resolve(parsedDoc.baseUrl, i.url, i))); this._cache.dependencyGraph.addDocument(resolvedUrl, importUrls); return {successful: true, value: scannedDocument}; } catch (e) { const message = (e && e.message) || `Unknown error during scan.`; const warning = new Warning({ code: 'could-not-scan', message, parsedDocument: parsedDoc, severity: Severity.ERROR, sourceRange: { file: resolvedUrl, start: {column: 0, line: 0}, end: {column: 0, line: 0} } }); this._cache.dependencyGraph.rejectDocument( resolvedUrl, new WarningCarryingException(warning)); return {successful: false, error: warning}; } }, cancelToken); } /** * Scan a toplevel document and all of its transitive dependencies. */ async scan(resolvedUrl: ResolvedUrl, cancelToken: MinimalCancelToken): Promise<Result<ScannedDocument, Warning>> { return this._cache.dependenciesScannedPromises.getOrCompute( resolvedUrl, async () => { const scannedDocumentResult = await this._scanLocal(resolvedUrl, cancelToken); if (scannedDocumentResult.successful === false) { return scannedDocumentResult; } const scannedDocument = scannedDocumentResult.value; const imports = scannedDocument.getNestedFeatures().filter( (e) => e instanceof ScannedImport) as ScannedImport[]; // Scan imports for (const scannedImport of imports) { if (scannedImport.url === undefined) { continue; } const importUrl = this.resolver.resolve( scannedDocument.document.baseUrl, scannedImport.url, scannedImport); if (importUrl === undefined) { continue; } // Request a scan of `importUrl` but do not wait for the results to // avoid deadlock in the case of cycles. Later we use the // DependencyGraph to wait for all transitive dependencies to load. this.scan(importUrl, cancelToken) .then((result) => { if (result.successful === true) { return; } scannedImport.error = result.error; }) .catch((e) => { if (isCancel(e)) { return; } throw e; }); } await this._cache.dependencyGraph.whenReady(resolvedUrl); return scannedDocumentResult; }, cancelToken); } /** * Scans a ParsedDocument. */ private async _scanDocument( document: ParsedDocument, maybeAttachedComment?: string, maybeContainingDocument?: ParsedDocument): Promise<ScannedDocument> { const {features: scannedFeatures, warnings} = await this._getScannedFeatures(document); // If there's an HTML comment that applies to this document then we assume // that it applies to the first feature. const firstScannedFeature = scannedFeatures[0]; if (firstScannedFeature && firstScannedFeature instanceof ScannedElement) { firstScannedFeature.applyHtmlComment( maybeAttachedComment, maybeContainingDocument); } const scannedDocument = new ScannedDocument(document, scannedFeatures, warnings); if (!scannedDocument.isInline) { if (this._cache.scannedDocuments.has(scannedDocument.url)) { throw new Error( 'Scanned document already in cache. This should never happen.'); } this._cache.scannedDocuments.set(scannedDocument.url, scannedDocument); } await this._scanInlineDocuments(scannedDocument); return scannedDocument; } private async _getScannedFeatures(document: ParsedDocument) { const scanners = this._scanners.get(document.type); if (scanners) { try { return await scan(document, scanners); } catch (e) { if (e instanceof WarningCarryingException) { throw e; } const message = e == null ? `Unknown error while scanning.` : `Error while scanning: ${String(e)}`; throw new WarningCarryingException(new Warning({ code: 'internal-scanning-error', message, parsedDocument: document, severity: Severity.ERROR, sourceRange: { file: document.url, start: {column: 0, line: 0}, end: {column: 0, line: 0}, } })); } } return {features: [], warnings: []}; } private async _scanInlineDocuments(containingDocument: ScannedDocument) { for (const feature of containingDocument.features) { if (!(feature instanceof ScannedInlineDocument)) { continue; } const locationOffset: LocationOffset = { line: feature.locationOffset.line, col: feature.locationOffset.col, filename: containingDocument.url }; try { const parsedDoc = this._parseContents( feature.type, feature.contents, containingDocument.url, { locationOffset, astNode: feature.astNode, baseUrl: containingDocument.document.baseUrl }); const scannedDoc = await this._scanDocument( parsedDoc, feature.attachedComment, containingDocument.document); feature.scannedDocument = scannedDoc; } catch (err) { if (err instanceof WarningCarryingException) { containingDocument.warnings.push(err.warning); continue; } throw err; } } } /** * Returns `true` if the provided resolved URL can be loaded. Obeys the * semantics defined by `UrlLoader` and should only be used to check * resolved URLs. */ canLoad(resolvedUrl: ResolvedUrl): boolean { return this.loader.canLoad(resolvedUrl); } /** * Loads the content at the provided resolved URL. Obeys the semantics * defined by `UrlLoader` and should only be used to attempt to load resolved * URLs. * * Currently does no caching. If the provided contents are given then they * are used instead of hitting the UrlLoader (e.g. when you have in-memory * contents that should override disk). */ async load(resolvedUrl: ResolvedUrl): Promise<Result<string, string>> { if (!this.canLoad(resolvedUrl)) { return { successful: false, error: `Configured URL Loader can not load URL ${resolvedUrl}` }; } try { const value = await this.loader.load(resolvedUrl); return {successful: true, value}; } catch (e) { const message = (e && e.message) || `Unknown failure while loading.`; return {successful: false, error: message}; } } /** * Caching + loading wrapper around _parseContents. */ private async _parse( resolvedUrl: ResolvedUrl, cancelToken: MinimalCancelToken): Promise<Result<ParsedDocument, Warning>> { return this._cache.parsedDocumentPromises.getOrCompute( resolvedUrl, async () => { const result = await this.load(resolvedUrl); if (!result.successful) { return { successful: false, error: new Warning({ code: 'could-not-load', parsedDocument: new UnparsableParsedDocument(resolvedUrl, ''), severity: Severity.ERROR, sourceRange: { file: resolvedUrl, start: {column: 0, line: 0}, end: {column: 0, line: 0} }, message: result.error }) }; } const extension = path.extname(resolvedUrl).substring(1); try { const parsedDoc = this._parseContents(extension, result.value, resolvedUrl); return {successful: true, value: parsedDoc}; } catch (e) { if (e instanceof WarningCarryingException) { return {successful: false, error: e.warning}; } const message = (e && e.message) || `Unknown error while parsing.`; return { successful: false, error: new Warning({ code: 'could-not-parse', parsedDocument: new UnparsableParsedDocument(resolvedUrl, result.value), severity: Severity.ERROR, sourceRange: { file: resolvedUrl, start: {column: 0, line: 0}, end: {column: 0, line: 0} }, message }) }; } }, cancelToken); } /** * Parse the given string into the Abstract Syntax Tree (AST) corresponding * to its type. */ private _parseContents( type: string, contents: string, url: ResolvedUrl, inlineInfo?: InlineDocInfo): ParsedDocument { const parser = this.parsers.get(type); if (parser == null) { throw new NoKnownParserError(`No parser for for file type ${type}`); } try { return parser.parse(contents, url, this.resolver, inlineInfo); } catch (error) { if (error instanceof WarningCarryingException) { throw error; } const parsedDocument = new UnparsableParsedDocument(url, contents); const message = error == null ? `Unable to parse as ${type}` : `Unable to parse as ${type}: ${error}`; throw new WarningCarryingException(new Warning({ parsedDocument, code: 'parse-error', message, severity: Severity.ERROR, sourceRange: {file: url, start: {line: 0, column: 0}, end: {line: 0, column: 0}} })); } } /** * Resolves all resolvable URLs in the list, removes unresolvable ones. */ resolveUserInputUrls(urls: PackageRelativeUrl[]): ResolvedUrl[] { return filterOutUndefineds(urls.map((u) => this.resolver.resolve(u))); } } function filterOutUndefineds<T>(arr: ReadonlyArray<T|undefined>): T[] { return arr.filter((t) => t !== undefined) as T[]; } /** * A warning for a weird situation that should never happen. * * Before calling getDocument(), which is synchronous, a caller must first * have finished loading and scanning, as those phases are asynchronous. * * So we need to construct a warning, but we don't have a parsed document, * so we construct this weird fake one. This is such a rare case that it's * worth going out of our way here so that warnings can uniformly expect to * have documents. */ function makeRequestedWithoutLoadingWarning(resolvedUrl: ResolvedUrl) { const parsedDocument = new UnparsableParsedDocument(resolvedUrl, ''); return new Warning({ sourceRange: { file: resolvedUrl, start: {line: 0, column: 0}, end: {line: 0, column: 0} }, code: 'unable-to-analyze', message: `[Internal Error] Document was requested ` + `before loading and scanning finished. This usually indicates an ` + `anomalous error during loading or analysis. Please file a bug at ` + `https://github.com/Polymer/polymer-analyzer/issues/new with info ` + `on the source code that caused this. ` + `Polymer Analyzer version: ${analyzerVersion}`, severity: Severity.ERROR, parsedDocument }); }
the_stack
import type { LiteralUnion } from '@/generalTypes' import type { ITEMS } from '@arguments' import type { BlockIdCriterion, DamageCriterion, DimensionCriterion, DistanceCriterion, EffectCriterion, EntityCriterion, ItemCriterion, LocationCriterion, NumberProvider, PlayerCriterion, PotionIdCriterion, SlotCriterion, } from './criteria' import type { PredicateJSON } from './predicate' // The advancement triggers type Trigger<NAME extends string, CONDITIONS extends Record<string, unknown> | never | null> = { /** * The trigger for this advancement; specifies what the game should check for the advancement. * * One of: * - `minecraft:bee_nest_destroyed`: Triggers when the player breaks a bee nest or beehive. * * - `minecraft:bred_animals`: Triggers after the player breeds 2 animals. * * - `minecraft:brewed_potion`: Triggers after the player takes any item out of a brewing stand. * * - `minecraft:changed_dimension`: Triggers after the player travels between two dimensions. * * - `minecraft:channeled_lightning`: Triggers after the player successfully uses the Channeling enchantment on an entity. * * - `minecraft:construct_beacon`: Triggers after the player changes the structure of a beacon. (When the beacon updates itself). * * - `minecraft:consume_item`: Triggers when the player consumes an item. * * - `minecraft:cured_zombie_villager`: Triggers when the player cures a zombie villager. * * - `minecraft:effects_changed`: Triggers after the player gets a status effect applied or taken from them. * * - `minecraft:enchanted_item`: Triggers after the player enchants an item through an enchanting table (does not get triggered through an anvil, or through commands). * * - `minecraft:enter_block`: Triggers when the player stands in a block. * Checks every tick and will try to trigger for each successful match (up to 8 times, the maximum amount of blocks a player can stand in), * which only works if the advancement is revoked from within the advancement using a function reward. * * - `minecraft:entity_hurt_player`: Triggers after a player gets hurt. * * - `minecraft:entity_killed_player`: Triggers after an entity kills a player. * * - `minecraft:filled_bucket`: Triggers after the player fills a bucket. * * - `minecraft:fishing_rod_hooked`: Triggers after the player successfully catches an item with a fishing rod or pulls an entity with a fishing rod. * * - `minecraft:hero_of_the_village`: Triggers when the player defeats a raid and checks where the player is. * * - `minecraft:impossible`: Triggers only using commands. * * - `minecraft:inventory_changed`: Triggers after any changes happen to the player's inventory. * * - `minecraft:item_durability_changed`: Triggers after any item in the inventory has been damaged in any form. * * - `minecraft:item_used_on_block`: Triggers when the player uses their hand or an item on a block. * * - `minecraft:killed_by_crossbow`: Triggers after the player kills a mob or player using a crossbow in ranged combat. * * - `minecraft:levitation`: Triggers when the player has the levitation status effect. * * - `minecraft:location`: Triggers every 20 ticks (1 second) and checks where the player is. * * - `minecraft:nether_travel`: Triggers when the player travels to the Nether and then returns to the Overworld. * * - `minecraft:placed_block`: Triggers when the player places a block. * * - `minecraft:player_generates_container_loot`: Triggers when the player generates the contents of a container with a loot table set. * * - `minecraft:player_hurt_entity`: Triggers after the player hurts a mob or player. * * - `minecraft:player_interacted_with_entity`: Triggers when the player interacts with an entity. * * - `minecraft:player_killed_entity`: Triggers after a player is the source of a mob or player being killed. * * - `minecraft:recipe_unlocked`: Triggers after the player unlocks a recipe (using a knowledge book for example). * * - `minecraft:shot_crossbow`: Triggers when the player shoots a crossbow. * * - `minecraft:slept_in_bed`: Triggers when the player enters a bed. * * - `minecraft:slide_down_block`: Triggers when the player slides down a block. * * - `minecraft:summoned_entity`: Triggers after an entity has been summoned. * Works with iron golems (pumpkin and iron blocks), snow golems (pumpkin and snow blocks), the ender dragon (end crystals) * and the wither (wither skulls and soul sand/soul soil). * Using dispensers to place the wither skulls or pumpkins will still activate this trigger. * Spawn eggs, commands and mob spawners will not work however. * * - `minecraft:tame_animal`: Triggers after the player tames an animal. * * - `minecraft:target_hit`: Triggers when the player shoots a target block. * * - `minecraft:thrown_item_picked_up_by_entity`: Triggers after the player throws an item and another entity picks it up. * * - `minecraft:tick`: Triggers every tick (20 times a second). * * - `minecraft:used_ender_eye`: Triggers when the player uses an eye of ender (in a world where strongholds generate). * * - `minecraft:used_totem`: Triggers when the player uses a totem. * * - `minecraft:villager_trade`: Triggers after the player trades with a villager or a wandering trader. * * - `minecraft:voluntary_exile`: Triggers when the player causes a raid and checks where the player is. * */ trigger: NAME /* * The "& unknown" is like "x1" or "+0", it doesn't change the initial type. * So it basically means "don't add anything to this object if CONDITIONS is undefined" */ } & (CONDITIONS extends never ? unknown : ({ /** All the conditions that need to be met when the trigger gets activated. */ conditions?: (CONDITIONS extends null ? unknown : Partial<CONDITIONS>) & { /** * A list of predicates that must pass in order for the trigger to activate. * The checks are applied to the player that would get the advancement. * * @example * player: [ * { * condition: '<any condition>', * // ... * } * ] */ player?: PredicateJSON } })) export type AdvancementTriggers = ( Trigger<'minecraft:bee_nest_destroyed', { /** The block that was destroyed. Accepts block IDs. */ block: BlockIdCriterion /** The item used to break the block. */ item: ItemCriterion /** The number of bees that were inside the bee nest/beehive before it was broken. */ nums_bees_inside: number }> | Trigger<'minecraft:bred_animals', { /** The child that results from the breeding. May also be a list of loot table conditions that must pass in order for the trigger to activate. */ child: EntityCriterion /** The parent. May also be a list of loot table conditions that must pass in order for the trigger to activate. */ parent: EntityCriterion /** The partner. (The entity the parent was bred with) May also be a list of loot table conditions that must pass in order for the trigger to activate. */ partner: EntityCriterion }> | Trigger<'minecraft:brewed_potion', { potion: PotionIdCriterion }> | Trigger<'minecraft:changed_dimension', { /** The dimension the entity traveled from. */ from: DimensionCriterion /** The dimension the entity traveled to. */ to: DimensionCriterion }> | Trigger<'minecraft:channeled_lightning', { /** * The victims hit by the lightning summoned by the Channeling enchantment. * All entities in this list must be hit. * Each entry may also be a list of loot table conditions that must pass in order for the trigger to activate. * The checks are applied to the victim hit by the enchanted trident. */ victims: EntityCriterion[] }> | Trigger<'minecraft:construct_beacon', { /** The tier of the updated beacon structure. */ level: number | { min?: number max?: number } }> | Trigger<'minecraft:consume_item', { /** The item that was consumed. */ item: ItemCriterion }> | Trigger<'minecraft:cured_zombie_villager', { /** * The villager that is the result of the conversion. * The 'type' tag is redundant since it will always be "villager". * May also be a list of loot table conditions that must pass in order for the trigger to activate. */ villager: EntityCriterion /** * The zombie villager right before the conversion is complete (not when it is initiated). * The `type` tag is redundant since it will always be `zombie_villager`. * May also be a list of loot table conditions that must pass in order for the trigger to activate. */ zombie: EntityCriterion }> | Trigger<'minecraft:effects_changed', { /** A list of status effects the player has. */ effects: EffectCriterion }> | Trigger<'minecraft:enchanted_item', { /** The item after it has been enchanted. */ item: ItemCriterion /** The levels spent by the player on the enchantment. */ levels: NumberProvider }> | Trigger<'minecraft:entity_hurt_player', { /** Checks the damage done to the player. */ damage: DamageCriterion }> | Trigger<'minecraft:entity_killed_player', { /** * Checks the entity that was the source of the damage that killed the player (for example: The skeleton that shot the arrow). * May also be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion /** Checks the type of damage that killed the player. Missing corresponding list of loot table conditions for the direct entity. */ killing_blow: DamageCriterion }> | Trigger<'minecraft:filled_bucket', { /** The item resulting from filling the bucket. */ item: ItemCriterion }> | Trigger<'minecraft:fishing_rod_hooked', { /** The entity that was pulled. May also be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion /** The item that was caught. */ item: ItemCriterion /** The fishing rod used. */ rod: ItemCriterion }> | Trigger<'minecraft:hero_of_the_village', { /** The location of the player. */ location: LocationCriterion }> | Trigger<'minecraft:impossible', never> | Trigger<'minecraft:inventory_changed', { items: ItemCriterion[] slots: SlotCriterion }> | Trigger<'minecraft:item_durability_changed', { /** The change in durability (negative numbers are used to indicate a decrease in durability). */ delta: NumberProvider /** The remaining durability of the item. */ durability: NumberProvider /** The item before it was damaged, allows you to check the durability before the item was damaged. */ item: ItemCriterion }> | Trigger<'minecraft:item_used_on_block', { /** The location at the center of the block the item was used on. */ location: LocationCriterion /** The item used on the block. */ item: ItemCriterion }> | Trigger<'minecraft:killed_by_crossbow', { /** The count of types of entities killed. */ unique_entity_types: NumberProvider /** A predicate for any of the killed entities. */ victims: EntityCriterion }> | Trigger<'minecraft:levitation', { /** The distance of levitation. */ distance: DistanceCriterion /** The duration of the levitation in ticks. */ duration: NumberProvider }> | Trigger<'minecraft:location', { /** The location of the player. */ location: LocationCriterion }> | Trigger<'minecraft:nether_travel', { /** The location where the player entered the Nether. */ entered: LocationCriterion /** The location where the player exited the Nether. */ exited: LocationCriterion /** The overworld distance between where the player entered the Nether and where the player exited the Nether. */ distance: DistanceCriterion }> | Trigger<'minecraft:placed_block', { /** The block that was placed. Accepts block IDs. */ block: BlockIdCriterion /** The item that was used to place the block before the item was consumed. */ item: ItemCriterion /** The location of the block that was placed. */ location: LocationCriterion /** The block states of the block. */ state: { /** A single block state, with the key name being the state name and the value being the required value of that state. */ [state_name: string]: string } }> | Trigger<'minecraft:player_generates_container_loot', { /** The resource location of the generated loot table. */ loot_table: string }> | Trigger<'minecraft:player_hurt_entity', { /** The damage that was dealt. Missing corresponding list of loot table conditions for the direct entity. */ damage: DamageCriterion /** The entity that was damaged. May be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion }> | Trigger<'minecraft:player_interacted_with_entity', { /** The damage that was dealt. Missing corresponding list of loot table conditions for the direct entity. */ damage: DamageCriterion /** The entity that was damaged. May be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion }> | Trigger<'minecraft:player_killed_entity', { /** The entity that was killed. May be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion /** The type of damage that killed an entity. Missing corresponding list of loot table conditions for the direct entity. */ killing_blow: DamageCriterion }> | Trigger<'minecraft:recipe_unlocked', { /** The recipe that was unlocked. */ recipe: string }> | Trigger<'minecraft:shot_crossbow', { /** The item that was used. */ item: ItemCriterion }> | Trigger<'minecraft:slept_in_bed', { /** The location of the player. */ location: LocationCriterion }> | Trigger<'minecraft:slide_down_block', { /** The block that the player slid on. */ block: BlockIdCriterion }> | Trigger<'minecraft:summoned_entity', { /** The summoned entity. May be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion }> | Trigger<'minecraft:tame_animal', { /** Checks the entity that was tamed. May be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion }> | Trigger<'minecraft:target_hit', { /** The redstone signal that will come out of the target block. */ signal_strength: number /** The projectile used to hit the target block. */ projectile: LiteralUnion<ITEMS> /** Entity predicate for the player who shot or threw the projectile. May be a list of loot table conditions that must pass in order for the trigger to activate. */ shooter: EntityCriterion }> | Trigger<'minecraft:thrown_item_picked_up_by_entity', { /** The thrown item which was picked up. */ item: ItemCriterion /** The entity which picked up the item. May be a list of loot table conditions that must pass in order for the trigger to activate. */ entity: EntityCriterion }> | Trigger<'minecraft:tick', null> | Trigger<'minecraft:used_ender_eye', { /** The horizontal distance between the player and the stronghold. */ distance: NumberProvider }> | Trigger<'minecraft:used_totem', { /** The item, only works with totem items. */ item: ItemCriterion }> | Trigger<'minecraft:villager_trade', { /** The item that was purchased. The "count" tag checks the count from one trade, not multiple. */ item: ItemCriterion /** The villager the item was purchased from. May be a list of loot table conditions that must pass in order for the trigger to activate. */ villager: EntityCriterion }> | Trigger<'minecraft:villager_trade', { /** The location of the player. */ location: LocationCriterion }> )
the_stack
// clang-format off import 'chrome://settings/settings.js'; import 'chrome://webui-test/cr_elements/cr_policy_strings.js'; import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ChooserException, ChooserExceptionListElement, ChooserType, ContentSettingsTypes, RawChooserException, RawSiteException, SiteException, SiteSettingSource, SiteSettingsPrefsBrowserProxyImpl} from 'chrome://settings/lazy_load.js'; import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js'; import { createContentSettingTypeToValuePair,createRawChooserException,createRawSiteException,createSiteSettingsPrefs,SiteSettingsPref} from './test_util.js'; // clang-format on /** @fileoverview Suite of tests for chooser-exception-list. */ /** * An example pref that does not contain any entries. */ let prefsEmpty: SiteSettingsPref; /** * An example pref with only user granted USB exception. */ let prefsUserProvider: SiteSettingsPref; /** * An example pref with only policy granted USB exception. */ let prefsPolicyProvider: SiteSettingsPref; /** * An example pref with 3 USB exception items. The first item will have a user * granted site exception and a policy granted site exception. The second item * will only have a policy granted site exception. The last item will only have * a user granted site exception. */ let prefsUsb: SiteSettingsPref; /** * Creates all the test */ function populateTestExceptions() { prefsEmpty = createSiteSettingsPrefs( [] /* defaultsList */, [] /* exceptionsList */, [] /* chooserExceptionsList */); prefsUserProvider = createSiteSettingsPrefs( [] /* defaultsList */, [] /* exceptionsList */, [createContentSettingTypeToValuePair(ContentSettingsTypes.USB_DEVICES, [ createRawChooserException( ChooserType.USB_DEVICES, [createRawSiteException('https://foo.com')]) ])] /* chooserExceptionsList */); prefsPolicyProvider = createSiteSettingsPrefs( [] /* defaultsList */, [] /* exceptionsList */, [createContentSettingTypeToValuePair(ContentSettingsTypes.USB_DEVICES, [ createRawChooserException( ChooserType.USB_DEVICES, [createRawSiteException( 'https://foo.com', {source: SiteSettingSource.POLICY})]) ])] /* chooserExceptionsList */); prefsUsb = createSiteSettingsPrefs([] /* defaultsList */, [] /* exceptionsList */, [ createContentSettingTypeToValuePair( ContentSettingsTypes.USB_DEVICES, [ createRawChooserException( ChooserType.USB_DEVICES, [ createRawSiteException( 'https://foo-policy.com', {source: SiteSettingSource.POLICY}), createRawSiteException('https://foo-user.com'), ], { displayName: 'Gadget', }), createRawChooserException( ChooserType.USB_DEVICES, [createRawSiteException('https://bar-policy.com', { source: SiteSettingSource.POLICY, })], { displayName: 'Gizmo', }), createRawChooserException( ChooserType.USB_DEVICES, [createRawSiteException('https://baz-user.com')], {displayName: 'Widget'}) ]), ] /* chooserExceptionsList */); } suite('ChooserExceptionList', function() { let testElement: ChooserExceptionListElement; /** * The mock proxy object to use during test. */ let browserProxy: TestSiteSettingsPrefsBrowserProxy; // Initialize a chooser-exception-list before each test. setup(function() { populateTestExceptions(); browserProxy = new TestSiteSettingsPrefsBrowserProxy(); SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; testElement = document.createElement('chooser-exception-list'); document.body.appendChild(testElement); }); /** * Configures the test element for a particular category. * @param chooserType The chooser type to set up the element for. * @param prefs The prefs to use. */ function setUpChooserType( contentType: ContentSettingsTypes, chooserType: ChooserType, prefs: SiteSettingsPref) { browserProxy.setPrefs(prefs); testElement.category = contentType; testElement.chooserType = chooserType; } function assertSiteOriginsEquals( site: RawSiteException, actualSite: SiteException) { assertEquals(site.origin, actualSite.origin); assertEquals(site.embeddingOrigin, actualSite.embeddingOrigin); } function assertChooserExceptionEquals( exception: RawChooserException, actualException: ChooserException) { assertEquals(exception.displayName, actualException.displayName); assertEquals(exception.chooserType, actualException.chooserType); assertDeepEquals(exception.object, actualException.object); const sites = exception.sites; const actualSites = actualException.sites; assertEquals(sites.length, actualSites.length); for (let i = 0; i < sites.length; ++i) { assertSiteOriginsEquals(sites[i]!, actualSites[i]!); } } test('getChooserExceptionList API used', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsUsb); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); // Flush the container to ensure that the container is populated. flush(); // Ensure that each chooser exception is rendered with a // chooser-exception-list-entry. const chooserExceptionListEntries = testElement.shadowRoot!.querySelectorAll( 'chooser-exception-list-entry'); assertEquals(3, chooserExceptionListEntries.length); for (let i = 0; i < chooserExceptionListEntries.length; ++i) { assertChooserExceptionEquals( prefsUsb.chooserExceptions[ContentSettingsTypes.USB_DEVICES][i]! , chooserExceptionListEntries[i]!.exception); } // The first chooser exception should render two site exceptions with // site-list-entry elements. const firstSiteListEntries = chooserExceptionListEntries[0]!.shadowRoot!.querySelectorAll( 'site-list-entry'); assertEquals(2, firstSiteListEntries.length); // The second chooser exception should render one site exception with // a site-list-entry element. const secondSiteListEntries = chooserExceptionListEntries[1]!.shadowRoot!.querySelectorAll( 'site-list-entry'); assertEquals(1, secondSiteListEntries.length); // The last chooser exception should render one site exception with a // site-list-entry element. const thirdSiteListEntries = chooserExceptionListEntries[2]!.shadowRoot!.querySelectorAll( 'site-list-entry'); assertEquals(1, thirdSiteListEntries.length); }); }); test( 'User granted chooser exceptions should show the reset button', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsUserProvider); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); // Flush the container to ensure that the container is populated. flush(); const chooserExceptionListEntry = testElement.shadowRoot!.querySelector( 'chooser-exception-list-entry'); assertTrue(!!chooserExceptionListEntry); const siteListEntry = chooserExceptionListEntry!.shadowRoot!.querySelector( 'site-list-entry'); assertTrue(!!siteListEntry); // Ensure that the action menu container is hidden. const dotsMenu = siteListEntry!.$.actionMenuButton; assertTrue(dotsMenu.hidden); // Ensure that the reset button is not hidden. const resetButton = siteListEntry!.$.resetSite; assertFalse(resetButton.hidden); // Ensure that the policy enforced indicator is hidden. const policyIndicator = siteListEntry!.shadowRoot!.querySelector( 'cr-policy-pref-indicator'); assertFalse(!!policyIndicator); }); }); test( 'Policy granted chooser exceptions should show the policy indicator icon', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsPolicyProvider); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); // Flush the container to ensure that the container is populated. flush(); const chooserExceptionListEntry = testElement.shadowRoot!.querySelector( 'chooser-exception-list-entry'); assertTrue(!!chooserExceptionListEntry); const siteListEntry = chooserExceptionListEntry!.shadowRoot!.querySelector( 'site-list-entry'); assertTrue(!!siteListEntry); // Ensure that the action menu container is hidden. const dotsMenu = siteListEntry!.$.actionMenuButton; assertTrue(!!dotsMenu); assertTrue(dotsMenu.hidden); // Ensure that the reset button is hidden. const resetButton = siteListEntry!.$.resetSite; assertTrue(resetButton.hidden); // Ensure that the policy enforced indicator not is hidden. const policyIndicator = siteListEntry!.shadowRoot!.querySelector( 'cr-policy-pref-indicator'); assertTrue(!!policyIndicator); }); }); test( 'Site exceptions from mixed sources should display properly', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsUsb); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); // Flush the container to ensure that the container is populated. flush(); const chooserExceptionListEntries = testElement.shadowRoot!.querySelectorAll( 'chooser-exception-list-entry'); assertEquals(3, chooserExceptionListEntries.length); // The first chooser exception contains mixed provider site // exceptions. const siteListEntries = chooserExceptionListEntries[0]!.shadowRoot!.querySelectorAll( 'site-list-entry'); assertEquals(2, siteListEntries.length); // The first site exception is a policy provided exception, so // only the policy indicator should be visible; const policyProvidedDotsMenu = siteListEntries[0]!.$.actionMenuButton; assertTrue(!!policyProvidedDotsMenu); assertTrue(policyProvidedDotsMenu.hidden); const policyProvidedResetButton = siteListEntries[0]!.$.resetSite; assertTrue(!!policyProvidedResetButton); assertTrue(policyProvidedResetButton.hidden); const policyProvidedPolicyIndicator = siteListEntries[0]!.shadowRoot!.querySelector( 'cr-policy-pref-indicator'); assertTrue(!!policyProvidedPolicyIndicator); // The second site exception is a user provided exception, so only // the reset button should be visible. const userProvidedDotsMenu = siteListEntries[1]!.$.actionMenuButton; assertTrue(!!userProvidedDotsMenu); assertTrue(userProvidedDotsMenu.hidden); const userProvidedResetButton = siteListEntries[1]!.$.resetSite; assertTrue(!!userProvidedResetButton); assertFalse(userProvidedResetButton.hidden); const userProvidedPolicyIndicator = siteListEntries[1]!.shadowRoot!.querySelector( 'cr-policy-pref-indicator'); assertFalse(!!userProvidedPolicyIndicator); }); }); test('Empty list', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsEmpty); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); assertEquals(0, testElement.chooserExceptions.length); const emptyListMessage = testElement.shadowRoot!.querySelector<HTMLElement>( '#empty-list-message')!; assertFalse(emptyListMessage.hidden); assertEquals( 'No USB devices found', emptyListMessage.textContent!.trim()); }); }); test('resetChooserExceptionForSite API used', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsUserProvider); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); assertEquals(1, testElement.chooserExceptions.length); assertChooserExceptionEquals( prefsUserProvider .chooserExceptions[ContentSettingsTypes.USB_DEVICES][0]!, testElement.chooserExceptions[0]!); // Flush the container to ensure that the container is populated. flush(); const chooserExceptionListEntry = testElement.shadowRoot!.querySelector( 'chooser-exception-list-entry'); assertTrue(!!chooserExceptionListEntry); const siteListEntry = chooserExceptionListEntry!.shadowRoot!.querySelector( 'site-list-entry'); assertTrue(!!siteListEntry); // Assert that the action button is hidden. const dotsMenu = siteListEntry!.$.actionMenuButton; assertTrue(!!dotsMenu); assertTrue(dotsMenu.hidden); // Assert that the reset button is visible. const resetButton = siteListEntry!.$.resetSite; assertFalse(resetButton.hidden); resetButton.click(); return browserProxy.whenCalled('resetChooserExceptionForSite'); }) .then(function(args) { assertEquals(ChooserType.USB_DEVICES, args[0]); assertEquals('https://foo.com', args[1]); assertEquals('https://foo.com', args[2]); assertDeepEquals({}, args[3]); }); }); test( 'The show-tooltip event is fired when mouse hovers over policy ' + 'indicator and the common tooltip is shown', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsPolicyProvider); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); assertEquals(1, testElement.chooserExceptions.length); assertChooserExceptionEquals( prefsPolicyProvider .chooserExceptions[ContentSettingsTypes.USB_DEVICES][0]!, testElement.chooserExceptions[0]!); // Flush the container to ensure that the container is populated. flush(); const chooserExceptionListEntry = testElement.shadowRoot!.querySelector( 'chooser-exception-list-entry'); assertTrue(!!chooserExceptionListEntry); const siteListEntry = chooserExceptionListEntry!.shadowRoot!.querySelector( 'site-list-entry'); assertTrue(!!siteListEntry); const tooltip = testElement.$.tooltip; assertTrue(!!tooltip); const innerTooltip = tooltip.shadowRoot!.querySelector('#tooltip'); assertTrue(!!innerTooltip); /** * Create an array of test parameters objects. The parameter * properties are the following: * |text| Tooltip text to display. * |el| Event target element. * |eventType| The event type to dispatch to |el|. * @type {Array<{text: string, el: !Element, eventType: string}>} */ const testsParams = [ {text: 'a', el: testElement, eventType: 'mouseleave'}, {text: 'b', el: testElement, eventType: 'click'}, {text: 'c', el: testElement, eventType: 'blur'}, {text: 'd', el: tooltip, eventType: 'mouseenter'}, ]; testsParams.forEach(params => { const text = params.text; const eventTarget = params.el; siteListEntry!.fire( 'show-tooltip', {target: testElement, text}); assertFalse(innerTooltip!.classList.contains('hidden')); assertEquals(text, tooltip.innerHTML.trim()); eventTarget.dispatchEvent(new MouseEvent(params.eventType)); assertTrue(innerTooltip!.classList.contains('hidden')); }); }); }); test('The exception list is updated when the prefs are modified', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsUserProvider); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); assertEquals(1, testElement.chooserExceptions.length); assertChooserExceptionEquals( prefsUserProvider .chooserExceptions[ContentSettingsTypes.USB_DEVICES][0]!, testElement.chooserExceptions[0]!); browserProxy.resetResolver('getChooserExceptionList'); // Simulate a change in preferences. setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsPolicyProvider); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); webUIListenerCallback( 'contentSettingChooserPermissionChanged', ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES); return browserProxy.whenCalled('getChooserExceptionList'); }) .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); assertEquals(1, testElement.chooserExceptions.length); assertChooserExceptionEquals( prefsPolicyProvider .chooserExceptions[ContentSettingsTypes.USB_DEVICES][0]!, testElement.chooserExceptions[0]!); }); }); test( 'The exception list is updated when incognito status is changed', function() { setUpChooserType( ContentSettingsTypes.USB_DEVICES, ChooserType.USB_DEVICES, prefsPolicyProvider); assertEquals(ContentSettingsTypes.USB_DEVICES, testElement.category); assertEquals(ChooserType.USB_DEVICES, testElement.chooserType); return browserProxy.whenCalled('getChooserExceptionList') .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); // Flush the container to ensure that the container is populated. flush(); const chooserExceptionListEntry = testElement.shadowRoot!.querySelector( 'chooser-exception-list-entry'); assertTrue(!!chooserExceptionListEntry); const siteListEntry = chooserExceptionListEntry!.shadowRoot!.querySelector( 'site-list-entry'); assertTrue(!!siteListEntry); // Ensure that the incognito tooltip is hidden. const incognitoTooltip = siteListEntry!.shadowRoot!.querySelector('#incognitoTooltip'); assertFalse(!!incognitoTooltip); // Simulate an incognito session being created. browserProxy.resetResolver('getChooserExceptionList'); browserProxy.setIncognito(true); return browserProxy.whenCalled('getChooserExceptionList'); }) .then(function(chooserType) { assertEquals(ChooserType.USB_DEVICES, chooserType); // Flush the container to ensure that the container is populated. flush(); const chooserExceptionListEntry = testElement.shadowRoot!.querySelector( 'chooser-exception-list-entry'); assertTrue(!!chooserExceptionListEntry); assertTrue(chooserExceptionListEntry!.$.listContainer .querySelector('iron-list')!.items!.some( item => item.incognito)); const siteListEntries = chooserExceptionListEntry!.shadowRoot!.querySelectorAll( 'site-list-entry'); assertEquals(2, siteListEntries.length); assertTrue(Array.from(siteListEntries) .some(entry => entry.model.incognito)); const tooltip = testElement.$.tooltip; assertTrue(!!tooltip); const innerTooltip = tooltip.shadowRoot!.querySelector('#tooltip'); assertTrue(!!innerTooltip); const text = loadTimeData.getString('incognitoSiteExceptionDesc'); // This filtered array should be non-empty due to above test that // checks for incognito exception. Array.from(siteListEntries) .filter(entry => entry.model.incognito) .forEach(entry => { const incognitoTooltip = entry.shadowRoot!.querySelector('#incognitoTooltip'); // Make sure it is not hidden if it is an incognito // exception assertTrue(!!incognitoTooltip); // Trigger mouse enter and check tooltip text incognitoTooltip!.dispatchEvent( new MouseEvent('mouseenter')); assertFalse(innerTooltip!.classList.contains('hidden')); assertEquals(text, tooltip.innerHTML.trim()); }); }); }); });
the_stack
const calculateSaves = () => { getAttrs([...attributes.map(attr => `${attr}_mod`), "level", "homebrew_luck_save", "save_physical", "save_mental", "save_evasion", "save_luck" ], v => { const base = 16 - (parseInt(v.level) || 1); const setting: {[key: string]: any} = { save_physical: base - (Math.max(parseInt(v.strength_mod), parseInt(v.constitution_mod)) || 0), save_mental: base - (Math.max(parseInt(v.charisma_mod), parseInt(v.wisdom_mod)) || 0), save_evasion: base - (Math.max(parseInt(v.intelligence_mod), parseInt(v.dexterity_mod)) || 0), }; if (v.homebrew_luck_save === "1") setting.save_luck = base; mySetAttrs(setting, v); }); }; const calculateEffort = () => { getSectionIDs("repeating_psychic-skills", idArray => { getAttrs([...effortAttributes, "psionics_total_effort", ...idArray.map(id => `repeating_psychic-skills_${id}_skill`)], v => { const attrBonus = Math.max(parseInt(v.wisdom_mod), parseInt(v.constitution_mod)) || 0, skillBonus = Math.max( ...skills.psionic.map(x => parseInt(v[`skill_${x}`]) || 0), ...idArray.map(id => parseInt(v[`repeating_psychic-skills_${id}_skill`]) || 0) ); const psionics_total_effort = (Math.max(1 + attrBonus + skillBonus, 1) + parseInt(v.psionics_extra_effort) - parseInt(v.psionics_committed_effort_current) - parseInt(v.psionics_committed_effort_scene) - parseInt(v.psionics_committed_effort_day)) || 0; mySetAttrs({ psionics_total_effort }, v); }); }); }; const calculateMagicEffort = () => { getAttrs(["magic_total_effort", "magic_committed_effort_current", "magic_committed_effort_scene", "magic_committed_effort_day", "magic_uncommitted_effort"], v => { const magic_uncommitted_effort = (parseInt(v.magic_total_effort) - (parseInt(v.magic_committed_effort_current) + parseInt(v.magic_committed_effort_scene) + parseInt(v.magic_committed_effort_day))) || 0; mySetAttrs({ magic_uncommitted_effort }, v); }); }; const calculateProcessing = () => { getSectionIDs("repeating_processing-nodes", idArray => { const sourceAttrs = [ ...idArray.map(id => `repeating_processing-nodes_${id}_node_value`), ...idArray.map(id => `repeating_processing-nodes_${id}_node_connected`), "wisdom_mod", "intelligence_mod", "ai_extra_processing", "ai_committed_processing_current", "ai_committed_processing_scene", "ai_committed_processing_day", "ai_total_processing" ]; getAttrs(sourceAttrs, v => { const maxProcessing = (1 + Math.max(parseInt(v.wisdom_mod) , parseInt(v.intelligence_mod)) || 0) + Math.max( ...idArray.filter(id => v[`repeating_processing-nodes_${id}_node_connected`] === "1") .map(id => parseInt(v[`repeating_processing-nodes_${id}_node_value`]) || 0) , 0 ); const ai_total_processing = (maxProcessing + parseInt(v.ai_extra_processing) - parseInt(v.ai_committed_processing_current) - parseInt(v.ai_committed_processing_scene) - parseInt(v.ai_committed_processing_day)) || 0; mySetAttrs({ ai_total_processing }, v); }); }); } const calculateAC = () => { getSectionIDs("repeating_armor", idArray => { const sourceAttrs = [ ...idArray.map(id => `repeating_armor_${id}_armor_ac`), ...idArray.map(id => `repeating_armor_${id}_armor_active`), ...idArray.map(id => `repeating_armor_${id}_armor_type`), "npc", "AC", "innate_ac", "dexterity_mod", ]; getAttrs(sourceAttrs, v => { if (v.npc === "1") return; const baseAC = Math.max( parseInt(v.innate_ac) || 0, ...idArray.filter(id => v[`repeating_armor_${id}_armor_active`] === "1") .filter(id => v[`repeating_armor_${id}_armor_type`] !== "SHIELD") .map(id => parseInt(v[`repeating_armor_${id}_armor_ac`]) || 0) ); const shieldAC = Math.max( 0, ...idArray.filter(id => v[`repeating_armor_${id}_armor_active`] === "1") .filter(id => v[`repeating_armor_${id}_armor_type`] === "SHIELD") .map(id => parseInt(v[`repeating_armor_${id}_armor_ac`]) || 0) ); const AC = (shieldAC > 0 ? shieldAC <= baseAC ? (baseAC + 1) : shieldAC : baseAC) + (parseInt(v.dexterity_mod) || 0); mySetAttrs({ AC }, v); }); }); }; const calculateMaxStrain = () => { getAttrs(["constitution", "strain_max"], v => { mySetAttrs({ strain_max: parseInt(v.constitution) || 0 }, v); }); }; const calculatePermanentStrain = () => { getAttrs(["cyberware_strain_total", "strain_permanent_extra", "strain_permanent"], v => { const permStrain = parseInt(v.cyberware_strain_total) + parseInt(v.strain_permanent_extra) || 0; mySetAttrs({ strain_permanent: permStrain }, v); }); }; const calculateCyberwareStrain = () => { //Loop through the cyberware and add up the strain. getSectionIDs("repeating_cyberware", idArray => { const sourceAttrs = [ ...idArray.map(id => `repeating_cyberware_${id}_cyberware_strain`), "cyberware_strain_total" ]; getAttrs(sourceAttrs, v => { const cyberwareStrain = idArray.reduce((m, id) => { m += parseInt(v[`repeating_cyberware_${id}_cyberware_strain`]) || 0; return m }, 0) mySetAttrs({ cyberware_strain_total: cyberwareStrain }, v); }); }); }; const calculateStrain = () => { //Add up all the strain getAttrs(["strain_permanent", "strain_extra", "strain", "strain_max", "strain_above_max"], v => { const strain = (parseInt(v.strain_permanent) || 0) + (parseInt(v.strain_extra) || 0) const strain_above_max = strain > parseInt(v.strain_max) ? 1 : 0 mySetAttrs({ strain: strain, strain_above_max: strain_above_max }, v) }) } const calculateAttr = (attr: string) => { getAttrs([attr, `${attr}_base`, `${attr}_boosts`], v => { const setting = { [`${attr}`]: `${(parseInt(v[`${attr}_base`]) || 10) + (parseInt(v[`${attr}_boosts`]) || 0)}` }; mySetAttrs(setting, v, null, () => { calculateMod(attr); }); }); } const calculateMod = (attr: string) => { getAttrs([attr, `${attr}_bonus`, `${attr}_mod`], v => { const mod = (value => { if (value >= 18) return 2; else if (value >= 14) return 1; else if (value >= 8) return 0; else if (value >= 4) return -1; else return -2; })(parseInt(v[attr]) || 10); const setting = { [`${attr}_mod`]: `${mod + (parseInt(v[`${attr}_bonus`]) || 0)}` }; mySetAttrs(setting, v, null, () => { calculateSaves(); generateWeaponDisplay(); calculateStrDexMod(); if (attr === "dexterity") calculateAC(); }); }); }; const calculateStrDexMod = () => { getAttrs(["str_dex_mod", "strength_mod", "dexterity_mod"], v => { const str_dex_mod = Math.max(parseInt(v.strength_mod) || 0, parseInt(v.dexterity_mod) || 0); mySetAttrs({ str_dex_mod }, v); }); }; const calculateShellAttrs = () => { const physicalAttrs = ["strength", "dexterity", "constitution"]; getSectionIDs("repeating_shells", idArray => { const sourceAttrs = [ ...idArray.map(id => `repeating_shells_${id}_shell_active`), ...idArray.map(id => `repeating_shells_${id}_shell_strength`), ...idArray.map(id => `repeating_shells_${id}_shell_dexterity`), ...idArray.map(id => `repeating_shells_${id}_shell_constitution`), ...physicalAttrs, "setting_transhuman_enable", "setting_ai_enable", ]; getAttrs(sourceAttrs, v => { if (v.setting_transhuman_enable === "transhuman" || v.setting_ai_enable === "ai"){ let attributes: {[key: string]: string} = {}; physicalAttrs.forEach(attr => attributes[attr] = idArray .filter(id => v[`repeating_shells_${id}_shell_active`] === "1") .map(id => v[`repeating_shells_${id}_shell_${attr}`])[0] || "None") mySetAttrs(attributes, v, null, () => { physicalAttrs.filter(attr => attributes[attr] !== "None").forEach(attr => calculateMod(attr)); }); } else { physicalAttrs.forEach(attr => calculateAttr(attr)); } }) }) } const calculateNextLevelXP = () => { const xp = [0, 3, 6, 12, 18, 27, 39, 54, 72, 93]; getAttrs(["level", "setting_xp_scheme"], v => { const level = parseInt(v.level) if (v.setting_xp_scheme === "xp") { if (level < 10) { setAttrs({ xp_next: xp[level] }); } else { setAttrs({ xp_next: 93 + ((level - 9) * 24) }); } } else if (v.setting_xp_scheme === "money") { setAttrs({ xp_next: 2500 * (2 * level) }); } }); }; const calculateGearReadiedStowed = () => { const doCalc = (gearIDs: string[], weaponIDs: string[], armorIDs: string[]) => { const attrs = [ ...gearIDs.map(id => `repeating_gear_${id}_gear_amount`), ...gearIDs.map(id => `repeating_gear_${id}_gear_encumbrance`), ...gearIDs.map(id => `repeating_gear_${id}_gear_status`), ...gearIDs.map(id => `repeating_gear_${id}_gear_bundled`), ...armorIDs.map(id => `repeating_armor_${id}_armor_encumbrance`), ...armorIDs.map(id => `repeating_armor_${id}_armor_encumbrance_bonus`), ...armorIDs.map(id => `repeating_armor_${id}_armor_status`), ...weaponIDs.map(id => `repeating_weapons_${id}_weapon_encumbrance`), ...weaponIDs.map(id => `repeating_weapons_${id}_weapon_status`), "gear_readied", "gear_stowed", "strength", "gear_readied_max", "gear_readied_over", "gear_stowed_over", "gear_stowed_max" ]; getAttrs(attrs, v => { const [gear_readied, gear_stowed] = armorIDs.reduce((m, id) => { if (v[`repeating_armor_${id}_armor_status`] === "READIED") { m[0] += parseInt(v[`repeating_armor_${id}_armor_encumbrance`]) || 0; } else if (v[`repeating_armor_${id}_armor_status`] === "STOWED") m[1] += parseInt(v[`repeating_armor_${id}_armor_encumbrance`]) || 0; return m; }, weaponIDs.reduce((m, id) => { if (v[`repeating_weapons_${id}_weapon_status`] === "READIED") m[0] += parseInt(v[`repeating_weapons_${id}_weapon_encumbrance`]) || 0; else if (v[`repeating_weapons_${id}_weapon_status`] === "STOWED") m[1] += parseInt(v[`repeating_weapons_${id}_weapon_encumbrance`]) || 0; return m; }, gearIDs.reduce((m, id) => { const amount = parseInt(v[`repeating_gear_${id}_gear_amount`]) || 0; let packingFactor = 1; if (v[`repeating_gear_${id}_gear_bundled`] === "on") { packingFactor = 3; } if (v[`repeating_gear_${id}_gear_status`] === "READIED") m[0] += Math.ceil((amount * parseFloat(v[`repeating_gear_${id}_gear_encumbrance`]))/packingFactor) || 0; else if (v[`repeating_gear_${id}_gear_status`] === "STOWED") m[1] += Math.ceil((amount * parseFloat(v[`repeating_gear_${id}_gear_encumbrance`]))/packingFactor) || 0; return m; }, [0, 0]))); const armor_encumbrance_bonus = Math.max(0, ...armorIDs.filter(id => v[`repeating_armor_${id}_armor_status`] === "READIED") .map(id => parseInt(v[`repeating_armor_${id}_armor_encumbrance_bonus`]) || 0) ); const gear_stowed_max = parseInt(v.strength) + armor_encumbrance_bonus || 0; const gear_readied_max = Math.floor(gear_stowed_max / 2); const setting = { gear_readied, gear_stowed, gear_readied_max, gear_stowed_max, gear_readied_over: (parseInt(v.gear_readied) > gear_readied_max) ? "1" : "0", gear_stowed_over: (parseInt(v.gear_stowed) > gear_stowed_max) ? "1" : "0", }; mySetAttrs(setting, v, { silent: true }); }); }; getSectionIDs("repeating_gear", gearIDs => { getSectionIDs("repeating_weapons", weaponIDs => { getSectionIDs("repeating_armor", armorIDs => doCalc(gearIDs, weaponIDs, armorIDs)); }); }); }; const generateWeaponDisplay = () => { // Generates the weapon menu and sets the display of weapons // in display mode in one go. getSectionIDs("repeating_weapons", idArray => { const prefixes = idArray.map(id => `repeating_weapons_${id}`); const sourceAttrs = [ ...prefixes.map(prefix => `${prefix}_weapon_attack`), ...prefixes.map(prefix => `${prefix}_weapon_name`), ...prefixes.map(prefix => `${prefix}_weapon_skill_bonus`), ...prefixes.map(prefix => `${prefix}_weapon_attribute_mod`), ...prefixes.map(prefix => `${prefix}_weapon_damage`), ...prefixes.map(prefix => `${prefix}_weapon_shock`), ...prefixes.map(prefix => `${prefix}_weapon_shock_damage`), ...prefixes.map(prefix => `${prefix}_weapon_shock_ac`), ...prefixes.map(prefix => `${prefix}_weapon_skill_to_damage`), ...prefixes.map(prefix => `${prefix}_weapon_attack_display`), ...prefixes.map(prefix => `${prefix}_weapon_damage_display`), ...attributes.map(attr => `${attr}_mod`), ...weaponSkills, "attack_bonus", "str_dex_mod", "macro_weapons" ]; getAttrs(sourceAttrs, v => { const setting: {[key: string]: string} = {}; const baseAttackBonus = parseInt(v.attack_bonus) || 0; prefixes.forEach(prefix => { const attrBonus = parseInt(v[(v[`${prefix}_weapon_attribute_mod`] || "").slice(2, -1)]) || 0; const skillBonus = parseInt(v[(v[`${prefix}_weapon_skill_bonus`] || "").slice(2, -1)]) || parseInt(v[`${prefix}_weapon_skill_bonus`]) || 0; const damageBonus = attrBonus + ((v[`${prefix}_weapon_skill_to_damage`] === "@{weapon_skill_bonus}") ? skillBonus : 0); const weaponDamage = (v[`${prefix}_weapon_damage`] === "0") ? "" : v[`${prefix}_weapon_damage`]; const shockString = (v[`${prefix}_weapon_shock`] !== "0") ? `, ${ (parseInt(v[`${prefix}_weapon_shock_damage`])||0) + damageBonus }\xa0${translate("SHOCK").toString().toLowerCase()}${ v[`${prefix}_weapon_shock_ac`] ? ` ${translate("VS_AC_LEQ")} ${v[`${prefix}_weapon_shock_ac`]}` : "" }` : ""; const attack = baseAttackBonus + (parseInt(v[`${prefix}_weapon_attack`]) || 0) + ((skillBonus === -1) ? -2 : skillBonus) + attrBonus; const damage = weaponDamage + (weaponDamage ? ((damageBonus === 0) ? "" : ((damageBonus > 0) ? ` + ${damageBonus}` : ` - ${-damageBonus}`)) : damageBonus); setting[`${prefix}_weapon_attack_display`] = (attack >= 0) ? `+${attack}` : attack.toString(); setting[`${prefix}_weapon_damage_display`] = `${damage || 0}\xa0${translate("DAMAGE").toString().toLowerCase()}${shockString}`; }); setting.macro_weapons = prefixes.map((prefix, index) => { const label = `${v[`${prefix}_weapon_name`]} (${setting[`${prefix}_weapon_attack_display`]})`; return buildLink(label, `${prefix}_attack`, index === prefixes.length - 1); }).join(" "); mySetAttrs(setting, v, { silent: true }); }); }); }; const handleAmmoAPI = (sName: string) => { const formula = (sName === "weapons") ? "[[-1 - @{weapon_burst}]]" : "-1"; getSectionIDs(`repeating_${sName}`, idArray => { getAttrs([ "setting_use_ammo", ...idArray.map(id => `repeating_${sName}_${id}_weapon_use_ammo`), ...idArray.map(id => `repeating_${sName}_${id}_weapon_api`) ], v => { const setting = idArray.reduce((m: {[k: string]: string}, id) => { m[`repeating_${sName}_${id}_weapon_api`] = (v.setting_use_ammo === "1" && v[`repeating_${sName}_${id}_weapon_use_ammo`] !== "0") ? `\n!modattr --mute --charid @{character_id} --repeating_${sName}_${id}_weapon_ammo|${formula}` : ""; return m; }, {}); mySetAttrs(setting, v, { silent: true }); }); }); };
the_stack
import { SVG } from "../util"; import { SVGPathBuilder } from "../util/SVG"; import { EMFJSError, Helper } from "./Helper"; import { Obj, PointL, PointS, RectL } from "./Primitives"; import { CreateSimpleRegion, Region } from "./Region"; import { Brush, ColorRef, Font, Pen } from "./Style"; interface ISelectedStyle { brush?: Brush; pen?: Pen; font?: Font; region?: Region; path?: Path; [key: string]: Obj | undefined; } class Path extends Obj { public svgPath: SVGPathBuilder; constructor(svgPath: SVGPathBuilder, copy?: Path) { super("path"); if (svgPath != null) { this.svgPath = svgPath; } else { this.svgPath = copy.svgPath; } } public clone(): Path { return new Path(null, this); } public toString(): string { return "{[path]}"; } } function createStockObjects(): { [key: string]: Obj } { // Create global stock objects const createSolidBrush = (r: number, g: number, b: number) => { return new Brush(null, { style: Helper.GDI.BrushStyle.BS_SOLID, color: new ColorRef(null, r, g, b), }); }; const createSolidPen = (r: number, g: number, b: number) => { return new Pen(null, Helper.GDI.PenStyle.PS_SOLID, 1, new ColorRef(null, r, g, b), null); }; const stockObjs: { [key: string]: Obj } = { WHITE_BRUSH: createSolidBrush(255, 255, 255), LTGRAY_BRUSH: createSolidBrush(212, 208, 200), GRAY_BRUSH: createSolidBrush(128, 128, 128), DKGRAY_BRUSH: createSolidBrush(64, 64, 64), BLACK_BRUSH: createSolidBrush(0, 0, 0), NULL_BRUSH: new Brush(null, { style: Helper.GDI.BrushStyle.BS_NULL, }), WHITE_PEN: createSolidPen(255, 255, 255), BLACK_PEN: createSolidPen(0, 0, 0), NULL_PEN: new Pen(null, Helper.GDI.PenStyle.PS_NULL, 0, null, null), OEM_FIXED_FONT: null, // TODO ANSI_FIXED_FONT: null, // TODO ANSI_VAR_FONT: null, // TODO SYSTEM_FONT: null, // TODO DEVICE_DEFAULT_FONT: null, // TODO DEFAULT_PALETTE: null, // TODO SYSTEM_FIXED_FONT: null, // TODO DEFAULT_GUI_FONT: null, // TODO }; const objs: { [key: string]: Obj } = {}; for (const t in stockObjs) { const stockObjects: { [key: string]: number } = Helper.GDI.StockObject as { [key: string]: number }; const idx = stockObjects[t] - 0x80000000; objs[idx.toString()] = stockObjs[t]; } return objs; } const _StockObjects = createStockObjects(); class GDIContextState { public _svggroup: SVGElement; public _svgclipChanged: boolean; public _svgtextbkfilter: SVGFilterElement; public mapmode: number; public stretchmode: number; public textalign: number; public bkmode: number; public textcolor: ColorRef; public bkcolor: ColorRef; public polyfillmode: number; public miterlimit: number; public wx: number; public wy: number; public ww: number; public wh: number; public vx: number; public vy: number; public vw: number; public vh: number; public x: number; public y: number; public nextbrx: number; public nextbry: number; public brx: number; public bry: number; public clip: Region; public ownclip: boolean; public selected: ISelectedStyle; constructor(copy: GDIContextState, defObjects?: ISelectedStyle) { if (copy != null) { this._svggroup = copy._svggroup; this._svgclipChanged = copy._svgclipChanged; this._svgtextbkfilter = copy._svgtextbkfilter; this.mapmode = copy.mapmode; this.stretchmode = copy.stretchmode; this.textalign = copy.textalign; this.bkmode = copy.bkmode; this.textcolor = copy.textcolor.clone(); this.bkcolor = copy.bkcolor.clone(); this.polyfillmode = copy.polyfillmode; this.miterlimit = copy.miterlimit; this.wx = copy.wx; this.wy = copy.wy; this.ww = copy.ww; this.wh = copy.wh; this.vx = copy.vx; this.vy = copy.vy; this.vw = copy.vw; this.vh = copy.vh; this.x = copy.x; this.y = copy.y; this.nextbrx = copy.nextbrx; this.nextbry = copy.nextbry; this.brx = copy.brx; this.bry = copy.bry; this.clip = copy.clip; this.ownclip = false; this.selected = {}; for (const type in copy.selected) { this.selected[type] = copy.selected[type]; } } else { this._svggroup = null; this._svgclipChanged = false; this._svgtextbkfilter = null; this.mapmode = Helper.GDI.MapMode.MM_ANISOTROPIC; this.stretchmode = Helper.GDI.StretchMode.COLORONCOLOR; this.textalign = 0; // TA_LEFT | TA_TOP | TA_NOUPDATECP this.bkmode = Helper.GDI.MixMode.OPAQUE; this.textcolor = new ColorRef(null, 0, 0, 0); this.bkcolor = new ColorRef(null, 255, 255, 255); this.polyfillmode = Helper.GDI.PolygonFillMode.ALTERNATE; this.miterlimit = 10; this.wx = 0; this.wy = 0; this.ww = 0; this.wh = 0; this.vx = 0; this.vy = 0; this.vw = 0; this.vh = 0; this.x = 0; this.y = 0; this.nextbrx = 0; this.nextbry = 0; this.brx = 0; this.bry = 0; this.clip = null; this.ownclip = false; this.selected = {}; for (const type in defObjects) { const defObj = defObjects[type]; this.selected[type] = defObj != null ? defObj.clone() : null; } } } } export class GDIContext { private _svg: SVG; private _svgdefs: SVGDefsElement; private _svgPatterns: { [key: string]: Brush }; private _svgClipPaths: { [key: string]: Region }; private _svgPath: SVGPathBuilder; private defObjects: ISelectedStyle; private state: GDIContextState; private statestack: GDIContextState[]; private objects: { [key: string]: Obj }; constructor(svg: SVG) { this._svg = svg; this._svgdefs = null; this._svgPatterns = {}; this._svgClipPaths = {}; this._svgPath = null; this.defObjects = { brush: new Brush(null, { style: Helper.GDI.BrushStyle.BS_SOLID, color: new ColorRef(null, 0, 0, 0), }), pen: new Pen(null, Helper.GDI.PenStyle.PS_SOLID, 1, new ColorRef(null, 0, 0, 0), null), font: new Font(null, null), palette: null, region: null, }; this.state = new GDIContextState(null, this.defObjects); this.statestack = [this.state]; this.objects = {}; } public setMapMode(mode: number): void { Helper.log("[gdi] setMapMode: mode=" + mode); this.state.mapmode = mode; this.state._svggroup = null; } public setWindowOrgEx(x: number, y: number): void { Helper.log("[gdi] setWindowOrgEx: x=" + x + " y=" + y); this.state.wx = x; this.state.wy = y; this.state._svggroup = null; } public setWindowExtEx(x: number, y: number): void { Helper.log("[gdi] setWindowExtEx: x=" + x + " y=" + y); this.state.ww = x; this.state.wh = y; this.state._svggroup = null; } public setViewportOrgEx(x: number, y: number): void { Helper.log("[gdi] setViewportOrgEx: x=" + x + " y=" + y); this.state.vx = x; this.state.vy = y; this.state._svggroup = null; } public setViewportExtEx(x: number, y: number): void { Helper.log("[gdi] setViewportExtEx: x=" + x + " y=" + y); this.state.vw = x; this.state.vh = y; this.state._svggroup = null; } public setBrushOrgEx(origin: PointL): void { Helper.log("[gdi] setBrushOrgEx: x=" + origin.x + " y=" + origin.y); this.state.nextbrx = origin.x; this.state.nextbry = origin.y; } public saveDC(): void { Helper.log("[gdi] saveDC"); const prevstate = this.state; this.state = new GDIContextState(this.state); this.statestack.push(prevstate); this.state._svggroup = null; } public restoreDC(saved: number): void { Helper.log("[gdi] restoreDC: saved=" + saved); if (this.statestack.length > 1) { if (saved === -1) { this.state = this.statestack.pop(); } else if (saved < -1) { throw new EMFJSError("restoreDC: relative restore not implemented"); } else if (saved > 1) { throw new EMFJSError("restoreDC: absolute restore not implemented"); } } else { throw new EMFJSError("No saved contexts"); } this.state._svggroup = null; } public setStretchBltMode(stretchMode: number): void { Helper.log("[gdi] setStretchBltMode: stretchMode=" + stretchMode); } public rectangle(rect: RectL, rw: number, rh: number): void { Helper.log("[gdi] rectangle: rect=" + rect.toString() + " with pen " + this.state.selected.pen.toString() + " and brush " + this.state.selected.brush.toString()); const bottom = this._todevY(rect.bottom); const right = this._todevX(rect.right); const top = this._todevY(rect.top); const left = this._todevX(rect.left); rw = this._todevH(rw); rh = this._todevH(rh); Helper.log("[gdi] rectangle: TRANSLATED: bottom=" + bottom + " right=" + right + " top=" + top + " left=" + left + " rh=" + rh + " rw=" + rw); this._pushGroup(); const opts = this._applyOpts(null, true, true, false); this._svg.rect(this.state._svggroup, left, top, right - left, bottom - top, rw / 2, rh / 2, opts); } public lineTo(x: number, y: number): void { Helper.log("[gdi] lineTo: x=" + x + " y=" + y + " with pen " + this.state.selected.pen.toString()); const toX = this._todevX(x); const toY = this._todevY(y); const fromX = this._todevX(this.state.x); const fromY = this._todevY(this.state.y); // Update position this.state.x = x; this.state.y = y; Helper.log("[gdi] lineTo: TRANSLATED: toX=" + toX + " toY=" + toY + " fromX=" + fromX + " fromY=" + fromY); this._pushGroup(); const opts = this._applyOpts(null, true, false, false); this._svg.line(this.state._svggroup, fromX, fromY, toX, toY, opts); } public moveToEx(x: number, y: number): void { Helper.log("[gdi] moveToEx: x=" + x + " y=" + y); this.state.x = x; this.state.y = y; if (this._svgPath != null) { this._svgPath.move(this.state.x, this.state.y); Helper.log("[gdi] new path: " + this._svgPath.path()); } } public polygon(points: PointS[] | PointL[], bounds: RectL, first: boolean): void { Helper.log("[gdi] polygon: points=" + points + " with pen " + this.state.selected.pen.toString() + " and brush " + this.state.selected.brush.toString()); const pts = []; for (let i = 0; i < points.length; i++) { const point = points[i]; pts.push([this._todevX(point.x), this._todevY(point.y)]); } if (first) { this._pushGroup(); } const opts = { "fill-rule": this.state.polyfillmode === Helper.GDI.PolygonFillMode.ALTERNATE ? "evenodd" : "nonzero", }; this._applyOpts(opts, true, true, false); this._svg.polygon(this.state._svggroup, pts, opts); } public polyPolygon(polygons: PointS[][] | PointL[][], bounds: RectL): void { Helper.log("[gdi] polyPolygon: polygons.length=" + polygons.length + " with pen " + this.state.selected.pen.toString() + " and brush " + this.state.selected.brush.toString()); const cnt = polygons.length; for (let i = 0; i < cnt; i++) { this.polygon(polygons[i], bounds, i === 0); } } public polyline(isLineTo: boolean, points: PointS[], bounds: RectL): void { Helper.log("[gdi] polyline: isLineTo=" + isLineTo.toString() + ", points=" + points + ", bounds=" + bounds.toString() + " with pen " + this.state.selected.pen.toString()); const pts: number[][] = []; for (let i = 0; i < points.length; i++) { const point = points[i]; pts.push([this._todevX(point.x), this._todevY(point.y)]); } if (this._svgPath != null) { if (!isLineTo || pts.length === 0) { this._svgPath.move(this._todevX(this.state.x), this._todevY(this.state.y)); } else { const firstPts = pts[0]; this._svgPath.move(firstPts[0], firstPts[1]); } this._svgPath.line(pts); Helper.log("[gdi] new path: " + this._svgPath.path()); } else { this._pushGroup(); const opts = this._applyOpts(null, true, false, false); if (isLineTo && points.length > 0) { const firstPt = points[0]; if (firstPt.x !== this.state.x || firstPt.y !== this.state.y) { pts.unshift([this._todevX(this.state.x), this._todevY(this.state.y)]); } } this._svg.polyline(this.state._svggroup, pts, opts); } if (points.length > 0) { const lastPt = points[points.length - 1]; this.state.x = lastPt.x; this.state.y = lastPt.y; } } public polybezier(isPolyBezierTo: boolean, points: PointS[], bounds: RectL): void { Helper.log("[gdi] polybezier: isPolyBezierTo=" + isPolyBezierTo.toString() + ", points=" + points + ", bounds=" + bounds.toString() + " with pen " + this.state.selected.pen.toString()); const pts = []; for (let i = 0; i < points.length; i++) { const point = points[i]; pts.push({x: this._todevX(point.x), y: this._todevY(point.y)}); } if (this._svgPath != null) { if (isPolyBezierTo && pts.length > 0) { const firstPts = pts[0]; this._svgPath.move(firstPts.x, firstPts.y); } else { this._svgPath.move(this._todevX(this.state.x), this._todevY(this.state.y)); } if (pts.length < (isPolyBezierTo ? 3 : 4)) { throw new EMFJSError("Not enough points to draw bezier"); } for (let i = isPolyBezierTo ? 1 : 0; i + 3 <= pts.length; i += 3) { const cp1 = pts[i]; const cp2 = pts[i + 1]; const ep = pts[i + 2]; this._svgPath.curveC(cp1.x, cp1.y, cp2.x, cp2.y, ep.x, ep.y); } Helper.log("[gdi] new path: " + this._svgPath.path()); } else { throw new EMFJSError("polybezier not implemented (not a path)"); } if (points.length > 0) { const lastPt = points[points.length - 1]; this.state.x = lastPt.x; this.state.y = lastPt.y; } } public selectClipPath(rgnMode: number): void { Helper.log("[gdi] selectClipPath: rgnMode=0x" + rgnMode.toString(16)); } public selectClipRgn(rgnMode: number, region: Region): void { Helper.log("[gdi] selectClipRgn: rgnMode=0x" + rgnMode.toString(16)); if (rgnMode === Helper.GDI.RegionMode.RGN_COPY) { this.state.selected.region = region; this.state.clip = null; this.state.ownclip = false; } else { if (region == null) { throw new EMFJSError("No clip region to select"); } throw new EMFJSError("Not implemented: rgnMode=0x" + rgnMode.toString(16)); } this.state._svgclipChanged = true; } public offsetClipRgn(offset: PointL): void { Helper.log("[gdi] offsetClipRgn: offset=" + offset.toString()); this._getClipRgn().offset(offset.x, offset.y); } public setTextAlign(textAlignmentMode: number): void { Helper.log("[gdi] setTextAlign: textAlignmentMode=0x" + textAlignmentMode.toString(16)); this.state.textalign = textAlignmentMode; } public setMiterLimit(miterLimit: number): void { Helper.log("[gdi] setMiterLimit: miterLimit=" + miterLimit); this.state.miterlimit = miterLimit; } public setBkMode(bkMode: number): void { Helper.log("[gdi] setBkMode: bkMode=0x" + bkMode.toString(16)); this.state.bkmode = bkMode; } public setBkColor(bkColor: ColorRef): void { Helper.log("[gdi] setBkColor: bkColor=" + bkColor.toString()); this.state.bkcolor = bkColor; this.state._svgtextbkfilter = null; } public setPolyFillMode(polyFillMode: number): void { Helper.log("[gdi] setPolyFillMode: polyFillMode=" + polyFillMode); this.state.polyfillmode = polyFillMode; } public createBrush(index: number, brush: Brush): void { const idx = this._storeObject(brush, index); Helper.log("[gdi] createBrush: brush=" + brush.toString() + " with handle " + idx); } public createPen(index: number, pen: Pen): void { const idx = this._storeObject(pen, index); Helper.log("[gdi] createPen: pen=" + pen.toString() + " width handle " + idx); } public createPenEx(index: number, pen: Pen): void { const idx = this._storeObject(pen, index); Helper.log("[gdi] createPenEx: pen=" + pen.toString() + " width handle " + idx); } public selectObject(objIdx: number, checkType: string): void { const obj = this._getObject(objIdx); if (obj != null && (checkType == null || obj.type === checkType)) { this._selectObject(obj); Helper.log("[gdi] selectObject: objIdx=" + objIdx + (obj ? " selected " + obj.type + ": " + obj.toString() : "[invalid index]")); } else { Helper.log("[gdi] selectObject: objIdx=" + objIdx + (obj ? " invalid object type: " + obj.type : "[invalid index]")); } } public abortPath(): void { Helper.log("[gdi] abortPath"); if (this._svgPath != null) { this._svgPath = null; } } public beginPath(): void { Helper.log("[gdi] beginPath"); if (this._svgPath != null) { this._svgPath = null; } this._svgPath = this._svg.createPath(); } public closeFigure(): void { Helper.log("[gdi] closeFigure"); if (this._svgPath == null) { throw new EMFJSError("No path bracket: cannot close figure"); } this._svgPath.close(); } public fillPath(bounds: RectL): void { Helper.log("[gdi] fillPath"); if (this.state.selected.path == null) { throw new EMFJSError("No path selected"); } const selPath = this.state.selected.path; const opts = this._applyOpts(null, true, true, false); this._svg.path(this.state._svggroup, selPath.svgPath, opts); this._pushGroup(); this.state.selected.path = null; } public strokePath(bounds: RectL): void { Helper.log("[gdi] strokePath"); if (this.state.selected.path == null) { throw new EMFJSError("No path selected"); } const selPath = this.state.selected.path; const opts = this._applyOpts({fill: "none"}, true, false, false); this._svg.path(this.state._svggroup, selPath.svgPath, opts); this._pushGroup(); this.state.selected.path = null; } public endPath(): void { Helper.log("[gdi] endPath"); if (this._svgPath == null) { throw new EMFJSError("No path bracket: cannot end path"); } this._pushGroup(); this._selectObject(new Path(this._svgPath)); this._svgPath = null; } public deleteObject(objIdx: number): void { const ret = this._deleteObject(objIdx); Helper.log("[gdi] deleteObject: objIdx=" + objIdx + (ret ? " deleted object" : "[invalid index]")); } private _pushGroup(): void { if (this.state._svggroup == null || this.state._svgclipChanged) { this.state._svgclipChanged = false; this.state._svgtextbkfilter = null; const settings: any = { viewBox: [this.state.vx, this.state.vy, this.state.vw, this.state.vh].join(" "), preserveAspectRatio: "none", }; if (this.state.clip != null) { Helper.log("[gdi] new svg x=" + this.state.vx + " y=" + this.state.vy + " width=" + this.state.vw + " height=" + this.state.vh + " with clipping"); settings["clip-path"] = "url(#" + this._getSvgClipPathForRegion(this.state.clip) + ")"; } else { Helper.log("[gdi] new svg x=" + this.state.vx + " y=" + this.state.vy + " width=" + this.state.vw + " height=" + this.state.vh + " without clipping"); } this.state._svggroup = this._svg.svg(this.state._svggroup, this.state.vx, this.state.vy, this.state.vw, this.state.vh, settings); } } private _getStockObject(idx: number) { if (idx >= 0x80000000 && idx <= 0x80000011) { return _StockObjects[(idx - 0x80000000).toString()]; } else if (idx === Helper.GDI.StockObject.DC_BRUSH) { return this.state.selected.brush; } else if (idx === Helper.GDI.StockObject.DC_PEN) { return this.state.selected.pen; } return null; } private _storeObject(obj: Obj, idx: number) { if (!idx) { idx = 0; while (this.objects[idx.toString()] != null && idx <= 65535) { idx++; } if (idx > 65535) { Helper.log("[gdi] Too many objects!"); return -1; } } this.objects[idx.toString()] = obj; return idx; } private _getObject(objIdx: number) { let obj = this.objects[objIdx.toString()]; if (obj == null) { obj = this._getStockObject(objIdx); if (obj == null) { Helper.log("[gdi] No object with handle " + objIdx); } } return obj; } private _getSvgDef() { if (this._svgdefs == null) { this._svgdefs = this._svg.defs(); } return this._svgdefs; } private _getSvgClipPathForRegion(region: Region) { for (const existingId in this._svgClipPaths) { const rgn = this._svgClipPaths[existingId]; if (rgn === region) { return existingId; } } const id = Helper._makeUniqueId("c"); const sclip = this._svg.clipPath(this._getSvgDef(), id, "userSpaceOnUse"); switch (region.complexity) { case 1: this._svg.rect(sclip, this._todevX(region.bounds.left), this._todevY(region.bounds.top), this._todevW(region.bounds.right - region.bounds.left), this._todevH(region.bounds.bottom - region.bounds.top), {"fill": "black", "stroke-width": 0}); break; case 2: for (let i = 0; i < region.scans.length; i++) { const scan = region.scans[i]; for (let j = 0; j < scan.scanlines.length; j++) { const scanline = scan.scanlines[j]; this._svg.rect(sclip, this._todevX(scanline.left), this._todevY(scan.top), this._todevW(scanline.right - scanline.left), this._todevH(scan.bottom - scan.top), {"fill": "black", "stroke-width": 0}); } } break; } this._svgClipPaths[id] = region; return id; } private _getSvgPatternForBrush(brush: Brush) { for (const existingId in this._svgPatterns) { const pat = this._svgPatterns[existingId]; if (pat === brush) { return existingId; } } let width; let height; let img; switch (brush.style) { case Helper.GDI.BrushStyle.BS_PATTERN: width = brush.pattern.getWidth(); height = brush.pattern.getHeight(); break; case Helper.GDI.BrushStyle.BS_DIBPATTERNPT: width = brush.dibpatternpt.getWidth(); height = brush.dibpatternpt.getHeight(); img = brush.dibpatternpt.base64ref(); break; default: throw new EMFJSError("Invalid brush style"); } const id = Helper._makeUniqueId("p"); const spat = this._svg.pattern(this._getSvgDef(), id, this.state.brx, this.state.bry, width, height, {patternUnits: "userSpaceOnUse"}); this._svg.image(spat, 0, 0, width, height, img); this._svgPatterns[id] = brush; return id; } private _selectObject(obj: Obj) { this.state.selected[obj.type] = obj; switch (obj.type) { case "region": this.state._svgclipChanged = true; break; case "brush": this.state.brx = this.state.nextbrx; this.state.bry = this.state.nextbry; break; } } private _deleteObject(objIdx: number) { const obj = this.objects[objIdx.toString()]; if (obj != null) { for (let i = 0; i < this.statestack.length; i++) { const state = this.statestack[i]; if (state.selected[obj.type] === obj) { state.selected[obj.type] = this.defObjects[obj.type].clone(); } } delete this.objects[objIdx.toString()]; return true; } Helper.log("[gdi] Cannot delete object with invalid handle " + objIdx); return false; } private _getClipRgn() { if (this.state.clip != null) { if (!this.state.ownclip) { this.state.clip = this.state.clip.clone(); } } else { if (this.state.selected.region != null) { this.state.clip = this.state.selected.region.clone(); } else { this.state.clip = CreateSimpleRegion(this.state.wx, this.state.wy, this.state.wx + this.state.ww, this.state.wy + this.state.wh); } } this.state.ownclip = true; return this.state.clip; } private _todevX(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor((val - this.state.wx) * (this.state.vw / this.state.ww)) + this.state.vx; } private _todevY(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor((val - this.state.wy) * (this.state.vh / this.state.wh)) + this.state.vy; } private _todevW(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor(val * (this.state.vw / this.state.ww)) + this.state.vx; } private _todevH(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor(val * (this.state.vh / this.state.wh)) + this.state.vy; } private _tologicalX(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor((val - this.state.vx) / (this.state.vw / this.state.ww)) + this.state.wx; } private _tologicalY(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor((val - this.state.vy) / (this.state.vh / this.state.wh)) + this.state.wy; } private _tologicalW(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor(val / (this.state.vw / this.state.ww)) + this.state.wx; } private _tologicalH(val: number) { // http://wvware.sourceforge.net/caolan/mapmode.html // logical -> device return Math.floor(val / (this.state.vh / this.state.wh)) + this.state.wy; } private _applyOpts(opts: any, usePen: boolean, useBrush: boolean, useFont: boolean) { if (opts == null) { opts = {}; } if (usePen) { const pen = this.state.selected.pen; if (pen.style !== Helper.GDI.PenStyle.PS_NULL) { opts.stroke = "#" + pen.color.toHex(); // TODO: pen style opts["stroke-width"] = pen.width; opts["stroke-miterlimit"] = this.state.miterlimit; opts["stroke-linecap"] = "round"; const dotWidth = 1; opts["stroke-linejoin"] = "round"; const dashWidth = opts["stroke-width"] * 4; const dotSpacing = opts["stroke-width"] * 2; switch (pen.style) { case Helper.GDI.PenStyle.PS_DASH: opts["stroke-dasharray"] = [dashWidth, dotSpacing].toString(); break; case Helper.GDI.PenStyle.PS_DOT: opts["stroke-dasharray"] = [dotWidth, dotSpacing].toString(); break; case Helper.GDI.PenStyle.PS_DASHDOT: opts["stroke-dasharray"] = [dashWidth, dotSpacing, dotWidth, dotSpacing].toString(); break; case Helper.GDI.PenStyle.PS_DASHDOTDOT: opts["stroke-dasharray"] = [dashWidth, dotSpacing, dotWidth, dotSpacing, dotWidth, dotSpacing].toString(); break; } } } if (useBrush) { const brush = this.state.selected.brush; switch (brush.style) { case Helper.GDI.BrushStyle.BS_SOLID: opts.fill = "#" + brush.color.toHex(); break; case Helper.GDI.BrushStyle.BS_PATTERN: case Helper.GDI.BrushStyle.BS_DIBPATTERNPT: opts.fill = "url(#" + this._getSvgPatternForBrush(brush) + ")"; break; case Helper.GDI.BrushStyle.BS_NULL: opts.fill = "none"; break; default: Helper.log("[gdi] unsupported brush style: " + brush.style); opts.fill = "none"; break; } } if (useFont) { const font = this.state.selected.font; opts["font-family"] = font.facename; opts["font-size"] = Math.abs(font.height); opts.fill = "#" + this.state.textcolor.toHex(); } return opts; } }
the_stack
import { PdfColor } from './../pdf-color'; import { PdfBrush } from './pdf-brush'; import { Dictionary } from './../../collections/dictionary'; import { KnownColor } from './enum'; import { PdfSolidBrush} from './pdf-solid-brush'; /** * `PdfBrushes` class provides objects used to fill the interiors of graphical shapes such as rectangles, * ellipses, pies, polygons, and paths. * @private */ export class PdfBrushes { //Static Fields /** * Local variable to store the brushes. */ private static sBrushes: Dictionary<KnownColor, PdfBrush> = new Dictionary<KnownColor, PdfBrush>(); //Static Properties /** * Gets the AliceBlue brush. * @public */ public static get AliceBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.AliceBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.AliceBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.AliceBlue); } return brush; } /** * Gets the antique white brush. * @public */ public static get AntiqueWhite(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.AntiqueWhite)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.AntiqueWhite))); } if ((brush == null)) { brush = this.getBrush(KnownColor.AntiqueWhite); } return brush; } /** * Gets the Aqua default brush. * @public */ public static get Aqua(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Aqua)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Aqua))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Aqua); } return brush; } /** * Gets the Aquamarine default brush. * @public */ public static get Aquamarine(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Aquamarine)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Aquamarine))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Aquamarine); } return brush; } /** * Gets the Azure default brush. * @public */ public static get Azure(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Azure)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Azure))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Azure); } return brush; } /** * Gets the Beige default brush. * @public */ public static get Beige(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Beige)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Beige))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Beige); } return brush; } /** * Gets the Bisque default brush. * @public */ public static get Bisque(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Bisque)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Bisque))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Bisque); } return brush; } /** * Gets the Black default brush. * @public */ public static get Black(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Black)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Black))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Black); } return brush; } /** * Gets the BlanchedAlmond default brush. * @public */ public static get BlanchedAlmond(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.BlanchedAlmond)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.BlanchedAlmond))); } if ((brush == null)) { brush = this.getBrush(KnownColor.BlanchedAlmond); } return brush; } /** * Gets the Blue default brush. * @public */ public static get Blue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Blue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Blue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Blue); } return brush; } /** * Gets the BlueViolet default brush. * @public */ public static get BlueViolet(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.BlueViolet)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.BlueViolet))); } if ((brush == null)) { brush = this.getBrush(KnownColor.BlueViolet); } return brush; } /** * Gets the Brown default brush. * @public */ public static get Brown(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Brown)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Brown))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Brown); } return brush; } /** * Gets the BurlyWood default brush. * @public */ public static get BurlyWood(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.BurlyWood)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.BurlyWood))); } if ((brush == null)) { brush = this.getBrush(KnownColor.BurlyWood); } return brush; } /** * Gets the CadetBlue default brush. * @public */ public static get CadetBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.CadetBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.CadetBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.CadetBlue); } return brush; } /** * Gets the Chartreuse default brush. * @public */ public static get Chartreuse(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Chartreuse)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Chartreuse))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Chartreuse); } return brush; } /** * Gets the Chocolate default brush. * @public */ public static get Chocolate(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Chocolate)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Chocolate))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Chocolate); } return brush; } /** * Gets the Coral default brush. * @public */ public static get Coral(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Coral)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Coral))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Coral); } return brush; } /** * Gets the CornflowerBlue default brush. * @public */ public static get CornflowerBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.CornflowerBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.CornflowerBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.CornflowerBlue); } return brush; } /** * Gets the Corn silk default brush. * @public */ public static get Cornsilk(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Cornsilk)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Cornsilk))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Cornsilk); } return brush; } /** * Gets the Crimson default brush. * @public */ public static get Crimson(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Crimson)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Crimson))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Crimson); } return brush; } /** * Gets the Cyan default brush. * @public */ public static get Cyan(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Cyan)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Cyan))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Cyan); } return brush; } /** * Gets the DarkBlue default brush. * @public */ public static get DarkBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkBlue); } return brush; } /** * Gets the DarkCyan default brush. * @public */ public static get DarkCyan(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkCyan)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkCyan))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkCyan); } return brush; } /** * Gets the DarkGoldenrod default brush. * @public */ public static get DarkGoldenrod(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkGoldenrod)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkGoldenrod))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkGoldenrod); } return brush; } /** * Gets the DarkGray default brush. * @public */ public static get DarkGray(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkGray)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkGray))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkGray); } return brush; } /** * Gets the DarkGreen default brush. * @public */ public static get DarkGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkGreen); } return brush; } /** * Gets the DarkKhaki default brush. * @public */ public static get DarkKhaki(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkKhaki)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkKhaki))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkKhaki); } return brush; } /** * Gets the DarkMagenta default brush. * @public */ public static get DarkMagenta(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkMagenta)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkMagenta))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkMagenta); } return brush; } /** * Gets the DarkOliveGreen default brush. * @public */ public static get DarkOliveGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkOliveGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkOliveGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkOliveGreen); } return brush; } /** * Gets the DarkOrange default brush. * @public */ public static get DarkOrange(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkOrange)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkOrange))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkOrange); } return brush; } /** * Gets the DarkOrchid default brush. * @public */ public static get DarkOrchid(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkOrchid)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkOrchid))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkOrchid); } return brush; } /** * Gets the DarkRed default brush. * @public */ public static get DarkRed(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkRed)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkRed))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkRed); } return brush; } /** * Gets the DarkSalmon default brush. * @public */ public static get DarkSalmon(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkSalmon)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkSalmon))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkSalmon); } return brush; } /** * Gets the DarkSeaGreen default brush. * @public */ public static get DarkSeaGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkSeaGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkSeaGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkSeaGreen); } return brush; } /** * Gets the DarkSlateBlue default brush. * @public */ public static get DarkSlateBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkSlateBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkSlateBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkSlateBlue); } return brush; } /** * Gets the DarkSlateGray default brush. * @public */ public static get DarkSlateGray(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkSlateGray)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkSlateGray))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkSlateGray); } return brush; } /** * Gets the DarkTurquoise default brush. * @public */ public static get DarkTurquoise(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkTurquoise)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkTurquoise))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkTurquoise); } return brush; } /** * Gets the DarkViolet default brush. * @public */ public static get DarkViolet(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DarkViolet)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DarkViolet))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DarkViolet); } return brush; } /** * Gets the DeepPink default brush. * @public */ public static get DeepPink(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DeepPink)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DeepPink))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DeepPink); } return brush; } /** * Gets the DeepSkyBlue default brush. * @public */ public static get DeepSkyBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DeepSkyBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DeepSkyBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DeepSkyBlue); } return brush; } /** * Gets the DimGray default brush. * @public */ public static get DimGray(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DimGray)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DimGray))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DimGray); } return brush; } /** * Gets the DodgerBlue default brush. * @public */ public static get DodgerBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.DodgerBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.DodgerBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.DodgerBlue); } return brush; } /** * Gets the Firebrick default brush. * @public */ public static get Firebrick(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Firebrick)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Firebrick))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Firebrick); } return brush; } /** * Gets the FloralWhite default brush. * @public */ public static get FloralWhite(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.FloralWhite)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.FloralWhite))); } if ((brush == null)) { brush = this.getBrush(KnownColor.FloralWhite); } return brush; } /** * Gets the ForestGreen default brush. * @public */ public static get ForestGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.ForestGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.ForestGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.ForestGreen); } return brush; } /** * Gets the Fuchsia default brush. * @public */ public static get Fuchsia(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Fuchsia)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Fuchsia))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Fuchsia); } return brush; } /** * Gets the Gainsborough default brush. * @public */ public static get Gainsboro(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Gainsboro)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Gainsboro))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Gainsboro); } return brush; } /** * Gets the GhostWhite default brush. * @public */ public static get GhostWhite(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.GhostWhite)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.GhostWhite))); } if ((brush == null)) { brush = this.getBrush(KnownColor.GhostWhite); } return brush; } /** * Gets the Gold default brush. * @public */ public static get Gold(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Gold)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Gold))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Gold); } return brush; } /** * Gets the Goldenrod default brush. * @public */ public static get Goldenrod(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Goldenrod)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Goldenrod))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Goldenrod); } return brush; } /** * Gets the Gray default brush. * @public */ public static get Gray(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Gray)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Gray))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Gray); } return brush; } /** * Gets the Green default brush. * @public */ public static get Green(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Green)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Green))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Green); } return brush; } /** * Gets the GreenYellow default brush. * @public */ public static get GreenYellow(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.GreenYellow)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.GreenYellow))); } if ((brush == null)) { brush = this.getBrush(KnownColor.GreenYellow); } return brush; } /** * Gets the Honeydew default brush. * @public */ public static get Honeydew(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Honeydew)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Honeydew))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Honeydew); } return brush; } /** * Gets the HotPink default brush. * @public */ public static get HotPink(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.HotPink)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.HotPink))); } if ((brush == null)) { brush = this.getBrush(KnownColor.HotPink); } return brush; } /** * Gets the IndianRed default brush. * @public */ public static get IndianRed(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.IndianRed)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.IndianRed))); } if ((brush == null)) { brush = this.getBrush(KnownColor.IndianRed); } return brush; } /** * Gets the Indigo default brush. * @public */ public static get Indigo(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Indigo)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Indigo))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Indigo); } return brush; } /** * Gets the Ivory default brush. * @public */ public static get Ivory(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Ivory)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Ivory))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Ivory); } return brush; } /** * Gets the Khaki default brush. * @public */ public static get Khaki(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Khaki)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Khaki))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Khaki); } return brush; } /** * Gets the Lavender default brush. * @public */ public static get Lavender(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Lavender)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Lavender))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Lavender); } return brush; } /** * Gets the LavenderBlush default brush. * @public */ public static get LavenderBlush(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LavenderBlush)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LavenderBlush))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LavenderBlush); } return brush; } /** * Gets the LawnGreen default brush. * @public */ public static get LawnGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LawnGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LawnGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LawnGreen); } return brush; } /** * Gets the LemonChiffon default brush. * @public */ public static get LemonChiffon(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LemonChiffon)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LemonChiffon))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LemonChiffon); } return brush; } /** * Gets the LightBlue default brush. * @public */ public static get LightBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightBlue); } return brush; } /** * Gets the LightCoral default brush. * @public */ public static get LightCoral(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightCoral)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightCoral))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightCoral); } return brush; } /** * Gets the LightCyan default brush. * @public */ public static get LightCyan(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightCyan)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightCyan))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightCyan); } return brush; } /** * Gets the LightGoldenrodYellow default brush. * @public */ public static get LightGoldenrodYellow(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightGoldenrodYellow)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightGoldenrodYellow))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightGoldenrodYellow); } return brush; } /** * Gets the LightGray default brush. * @public */ public static get LightGray(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightGray)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightGray))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightGray); } return brush; } /** * Gets the LightGreen default brush. * @public */ public static get LightGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightGreen); } return brush; } /** * Gets the LightPink default brush. * @public */ public static get LightPink(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightPink)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightPink))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightPink); } return brush; } /** * Gets the LightSalmon default brush. * @public */ public static get LightSalmon(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightSalmon)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightSalmon))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightSalmon); } return brush; } /** * Gets the LightSeaGreen default brush. * @public */ public static get LightSeaGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightSeaGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightSeaGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightSeaGreen); } return brush; } /** * Gets the LightSkyBlue default brush. * @public */ public static get LightSkyBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightSkyBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightSkyBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightSkyBlue); } return brush; } /** * Gets the LightSlateGray default brush. * @public */ public static get LightSlateGray(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightSlateGray)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightSlateGray))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightSlateGray); } return brush; } /** * Gets the LightSteelBlue default brush. * @public */ public static get LightSteelBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightSteelBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightSteelBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightSteelBlue); } return brush; } /** * Gets the LightYellow default brush. * @public */ public static get LightYellow(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LightYellow)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LightYellow))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LightYellow); } return brush; } /** * Gets the Lime default brush. * @public */ public static get Lime(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Lime)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Lime))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Lime); } return brush; } /** * Gets the LimeGreen default brush. * @public */ public static get LimeGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.LimeGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.LimeGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.LimeGreen); } return brush; } /** * Gets the Linen default brush. * @public */ public static get Linen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Linen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Linen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Linen); } return brush; } /** * Gets the Magenta default brush. * @public */ public static get Magenta(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Magenta)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Magenta))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Magenta); } return brush; } /** * Gets the Maroon default brush. * @public */ public static get Maroon(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Maroon)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Maroon))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Maroon); } return brush; } /** * Gets the MediumAquamarine default brush. * @public */ public static get MediumAquamarine(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumAquamarine)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumAquamarine))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumAquamarine); } return brush; } /** * Gets the MediumBlue default brush. * @public */ public static get MediumBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumBlue); } return brush; } /** * Gets the MediumOrchid default brush. * @public */ public static get MediumOrchid(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumOrchid)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumOrchid))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumOrchid); } return brush; } /** * Gets the MediumPurple default brush. * @public */ public static get MediumPurple(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumPurple)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumPurple))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumPurple); } return brush; } /** * Gets the MediumSeaGreen default brush. * @public */ public static get MediumSeaGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumSeaGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumSeaGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumSeaGreen); } return brush; } /** * Gets the MediumSlateBlue default brush. * @public */ public static get MediumSlateBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumSlateBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumSlateBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumSlateBlue); } return brush; } /** * Gets the MediumSpringGreen default brush. * @public */ public static get MediumSpringGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumSpringGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumSpringGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumSpringGreen); } return brush; } /** * Gets the MediumTurquoise default brush. * @public */ public static get MediumTurquoise(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumTurquoise)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumTurquoise))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumTurquoise); } return brush; } /** * Gets the MediumVioletRed default brush. * @public */ public static get MediumVioletRed(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MediumVioletRed)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MediumVioletRed))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MediumVioletRed); } return brush; } /** * Gets the MidnightBlue default brush. * @public */ public static get MidnightBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MidnightBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MidnightBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MidnightBlue); } return brush; } /** * Gets the MintCream default brush. * @public */ public static get MintCream(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MintCream)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MintCream))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MintCream); } return brush; } /** * Gets the MistyRose default brush. * @public */ public static get MistyRose(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.MistyRose)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.MistyRose))); } if ((brush == null)) { brush = this.getBrush(KnownColor.MistyRose); } return brush; } /** * Gets the Moccasin default brush. * @public */ public static get Moccasin(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Moccasin)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Moccasin))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Moccasin); } return brush; } /** * Gets the NavajoWhite default brush. * @public */ public static get NavajoWhite(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.NavajoWhite)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.NavajoWhite))); } if ((brush == null)) { brush = this.getBrush(KnownColor.NavajoWhite); } return brush; } /** * Gets the Navy default brush. * @public */ public static get Navy(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Navy)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Navy))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Navy); } return brush; } /** * Gets the OldLace default brush. * @public */ public static get OldLace(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.OldLace)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.OldLace))); } if ((brush == null)) { brush = this.getBrush(KnownColor.OldLace); } return brush; } /** * Gets the Olive default brush. * @public */ public static get Olive(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Olive)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Olive))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Olive); } return brush; } /** * Gets the OliveDrab default brush. * @public */ public static get OliveDrab(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.OliveDrab)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.OliveDrab))); } if ((brush == null)) { brush = this.getBrush(KnownColor.OliveDrab); } return brush; } /** * Gets the Orange default brush. * @public */ public static get Orange(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Orange)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Orange))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Orange); } return brush; } /** * Gets the OrangeRed default brush. * @public */ public static get OrangeRed(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.OrangeRed)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.OrangeRed))); } if ((brush == null)) { brush = this.getBrush(KnownColor.OrangeRed); } return brush; } /** * Gets the Orchid default brush. * @public */ public static get Orchid(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Orchid)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Orchid))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Orchid); } return brush; } /** * Gets the PaleGoldenrod default brush. * @public */ public static get PaleGoldenrod(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.PaleGoldenrod)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.PaleGoldenrod))); } if ((brush == null)) { brush = this.getBrush(KnownColor.PaleGoldenrod); } return brush; } /** * Gets the PaleGreen default brush. * @public */ public static get PaleGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.PaleGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.PaleGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.PaleGreen); } return brush; } /** * Gets the PaleTurquoise default brush. * @public */ public static get PaleTurquoise(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.PaleTurquoise)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.PaleTurquoise))); } if ((brush == null)) { brush = this.getBrush(KnownColor.PaleTurquoise); } return brush; } /** * Gets the PaleVioletRed default brush. * @public */ public static get PaleVioletRed(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.PaleVioletRed)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.PaleVioletRed))); } if ((brush == null)) { brush = this.getBrush(KnownColor.PaleVioletRed); } return brush; } /** * Gets the PapayaWhip default brush. * @public */ public static get PapayaWhip(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.PapayaWhip)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.PapayaWhip))); } if ((brush == null)) { brush = this.getBrush(KnownColor.PapayaWhip); } return brush; } /** * Gets the PeachPuff default brush. * @public */ public static get PeachPuff(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.PeachPuff)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.PeachPuff))); } if ((brush == null)) { brush = this.getBrush(KnownColor.PeachPuff); } return brush; } /** * Gets the Peru default brush. * @public */ public static get Peru(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Peru)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Peru))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Peru); } return brush; } /** * Gets the Pink default brush. * @public */ public static get Pink(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Pink)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Pink))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Pink); } return brush; } /** * Gets the Plum default brush. * @public */ public static get Plum(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Plum)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Plum))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Plum); } return brush; } /** * Gets the PowderBlue default brush. * @public */ public static get PowderBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.PowderBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.PowderBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.PowderBlue); } return brush; } /** * Gets the Purple default brush. * @public */ public static get Purple(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Purple)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Purple))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Purple); } return brush; } /** * Gets the Red default brush. * @public */ public static get Red(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Red)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Red))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Red); } return brush; } /** * Gets the RosyBrown default brush. * @public */ public static get RosyBrown(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.RosyBrown)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.RosyBrown))); } if ((brush == null)) { brush = this.getBrush(KnownColor.RosyBrown); } return brush; } /** * Gets the RoyalBlue default brush. * @public */ public static get RoyalBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.RoyalBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.RoyalBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.RoyalBlue); } return brush; } /** * Gets the SaddleBrown default brush. * @public */ public static get SaddleBrown(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SaddleBrown)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SaddleBrown))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SaddleBrown); } return brush; } /** * Gets the Salmon default brush. * @public */ public static get Salmon(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Salmon)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Salmon))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Salmon); } return brush; } /** * Gets the SandyBrown default brush. * @public */ public static get SandyBrown(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SandyBrown)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SandyBrown))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SandyBrown); } return brush; } /** * Gets the SeaGreen default brush. * @public */ public static get SeaGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SeaGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SeaGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SeaGreen); } return brush; } /** * Gets the SeaShell default brush. * @public */ public static get SeaShell(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SeaShell)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SeaShell))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SeaShell); } return brush; } /** * Gets the Sienna default brush. * @public */ public static get Sienna(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Sienna)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Sienna))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Sienna); } return brush; } /** * Gets the Silver default brush. * @public */ public static get Silver(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Silver)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Silver))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Silver); } return brush; } /** * Gets the SkyBlue default brush. * @public */ public static get SkyBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SkyBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SkyBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SkyBlue); } return brush; } /** * Gets the SlateBlue default brush. * @public */ public static get SlateBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SlateBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SlateBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SlateBlue); } return brush; } /** * Gets the SlateGray default brush. * @public */ public static get SlateGray(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SlateGray)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SlateGray))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SlateGray); } return brush; } /** * Gets the Snow default brush. * @public */ public static get Snow(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Snow)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Snow))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Snow); } return brush; } /** * Gets the SpringGreen default brush. * @public */ public static get SpringGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SpringGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SpringGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SpringGreen); } return brush; } /** * Gets the SteelBlue default brush. * @public */ public static get SteelBlue(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.SteelBlue)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.SteelBlue))); } if ((brush == null)) { brush = this.getBrush(KnownColor.SteelBlue); } return brush; } /** * Gets the Tan default brush. * @public */ public static get Tan(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Tan)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Tan))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Tan); } return brush; } /** * Gets the Teal default brush. * @public */ public static get Teal(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Teal)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Teal))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Teal); } return brush; } /** * Gets the Thistle default brush. * @public */ public static get Thistle(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Thistle)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Thistle))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Thistle); } return brush; } /** * Gets the Tomato default brush. * @public */ public static get Tomato(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Tomato)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Tomato))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Tomato); } return brush; } /** * Gets the Transparent default brush. * @public */ public static get Transparent(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Transparent)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Transparent))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Transparent); } return brush; } /** * Gets the Turquoise default brush. * @public */ public static get Turquoise(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Turquoise)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Turquoise))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Turquoise); } return brush; } /** * Gets the Violet default brush. * @public */ public static get Violet(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Violet)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Violet))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Violet); } return brush; } /** * Gets the Wheat default brush. * @public */ public static get Wheat(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Wheat)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Wheat))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Wheat); } return brush; } /** * Gets the White default brush. * @public */ public static get White(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.White)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.White))); } if ((brush == null)) { brush = this.getBrush(KnownColor.White); } return brush; } /** * Gets the WhiteSmoke default brush. * @public */ public static get WhiteSmoke(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.WhiteSmoke)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.WhiteSmoke))); } if ((brush == null)) { brush = this.getBrush(KnownColor.WhiteSmoke); } return brush; } /** * Gets the Yellow default brush. * @public */ public static get Yellow(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.Yellow)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.Yellow))); } if ((brush == null)) { brush = this.getBrush(KnownColor.Yellow); } return brush; } /** * Gets the YellowGreen default brush. * @public */ public static get YellowGreen(): PdfBrush { let brush: PdfBrush = null; if (this.sBrushes.containsKey(KnownColor.YellowGreen)) { brush = (<PdfBrush>(this.sBrushes.getValue(KnownColor.YellowGreen))); } if ((brush == null)) { brush = this.getBrush(KnownColor.YellowGreen); } return brush; } /** * Get the brush. */ private static getBrush(colorName: KnownColor): PdfBrush { let pdfColor: PdfColor = this.getColorValue(colorName); let brush: PdfBrush = new PdfSolidBrush(pdfColor); this.sBrushes.setValue(colorName, brush); return brush; } /** * Get the color value. * @param colorName The KnownColor name. */ /* tslint:disable */ private static getColorValue(colorName : KnownColor): PdfColor { let color : PdfColor = new PdfColor(); switch (colorName) { case KnownColor.Transparent: color = new PdfColor(0, 255, 255, 255); break; case KnownColor.AliceBlue: color = new PdfColor(255, 240, 248, 255); break; case KnownColor.AntiqueWhite: color = new PdfColor(255, 250, 235, 215); break; case KnownColor.Aqua: color = new PdfColor(255, 0, 255, 255); break; case KnownColor.Aquamarine: color = new PdfColor(255, 127, 255, 212); break; case KnownColor.Azure: color = new PdfColor(255, 240, 255, 255); break; case KnownColor.Beige: color = new PdfColor(255, 245, 245, 220); break; case KnownColor.Bisque: color = new PdfColor(255, 255, 228, 196); break; case KnownColor.Black: color = new PdfColor(255, 0, 0, 0); break; case KnownColor.BlanchedAlmond: color = new PdfColor(255, 255, 235, 205); break; case KnownColor.Blue: color = new PdfColor(255, 0, 0, 255); break; case KnownColor.BlueViolet: color = new PdfColor(255, 138, 43, 226); break; case KnownColor.Brown: color = new PdfColor(255, 165, 42, 42); break; case KnownColor.BurlyWood: color = new PdfColor(255, 222, 184, 135); break; case KnownColor.CadetBlue: color = new PdfColor(255, 95, 158, 160); break; case KnownColor.Chartreuse: color = new PdfColor(255, 127, 255, 0); break; case KnownColor.Chocolate: color = new PdfColor(255, 210, 105, 30); break; case KnownColor.Coral: color = new PdfColor(255, 255, 127, 80); break; case KnownColor.CornflowerBlue: color = new PdfColor(255, 100, 149, 237); break; case KnownColor.Cornsilk: color = new PdfColor(255, 255, 248, 220); break; case KnownColor.Crimson: color = new PdfColor(255, 220, 20, 60); break; case KnownColor.Cyan: color = new PdfColor(255, 0, 255, 255); break; case KnownColor.DarkBlue: color = new PdfColor(255, 0, 0, 139); break; case KnownColor.DarkCyan: color = new PdfColor(255, 0, 139, 139); break; case KnownColor.DarkGoldenrod: color = new PdfColor(255, 184, 134, 11); break; case KnownColor.DarkGray: color = new PdfColor(255, 169, 169, 169); break; case KnownColor.DarkGreen: color = new PdfColor(255, 0, 100, 0); break; case KnownColor.DarkKhaki: color = new PdfColor(255, 189, 183, 107); break; case KnownColor.DarkMagenta: color = new PdfColor(255, 139, 0, 139); break; case KnownColor.DarkOliveGreen: color = new PdfColor(255, 85, 107, 47); break; case KnownColor.DarkOrange: color = new PdfColor(255, 255, 140, 0); break; case KnownColor.DarkOrchid: color = new PdfColor(255, 153, 50, 204); break; case KnownColor.DarkRed: color = new PdfColor(255, 139, 0, 0); break; case KnownColor.DarkSalmon: color = new PdfColor(255, 233, 150, 122); break; case KnownColor.DarkSeaGreen: color = new PdfColor(255, 143, 188, 139); break; case KnownColor.DarkSlateBlue: color = new PdfColor(255, 72, 61, 139); break; case KnownColor.DarkSlateGray: color = new PdfColor(255, 47, 79, 79); break; case KnownColor.DarkTurquoise: color = new PdfColor(255, 0, 206, 209); break; case KnownColor.DarkViolet: color = new PdfColor(255, 148, 0, 211); break; case KnownColor.DeepPink: color = new PdfColor(255, 255, 20, 147); break; case KnownColor.DeepSkyBlue: color = new PdfColor(255, 0, 191, 255); break; case KnownColor.DimGray: color = new PdfColor(255, 105, 105, 105); break; case KnownColor.DodgerBlue: color = new PdfColor(255, 30, 144, 255); break; case KnownColor.Firebrick: color = new PdfColor(255, 178, 34, 34); break; case KnownColor.FloralWhite: color = new PdfColor(255, 255, 250, 240); break; case KnownColor.ForestGreen: color = new PdfColor(255, 34, 139, 34); break; case KnownColor.Fuchsia: color = new PdfColor(255, 255, 0, 255); break; case KnownColor.Gainsboro: color = new PdfColor(255, 220, 220, 220); break; case KnownColor.GhostWhite: color = new PdfColor(255, 248, 248, 255); break; case KnownColor.Gold: color = new PdfColor(255, 255, 215, 0); break; case KnownColor.Goldenrod: color = new PdfColor(255, 218, 165, 32); break; case KnownColor.Gray: color = new PdfColor(255, 128, 128, 128); break; case KnownColor.Green: color = new PdfColor(255, 0, 128, 0); break; case KnownColor.GreenYellow: color = new PdfColor(255, 173, 255, 47); break; case KnownColor.Honeydew: color = new PdfColor(255, 240, 255, 240); break; case KnownColor.HotPink: color = new PdfColor(255, 255, 105, 180); break; case KnownColor.IndianRed: color = new PdfColor(255, 205, 92, 92); break; case KnownColor.Indigo: color = new PdfColor(255, 75, 0, 130); break; case KnownColor.Ivory: color = new PdfColor(255, 255, 255, 240); break; case KnownColor.Khaki: color = new PdfColor(255, 240, 230, 140); break; case KnownColor.Lavender: color = new PdfColor(255, 230, 230, 250); break; case KnownColor.LavenderBlush: color = new PdfColor(255, 255, 240, 245); break; case KnownColor.LawnGreen: color = new PdfColor(255, 124, 252, 0); break; case KnownColor.LemonChiffon: color = new PdfColor(255, 255, 250, 205); break; case KnownColor.LightBlue: color = new PdfColor(255, 173, 216, 230); break; case KnownColor.LightCoral: color = new PdfColor(255, 240, 128, 128); break; case KnownColor.LightCyan: color = new PdfColor(255, 224, 255, 255); break; case KnownColor.LightGoldenrodYellow: color = new PdfColor(255, 250, 250, 210); break; case KnownColor.LightGreen: color = new PdfColor(255, 144, 238, 144); break; case KnownColor.LightGray: color = new PdfColor(255, 211, 211, 211); break; case KnownColor.LightPink: color = new PdfColor(255, 255, 182, 193); break; case KnownColor.LightSalmon: color = new PdfColor(255, 255, 160, 122); break; case KnownColor.LightSeaGreen: color = new PdfColor(255, 32, 178, 170); break; case KnownColor.LightSkyBlue: color = new PdfColor(255, 135, 206, 250); break; case KnownColor.LightSlateGray: color = new PdfColor(255, 119, 136, 153); break; case KnownColor.LightSteelBlue: color = new PdfColor(255, 176, 196, 222); break; case KnownColor.LightYellow: color = new PdfColor(255, 255, 255, 224); break; case KnownColor.Lime: color = new PdfColor(255, 0, 255, 0); break; case KnownColor.LimeGreen: color = new PdfColor(255, 50, 205, 50); break; case KnownColor.Linen: color = new PdfColor(255, 250, 240, 230); break; case KnownColor.Magenta: color = new PdfColor(255, 255, 0, 255); break; case KnownColor.Maroon: color = new PdfColor(255, 128, 0, 0); break; case KnownColor.MediumAquamarine: color = new PdfColor(255, 102, 205, 170); break; case KnownColor.MediumBlue: color = new PdfColor(255, 0, 0, 205); break; case KnownColor.MediumOrchid: color = new PdfColor(255, 186, 85, 211); break; case KnownColor.MediumPurple: color = new PdfColor(255, 147, 112, 219); break; case KnownColor.MediumSeaGreen: color = new PdfColor(255, 60, 179, 113); break; case KnownColor.MediumSlateBlue: color = new PdfColor(255, 123, 104, 238); break; case KnownColor.MediumSpringGreen: color = new PdfColor(255, 0, 250, 154); break; case KnownColor.MediumTurquoise: color = new PdfColor(255, 72, 209, 204); break; case KnownColor.MediumVioletRed: color = new PdfColor(255, 199, 21, 133); break; case KnownColor.MidnightBlue: color = new PdfColor(255, 25, 25, 112); break; case KnownColor.MintCream: color = new PdfColor(255, 245, 255, 250); break; case KnownColor.MistyRose: color = new PdfColor(255, 255, 228, 225); break; case KnownColor.Moccasin: color = new PdfColor(255, 255, 228, 181); break; case KnownColor.NavajoWhite: color = new PdfColor(255, 255, 222, 173); break; case KnownColor.Navy: color = new PdfColor(255, 0, 0, 128); break; case KnownColor.OldLace: color = new PdfColor(255, 253, 245, 230); break; case KnownColor.Olive: color = new PdfColor(255, 128, 128, 0); break; case KnownColor.OliveDrab: color = new PdfColor(255, 107, 142, 35); break; case KnownColor.Orange: color = new PdfColor(255, 255, 165, 0); break; case KnownColor.OrangeRed: color = new PdfColor(255, 255, 69, 0); break; case KnownColor.Orchid: color = new PdfColor(255, 218, 112, 214); break; case KnownColor.PaleGoldenrod: color = new PdfColor(255, 238, 232, 170); break; case KnownColor.PaleGreen: color = new PdfColor(255, 152, 251, 152); break; case KnownColor.PaleTurquoise: color = new PdfColor(255, 175, 238, 238); break; case KnownColor.PaleVioletRed: color = new PdfColor(255, 219, 112, 147); break; case KnownColor.PapayaWhip: color = new PdfColor(255, 255, 239, 213); break; case KnownColor.PeachPuff: color = new PdfColor(255, 255, 218, 185); break; case KnownColor.Peru: color = new PdfColor(255, 205, 133, 63); break; case KnownColor.Pink: color = new PdfColor(255, 255, 192, 203); break; case KnownColor.Plum: color = new PdfColor(255, 221, 160, 221); break; case KnownColor.PowderBlue: color = new PdfColor(255, 176, 224, 230); break; case KnownColor.Purple: color = new PdfColor(255, 128, 0, 128); break; case KnownColor.Red: color = new PdfColor(255, 255, 0, 0); break; case KnownColor.RosyBrown: color = new PdfColor(255, 188, 143, 143); break; case KnownColor.RoyalBlue: color = new PdfColor(255, 65, 105, 225); break; case KnownColor.SaddleBrown: color = new PdfColor(255, 139, 69, 19); break; case KnownColor.Salmon: color = new PdfColor(255, 250, 128, 114); break; case KnownColor.SandyBrown: color = new PdfColor(255, 244, 164, 96); break; case KnownColor.SeaGreen: color = new PdfColor(255, 46, 139, 87); break; case KnownColor.SeaShell: color = new PdfColor(255, 255, 245, 238); break; case KnownColor.Sienna: color = new PdfColor(255, 160, 82, 45); break; case KnownColor.Silver: color = new PdfColor(255, 192, 192, 192); break; case KnownColor.SkyBlue: color = new PdfColor(255, 135, 206, 235); break; case KnownColor.SlateBlue: color = new PdfColor(255, 106, 90, 205); break; case KnownColor.SlateGray: color = new PdfColor(255, 112, 128, 144); break; case KnownColor.Snow: color = new PdfColor(255, 255, 250, 250); break; case KnownColor.SpringGreen: color = new PdfColor(255, 0, 255, 127); break; case KnownColor.SteelBlue: color = new PdfColor(255, 70, 130, 180); break; case KnownColor.Tan: color = new PdfColor(255, 210, 180, 140); break; case KnownColor.Teal: color = new PdfColor(255, 0, 128, 128); break; case KnownColor.Thistle: color = new PdfColor(255, 216, 191, 216); break; case KnownColor.Tomato: color = new PdfColor(255, 255, 99, 71); break; case KnownColor.Turquoise: color = new PdfColor(255, 64, 224, 208); break; case KnownColor.Violet: color = new PdfColor(255, 238, 130, 238); break; case KnownColor.Wheat: color = new PdfColor(255, 245, 222, 179); break; case KnownColor.White: color = new PdfColor(255, 255, 255, 255); break; case KnownColor.WhiteSmoke: color = new PdfColor(255, 245, 245, 245); break; case KnownColor.Yellow: color = new PdfColor(255, 255, 255, 0); break; case KnownColor.YellowGreen: color = new PdfColor(255, 154, 205, 50); break; } return color; } }
the_stack
import { PAGModule } from '../binding'; import { destroyVerify, wasmAwaitRewind } from '../utils/decorators'; import { MatrixIndex } from '../types'; @destroyVerify @wasmAwaitRewind export class Matrix { /** * Sets Matrix to: * * | scaleX skewX transX | * | skewY scaleY transY | * | pers0 pers1 pers2 | * * @param scaleX horizontal scale factor * @param skewX horizontal skew factor * @param transX horizontal translation * @param skewY vertical skew factor * @param scaleY vertical scale factor * @param transY vertical translation * @param pers0 input x-axis perspective factor * @param pers1 input y-axis perspective factor * @param pers2 perspective scale factor * @return Matrix constructed from parameters */ public static makeAll( scaleX: number, skewX: number, transX: number, skewY: number, scaleY: number, transY: number, pers0 = 0, pers1 = 0, pers2 = 1, ): Matrix { const wasmIns = PAGModule._Matrix._MakeAll(scaleX, skewX, transX, skewY, scaleY, transY, pers0, pers1, pers2); if (!wasmIns) throw new Error('Matrix.makeAll fail, please check parameters valid!'); return new Matrix(wasmIns); } /** * Sets Matrix to scale by (sx, sy). Returned matrix is: * * | sx 0 0 | * | 0 sy 0 | * | 0 0 1 | * * @param scaleX horizontal scale factor * @param scaleY [optionals] vertical scale factor, default equal scaleX. * @return Matrix with scale */ public static makeScale(scaleX: number, scaleY?: number): Matrix { let wasmIns; if (scaleY !== undefined) { wasmIns = PAGModule._Matrix._MakeScale(scaleX, scaleY); } else { wasmIns = PAGModule._Matrix._MakeScale(scaleX); } if (!wasmIns) throw new Error('Matrix.makeScale fail, please check parameters valid!'); return new Matrix(wasmIns); } /** * Sets Matrix to translate by (dx, dy). Returned matrix is: * * | 1 0 dx | * | 0 1 dy | * | 0 0 1 | * * @param dx horizontal translation * @param dy vertical translation * @return Matrix with translation */ public static makeTrans(dx: number, dy: number): Matrix { const wasmIns = PAGModule._Matrix._MakeTrans(dx, dy); if (!wasmIns) throw new Error('Matrix.makeTrans fail, please check parameters valid!'); return new Matrix(wasmIns); } public wasmIns; public isDestroyed = false; public constructor(wasmIns: any) { this.wasmIns = wasmIns; } /** * scaleX; horizontal scale factor to store */ public get a(): number { return this.wasmIns ? this.wasmIns._get(MatrixIndex.a) : 0; } public set a(value: number) { this.wasmIns?._set(MatrixIndex.a, value); } /** * skewY; vertical skew factor to store */ public get b(): number { return this.wasmIns ? this.wasmIns._get(MatrixIndex.b) : 0; } public set b(value: number) { this.wasmIns?._set(MatrixIndex.b, value); } /** * skewX; horizontal skew factor to store */ public get c(): number { return this.wasmIns ? this.wasmIns._get(MatrixIndex.c) : 0; } public set c(value: number) { this.wasmIns?._set(MatrixIndex.c, value); } /** * scaleY; vertical scale factor to store */ public get d(): number { return this.wasmIns ? this.wasmIns._get(MatrixIndex.d) : 0; } public set d(value: number) { this.wasmIns?._set(MatrixIndex.d, value); } /** * transX; horizontal translation to store */ public get tx(): number { return this.wasmIns ? this.wasmIns._get(MatrixIndex.tx) : 0; } public set tx(value: number) { this.wasmIns?._set(MatrixIndex.tx, value); } /** * transY; vertical translation to store */ public get ty(): number { return this.wasmIns ? this.wasmIns._get(MatrixIndex.ty) : 0; } public set ty(value: number) { this.wasmIns?._set(MatrixIndex.ty, value); } /** * Returns one matrix value. */ public get(index: MatrixIndex): number { return this.wasmIns ? this.wasmIns._get(index) : 0; } /** * Sets Matrix value. */ public set(index: MatrixIndex, value: number) { this.wasmIns?._set(index, value); } /** * Sets all values from parameters. Sets matrix to: * * | scaleX skewX transX | * | skewY scaleY transY | * | persp0 persp1 persp2 | * * @param scaleX horizontal scale factor to store * @param skewX horizontal skew factor to store * @param transX horizontal translation to store * @param skewY vertical skew factor to store * @param scaleY vertical scale factor to store * @param transY vertical translation to store * @param persp0 input x-axis values perspective factor to store * @param persp1 input y-axis values perspective factor to store * @param persp2 perspective scale factor to store */ public setAll( scaleX: number, skewX: number, transX: number, skewY: number, scaleY: number, transY: number, pers0 = 0, pers1 = 0, pers2 = 1, ) { this.wasmIns?._setAll(scaleX, skewX, transX, skewY, scaleY, transY, pers0, pers1, pers2); } public setAffine(a: number, b: number, c: number, d: number, tx: number, ty: number) { this.wasmIns?._setAffine(a, b, c, d, tx, ty); } /** * Sets Matrix to identity; which has no effect on mapped Point. Sets Matrix to: * * | 1 0 0 | * | 0 1 0 | * | 0 0 1 | * * Also called setIdentity(); use the one that provides better inline documentation. */ public reset() { this.wasmIns?._reset(); } /** * Sets Matrix to translate by (dx, dy). * @param dx horizontal translation * @param dy vertical translation */ public setTranslate(dx: number, dy: number) { this.wasmIns?._setTranslate(dx, dy); } /** * Sets Matrix to scale by sx and sy, about a pivot point at (px, py). The pivot point is * unchanged when mapped with Matrix. * @param sx horizontal scale factor * @param sy vertical scale factor * @param px pivot on x-axis * @param py pivot on y-axis */ public setScale(sx: number, sy: number, px = 0, py = 0) { this.wasmIns?._setScale(sx, sy, px, py); } /** * Sets Matrix to rotate by degrees about a pivot point at (px, py). The pivot point is * unchanged when mapped with Matrix. Positive degrees rotates clockwise. * @param degrees angle of axes relative to upright axes * @param px pivot on x-axis * @param py pivot on y-axis */ public setRotate(degrees: number, px = 0, py = 0) { this.wasmIns?._setRotate(degrees, px, py); } /** * Sets Matrix to rotate by sinValue and cosValue, about a pivot point at (px, py). * The pivot point is unchanged when mapped with Matrix. * Vector (sinValue, cosValue) describes the angle of rotation relative to (0, 1). * Vector length specifies scale. */ public setSinCos(sinV: number, cosV: number, px = 0, py = 0) { this.wasmIns?._setSinCos(sinV, cosV, px, py); } /** * Sets Matrix to skew by kx and ky, about a pivot point at (px, py). The pivot point is * unchanged when mapped with Matrix. * @param kx horizontal skew factor * @param ky vertical skew factor * @param px pivot on x-axis * @param py pivot on y-axis */ public setSkew(kx: number, ky: number, px = 0, py = 0) { this.wasmIns?._setSkew(kx, ky, px, py); } /** * Sets Matrix to Matrix a multiplied by Matrix b. Either a or b may be this. * * Given: * * | A B C | | J K L | * a = | D E F |, b = | M N O | * | G H I | | P Q R | * * sets Matrix to: * * | A B C | | J K L | | AJ+BM+CP AK+BN+CQ AL+BO+CR | * a * b = | D E F | * | M N O | = | DJ+EM+FP DK+EN+FQ DL+EO+FR | * | G H I | | P Q R | | GJ+HM+IP GK+HN+IQ GL+HO+IR | * * @param a Matrix on left side of multiply expression * @param b Matrix on right side of multiply expression */ public setConcat(a: Matrix, b: Matrix) { this.wasmIns?._setConcat(a.wasmIns, b.wasmIns); } /** * Preconcats the matrix with the specified scale. M' = M * S(sx, sy) */ public preTranslate(dx: number, dy: number) { this.wasmIns?._preTranslate(dx, dy); } /** * Postconcats the matrix with the specified scale. M' = S(sx, sy, px, py) * M */ public preScale(sx: number, sy: number, px = 0, py = 0) { this.wasmIns?._preScale(sx, sy, px, py); } /** * Preconcats the matrix with the specified rotation. M' = M * R(degrees, px, py) */ public preRotate(degrees: number, px = 0, py = 0) { this.wasmIns?._preRotate(degrees, px, py); } /** * Preconcats the matrix with the specified skew. M' = M * K(kx, ky, px, py) */ public preSkew(kx: number, ky: number, px = 0, py = 0) { this.wasmIns?._preSkew(kx, ky, px, py); } /** * Preconcats the matrix with the specified matrix. M' = M * other */ public preConcat(other: Matrix) { this.wasmIns?._preConcat(other.wasmIns); } /** * Postconcats the matrix with the specified translation. M' = T(dx, dy) * M */ public postTranslate(dx: number, dy: number) { this.wasmIns?._postTranslate(dx, dy); } /** * Postconcats the matrix with the specified scale. M' = S(sx, sy, px, py) * M */ public postScale(sx: number, sy: number, px = 0, py = 0) { this.wasmIns?._postScale(sx, sy, px, py); } /** * Postconcats the matrix with the specified rotation. M' = R(degrees, px, py) * M */ public postRotate(degrees: number, px = 0, py = 0) { this.wasmIns?._postRotate(degrees, px, py); } /** * Postconcats the matrix with the specified skew. M' = K(kx, ky, px, py) * M */ public postSkew(kx: number, ky: number, px = 0, py = 0) { this.wasmIns?._postSkew(kx, ky, px, py); } /** * Postconcats the matrix with the specified matrix. M' = other * M */ public postConcat(other: Matrix) { this.wasmIns?._postConcat(other.wasmIns); } public destroy() { this.wasmIns.delete(); } }
the_stack
import * as io from '../../io/src/io' import * as path from 'path' import {promises as fs} from 'fs' import * as core from '@actions/core' import {getUploadSpecification} from '../src/internal/upload-specification' const artifactName = 'my-artifact' const root = path.join(__dirname, '_temp', 'upload-specification') const goodItem1Path = path.join( root, 'folder-a', 'folder-b', 'folder-c', 'good-item1.txt' ) const goodItem2Path = path.join(root, 'folder-d', 'good-item2.txt') const goodItem3Path = path.join(root, 'folder-d', 'good-item3.txt') const goodItem4Path = path.join(root, 'folder-d', 'good-item4.txt') const goodItem5Path = path.join(root, 'good-item5.txt') const badItem1Path = path.join( root, 'folder-a', 'folder-b', 'folder-c', 'bad-item1.txt' ) const badItem2Path = path.join(root, 'folder-d', 'bad-item2.txt') const badItem3Path = path.join(root, 'folder-f', 'bad-item3.txt') const badItem4Path = path.join(root, 'folder-h', 'folder-i', 'bad-item4.txt') const badItem5Path = path.join(root, 'folder-h', 'folder-i', 'bad-item5.txt') const extraFileInFolderCPath = path.join( root, 'folder-a', 'folder-b', 'folder-c', 'extra-file-in-folder-c.txt' ) const amazingFileInFolderHPath = path.join(root, 'folder-h', 'amazing-item.txt') const artifactFilesToUpload = [ goodItem1Path, goodItem2Path, goodItem3Path, goodItem4Path, goodItem5Path, extraFileInFolderCPath, amazingFileInFolderHPath ] describe('Search', () => { beforeAll(async () => { // mock all output so that there is less noise when running tests jest.spyOn(console, 'log').mockImplementation(() => {}) jest.spyOn(core, 'debug').mockImplementation(() => {}) jest.spyOn(core, 'info').mockImplementation(() => {}) jest.spyOn(core, 'warning').mockImplementation(() => {}) // clear temp directory await io.rmRF(root) await fs.mkdir(path.join(root, 'folder-a', 'folder-b', 'folder-c'), { recursive: true }) await fs.mkdir(path.join(root, 'folder-a', 'folder-b', 'folder-e'), { recursive: true }) await fs.mkdir(path.join(root, 'folder-d'), { recursive: true }) await fs.mkdir(path.join(root, 'folder-f'), { recursive: true }) await fs.mkdir(path.join(root, 'folder-g'), { recursive: true }) await fs.mkdir(path.join(root, 'folder-h', 'folder-i'), { recursive: true }) await fs.writeFile(goodItem1Path, 'good item1 file') await fs.writeFile(goodItem2Path, 'good item2 file') await fs.writeFile(goodItem3Path, 'good item3 file') await fs.writeFile(goodItem4Path, 'good item4 file') await fs.writeFile(goodItem5Path, 'good item5 file') await fs.writeFile(badItem1Path, 'bad item1 file') await fs.writeFile(badItem2Path, 'bad item2 file') await fs.writeFile(badItem3Path, 'bad item3 file') await fs.writeFile(badItem4Path, 'bad item4 file') await fs.writeFile(badItem5Path, 'bad item5 file') await fs.writeFile(extraFileInFolderCPath, 'extra file') await fs.writeFile(amazingFileInFolderHPath, 'amazing file') /* Directory structure of files that get created: root/ folder-a/ folder-b/ folder-c/ good-item1.txt bad-item1.txt extra-file-in-folder-c.txt folder-e/ folder-d/ good-item2.txt good-item3.txt good-item4.txt bad-item2.txt folder-f/ bad-item3.txt folder-g/ folder-h/ amazing-item.txt folder-i/ bad-item4.txt bad-item5.txt good-item5.txt */ }) it('Upload Specification - Fail non-existent rootDirectory', async () => { const invalidRootDirectory = path.join( __dirname, '_temp', 'upload-specification-invalid' ) expect(() => { getUploadSpecification( artifactName, invalidRootDirectory, artifactFilesToUpload ) }).toThrow(`Provided rootDirectory ${invalidRootDirectory} does not exist`) }) it('Upload Specification - Fail invalid rootDirectory', async () => { expect(() => { getUploadSpecification(artifactName, goodItem1Path, artifactFilesToUpload) }).toThrow( `Provided rootDirectory ${goodItem1Path} is not a valid directory` ) }) it('Upload Specification - File does not exist', async () => { const fakeFilePath = path.join( artifactName, 'folder-a', 'folder-b', 'non-existent-file.txt' ) expect(() => { getUploadSpecification(artifactName, root, [fakeFilePath]) }).toThrow(`File ${fakeFilePath} does not exist`) }) it('Upload Specification - Non parent directory', async () => { const folderADirectory = path.join(root, 'folder-a') const artifactFiles = [ goodItem1Path, badItem1Path, extraFileInFolderCPath, goodItem5Path ] expect(() => { getUploadSpecification(artifactName, folderADirectory, artifactFiles) }).toThrow( `The rootDirectory: ${folderADirectory} is not a parent directory of the file: ${goodItem5Path}` ) }) it('Upload Specification - Success', async () => { const specifications = getUploadSpecification( artifactName, root, artifactFilesToUpload ) expect(specifications.length).toEqual(7) const absolutePaths = specifications.map(item => item.absoluteFilePath) expect(absolutePaths).toContain(goodItem1Path) expect(absolutePaths).toContain(goodItem2Path) expect(absolutePaths).toContain(goodItem3Path) expect(absolutePaths).toContain(goodItem4Path) expect(absolutePaths).toContain(goodItem5Path) expect(absolutePaths).toContain(extraFileInFolderCPath) expect(absolutePaths).toContain(amazingFileInFolderHPath) for (const specification of specifications) { if (specification.absoluteFilePath === goodItem1Path) { expect(specification.uploadFilePath).toEqual( path.join( artifactName, 'folder-a', 'folder-b', 'folder-c', 'good-item1.txt' ) ) } else if (specification.absoluteFilePath === goodItem2Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item2.txt') ) } else if (specification.absoluteFilePath === goodItem3Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item3.txt') ) } else if (specification.absoluteFilePath === goodItem4Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item4.txt') ) } else if (specification.absoluteFilePath === goodItem5Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'good-item5.txt') ) } else if (specification.absoluteFilePath === extraFileInFolderCPath) { expect(specification.uploadFilePath).toEqual( path.join( artifactName, 'folder-a', 'folder-b', 'folder-c', 'extra-file-in-folder-c.txt' ) ) } else if (specification.absoluteFilePath === amazingFileInFolderHPath) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-h', 'amazing-item.txt') ) } else { throw new Error( 'Invalid specification found. This should never be reached' ) } } }) it('Upload Specification - Success with extra slash', async () => { const rootWithSlash = `${root}/` const specifications = getUploadSpecification( artifactName, rootWithSlash, artifactFilesToUpload ) expect(specifications.length).toEqual(7) const absolutePaths = specifications.map(item => item.absoluteFilePath) expect(absolutePaths).toContain(goodItem1Path) expect(absolutePaths).toContain(goodItem2Path) expect(absolutePaths).toContain(goodItem3Path) expect(absolutePaths).toContain(goodItem4Path) expect(absolutePaths).toContain(goodItem5Path) expect(absolutePaths).toContain(extraFileInFolderCPath) expect(absolutePaths).toContain(amazingFileInFolderHPath) for (const specification of specifications) { if (specification.absoluteFilePath === goodItem1Path) { expect(specification.uploadFilePath).toEqual( path.join( artifactName, 'folder-a', 'folder-b', 'folder-c', 'good-item1.txt' ) ) } else if (specification.absoluteFilePath === goodItem2Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item2.txt') ) } else if (specification.absoluteFilePath === goodItem3Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item3.txt') ) } else if (specification.absoluteFilePath === goodItem4Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item4.txt') ) } else if (specification.absoluteFilePath === goodItem5Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'good-item5.txt') ) } else if (specification.absoluteFilePath === extraFileInFolderCPath) { expect(specification.uploadFilePath).toEqual( path.join( artifactName, 'folder-a', 'folder-b', 'folder-c', 'extra-file-in-folder-c.txt' ) ) } else if (specification.absoluteFilePath === amazingFileInFolderHPath) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-h', 'amazing-item.txt') ) } else { throw new Error( 'Invalid specification found. This should never be reached' ) } } }) it('Upload Specification - Directories should not be included', async () => { const folderEPath = path.join(root, 'folder-a', 'folder-b', 'folder-e') const filesWithDirectory = [ goodItem1Path, goodItem4Path, folderEPath, badItem3Path ] const specifications = getUploadSpecification( artifactName, root, filesWithDirectory ) expect(specifications.length).toEqual(3) const absolutePaths = specifications.map(item => item.absoluteFilePath) expect(absolutePaths).toContain(goodItem1Path) expect(absolutePaths).toContain(goodItem4Path) expect(absolutePaths).toContain(badItem3Path) for (const specification of specifications) { if (specification.absoluteFilePath === goodItem1Path) { expect(specification.uploadFilePath).toEqual( path.join( artifactName, 'folder-a', 'folder-b', 'folder-c', 'good-item1.txt' ) ) } else if (specification.absoluteFilePath === goodItem2Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item2.txt') ) } else if (specification.absoluteFilePath === goodItem4Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-d', 'good-item4.txt') ) } else if (specification.absoluteFilePath === badItem3Path) { expect(specification.uploadFilePath).toEqual( path.join(artifactName, 'folder-f', 'bad-item3.txt') ) } else { throw new Error( 'Invalid specification found. This should never be reached' ) } } }) })
the_stack
import { Component, forwardRef, NgModule, Input, Output, ChangeDetectorRef, OnInit, OnDestroy, ContentChildren, QueryList, Optional, EventEmitter, ChangeDetectionStrategy, NgZone, ViewChild, ElementRef, Renderer2, AfterViewInit } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor, FormsModule, } from '@angular/forms'; import { CommonModule } from '@angular/common'; import { LyCommonModule, LyTheme2, LyCoreStyles, toBoolean, mixinDisableRipple, ThemeVariables, LyFocusState, LY_COMMON_STYLES, lyl, StyleCollection, LyClasses, StyleTemplate, ThemeRef, StyleRenderer} from '@alyle/ui'; import { Platform } from '@angular/cdk/platform'; export interface LyRadioTheme { /** Styles for Radio Component */ root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)> | ((classes: LyClasses<typeof STYLES>) => StyleTemplate); } export interface LyRadioVariables { radio?: LyRadioTheme; } const STYLE_PRIORITY = -2; const DEFAULT_DISABLE_RIPPLE = false; const DEFAULT_COLOR = 'accent'; export const LY_RADIO_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => LyRadioGroup), multi: true }; let idx = 0; export class UndefinedValue { constructor() { } } export const STYLES = (theme: ThemeVariables & LyRadioVariables, ref: ThemeRef) => { const radio = ref.selectorsOf(STYLES); const { after, before } = theme; return { $priority: STYLE_PRIORITY, /** ly-radio-group */ root: ( ) => lyl `{ display: inline-block { ...${ (theme.radio && theme.radio.root && (theme.radio.root instanceof StyleCollection ? theme.radio.root.setTransformer(fn => fn(radio)) : theme.radio.root(radio)) ) } } }`, radio: ( ) => lyl `{ display: inline-block -webkit-tap-highlight-color: transparent &${radio.checked} { ${radio.container} { div:nth-child(1) { transform: scale(1.25) } div:nth-child(2) { transform: scale(0.8) } } } &${radio.onFocusByKeyboard} ${radio.container}::after { box-shadow: 0 0 0 12px background: currentColor opacity: .13 border-radius: 50% } }`, label: lyl `{ user-select: none cursor: pointer white-space: nowrap position: relative display: flex align-items: baseline }`, labelContent: null, container: lyl `{ position: relative margin-${before}: .125em margin-${after}: .5em margin-top: auto margin-bottom: auto width: 16px height: 16px div { margin: auto border-radius: 50% width: 1em height: 1em box-sizing: border-box } &::after { content: '' ...${LY_COMMON_STYLES.fill} width: 16px height: 16px margin: auto } div:nth-child(2) { background: currentColor transform: scale(0) } div:nth-child(1) { transform: scale(1) border: solid .08em currentColor color: ${theme.text.disabled} } }`, checked: null, _animations: ( ) => lyl `{ ${radio.container} div { transition: transform cubic-bezier(.1, 1, 0.5, 1) transition-duration: 250ms } }`, onFocusByKeyboard: null, disabled: ( ) => lyl `{ color: ${theme.disabled.contrast} ${radio.container} div { color: ${theme.disabled.contrast}!important } }` }; }; @Component({ selector: 'ly-radio-group', template: `<ng-content></ng-content>`, providers: [LY_RADIO_CONTROL_VALUE_ACCESSOR], changeDetection: ChangeDetectionStrategy.OnPush, preserveWhitespaces: false, exportAs: 'lyRadioGroup' }) export class LyRadioGroup implements ControlValueAccessor { /** @docs-private */ static readonly и = 'LyRadioGroup'; /** @docs-private */ readonly classes = this._theme.renderStyleSheet(STYLES); private _value: any; /** @docs-private */ name = `ly-radio-name-${idx++}`; @Input() set value(val: any) { if (this._value !== val) { if (this._radios) { this._updateCheckFromValue(val); } } } get value() { return this._value; } @Output() readonly change: EventEmitter<void> = new EventEmitter<void>(); @Input() color = 'accent'; @ContentChildren(forwardRef(() => LyRadio)) _radios: QueryList<LyRadio>; /** The method to be called in order to update ngModel */ _controlValueAccessorChangeFn: (value: any) => void = () => {}; /** * onTouch function registered via registerOnTouch (ControlValueAccessor). * @docs-private */ onTouched: () => any = () => {}; /** * Mark this group as being "touched" (for ngModel). Meant to be called by the contained * radio buttons upon their blur. */ _touch() { if (this.onTouched) { this.onTouched(); } } /** @docs-private */ writeValue(value: any) { if (!!this._radios) { this.value = value; this._markForCheck(); } } /** * Registers a callback to be triggered when the model value changes. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. * @docs-private */ registerOnChange(fn: (value: any) => void) { this._controlValueAccessorChangeFn = fn; } /** * Registers a callback to be triggered when the control is touched. * Implemented as part of ControlValueAccessor. * @param fn Callback to be registered. * @docs-private */ registerOnTouched(fn: any) { this.onTouched = fn; } /** * Sets the disabled state of the control. Implemented as a part of ControlValueAccessor. * @param _isDisabled Whether the control should be disabled. * @docs-private */ setDisabledState(_isDisabled: boolean) { // this.disabled = isDisabled; this._markForCheck(); } constructor( elementRef: ElementRef, renderer: Renderer2, private _theme: LyTheme2, private _cd: ChangeDetectorRef ) { renderer.addClass(elementRef.nativeElement, this.classes.root); } _updateCheckFromValue(val: any) { let newChecked: boolean; this._radios.forEach(radioButton => { if (val === radioButton.value) { this.updatevalue(val); newChecked = true; radioButton.checked = true; } else if (radioButton.checked) { radioButton.checked = false; } }); if (!newChecked!) { /** when val not exist in radio button !== */ this._controlValueAccessorChangeFn(null); if (this._value != null) { this._value = null; } } } /** @docs-private */ updatevalue(value: any) { this._value = value; this._controlValueAccessorChangeFn(value); this.change.emit(); this._markForCheck(); } _markForCheck() { this._cd.markForCheck(); } _radioResetChecked() { this._radios.forEach(_ => _._setCheckedToFalsy()); } } /** @docs-private */ export class LyRadioBase { constructor( public _theme: LyTheme2, public _ngZone: NgZone, public _platform: Platform ) { } } /** @docs-private */ export const LyRadioMixinBase = mixinDisableRipple(LyRadioBase); @Component({ selector: 'ly-radio', templateUrl: 'radio.html', changeDetection: ChangeDetectionStrategy.OnPush, preserveWhitespaces: false, inputs: [ 'disableRipple' ], providers: [ StyleRenderer ] }) export class LyRadio extends LyRadioMixinBase implements OnInit, AfterViewInit, OnDestroy { /** @docs-private */ static readonly и = 'LyRadio'; /** @docs-private */ readonly classes = this.radioGroup.classes; /** @docs-private */ id = `ly-radio-id-${idx++}`; /** @docs-private */ name = ''; private _value = null; private _checked = false; private _color: string; private _animClass: string; private _disabled: boolean; private _disabledClass?: string; @ViewChild('_input') _input: ElementRef; @ViewChild('_radioContainer') private _radioContainer: ElementRef; @ViewChild('_labelContainer') _labelContainer: ElementRef; @Output() change = new EventEmitter<boolean>(); @Input() set value(val) { if (this._value !== val) { this._value = val; } } get value() { return this._value; } @Input() set color(val) { if (this._color !== val) { this._color = val; this[0x1] = this._styleRenderer.add( `${LyRadio.и}--color-${val}`, (theme: ThemeVariables, ref) => { const { checked, container } = ref.selectorsOf(STYLES); return lyl `{ &${checked} ${container}, &${checked} ${container} div:nth-child(1), & ${container} div:nth-child(2) { color: ${theme.colorOf(val)} } }`; }, STYLE_PRIORITY, this[0x1] ); } } get color() { return this._color; } [0x1]: string; @Input() set checked(val: boolean) { const newCheckedState = toBoolean(val); const before = this._checked; if (before !== newCheckedState) { this._checked = newCheckedState; if (!before && newCheckedState) { /** Add class checked */ this._renderer.addClass(this._elementRef.nativeElement, this.classes.checked); if (this.value !== this.radioGroup.value) { /** update Value */ this.radioGroup.updatevalue(this.value); } } else { /** Remove class checked */ this._renderer.removeClass(this._elementRef.nativeElement, this.classes.checked); } this._markForCheck(); } } get checked() { return this._checked; } /** @docs-private */ get inputId(): string { return `${this.id}-input`; } @Input() get disabled(): boolean { return this._disabled; } set disabled(value) { const newVal = toBoolean(value); if (newVal) { this._renderer.addClass(this._elementRef.nativeElement, this.classes.disabled); this._disabledClass = this.classes.disabled; } else if (this._disabledClass) { this._renderer.removeClass(this._elementRef.nativeElement, this.classes.disabled); this._disabledClass = undefined; } this._disabled = toBoolean(value); this._markForCheck(); } constructor( /** @docs-private */ @Optional() public radioGroup: LyRadioGroup, private _elementRef: ElementRef, private _renderer: Renderer2, theme: LyTheme2, private changeDetectorRef: ChangeDetectorRef, ngZone: NgZone, public _coreStyles: LyCoreStyles, private _focusState: LyFocusState, private _styleRenderer: StyleRenderer, platform: Platform ) { super(theme, ngZone, platform); this._triggerElement = this._elementRef; this._rippleConfig = { centered: true, radius: 'containerSize', percentageToIncrease: 150 }; _renderer.addClass(_elementRef.nativeElement, radioGroup.classes.radio); } ngOnInit() { if (this.radioGroup) { // Copy name from parent radio group this.name = this.radioGroup.name; } if (!this.color) { this.color = this.radioGroup.color || DEFAULT_COLOR; } } ngAfterViewInit() { this._rippleContainer = this._radioContainer; // set default disable ripple if (this.disableRipple == null) { this.disableRipple = DEFAULT_DISABLE_RIPPLE; } const focusState = this._focusState.listen(this._input, this._elementRef); if (focusState) { focusState.subscribe((event) => { if (event === 'keyboard') { this._renderer.addClass(this._elementRef.nativeElement, this.classes.onFocusByKeyboard); } else if (event == null) { this._renderer.removeClass(this._elementRef.nativeElement, this.classes.onFocusByKeyboard); } }); } } _markForCheck() { this.changeDetectorRef.markForCheck(); } ngOnDestroy() { this._focusState.unlisten(this._elementRef); this._removeRippleEvents(); } _onInputChange(event: any) { event.stopPropagation(); this.radioGroup._updateCheckFromValue(this.value); this.radioGroup._touch(); this._addAnim(); } private _addAnim() { if (!this._animClass) { this._renderer.addClass(this._elementRef.nativeElement, this.classes._animations); this._animClass = this.classes._animations; } } _onInputClick(event: Event) { event.stopPropagation(); } _setCheckedToFalsy() { this.checked = false; } } @NgModule({ imports: [CommonModule, FormsModule, LyCommonModule], exports: [LyRadioGroup, LyRadio], declarations: [LyRadioGroup, LyRadio], }) export class LyRadioModule { }
the_stack
import { _In, _Out, QueueSym } from "@effect/core/io/Queue/definition" import { unsafeCompleteDeferred } from "@effect/core/io/Queue/operations/_internal/unsafeCompleteDeferred" import { unsafeCompleteTakers } from "@effect/core/io/Queue/operations/_internal/unsafeCompleteTakers" import { unsafeOfferAll } from "@effect/core/io/Queue/operations/_internal/unsafeOfferAll" import { unsafePollAll } from "@effect/core/io/Queue/operations/_internal/unsafePollAll" import { unsafePollN } from "@effect/core/io/Queue/operations/_internal/unsafePollN" import { unsafeRemove } from "@effect/core/io/Queue/operations/_internal/unsafeRemove" import type { Strategy } from "@effect/core/io/Queue/operations/strategy" import type { State } from "@effect/core/io/Scope/ReleaseMap/_internal/State" import { Exited } from "@effect/core/io/Scope/ReleaseMap/_internal/State" // ----------------------------------------------------------------------------- // forEach // ----------------------------------------------------------------------------- /** * Applies the function `f` to each element of the `Collection<A>` and returns * the results in a new `Chunk<B>`. * * For a parallel version of this method, see `forEachPar`. If you do not need * the results, see `forEachDiscard` for a more efficient implementation. * * @tsplus static ets/Effect/Ops forEach */ export function forEach<A, R, E, B>( as: LazyArg<Collection<A>>, f: (a: A) => Effect<R, E, B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.suspendSucceed(() => { const acc: B[] = [] return Effect.forEachDiscard(as, (a) => f(a).map((b) => { acc.push(b) })).map(() => Chunk.from(acc)) }) } // ----------------------------------------------------------------------------- // forEachWithIndex // ----------------------------------------------------------------------------- /** * Same as `forEach`, except that the function `f` is supplied * a second argument that corresponds to the index (starting from 0) * of the current element being iterated over. * * @tsplus static ets/Effect/Ops forEachWithIndex */ export function forEachWithIndex<A, R, E, B>( as: LazyArg<Collection<A>>, f: (a: A, i: number) => Effect<R, E, B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.suspendSucceed(() => { let index = 0 const acc: B[] = [] return Effect.forEachDiscard(as, (a) => f(a, index).map((b) => { acc.push(b) index++ })).map(() => Chunk.from(acc)) }) } // ----------------------------------------------------------------------------- // forEachDiscard // ----------------------------------------------------------------------------- /** * Applies the function `f` to each element of the `Collection<A>` and runs * produced effects sequentially. * * Equivalent to `asUnit(forEach(as, f))`, but without the cost of building * the list of results. * * @tsplus static ets/Effect/Ops forEachDiscard */ export function forEachDiscard<R, E, A, X>( as: LazyArg<Collection<A>>, f: (a: A) => Effect<R, E, X>, __tsplusTrace?: string ): Effect<R, E, void> { return Effect.succeed(as).flatMap((Collection) => forEachDiscardLoop(Collection[Symbol.iterator](), f)) } function forEachDiscardLoop<R, E, A, X>( iterator: Iterator<A, any, undefined>, f: (a: A) => Effect<R, E, X> ): Effect<R, E, void> { const next = iterator.next() return next.done ? Effect.unit : f(next.value) > forEachDiscardLoop(iterator, f) } // ----------------------------------------------------------------------------- // forEachPar // ----------------------------------------------------------------------------- /** * Applies the function `f` to each element of the `Collection<A>` in parallel, * and returns the results in a new `Chunk<B>`. * * For a sequential version of this method, see `forEach`. * * @tsplus static ets/Effect/Ops forEachPar */ export function forEachPar<R, E, A, B>( as: LazyArg<Collection<A>>, f: (a: A) => Effect<R, E, B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.parallelismWith((option) => option.fold( () => forEachParUnbounded(as, f), (n) => forEachParN(as, n, f) ) ) } /** * Applies the function `f` to each element of the `Collection<A>` in parallel, * and returns the results in a new `Chunk<B>`. */ function forEachParUnbounded<R, E, A, B>( as: LazyArg<Collection<A>>, f: (a: A) => Effect<R, E, B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.suspendSucceed( Effect.succeed<B[]>([]).flatMap((array) => forEachParUnboundedDiscard( as().map((a, n) => [a, n] as [A, number]), ([a, n]) => Effect.suspendSucceed(f(a)).flatMap((b) => Effect.succeed(() => { array[n] = b }) ) ).map(() => Chunk.from(array)) ) ) } function forEachParN<R, E, A, B>( as: LazyArg<Collection<A>>, n: number, f: (a: A) => Effect<R, E, B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.suspendSucceed<R, E, Chunk<B>>(() => { if (n < 1) { return Effect.dieMessage( `Unexpected nonpositive value "${n}" passed to foreachParN` ) } const as0 = Chunk.from(as()) const size = as0.size if (size === 0) { return Effect.succeedNow(Chunk.empty()) } function worker( queue: Queue<Tuple<[A, number]>>, array: Array<B> ): Effect<R, E, void> { return queue .takeUpTo(1) .map((_) => _.head) .flatMap((_) => _.fold( () => Effect.unit, ({ tuple: [a, n] }) => f(a) .tap((b) => Effect.succeed(() => { array[n] = b }) ) .flatMap(() => worker(queue, array)) ) ) } return Effect.succeed(new Array<B>(size)).flatMap((array) => makeBoundedQueue<Tuple<[A, number]>>(size).flatMap((queue) => queue .offerAll(as0.zipWithIndex()) .flatMap(() => forEachParUnboundedDiscard(worker(queue, array).replicate(n), identity).map( () => Chunk.from(array) ) ) ) ) }) } // ----------------------------------------------------------------------------- // forEachParWithIndex // ----------------------------------------------------------------------------- /** * Same as `forEachPar_`, except that the function `f` is supplied * a second argument that corresponds to the index (starting from 0) * of the current element being iterated over. * * @tsplus static ets/Effect/Ops forEachParWithIndex */ export function forEachParWithIndex<R, E, A, B>( as: LazyArg<Collection<A>>, f: (a: A, i: number) => Effect<R, E, B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.suspendSucceed( Effect.succeed<B[]>([]).flatMap((array) => Effect.forEachParDiscard( as().map((a, n) => [a, n] as [A, number]), ([a, n]) => Effect.suspendSucceed(f(a, n)).flatMap((b) => Effect.succeed(() => { array[n] = b }) ) ).map(() => Chunk.from(array)) ) ) } // ----------------------------------------------------------------------------- // forEachParDiscard // ----------------------------------------------------------------------------- /** * Applies the function `f` to each element of the `Collection<A>` and runs * produced effects in parallel, discarding the results. * * For a sequential version of this method, see `forEachDiscard`. * * Optimized to avoid keeping full tree of effects, so that method could be * able to handle large input sequences. Additionally, interrupts all effects * on any failure. * * @tsplus static ets/Effect/Ops forEachParDiscard */ export function forEachParDiscard<R, E, A, X>( as: LazyArg<Collection<A>>, f: (a: A) => Effect<R, E, X>, __tsplusTrace?: string ): Effect<R, E, void> { return Effect.parallelismWith((option) => option.fold( () => forEachParUnboundedDiscard(as, f), (n) => forEachParNDiscard(as, n, f) ) ) } function forEachParUnboundedDiscard<R, E, A, X>( as: LazyArg<Collection<A>>, f: (a: A) => Effect<R, E, X>, __tsplusTrace?: string ): Effect<R, E, void> { return Effect.suspendSucceed<R, E, void>(() => { const bs = Chunk.from(as()) const size = bs.size if (size === 0) { return Effect.unit } return Effect.uninterruptibleMask(({ restore }) => { const deferred = Deferred.unsafeMake<void, void>(FiberId.none) const ref = new AtomicNumber(0) return Effect.transplant((graft) => Effect.forEach(bs, (a) => graft( restore(Effect.suspendSucceed(f(a))).foldCauseEffect( (cause) => deferred.fail(undefined) > Effect.failCauseNow(cause), () => { if (ref.incrementAndGet() === size) { deferred.unsafeDone(Effect.unit) return Effect.unit } else { return Effect.unit } } ) ).forkDaemon()) ).flatMap((fibers) => restore(deferred.await()).foldCauseEffect( (cause) => forEachParUnbounded(fibers, (fiber) => fiber.interrupt()).flatMap( (exits) => { const collected = Exit.collectAllPar(exits) if (collected._tag === "Some" && collected.value._tag === "Failure") { return Effect.failCause( Cause.both(cause.stripFailures(), collected.value.cause) ) } return Effect.failCause(cause.stripFailures()) } ), (_) => Effect.forEachDiscard(fibers, (fiber) => fiber.inheritRefs()) ) ) }) }) } function forEachParNDiscard<R, E, A, X>( as: LazyArg<Collection<A>>, n: number, f: (a: A) => Effect<R, E, X>, __tsplusTrace?: string ): Effect<R, E, void> { return Effect.suspendSucceed(() => { const as0 = as() const bs = Chunk.from(as0) const size = bs.size if (size === 0) { return Effect.unit } function worker(queue: Queue<A>): Effect<R, E, void> { return queue .takeUpTo(1) .map((chunk) => chunk.head) .flatMap((option) => option.fold( () => Effect.unit, (a) => f(a).flatMap(() => worker(queue)) ) ) } return makeBoundedQueue<A>(size).flatMap((queue) => queue .offerAll(as0) .flatMap(() => forEachParUnboundedDiscard(worker(queue).replicate(n), identity)) ) }) } // ----------------------------------------------------------------------------- // forEachExec // ----------------------------------------------------------------------------- /** * Applies the function `f` to each element of the `Collection<A>` and returns * the result in a new `Chunk<B>` using the specified execution strategy. * * @tsplus static ets/Effect/Ops forEachExec */ export function forEachExec<R, E, A, B>( as: LazyArg<Collection<A>>, f: (a: A) => Effect<R, E, B>, strategy: ExecutionStrategy, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.suspendSucceed(() => { switch (strategy._tag) { case "Parallel": { return Effect.forEachPar(as, f).withParallelismUnbounded() } case "ParallelN": { return Effect.forEachPar(as, f).withParallelism(strategy.n) } case "Sequential": { return Effect.forEach(as, f) } } }) } // ----------------------------------------------------------------------------- // collectAll // ----------------------------------------------------------------------------- /** * Evaluate each effect in the structure from left to right, and collect the * results. For a parallel version, see `collectAllPar`. * * @tsplus static ets/Effect/Ops collectAll */ export function collectAll<R, E, A>( as: LazyArg<Collection<Effect<R, E, A>>>, __tsplusTrace?: string ) { return Effect.forEach(as, identity) } // ----------------------------------------------------------------------------- // collectAllPar // ----------------------------------------------------------------------------- /** * Evaluate each effect in the structure in parallel, and collect the * results. For a sequential version, see `collectAll`. * * @tsplus static ets/Effect/Ops collectAllPar */ export function collectAllPar<R, E, A>( as: LazyArg<Collection<Effect<R, E, A>>>, __tsplusTrace?: string ): Effect<R, E, Chunk<A>> { return Effect.forEachPar(as, identity) } // ----------------------------------------------------------------------------- // collectAllDiscard // ----------------------------------------------------------------------------- /** * Evaluate each effect in the structure from left to right, and discard the * results. For a parallel version, see `collectAllParDiscard`. * * @tsplus static ets/Effect/Ops collectAllDiscard */ export function collectAllDiscard<R, E, A>( as: LazyArg<Collection<Effect<R, E, A>>>, __tsplusTrace?: string ): Effect<R, E, void> { return Effect.forEachDiscard(as, identity) } // ----------------------------------------------------------------------------- // collectAllParDiscard // ----------------------------------------------------------------------------- /** * Evaluate each effect in the structure in parallel, and discard the * results. For a sequential version, see `collectAllDiscard`. * * @tsplus static ets/Effect/Ops collectAllParDiscard */ export function collectAllParDiscard<R, E, A>( as: LazyArg<Collection<Effect<R, E, A>>>, __tsplusTrace?: string ): Effect<R, E, void> { return Effect.forEachParDiscard(as, identity) } // ----------------------------------------------------------------------------- // collectAllWith // ----------------------------------------------------------------------------- /** * Evaluate each effect in the structure with `collectAll`, and collect * the results with given partial function. * * @tsplus static ets/Effect/Ops collectAllWith */ export function collectAllWith<R, E, A, B>( as: LazyArg<Collection<Effect<R, E, A>>>, pf: (a: A) => Option<B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.collectAll(as).map((chunk) => chunk.collect(pf)) } // ----------------------------------------------------------------------------- // collectAllWithPar // ----------------------------------------------------------------------------- /** * Evaluate each effect in the structure with `collectAll`, and collect * the results with given partial function. * * @tsplus static ets/Effect/Ops collectAllWithPar */ export function collectAllWithPar<R, E, A, B>( as: LazyArg<Collection<Effect<R, E, A>>>, pf: (a: A) => Option<B>, __tsplusTrace?: string ): Effect<R, E, Chunk<B>> { return Effect.collectAllPar(as).map((chunk) => chunk.collect(pf)) } // ----------------------------------------------------------------------------- // collectAllSuccesses // ----------------------------------------------------------------------------- /** * Evaluate and run each effect in the structure and collect discarding failed ones. * * @tsplus static ets/Effect/Ops collectAllSuccesses */ export function collectAllSuccesses<R, E, A>( as: LazyArg<Collection<Effect<R, E, A>>>, __tsplusTrace?: string ): Effect<R, never, Chunk<A>> { return Effect.collectAllWith( as().map((effect) => effect.exit()), (exit) => (exit._tag === "Success" ? Option.some(exit.value) : Option.none) ) } // ----------------------------------------------------------------------------- // collectAllSuccessesPar // ----------------------------------------------------------------------------- /** * Evaluate and run each effect in the structure in parallel, and collect discarding failed ones. * * @tsplus static ets/Effect/Ops collectAllSuccessesPar */ export function collectAllSuccessesPar<R, E, A>( as: LazyArg<Collection<Effect<R, E, A>>>, __tsplusTrace?: string ): Effect<R, never, Chunk<A>> { return Effect.collectAllWithPar( as().map((effect) => effect.exit()), (exit) => (exit._tag === "Success" ? Option.some(exit.value) : Option.none) ) } // ----------------------------------------------------------------------------- // Fiber // ----------------------------------------------------------------------------- /** * Joins all fibers, awaiting their _successful_ completion. * Attempting to join a fiber that has erred will result in * a catchable error, _if_ that error does not result from interruption. */ export function fiberJoinAll<E, A>( as: LazyArg<Collection<Fiber<E, A>>>, __tsplusTrace?: string ): Effect<unknown, E, Chunk<A>> { return fiberWaitAll(as) .flatMap((exit) => Effect.done(exit)) .tap(() => Effect.forEach(as, (fiber) => fiber.inheritRefs())) } /** * Awaits on all fibers to be completed, successfully or not. */ export function fiberWaitAll<E, A>( as: LazyArg<Collection<Fiber<E, A>>>, __tsplusTrace?: string ): Effect.RIO<unknown, Exit<E, Chunk<A>>> { return Effect.forEachPar(as, (fiber) => fiber.await().flatMap((exit) => Effect.done(exit))).exit() } // ----------------------------------------------------------------------------- // ReleaseMap // ----------------------------------------------------------------------------- /** * Releases all the finalizers in the releaseMap according to the ExecutionStrategy. */ export function releaseMapReleaseAll( self: ReleaseMap, ex: Exit<unknown, unknown>, execStrategy: ExecutionStrategy, __tsplusTrace?: string ): Effect.UIO<unknown> { return self.ref .modify((s): Tuple<[Effect.UIO<unknown>, State]> => { switch (s._tag) { case "Exited": { return Tuple(Effect.unit, s) } case "Running": { switch (execStrategy._tag) { case "Sequential": { return Tuple( Effect.forEach(Array.from(s.finalizers()).reverse(), ([_, f]) => s.update(f)(ex).exit()).flatMap(( results ) => Effect.done(Exit.collectAll(results).getOrElse(Exit.unit))), new Exited(s.nextKey, ex, s.update) ) } case "Parallel": { return Tuple( Effect.forEachPar(Array.from(s.finalizers()).reverse(), ([_, f]) => s.update(f)(ex).exit()).flatMap(( results ) => Effect.done(Exit.collectAllPar(results).getOrElse(Exit.unit))), new Exited(s.nextKey, ex, s.update) ) } case "ParallelN": { return Tuple( Effect.forEachPar(Array.from(s.finalizers()).reverse(), ([_, f]) => s.update(f)(ex).exit()) .flatMap((results) => Effect.done(Exit.collectAllPar(results).getOrElse(Exit.unit))) .withParallelism(execStrategy.n) as Effect.UIO<unknown>, new Exited(s.nextKey, ex, s.update) ) } } } } }) .flatten() } // ----------------------------------------------------------------------------- // ReleaseMap // ----------------------------------------------------------------------------- export function makeBoundedQueue<A>( requestedCapacity: number, __tsplusTrace?: string ): Effect.UIO<Queue<A>> { return Effect.succeed(MutableQueue.bounded<A>(requestedCapacity)).flatMap((queue) => createQueue(queue, new BackPressureStrategy()) ) } export function createQueue<A>( queue: MutableQueue<A>, strategy: Strategy<A>, __tsplusTrace?: string ): Effect.UIO<Queue<A>> { return Deferred.make<never, void>().map((deferred) => unsafeCreateQueue( queue, MutableQueue.unbounded(), deferred, new AtomicBoolean(false), strategy ) ) } export function unsafeCreateQueue<A>( queue: MutableQueue<A>, takers: MutableQueue<Deferred<never, A>>, shutdownHook: Deferred<never, void>, shutdownFlag: AtomicBoolean, strategy: Strategy<A> ): Queue<A> { return new UnsafeCreate(queue, takers, shutdownHook, shutdownFlag, strategy) } export class UnsafeCreate<A> implements Queue<A> { readonly [QueueSym]: QueueSym = QueueSym readonly [_In]!: (_: A) => void readonly [_Out]!: () => A constructor( readonly queue: MutableQueue<A>, readonly takers: MutableQueue<Deferred<never, A>>, readonly shutdownHook: Deferred<never, void>, readonly shutdownFlag: AtomicBoolean, readonly strategy: Strategy<A> ) {} capacity: number = this.queue.capacity size: Effect.UIO<number> = Effect.suspendSucceed( this.shutdownFlag.get ? Effect.interrupt : Effect.succeedNow( this.queue.size - this.takers.size + this.strategy.surplusSize ) ) awaitShutdown: Effect.UIO<void> = this.shutdownHook.await() isShutdown: Effect.UIO<boolean> = Effect.succeed(this.shutdownFlag.get) shutdown: Effect.UIO<void> = Effect.suspendSucceedWith((_, fiberId) => { this.shutdownFlag.set(true) return Effect.whenEffect( this.shutdownHook.succeed(undefined), Effect.forEachParDiscard(unsafePollAll(this.takers), (deferred) => deferred.interruptAs(fiberId)) > this.strategy.shutdown ).asUnit() }).uninterruptible() offer(a: A, __tsplusTrace?: string): Effect<unknown, never, boolean> { return Effect.suspendSucceed(() => { if (this.shutdownFlag.get) { return Effect.interrupt } let noRemaining: boolean if (this.queue.isEmpty) { const taker = this.takers.poll(EmptyMutableQueue) if (taker !== EmptyMutableQueue) { unsafeCompleteDeferred(taker, a) noRemaining = true } else { noRemaining = false } } else { noRemaining = false } if (noRemaining) { return Effect.succeedNow(true) } // Not enough takers, offer to the queue const succeeded = this.queue.offer(a) unsafeCompleteTakers(this.strategy, this.queue, this.takers) return succeeded ? Effect.succeedNow(true) : this.strategy.handleSurplus( Chunk.single(a), this.queue, this.takers, this.shutdownFlag ) }) } offerAll(as: Collection<A>, __tsplusTrace?: string): Effect<unknown, never, boolean> { return Effect.suspendSucceed(() => { if (this.shutdownFlag.get) { return Effect.interrupt } const as0 = Chunk.from(as) const pTakers = this.queue.isEmpty ? unsafePollN(this.takers, as0.size) : Chunk.empty<Deferred<never, A>>() const { tuple: [forTakers, remaining] } = as0.splitAt(pTakers.size) pTakers.zip(forTakers).forEach(({ tuple: [taker, item] }) => { unsafeCompleteDeferred(taker, item) }) if (remaining.isEmpty()) { return Effect.succeedNow(true) } // Not enough takers, offer to the queue const surplus = unsafeOfferAll(this.queue, remaining) unsafeCompleteTakers(this.strategy, this.queue, this.takers) return surplus.isEmpty() ? Effect.succeedNow(true) : this.strategy.handleSurplus( surplus, this.queue, this.takers, this.shutdownFlag ) }) } take: Effect<unknown, never, A> = Effect.suspendSucceedWith((_, fiberId) => { if (this.shutdownFlag.get) { return Effect.interrupt } const item = this.queue.poll(EmptyMutableQueue) if (item !== EmptyMutableQueue) { this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers) return Effect.succeedNow(item) } else { // Add the deferred to takers, then: // - Try to take again in case a value was added since // - Wait for the deferred to be completed // - Clean up resources in case of interruption const deferred = Deferred.unsafeMake<never, A>(fiberId) return Effect.suspendSucceed(() => { this.takers.offer(deferred) unsafeCompleteTakers(this.strategy, this.queue, this.takers) return this.shutdownFlag.get ? Effect.interrupt : deferred.await() }).onInterrupt(() => { return Effect.succeed(unsafeRemove(this.takers, deferred)) }) } }) takeAll: Effect<unknown, never, Chunk<A>> = Effect.suspendSucceed(() => this.shutdownFlag.get ? Effect.interrupt : Effect.succeed(() => { const as = unsafePollAll(this.queue) this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers) return as }) ) takeUpTo(n: number, __tsplusTrace?: string): Effect<unknown, never, Chunk<A>> { return Effect.suspendSucceed(() => this.shutdownFlag.get ? Effect.interrupt : Effect.succeed(() => { const as = unsafePollN(this.queue, n) this.strategy.unsafeOnQueueEmptySpace(this.queue, this.takers) return as }) ) } } export function makeBackPressureStrategy<A>() { return new BackPressureStrategy<A>() } export class BackPressureStrategy<A> implements Strategy<A> { /** * - `A` is an item to add * - `Deferred<never, boolean>` is the deferred completing the whole `offerAll` * - `boolean` indicates if it's the last item to offer (deferred should be * completed once this item is added) */ private putters = MutableQueue.unbounded<Tuple<[A, Deferred<never, boolean>, boolean]>>() handleSurplus( as: Chunk<A>, queue: MutableQueue<A>, takers: MutableQueue<Deferred<never, A>>, isShutdown: AtomicBoolean, __tsplusTrace?: string ): Effect.UIO<boolean> { return Effect.suspendSucceedWith((_, fiberId) => { const deferred = Deferred.unsafeMake<never, boolean>(fiberId) return Effect.suspendSucceed(() => { this.unsafeOffer(as, deferred) this.unsafeOnQueueEmptySpace(queue, takers) unsafeCompleteTakers(this, queue, takers) return isShutdown.get ? Effect.interrupt : deferred.await() }).onInterrupt(() => Effect.succeed(this.unsafeRemove(deferred))) }) } unsafeRemove(deferred: Deferred<never, boolean>): void { unsafeOfferAll( this.putters, unsafePollAll(this.putters).filter(({ tuple: [, _] }) => _ !== deferred) ) } unsafeOffer(as: Chunk<A>, deferred: Deferred<never, boolean>): void { let bs = as while (bs.size > 0) { const head = bs.unsafeGet(0)! bs = bs.drop(1) if (bs.size === 0) { this.putters.offer(Tuple(head, deferred, true)) } else { this.putters.offer(Tuple(head, deferred, false)) } } } unsafeOnQueueEmptySpace( queue: MutableQueue<A>, takers: MutableQueue<Deferred<never, A>> ): void { let keepPolling = true while (keepPolling && !queue.isFull) { const putter = this.putters.poll(EmptyMutableQueue) if (putter !== EmptyMutableQueue) { const offered = queue.offer(putter.get(0)) if (offered && putter.get(2)) { unsafeCompleteDeferred(putter.get(1), true) } else if (!offered) { unsafeOfferAll(this.putters, unsafePollAll(this.putters).prepend(putter)) } unsafeCompleteTakers(this, queue, takers) } else { keepPolling = false } } } get surplusSize(): number { return this.putters.size } get shutdown(): Effect.UIO<void> { return Do(($) => { const fiberId = $(Effect.fiberId) const putters = $(Effect.succeed(unsafePollAll(this.putters))) $(Effect.forEachPar( putters, ({ tuple: [_, promise, lastItem] }) => lastItem ? promise.interruptAs(fiberId) : Effect.unit )) }) } }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * @interface * An interface representing Resource. * Azure resource. * * @extends BaseResource */ export interface Resource extends BaseResource { /** * @member {string} [id] Specifies the resource ID. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] Specifies the name of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} location Specifies the location of the resource. */ location: string; /** * @member {string} [type] Specifies the type of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; /** * @member {{ [propertyName: string]: string }} [tags] Contains resource tags * defined as key/value pairs. */ tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing WebServiceKeys. * Access keys for the web service calls. * */ export interface WebServiceKeys { /** * @member {string} [primary] The primary access key. */ primary?: string; /** * @member {string} [secondary] The secondary access key. */ secondary?: string; } /** * @interface * An interface representing RealtimeConfiguration. * Holds the available configuration options for an Azure ML web service * endpoint. * */ export interface RealtimeConfiguration { /** * @member {number} [maxConcurrentCalls] Specifies the maximum concurrent * calls that can be made to the web service. Minimum value: 4, Maximum * value: 200. */ maxConcurrentCalls?: number; } /** * @interface * An interface representing DiagnosticsConfiguration. * Diagnostics settings for an Azure ML web service. * */ export interface DiagnosticsConfiguration { /** * @member {DiagnosticsLevel} level Specifies the verbosity of the diagnostic * output. Valid values are: None - disables tracing; Error - collects only * error (stderr) traces; All - collects all traces (stdout and stderr). * Possible values include: 'None', 'Error', 'All' */ level: DiagnosticsLevel; /** * @member {Date} [expiry] Specifies the date and time when the logging will * cease. If null, diagnostic collection is not time limited. */ expiry?: Date; } /** * @interface * An interface representing StorageAccount. * Access information for a storage account. * */ export interface StorageAccount { /** * @member {string} [name] Specifies the name of the storage account. */ name?: string; /** * @member {string} [key] Specifies the key used to access the storage * account. */ key?: string; } /** * @interface * An interface representing MachineLearningWorkspace. * Information about the machine learning workspace containing the experiment * that is source for the web service. * */ export interface MachineLearningWorkspace { /** * @member {string} id Specifies the workspace ID of the machine learning * workspace associated with the web service */ id: string; } /** * @interface * An interface representing CommitmentPlan. * Information about the machine learning commitment plan associated with the * web service. * */ export interface CommitmentPlan { /** * @member {string} id Specifies the Azure Resource Manager ID of the * commitment plan associated with the web service. */ id: string; } /** * @interface * An interface representing ColumnSpecification. * Swagger 2.0 schema for a column within the data table representing a web * service input or output. See Swagger specification: * http://swagger.io/specification/ * */ export interface ColumnSpecification { /** * @member {ColumnType} type Data type of the column. Possible values * include: 'Boolean', 'Integer', 'Number', 'String' */ type: ColumnType; /** * @member {ColumnFormat} [format] Additional format information for the data * type. Possible values include: 'Byte', 'Char', 'Complex64', 'Complex128', * 'Date-time', 'Date-timeOffset', 'Double', 'Duration', 'Float', 'Int8', * 'Int16', 'Int32', 'Int64', 'Uint8', 'Uint16', 'Uint32', 'Uint64' */ format?: ColumnFormat; /** * @member {any[]} [enum] If the data type is categorical, this provides the * list of accepted categories. */ enum?: any[]; /** * @member {boolean} [xMsIsnullable] Flag indicating if the type supports * null values or not. */ xMsIsnullable?: boolean; /** * @member {boolean} [xMsIsordered] Flag indicating whether the categories * are treated as an ordered set or not, if this is a categorical column. */ xMsIsordered?: boolean; } /** * @interface * An interface representing TableSpecification. * The swagger 2.0 schema describing a single service input or output. See * Swagger specification: http://swagger.io/specification/ * */ export interface TableSpecification { /** * @member {string} [title] Swagger schema title. */ title?: string; /** * @member {string} [description] Swagger schema description. */ description?: string; /** * @member {string} type The type of the entity described in swagger. Default * value: 'object' . */ type: string; /** * @member {string} [format] The format, if 'type' is not 'object' */ format?: string; /** * @member {{ [propertyName: string]: ColumnSpecification }} [properties] The * set of columns within the data table. */ properties?: { [propertyName: string]: ColumnSpecification }; } /** * @interface * An interface representing ServiceInputOutputSpecification. * The swagger 2.0 schema describing the service's inputs or outputs. See * Swagger specification: http://swagger.io/specification/ * */ export interface ServiceInputOutputSpecification { /** * @member {string} [title] The title of your Swagger schema. */ title?: string; /** * @member {string} [description] The description of the Swagger schema. */ description?: string; /** * @member {string} type The type of the entity described in swagger. Always * 'object'. Default value: 'object' . */ type: string; /** * @member {{ [propertyName: string]: TableSpecification }} properties * Specifies a collection that contains the column schema for each input or * output of the web service. For more information, see the Swagger * specification. */ properties: { [propertyName: string]: TableSpecification }; } /** * @interface * An interface representing ExampleRequest. * Sample input data for the service's input(s). * */ export interface ExampleRequest { /** * @member {{ [propertyName: string]: any[][] }} [inputs] Sample input data * for the web service's input(s) given as an input name to sample input * values matrix map. */ inputs?: { [propertyName: string]: any[][] }; /** * @member {{ [propertyName: string]: any }} [globalParameters] Sample input * data for the web service's global parameters */ globalParameters?: { [propertyName: string]: any }; } /** * @interface * An interface representing BlobLocation. * Describes the access location for a blob. * */ export interface BlobLocation { /** * @member {string} uri The URI from which the blob is accessible from. For * example, aml://abc for system assets or https://xyz for user assets or * payload. */ uri: string; /** * @member {string} [credentials] Access credentials for the blob, if * applicable (e.g. blob specified by storage account connection string + * blob URI) */ credentials?: string; } /** * @interface * An interface representing InputPort. * Asset input port * */ export interface InputPort { /** * @member {InputPortType} [type] Port data type. Possible values include: * 'Dataset'. Default value: 'Dataset' . */ type?: InputPortType; } /** * @interface * An interface representing OutputPort. * Asset output port * */ export interface OutputPort { /** * @member {OutputPortType} [type] Port data type. Possible values include: * 'Dataset'. Default value: 'Dataset' . */ type?: OutputPortType; } /** * @interface * An interface representing ModeValueInfo. * Nested parameter definition. * */ export interface ModeValueInfo { /** * @member {string} [interfaceString] The interface string name for the * nested parameter. */ interfaceString?: string; /** * @member {ModuleAssetParameter[]} [parameters] The definition of the * parameter. */ parameters?: ModuleAssetParameter[]; } /** * @interface * An interface representing ModuleAssetParameter. * Parameter definition for a module asset. * */ export interface ModuleAssetParameter { /** * @member {string} [name] Parameter name. */ name?: string; /** * @member {string} [parameterType] Parameter type. */ parameterType?: string; /** * @member {{ [propertyName: string]: ModeValueInfo }} [modeValuesInfo] * Definitions for nested interface parameters if this is a complex module * parameter. */ modeValuesInfo?: { [propertyName: string]: ModeValueInfo }; } /** * @interface * An interface representing AssetItem. * Information about an asset associated with the web service. * */ export interface AssetItem { /** * @member {string} name Asset's friendly name. */ name: string; /** * @member {string} [id] Asset's Id. */ id?: string; /** * @member {AssetType} type Asset's type. Possible values include: 'Module', * 'Resource' */ type: AssetType; /** * @member {BlobLocation} locationInfo Access information for the asset. */ locationInfo: BlobLocation; /** * @member {{ [propertyName: string]: InputPort }} [inputPorts] Information * about the asset's input ports. */ inputPorts?: { [propertyName: string]: InputPort }; /** * @member {{ [propertyName: string]: OutputPort }} [outputPorts] Information * about the asset's output ports. */ outputPorts?: { [propertyName: string]: OutputPort }; /** * @member {{ [propertyName: string]: string }} [metadata] If the asset is a * custom module, this holds the module's metadata. */ metadata?: { [propertyName: string]: string }; /** * @member {ModuleAssetParameter[]} [parameters] If the asset is a custom * module, this holds the module's parameters. */ parameters?: ModuleAssetParameter[]; } /** * @interface * An interface representing WebServiceParameter. * Web Service Parameter object for node and global parameter * */ export interface WebServiceParameter { /** * @member {any} [value] The parameter value */ value?: any; /** * @member {string} [certificateThumbprint] If the parameter value in 'value' * field is encrypted, the thumbprint of the certificate should be put here. */ certificateThumbprint?: string; } /** * Contains the possible cases for WebServiceProperties. */ export type WebServicePropertiesUnion = WebServiceProperties | WebServicePropertiesForGraph; /** * @interface * An interface representing WebServiceProperties. * The set of properties specific to the Azure ML web service resource. * */ export interface WebServiceProperties { /** * @member {string} packageType Polymorphic Discriminator */ packageType: "WebServiceProperties"; /** * @member {string} [title] The title of the web service. */ title?: string; /** * @member {string} [description] The description of the web service. */ description?: string; /** * @member {Date} [createdOn] Read Only: The date and time when the web * service was created. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly createdOn?: Date; /** * @member {Date} [modifiedOn] Read Only: The date and time when the web * service was last modified. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly modifiedOn?: Date; /** * @member {ProvisioningState} [provisioningState] Read Only: The provision * state of the web service. Valid values are Unknown, Provisioning, * Succeeded, and Failed. Possible values include: 'Unknown', 'Provisioning', * 'Succeeded', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {WebServiceKeys} [keys] Contains the web service provisioning * keys. If you do not specify provisioning keys, the Azure Machine Learning * system generates them for you. Note: The keys are not returned from calls * to GET operations. */ keys?: WebServiceKeys; /** * @member {boolean} [readOnly] When set to true, indicates that the web * service is read-only and can no longer be updated or patched, only * removed. Default, is false. Note: Once set to true, you cannot change its * value. */ readOnly?: boolean; /** * @member {string} [swaggerLocation] Read Only: Contains the URI of the * swagger spec associated with this web service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly swaggerLocation?: string; /** * @member {boolean} [exposeSampleData] When set to true, sample data is * included in the web service's swagger definition. The default value is * true. */ exposeSampleData?: boolean; /** * @member {RealtimeConfiguration} [realtimeConfiguration] Contains the * configuration settings for the web service endpoint. */ realtimeConfiguration?: RealtimeConfiguration; /** * @member {DiagnosticsConfiguration} [diagnostics] Settings controlling the * diagnostics traces collection for the web service. */ diagnostics?: DiagnosticsConfiguration; /** * @member {StorageAccount} [storageAccount] Specifies the storage account * that Azure Machine Learning uses to store information about the web * service. Only the name of the storage account is returned from calls to * GET operations. When updating the storage account information, you must * ensure that all necessary assets are available in the new storage account * or calls to your web service will fail. */ storageAccount?: StorageAccount; /** * @member {MachineLearningWorkspace} [machineLearningWorkspace] Specifies * the Machine Learning workspace containing the experiment that is source * for the web service. */ machineLearningWorkspace?: MachineLearningWorkspace; /** * @member {CommitmentPlan} [commitmentPlan] Contains the commitment plan * associated with this web service. Set at creation time. Once set, this * value cannot be changed. Note: The commitment plan is not returned from * calls to GET operations. */ commitmentPlan?: CommitmentPlan; /** * @member {ServiceInputOutputSpecification} [input] Contains the Swagger 2.0 * schema describing one or more of the web service's inputs. For more * information, see the Swagger specification. */ input?: ServiceInputOutputSpecification; /** * @member {ServiceInputOutputSpecification} [output] Contains the Swagger * 2.0 schema describing one or more of the web service's outputs. For more * information, see the Swagger specification. */ output?: ServiceInputOutputSpecification; /** * @member {ExampleRequest} [exampleRequest] Defines sample input data for * one or more of the service's inputs. */ exampleRequest?: ExampleRequest; /** * @member {{ [propertyName: string]: AssetItem }} [assets] Contains user * defined properties describing web service assets. Properties are expressed * as Key/Value pairs. */ assets?: { [propertyName: string]: AssetItem }; /** * @member {{ [propertyName: string]: WebServiceParameter }} [parameters] The * set of global parameters values defined for the web service, given as a * global parameter name to default value map. If no default value is * specified, the parameter is considered to be required. */ parameters?: { [propertyName: string]: WebServiceParameter }; /** * @member {boolean} [payloadsInBlobStorage] When set to true, indicates that * the payload size is larger than 3 MB. Otherwise false. If the payload size * exceed 3 MB, the payload is stored in a blob and the PayloadsLocation * parameter contains the URI of the blob. Otherwise, this will be set to * false and Assets, Input, Output, Package, Parameters, ExampleRequest are * inline. The Payload sizes is determined by adding the size of the Assets, * Input, Output, Package, Parameters, and the ExampleRequest. */ payloadsInBlobStorage?: boolean; /** * @member {BlobLocation} [payloadsLocation] The URI of the payload blob. * This paramater contains a value only if the payloadsInBlobStorage * parameter is set to true. Otherwise is set to null. */ payloadsLocation?: BlobLocation; } /** * @interface * An interface representing WebService. * Instance of an Azure ML web service resource. * * @extends Resource */ export interface WebService extends Resource { /** * @member {WebServicePropertiesUnion} properties Contains the property * payload that describes the web service. */ properties: WebServicePropertiesUnion; } /** * @interface * An interface representing GraphNode. * Specifies a node in the web service graph. The node can either be an input, * output or asset node, so only one of the corresponding id properties is * populated at any given time. * */ export interface GraphNode { /** * @member {string} [assetId] The id of the asset represented by this node. */ assetId?: string; /** * @member {string} [inputId] The id of the input element represented by this * node. */ inputId?: string; /** * @member {string} [outputId] The id of the output element represented by * this node. */ outputId?: string; /** * @member {{ [propertyName: string]: WebServiceParameter }} [parameters] If * applicable, parameters of the node. Global graph parameters map into * these, with values set at runtime. */ parameters?: { [propertyName: string]: WebServiceParameter }; } /** * @interface * An interface representing GraphEdge. * Defines an edge within the web service's graph. * */ export interface GraphEdge { /** * @member {string} [sourceNodeId] The source graph node's identifier. */ sourceNodeId?: string; /** * @member {string} [sourcePortId] The identifier of the source node's port * that the edge connects from. */ sourcePortId?: string; /** * @member {string} [targetNodeId] The destination graph node's identifier. */ targetNodeId?: string; /** * @member {string} [targetPortId] The identifier of the destination node's * port that the edge connects into. */ targetPortId?: string; } /** * @interface * An interface representing GraphParameterLink. * Association link for a graph global parameter to a node in the graph. * */ export interface GraphParameterLink { /** * @member {string} nodeId The graph node's identifier */ nodeId: string; /** * @member {string} parameterKey The identifier of the node parameter that * the global parameter maps to. */ parameterKey: string; } /** * @interface * An interface representing GraphParameter. * Defines a global parameter in the graph. * */ export interface GraphParameter { /** * @member {string} [description] Description of this graph parameter. */ description?: string; /** * @member {ParameterType} type Graph parameter's type. Possible values * include: 'String', 'Int', 'Float', 'Enumerated', 'Script', 'Mode', * 'Credential', 'Boolean', 'Double', 'ColumnPicker', 'ParameterRange', * 'DataGatewayName' */ type: ParameterType; /** * @member {GraphParameterLink[]} links Association links for this parameter * to nodes in the graph. */ links: GraphParameterLink[]; } /** * @interface * An interface representing GraphPackage. * Defines the graph of modules making up the machine learning solution. * */ export interface GraphPackage { /** * @member {{ [propertyName: string]: GraphNode }} [nodes] The set of nodes * making up the graph, provided as a nodeId to GraphNode map */ nodes?: { [propertyName: string]: GraphNode }; /** * @member {GraphEdge[]} [edges] The list of edges making up the graph. */ edges?: GraphEdge[]; /** * @member {{ [propertyName: string]: GraphParameter }} [graphParameters] The * collection of global parameters for the graph, given as a global parameter * name to GraphParameter map. Each parameter here has a 1:1 match with the * global parameters values map declared at the WebServiceProperties level. */ graphParameters?: { [propertyName: string]: GraphParameter }; } /** * @interface * An interface representing WebServicePropertiesForGraph. * Properties specific to a Graph based web service. * */ export interface WebServicePropertiesForGraph { /** * @member {string} packageType Polymorphic Discriminator */ packageType: "Graph"; /** * @member {string} [title] The title of the web service. */ title?: string; /** * @member {string} [description] The description of the web service. */ description?: string; /** * @member {Date} [createdOn] Read Only: The date and time when the web * service was created. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly createdOn?: Date; /** * @member {Date} [modifiedOn] Read Only: The date and time when the web * service was last modified. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly modifiedOn?: Date; /** * @member {ProvisioningState} [provisioningState] Read Only: The provision * state of the web service. Valid values are Unknown, Provisioning, * Succeeded, and Failed. Possible values include: 'Unknown', 'Provisioning', * 'Succeeded', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {WebServiceKeys} [keys] Contains the web service provisioning * keys. If you do not specify provisioning keys, the Azure Machine Learning * system generates them for you. Note: The keys are not returned from calls * to GET operations. */ keys?: WebServiceKeys; /** * @member {boolean} [readOnly] When set to true, indicates that the web * service is read-only and can no longer be updated or patched, only * removed. Default, is false. Note: Once set to true, you cannot change its * value. */ readOnly?: boolean; /** * @member {string} [swaggerLocation] Read Only: Contains the URI of the * swagger spec associated with this web service. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly swaggerLocation?: string; /** * @member {boolean} [exposeSampleData] When set to true, sample data is * included in the web service's swagger definition. The default value is * true. */ exposeSampleData?: boolean; /** * @member {RealtimeConfiguration} [realtimeConfiguration] Contains the * configuration settings for the web service endpoint. */ realtimeConfiguration?: RealtimeConfiguration; /** * @member {DiagnosticsConfiguration} [diagnostics] Settings controlling the * diagnostics traces collection for the web service. */ diagnostics?: DiagnosticsConfiguration; /** * @member {StorageAccount} [storageAccount] Specifies the storage account * that Azure Machine Learning uses to store information about the web * service. Only the name of the storage account is returned from calls to * GET operations. When updating the storage account information, you must * ensure that all necessary assets are available in the new storage account * or calls to your web service will fail. */ storageAccount?: StorageAccount; /** * @member {MachineLearningWorkspace} [machineLearningWorkspace] Specifies * the Machine Learning workspace containing the experiment that is source * for the web service. */ machineLearningWorkspace?: MachineLearningWorkspace; /** * @member {CommitmentPlan} [commitmentPlan] Contains the commitment plan * associated with this web service. Set at creation time. Once set, this * value cannot be changed. Note: The commitment plan is not returned from * calls to GET operations. */ commitmentPlan?: CommitmentPlan; /** * @member {ServiceInputOutputSpecification} [input] Contains the Swagger 2.0 * schema describing one or more of the web service's inputs. For more * information, see the Swagger specification. */ input?: ServiceInputOutputSpecification; /** * @member {ServiceInputOutputSpecification} [output] Contains the Swagger * 2.0 schema describing one or more of the web service's outputs. For more * information, see the Swagger specification. */ output?: ServiceInputOutputSpecification; /** * @member {ExampleRequest} [exampleRequest] Defines sample input data for * one or more of the service's inputs. */ exampleRequest?: ExampleRequest; /** * @member {{ [propertyName: string]: AssetItem }} [assets] Contains user * defined properties describing web service assets. Properties are expressed * as Key/Value pairs. */ assets?: { [propertyName: string]: AssetItem }; /** * @member {{ [propertyName: string]: WebServiceParameter }} [parameters] The * set of global parameters values defined for the web service, given as a * global parameter name to default value map. If no default value is * specified, the parameter is considered to be required. */ parameters?: { [propertyName: string]: WebServiceParameter }; /** * @member {boolean} [payloadsInBlobStorage] When set to true, indicates that * the payload size is larger than 3 MB. Otherwise false. If the payload size * exceed 3 MB, the payload is stored in a blob and the PayloadsLocation * parameter contains the URI of the blob. Otherwise, this will be set to * false and Assets, Input, Output, Package, Parameters, ExampleRequest are * inline. The Payload sizes is determined by adding the size of the Assets, * Input, Output, Package, Parameters, and the ExampleRequest. */ payloadsInBlobStorage?: boolean; /** * @member {BlobLocation} [payloadsLocation] The URI of the payload blob. * This paramater contains a value only if the payloadsInBlobStorage * parameter is set to true. Otherwise is set to null. */ payloadsLocation?: BlobLocation; /** * @member {GraphPackage} [packageProperty] The definition of the graph * package making up this web service. */ packageProperty?: GraphPackage; } /** * @interface * An interface representing AsyncOperationErrorInfo. * The error detail information for async operation * */ export interface AsyncOperationErrorInfo { /** * @member {string} [code] The error code. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly code?: string; /** * @member {string} [target] The error target. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly target?: string; /** * @member {string} [message] The error message. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly message?: string; /** * @member {AsyncOperationErrorInfo[]} [details] An array containing error * information. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly details?: AsyncOperationErrorInfo[]; } /** * @interface * An interface representing AsyncOperationStatus. * Azure async operation status. * */ export interface AsyncOperationStatus { /** * @member {string} [id] Async operation id. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] Async operation name. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {ProvisioningState} [provisioningState] Read Only: The * provisioning state of the web service. Valid values are Unknown, * Provisioning, Succeeded, and Failed. Possible values include: 'Unknown', * 'Provisioning', 'Succeeded', 'Failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {Date} [startTime] The date time that the async operation started. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly startTime?: Date; /** * @member {Date} [endTime] The date time that the async operation finished. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly endTime?: Date; /** * @member {number} [percentComplete] Async operation progress. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly percentComplete?: number; /** * @member {AsyncOperationErrorInfo} [errorInfo] If the async operation * fails, this structure contains the error details. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly errorInfo?: AsyncOperationErrorInfo; } /** * @interface * An interface representing OperationDisplayInfo. * The API operation info. * */ export interface OperationDisplayInfo { /** * @member {string} [description] The description of the operation. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly description?: string; /** * @member {string} [operation] The action that users can perform, based on * their permission level. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly operation?: string; /** * @member {string} [provider] The service provider. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provider?: string; /** * @member {string} [resource] The resource on which the operation is * performed. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly resource?: string; } /** * @interface * An interface representing OperationEntity. * An API operation. * */ export interface OperationEntity { /** * @member {string} [name] Operation name: {provider}/{resource}/{operation}. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {OperationDisplayInfo} [display] The API operation info. */ display?: OperationDisplayInfo; } /** * @interface * An interface representing WebServicesGetOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface WebServicesGetOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [region] The region for which encrypted credential * parameters are valid. */ region?: string; } /** * @interface * An interface representing WebServicesListByResourceGroupOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface WebServicesListByResourceGroupOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [skiptoken] Continuation token for pagination. */ skiptoken?: string; } /** * @interface * An interface representing WebServicesListBySubscriptionIdOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface WebServicesListBySubscriptionIdOptionalParams extends msRest.RequestOptionsBase { /** * @member {string} [skiptoken] Continuation token for pagination. */ skiptoken?: string; } /** * @interface * An interface representing AzureMLWebServicesManagementClientOptions. * @extends AzureServiceClientOptions */ export interface AzureMLWebServicesManagementClientOptions extends AzureServiceClientOptions { /** * @member {string} [baseUri] */ baseUri?: string; } /** * @interface * An interface representing the OperationEntityListResult. * The list of REST API operations. * * @extends Array<OperationEntity> */ export interface OperationEntityListResult extends Array<OperationEntity> { } /** * @interface * An interface representing the PaginatedWebServicesList. * Paginated list of web services. * * @extends Array<WebService> */ export interface PaginatedWebServicesList extends Array<WebService> { /** * @member {string} [nextLink] A continuation link (absolute URI) to the next * page of results in the list. */ nextLink?: string; } /** * Defines values for ProvisioningState. * Possible values include: 'Unknown', 'Provisioning', 'Succeeded', 'Failed' * @readonly * @enum {string} */ export type ProvisioningState = 'Unknown' | 'Provisioning' | 'Succeeded' | 'Failed'; /** * Defines values for DiagnosticsLevel. * Possible values include: 'None', 'Error', 'All' * @readonly * @enum {string} */ export type DiagnosticsLevel = 'None' | 'Error' | 'All'; /** * Defines values for ColumnType. * Possible values include: 'Boolean', 'Integer', 'Number', 'String' * @readonly * @enum {string} */ export type ColumnType = 'Boolean' | 'Integer' | 'Number' | 'String'; /** * Defines values for ColumnFormat. * Possible values include: 'Byte', 'Char', 'Complex64', 'Complex128', 'Date-time', * 'Date-timeOffset', 'Double', 'Duration', 'Float', 'Int8', 'Int16', 'Int32', 'Int64', 'Uint8', * 'Uint16', 'Uint32', 'Uint64' * @readonly * @enum {string} */ export type ColumnFormat = 'Byte' | 'Char' | 'Complex64' | 'Complex128' | 'Date-time' | 'Date-timeOffset' | 'Double' | 'Duration' | 'Float' | 'Int8' | 'Int16' | 'Int32' | 'Int64' | 'Uint8' | 'Uint16' | 'Uint32' | 'Uint64'; /** * Defines values for AssetType. * Possible values include: 'Module', 'Resource' * @readonly * @enum {string} */ export type AssetType = 'Module' | 'Resource'; /** * Defines values for InputPortType. * Possible values include: 'Dataset' * @readonly * @enum {string} */ export type InputPortType = 'Dataset'; /** * Defines values for OutputPortType. * Possible values include: 'Dataset' * @readonly * @enum {string} */ export type OutputPortType = 'Dataset'; /** * Defines values for ParameterType. * Possible values include: 'String', 'Int', 'Float', 'Enumerated', 'Script', 'Mode', 'Credential', * 'Boolean', 'Double', 'ColumnPicker', 'ParameterRange', 'DataGatewayName' * @readonly * @enum {string} */ export type ParameterType = 'String' | 'Int' | 'Float' | 'Enumerated' | 'Script' | 'Mode' | 'Credential' | 'Boolean' | 'Double' | 'ColumnPicker' | 'ParameterRange' | 'DataGatewayName'; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationEntityListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationEntityListResult; }; }; /** * Contains response data for the createOrUpdate operation. */ export type WebServicesCreateOrUpdateResponse = WebService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebService; }; }; /** * Contains response data for the get operation. */ export type WebServicesGetResponse = WebService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebService; }; }; /** * Contains response data for the patch operation. */ export type WebServicesPatchResponse = WebService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebService; }; }; /** * Contains response data for the createRegionalProperties operation. */ export type WebServicesCreateRegionalPropertiesResponse = AsyncOperationStatus & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: AsyncOperationStatus; }; }; /** * Contains response data for the listKeys operation. */ export type WebServicesListKeysResponse = WebServiceKeys & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebServiceKeys; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type WebServicesListByResourceGroupResponse = PaginatedWebServicesList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PaginatedWebServicesList; }; }; /** * Contains response data for the listBySubscriptionId operation. */ export type WebServicesListBySubscriptionIdResponse = PaginatedWebServicesList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PaginatedWebServicesList; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type WebServicesBeginCreateOrUpdateResponse = WebService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebService; }; }; /** * Contains response data for the beginPatch operation. */ export type WebServicesBeginPatchResponse = WebService & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WebService; }; }; /** * Contains response data for the beginCreateRegionalProperties operation. */ export type WebServicesBeginCreateRegionalPropertiesResponse = AsyncOperationStatus & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: AsyncOperationStatus; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type WebServicesListByResourceGroupNextResponse = PaginatedWebServicesList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PaginatedWebServicesList; }; }; /** * Contains response data for the listBySubscriptionIdNext operation. */ export type WebServicesListBySubscriptionIdNextResponse = PaginatedWebServicesList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PaginatedWebServicesList; }; };
the_stack
import { WorkflowState, WorkflowStatus } from '../workflow-state' import { Message, MessageAttributes } from '@node-ts/bus-messages' import { MessageWorkflowMapping } from '../message-workflow-mapping' import * as uuid from 'uuid' import { Workflow, OnWhenHandler, WorkflowMapper } from '../workflow' import { ClassConstructor, CoreDependencies } from '../../util' import { PersistenceNotConfigured } from '../persistence/error' import { WorkflowAlreadyInitialized } from '../error' import { messageHandlingContext } from '../../message-handling-context' import { ContainerAdapter } from '../../container' import { HandlerDispatchRejected, HandlerRegistry } from '../../handler' import { Logger } from '../../logger' import { Persistence } from '../persistence' /** * A default lookup that will match a workflow by its id with the workflowId * stored in the sticky attributes */ const workflowLookup: MessageWorkflowMapping = { lookup: (_, attributes) => attributes.stickyAttributes.workflowId as string | undefined, mapsTo: '$workflowId' } /** * The central workflow registry that holds all workflows managed by the application. This includes * - the list of workflows * - what messages start the workflow * - what messages are handled by each workflow * This registry is also responsible for dispatching messages to workflows as they are received. */ export class WorkflowRegistry { private workflowRegistry: ClassConstructor<Workflow<WorkflowState>>[] = [] private isInitialized = false private isInitializing = false private logger: Logger private persistence: Persistence prepare (coreDependencies: CoreDependencies, persistence: Persistence): void { this.logger = coreDependencies.loggerFactory('@node-ts/bus-core:workflow-registry') this.persistence = persistence } async register (workflow: ClassConstructor<Workflow<WorkflowState>>): Promise<void> { if (this.isInitialized) { throw new Error( `Attempted to register workflow (${workflow.prototype.constructor.name}) after workflows have been initialized` ) } const duplicateWorkflowName = this.workflowRegistry .some(r => r.prototype.constructor.name === workflow.prototype.constructor.name) if (duplicateWorkflowName) { throw new Error(`Attempted to register two workflows with the same name (${workflow.prototype.constructor.name})`) } this.workflowRegistry.push(workflow) } /** * Initialize all services that are used to support workflows. This registers all messages subscribed to * in workflows as handlers with the bus, as well as initializing the persistence service so that workflow * states can be stored. * * This should be called once as the application is starting. */ async initialize ( handlerRegistry: HandlerRegistry, container: ContainerAdapter | undefined ): Promise<void> { if (this.workflowRegistry.length === 0) { this.logger.info('No workflows registered, skipping this step.') return } if (this.isInitialized || this.isInitializing) { throw new WorkflowAlreadyInitialized() } this.logger.info('Initializing workflows...', { numWorkflows: this.workflowRegistry.length }) this.isInitializing = true for (const WorkflowCtor of this.workflowRegistry) { this.logger.debug('Initializing workflow', { workflow: WorkflowCtor.prototype.constructor.name }) const workflowInstance = container ? container.get(WorkflowCtor) : new WorkflowCtor() const mapper = new WorkflowMapper(WorkflowCtor) workflowInstance.configureWorkflow(mapper) if (!mapper.workflowStateCtor) { throw new Error('Workflow state not provided. Use .withState()') } this.registerFnStartedBy(mapper, handlerRegistry, container) this.registerFnHandles(mapper, handlerRegistry, WorkflowCtor, container) const messageWorkflowMappings: MessageWorkflowMapping[] = Array.from<[ClassConstructor<Message>, OnWhenHandler], MessageWorkflowMapping>( mapper.onWhen, ([_, onWhenHandler]) => onWhenHandler.customLookup || workflowLookup ) await this.persistence.initializeWorkflow(mapper.workflowStateCtor!, messageWorkflowMappings) this.logger.debug('Workflow initialized', { workflowName: WorkflowCtor.prototype.name }) } this.workflowRegistry = [] if (this.persistence.initialize) { this.logger.info('Initializing persistence...') await this.persistence.initialize!() } this.isInitialized = true this.isInitializing = false this.logger.info('Workflows initialized') } async dispose (): Promise<void> { this.logger.debug('Disposing workflow registry') try { if (this.persistence.dispose) { await this.persistence.dispose!() } } catch (error) { if (error instanceof PersistenceNotConfigured) { return } throw error } } private registerFnStartedBy ( mapper: WorkflowMapper<any, any>, handlerRegistry: HandlerRegistry, container: ContainerAdapter | undefined ): void { this.logger.debug( 'Registering started by handlers for workflow', { numHandlers: mapper.onStartedBy.size } ) mapper.onStartedBy.forEach((options, messageConstructor) => handlerRegistry.register( messageConstructor, async (message, messageAttributes) => { this.logger.debug( 'Starting new workflow instance', { workflow: options.workflowCtor, msg: message } ) const workflowState = this.createWorkflowState(mapper.workflowStateCtor!) const immutableWorkflowState = Object.freeze({...workflowState}) this.startWorkflowHandlingContext(immutableWorkflowState) try { const workflow = container ? container.get(options.workflowCtor) : new options.workflowCtor() const handler = workflow[options.workflowHandler as keyof Workflow<WorkflowState>] as Function const result = await handler.bind(workflow)(message, immutableWorkflowState, messageAttributes) this.logger.debug( 'Finished handling for new workflow', { workflow: options.workflowCtor, msg: message, workflowState: result } ) if (result) { await this.persistence.saveWorkflowState({ ...workflowState, ...result }) } } finally { this.endWorkflowHandlingContext() } } )) } private registerFnHandles ( mapper: WorkflowMapper<WorkflowState, Workflow<WorkflowState>>, handlerRegistry: HandlerRegistry, workflowCtor: ClassConstructor<Workflow<WorkflowState>>, container: ContainerAdapter | undefined ): void { this.logger.debug( 'Registering handles for workflow', { workflow: workflowCtor, numHandlers: mapper.onWhen.size } ) mapper.onWhen.forEach((handler, messageConstructor) => { // TODO implement outbound tagging of workflowId to stickyAttributes const messageMapping = handler.customLookup || workflowLookup handlerRegistry.register( messageConstructor, async (message, attributes) => { this.logger.debug('Getting workflow state for message handler', { msg: message, workflow: workflowCtor }) const workflowState = await this.persistence.getWorkflowState<WorkflowState, Message>( mapper.workflowStateCtor!, messageMapping, message, attributes, false ) if (!workflowState.length) { this.logger.info('No existing workflow state found for message. Ignoring.', { message }) return } const workflowHandlers = workflowState.map(async state => { try { this.startWorkflowHandlingContext(state) await this.dispatchMessageToWorkflow( message, attributes, workflowCtor, state, mapper.workflowStateCtor!, handler.workflowHandler, container ) } finally { this.endWorkflowHandlingContext() } }) const handlerResults = await Promise.allSettled(workflowHandlers) const failedHandlers = handlerResults.filter(r => r.status === 'rejected') if (failedHandlers.length) { const reasons = (failedHandlers as PromiseRejectedResult[]).map(h => h.reason) throw new HandlerDispatchRejected(reasons) } } ) }) } private createWorkflowState<TWorkflowState extends WorkflowState> (workflowStateType: ClassConstructor<TWorkflowState>) { const data = new workflowStateType() data.$status = WorkflowStatus.Running data.$workflowId = uuid.v4() this.logger.debug('Created new workflow state', { workflowId: data.$workflowId, workflowStateType }) return data } /** * Creates a new handling context for a single workflow. This is used so * that the `$workflowId` is attached to outgoing messages in sticky * attributes. This allows message chains to be automatically mapped * back to the workflow if handled. */ private async startWorkflowHandlingContext (workflowState: WorkflowState) { this.logger.debug('Starting new workflow handling context', { workflowState }) const handlingContext = messageHandlingContext.get()!.message const workflowHandlingContext = JSON.parse(JSON.stringify(handlingContext)) as typeof handlingContext workflowHandlingContext.attributes.stickyAttributes.workflowId = workflowState.$workflowId messageHandlingContext.set(workflowHandlingContext) } private endWorkflowHandlingContext () { this.logger.debug('Ending workflow handling context') messageHandlingContext.destroy() } private async dispatchMessageToWorkflow ( message: Message, attributes: MessageAttributes, workflowCtor: ClassConstructor<Workflow<WorkflowState>>, workflowState: WorkflowState, workflowStateConstructor: ClassConstructor<WorkflowState>, workflowHandler: keyof Workflow<WorkflowState>, container: ContainerAdapter | undefined ) { this.logger.debug('Dispatching message to workflow', { msg: message, workflow: workflowCtor }) const workflow = container ? container.get(workflowCtor) : new workflowCtor() const immutableWorkflowState = Object.freeze({...workflowState}) const handler = workflow[workflowHandler] as Function const workflowStateOutput = await handler.bind(workflow)(message, immutableWorkflowState, attributes) const workflowName = workflowCtor.prototype.name if (workflowStateOutput && workflowStateOutput.$status === WorkflowStatus.Discard) { this.logger.debug( 'Workflow step is discarding state changes. State changes will not be persisted', { workflowId: immutableWorkflowState.$workflowId, workflowName } ) } else if (workflowStateOutput) { this.logger.debug( 'Changes detected in workflow state and will be persisted.', { workflowId: immutableWorkflowState.$workflowId, workflowName, changes: workflowStateOutput } ) const updatedWorkflowState = Object.assign( new workflowStateConstructor(), workflowState, workflowStateOutput ) try { await this.persist(updatedWorkflowState) } catch (error) { this.logger.warn( 'Error persisting workflow state', { err: error, workflow: workflowName } ) throw error } } else { this.logger.trace('No changes detected in workflow state.', { workflowId: immutableWorkflowState.$workflowId }) } } private async persist (data: WorkflowState) { try { await this.persistence.saveWorkflowState(data) this.logger.info('Workflow state saved', { data }) } catch (err) { this.logger.error('Error persisting workflow state', { err }) throw err } } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/backupSchedulesMappers"; import * as Parameters from "../models/parameters"; import { StorSimple8000SeriesManagementClientContext } from "../storSimple8000SeriesManagementClientContext"; /** Class representing a BackupSchedules. */ export class BackupSchedules { private readonly client: StorSimple8000SeriesManagementClientContext; /** * Create a BackupSchedules. * @param {StorSimple8000SeriesManagementClientContext} client Reference to the service client. */ constructor(client: StorSimple8000SeriesManagementClientContext) { this.client = client; } /** * Gets all the backup schedules in a backup policy. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.BackupSchedulesListByBackupPolicyResponse> */ listByBackupPolicy(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupSchedulesListByBackupPolicyResponse>; /** * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ listByBackupPolicy(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.BackupScheduleList>): void; /** * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ listByBackupPolicy(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BackupScheduleList>): void; listByBackupPolicy(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BackupScheduleList>, callback?: msRest.ServiceCallback<Models.BackupScheduleList>): Promise<Models.BackupSchedulesListByBackupPolicyResponse> { return this.client.sendOperationRequest( { deviceName, backupPolicyName, resourceGroupName, managerName, options }, listByBackupPolicyOperationSpec, callback) as Promise<Models.BackupSchedulesListByBackupPolicyResponse>; } /** * Gets the properties of the specified backup schedule name. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupScheduleName The name of the backup schedule to be fetched * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.BackupSchedulesGetResponse> */ get(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupSchedulesGetResponse>; /** * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupScheduleName The name of the backup schedule to be fetched * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ get(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.BackupSchedule>): void; /** * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupScheduleName The name of the backup schedule to be fetched * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ get(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BackupSchedule>): void; get(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BackupSchedule>, callback?: msRest.ServiceCallback<Models.BackupSchedule>): Promise<Models.BackupSchedulesGetResponse> { return this.client.sendOperationRequest( { deviceName, backupPolicyName, backupScheduleName, resourceGroupName, managerName, options }, getOperationSpec, callback) as Promise<Models.BackupSchedulesGetResponse>; } /** * Creates or updates the backup schedule. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupScheduleName The backup schedule name. * @param parameters The backup schedule. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.BackupSchedulesCreateOrUpdateResponse> */ createOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: Models.BackupSchedule, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupSchedulesCreateOrUpdateResponse> { return this.beginCreateOrUpdate(deviceName,backupPolicyName,backupScheduleName,parameters,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BackupSchedulesCreateOrUpdateResponse>; } /** * Deletes the backup schedule. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupScheduleName The name the backup schedule. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(deviceName,backupPolicyName,backupScheduleName,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Creates or updates the backup schedule. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupScheduleName The backup schedule name. * @param parameters The backup schedule. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(deviceName: string, backupPolicyName: string, backupScheduleName: string, parameters: Models.BackupSchedule, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, backupPolicyName, backupScheduleName, parameters, resourceGroupName, managerName, options }, beginCreateOrUpdateOperationSpec, options); } /** * Deletes the backup schedule. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupScheduleName The name the backup schedule. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(deviceName: string, backupPolicyName: string, backupScheduleName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, backupPolicyName, backupScheduleName, resourceGroupName, managerName, options }, beginDeleteMethodOperationSpec, options); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByBackupPolicyOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}/schedules", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BackupScheduleList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}/schedules/{backupScheduleName}", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.backupScheduleName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BackupSchedule }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}/schedules/{backupScheduleName}", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.backupScheduleName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.BackupSchedule, required: true } }, responses: { 200: { bodyMapper: Mappers.BackupSchedule }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}/schedules/{backupScheduleName}", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.backupScheduleName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import oboe from "oboe"; interface DeduplicationContext { JSONroot:any, currentDepth:number, } export default class StreamingJSONParser { // this expects to get a valid qlog-formatted string and parses it to JSON format // we don't directly use JSON.parse since the qlog string might not be valid JSON in and of itself (e.g., missing closing brackets) public static parseQlogText( text:string, streamOnlyAsFallback:boolean = true ):any { // by default, first tries to use JSON.parse (because it's more performant) // Falls back to a streaming parser in case JSON.parse produces errors (e.g., file wasn't closed correctly) if ( streamOnlyAsFallback ) { try { return JSON.parse( text ); } catch (e) { console.error("StreamingJSONParser:parse : JSON.parse returned an error, trying again with oboe.js fallback parser! Error was: : ", e); return StreamingJSONParser.parseQlogText( text, false ); } } else { let finalOutput:any = undefined; let cleanExit = false; // if there are event entries after the closing of the file (e.g., the closing brackets are written by thread 1, then thread 2 writes more events) // the oboe parser will start generating a new root, which is not exactly the one we want (the old one is typically better) // As long as we're parsing normally, the original root shouldn't change // so we track that one and then, if there are errors, compare it with the latest one and pick the most likely candidate let initialRoot:any = undefined; const oboeStream = oboe() // .node({ // 'node:*': ( node:any, path:any ) => { // return node; // successful parse just gives us the value, which we can return, is gathered correctly by oboe // }, // }) .on('node:*', (node:any, path:Array<any>, ancestors:any) => { if ( !initialRoot ) { initialRoot = oboeStream.root(); } // console.log("Node parsed", oboeStream.root()); return node; }) .done( (output:any) => { finalOutput = output; cleanExit = true; }) .fail( (errorReport:any ) => { // any fails will get here, and we can ignore them for the final output console.error( "StreamingJSONParser: There were errors in your qlog/JSON file. It was parsed with the fallback parser up until the point of the error.", errorReport, oboeStream.root() ); let initialLength = 0; let currentLength = 0; const currentRoot = oboeStream.root(); if ( initialRoot && initialRoot.traces && initialRoot.traces.length && initialRoot.traces.length > 0 && initialRoot.traces[0].events && initialRoot.traces[0].events.length > 0 ) { initialLength = initialRoot.traces[0].events.length; } if ( currentRoot && currentRoot.traces && currentRoot.traces.length && currentRoot.traces.length > 0 && currentRoot.traces[0].events && currentRoot.traces[0].events.length > 0 ) { currentLength = currentRoot.traces[0].events.length; } if ( currentLength >= initialLength ) { finalOutput = currentRoot; } else { finalOutput = initialRoot; } }); oboeStream.emit('data', text); // so, it depends on what's wrong with the input file what we get // if the JSON simply isn't properly closed, the done() callback never fires (neither does fail()) // fail() mainly seems to fire when we have an error in the middle of the file instead of at the end // -> parsing then also only goes so far and stops there // this means we get here after the emit() call and have to figure out if it worked or not. // we use oboeStream.root() to get the parsed JSON up to this point (because finalOutput is probably not set) if ( cleanExit ) { // assume all is up to snuff, just return the output return finalOutput; } else { if ( !finalOutput ) { finalOutput = oboeStream.root(); } // oboe parses field-by-field, so if the JSON is cut off after some fields but not enough to form a full qlog event, it still fails... // (in other words: we have valid JSON, but not valid qlog) // so, need to make sure our events are of proper shape (each event_field is present) // this is probably not enough to deal with all problems, but should be ok for most if ( finalOutput.traces ) { for ( const trace of finalOutput.traces ) { if ( trace.event_fields ) { const eventFieldsLength = trace.event_fields.length; if ( trace.events ) { const eventCount = trace.events.length; for ( let i = eventCount - 1; i >= 0; --i ){ if ( trace.events[i].length !== eventFieldsLength ) { const removed = trace.events.pop(); console.error("StreamingJSONParser: incomplete event found, ignored in output.", removed); } } } } } } return finalOutput; } } } // this expects raw JSON of any format and de-duplicates its key entries // main use-case is for loading wireshark/tshark JSON packet captures, since those often contain duplicate keys public static parseJSONWithDeduplication( text:string ) { const context:DeduplicationContext = { JSONroot:undefined, currentDepth:0, }; const oboeStream = oboe() .on('node:*', (node:any, path:Array<any>, ancestors:any) => { return StreamingJSONParser.onFieldParsed( context, node, path ); }) .done( (output:any) => { console.log( "Result from deduped parser (which we will discard) :", output ); }) .fail( (errorReport:any ) => { // any fails will get here, and we can ignore them for the final output console.log( "Oboe failed, ignoring", errorReport ); }); oboeStream.emit('data', text); return context.JSONroot; } // this is some of the worst code I've ever written, // took me two days of nightmare filled debugging on many different input files // this can probably be cleaned up considerably, but I was just so happy to finally find something that works that I didn't have the heart for it. // This is custom de-duplication logic highly tied to how oboe.js callbacks provide data about fields that are parsed // I wrote this because nowhere on the internet I can seem to find a general-purpose de-duplication algorithm (though some JSON parsing websites do seem to include it...) // It was needed because tshark's --no-duplicate-keys option has a bug that sometimes drops data from the output (some of the duplicate key's data is replaced with earlier data) protected static onFieldParsed( context:DeduplicationContext, value:any, path :Array<any>) { // const currentDepth = context.currentDepth; if ( !context.JSONroot ) { console.log("StreamingJSONparser:onFieldParsed : deciding on root for JSON", value, path, context.JSONroot ); // the real root hasn't been set yet because we don't know if it's an object or an array if ( path[0] === 0 ) { context.JSONroot = []; } else { context.JSONroot = {}; } } // oboe unrolls after parsing a complete object (e.g., first gives us 5, 5, then 4, 3, then 5, 5 again // so keep track of the previous depth and only start adding new arrays if we are at that depth or lower const previousDepth = context.currentDepth; context.currentDepth = path.length; if ( context.currentDepth < previousDepth ) { return; // nothing to add, simply cascading back up, only needed to set previousDepth to know that } // 2 phases: first move towards the current root, then start adding logic // -2 because depth is the length, so -1 is the last element. We want the one before that const currentRootIndex = previousDepth - 2; // if ( currentDepth === previousDepth ) // currentRootIndex -= 1; // need to move one back because new one is still adding // console.log("Looking for root at index", currentRootIndex, path, JSON.stringify(JSONroot)); let root = context.JSONroot; for ( let i = 0; i <= currentRootIndex; ++i ) { const currentKey = path[i]; const nextPathElementIsArrayIndex = (typeof path[ i + 1 ] === "number"); // console.log("current key", currentKey, JSON.stringify(root) ); // dichotomy: // we both have arrays inside the json we want to keep, and duplicate keys that we want to make into arrays ourselves // the first type we want to keep the array as a root, the second we want to advanced beyond the array... if ( Array.isArray(root[currentKey]) ) { if ( !nextPathElementIsArrayIndex ) { root = root[currentKey][ root[currentKey].length - 1 ]; } else { root = root[currentKey]; } } else { root = root[currentKey]; } } // console.log("Current root found is", currentRootIndex, path, JSON.stringify(root) ); const pathStartIndex = Math.max(0, currentRootIndex + 1); if ( pathStartIndex >= path.length ) { console.error("StreamingJSONParser: Path isn't long enough to encompass new entry, shouldn't happen!", pathStartIndex, path); return; } for ( let i = pathStartIndex; i < path.length; ++i ) { const isFinalElement = i === path.length - 1; const currentKey = path[i]; const nextPathElementIsArrayIndex = !isFinalElement && (typeof path[ i + 1 ] === "number"); // console.log("-".repeat(i) + "Adding as final element?", isFinalElement, JSON.stringify(root)); if ( Array.isArray(root[currentKey]) ){ // we've seen it before and it's already an array, so we need to append to the array (3 or more items of the same type) if ( isFinalElement ) { root[currentKey].push( value ); } else { if ( nextPathElementIsArrayIndex ) { root[currentKey].push( [] ); } else { root[currentKey].push( {} ); } } root = root[currentKey][ root[currentKey].length - 1 ]; // console.log("-".repeat(i) + "Current key was array, pushed now:", currentKey, JSON.stringify(JSONroot) ); } else if ( !root.hasOwnProperty(currentKey) ) { // first time we see this thing if ( !isFinalElement ) { if (nextPathElementIsArrayIndex ) { root[currentKey] = []; } else { root[currentKey] = {}; } } else { root[currentKey] = value; } root = root[currentKey]; // console.log("-".repeat(i) + "Current key was unknown object, added now:", currentKey, JSON.stringify(JSONroot)); } else { // second time we see this thing: need to create an array for it // console.log("-".repeat(i) + "Current key has to be added to a new array", currentKey, root); const curValue = root[currentKey]; root[currentKey] = []; root[currentKey].push( curValue ); if ( isFinalElement ) { root[currentKey].push( value ); } else { root[currentKey].push( {} ); } root = root[currentKey][ root[currentKey].length - 1 ]; } } // && value because sometimes the value is null/undefined in the JSON and that is a valid value, believe it or not if ( !root && value ) { console.error("StreamingJSONParser: WEIRD STUFF", root, path, context.JSONroot); } return value; } }
the_stack
import { ether, expectEvent, expectRevert } from '@openzeppelin/test-helpers' import BN from 'bn.js' import { Transaction, AccessListEIP2930Transaction, FeeMarketEIP1559Transaction } from '@ethereumjs/tx' import Common from '@ethereumjs/common' import { TxOptions } from '@ethereumjs/tx/dist/types' import { encode } from 'rlp' import { expect } from 'chai' import { privateToAddress, bnToRlp, ecsign, keccak256, bufferToHex } from 'ethereumjs-util' import { RelayRequest } from '@opengsn/common/dist/EIP712/RelayRequest' import { getEip712Signature, removeHexPrefix, signatureRSV2Hex } from '@opengsn/common/dist/Utils' import { TypedRequestData } from '@opengsn/common/dist/EIP712/TypedRequestData' import { defaultEnvironment } from '@opengsn/common/dist/Environments' import { PenalizerInstance, RelayHubInstance, StakeManagerInstance, TestPaymasterEverythingAcceptedInstance, TestRecipientInstance, TestTokenInstance } from '@opengsn/contracts/types/truffle-contracts' import { deployHub, evmMineMany, revert, snapshot } from './TestUtils' import { getRawTxOptions } from '@opengsn/common/dist/ContractInteractor' import { registerForwarderForGsn } from '@opengsn/common/dist/EIP712/ForwarderUtil' import { StakeUnlocked } from '@opengsn/common/dist/types/GSNContractsDataTypes' import { getDataAndSignature, constants } from '@opengsn/common/dist' import { balanceTrackerErc20 } from './utils/ERC20BalanceTracker' const RelayHub = artifacts.require('RelayHub') const StakeManager = artifacts.require('StakeManager') const Penalizer = artifacts.require('Penalizer') const TestRecipient = artifacts.require('TestRecipient') const TestToken = artifacts.require('TestToken') const TestPaymasterEverythingAccepted = artifacts.require('TestPaymasterEverythingAccepted') const Forwarder = artifacts.require('Forwarder') const paymasterData = '0x' const clientId = '0' contract('RelayHub Penalizations', function ([_, relayOwner, committer, nonCommitter, sender, other, relayManager, reporterRelayManager]) { // eslint-disable-line no-unused-vars const chainId = defaultEnvironment.chainId let stakeManager: StakeManagerInstance let relayHub: RelayHubInstance let penalizer: PenalizerInstance let recipient: TestRecipientInstance let paymaster: TestPaymasterEverythingAcceptedInstance let testToken: TestTokenInstance let transactionOptions: TxOptions let forwarder: string const relayWorkerPrivateKey = Buffer.from('92db14e403b83dfe3df233f83dfa3a0d7096f21ca9b0d6d6b8d88b2b4ec1564e', 'hex') const relayWorker = privateToAddress(relayWorkerPrivateKey).toString('hex') const anotherRelayWorkerPrivateKey = Buffer.from('4bbbf85ce3377467afe5d46f804f221813b2bb87f24d81f60f1fcdbf7cbf4356', 'hex') const anotherRelayWorker = privateToAddress(anotherRelayWorkerPrivateKey).toString('hex') const stake = ether('1') const encodedCallArgs = { sender, recipient: '0x1820b744B33945482C17Dc37218C01D858EBc714', data: '0x1234', baseFee: 1000, fee: 10, maxFeePerGas: 50, maxPriorityFeePerGas: 50, gasLimit: 1e6, nonce: 0, paymaster: '' } const relayCallArgs = { gasPrice: 50, gasLimit: 1e6, nonce: 0, value: 0, privateKey: relayWorkerPrivateKey } // TODO: 'before' is a bad thing in general. Use 'beforeEach', this tests all depend on each other!!! before(async function () { testToken = await TestToken.new() stakeManager = await StakeManager.new(defaultEnvironment.maxUnstakeDelay, 0, 0, constants.BURN_ADDRESS, constants.BURN_ADDRESS) penalizer = await Penalizer.new(defaultEnvironment.penalizerConfiguration.penalizeBlockDelay, 40) relayHub = await deployHub(stakeManager.address, penalizer.address, constants.ZERO_ADDRESS, testToken.address, stake.toString()) const forwarderInstance = await Forwarder.new() forwarder = forwarderInstance.address recipient = await TestRecipient.new(forwarder) // register hub's RelayRequest with forwarder, if not already done. await registerForwarderForGsn(forwarderInstance) paymaster = await TestPaymasterEverythingAccepted.new() encodedCallArgs.paymaster = paymaster.address await testToken.mint(stake, { from: relayOwner }) await testToken.approve(stakeManager.address, stake, { from: relayOwner }) await stakeManager.setRelayManagerOwner(relayOwner, { from: relayManager }) await stakeManager.stakeForRelayManager(testToken.address, relayManager, 15000, stake, { from: relayOwner }) await stakeManager.authorizeHubByOwner(relayManager, relayHub.address, { from: relayOwner }) await paymaster.setTrustedForwarder(forwarder) await paymaster.setRelayHub(relayHub.address) await relayHub.addRelayWorkers([relayWorker], { from: relayManager }) // @ts-ignore Object.keys(StakeManager.events).forEach(function (topic) { // @ts-ignore RelayHub.network.events[topic] = StakeManager.events[topic] }) // @ts-ignore Object.keys(StakeManager.events).forEach(function (topic) { // @ts-ignore Penalizer.network.events[topic] = StakeManager.events[topic] }) const networkId = await web3.eth.net.getId() const chain = await web3.eth.net.getNetworkType() transactionOptions = getRawTxOptions(chainId, networkId, chain) }) describe('penalizations', function () { describe('TransactionType penalization', function () { let relayRequest: RelayRequest let encodedCall: string let common: Common let legacyTx: Transaction let eip2930Transaction: AccessListEIP2930Transaction let eip1559Transaction: FeeMarketEIP1559Transaction let describeSnapshotId: string before(async function () { common = new Common({ chain: 'mainnet', hardfork: 'london' }) // TODO: 'encodedCallArgs' is no longer needed. just keep the RelayRequest in test relayRequest = { request: { to: encodedCallArgs.recipient, data: encodedCallArgs.data, from: encodedCallArgs.sender, nonce: encodedCallArgs.nonce.toString(), value: '0', gas: encodedCallArgs.gasLimit.toString(), validUntilTime: '0' }, relayData: { baseRelayFee: encodedCallArgs.baseFee.toString(), pctRelayFee: encodedCallArgs.fee.toString(), maxFeePerGas: encodedCallArgs.maxFeePerGas.toString(), maxPriorityFeePerGas: encodedCallArgs.maxPriorityFeePerGas.toString(), transactionCalldataGasUsed: '0', relayWorker: relayWorker, forwarder, paymaster: encodedCallArgs.paymaster, paymasterData, clientId } } encodedCall = relayHub.contract.methods.relayCall(10e6, relayRequest, '0xabcdef123456', '0x').encodeABI() legacyTx = new Transaction({ nonce: relayCallArgs.nonce, gasLimit: relayCallArgs.gasLimit, gasPrice: relayCallArgs.gasPrice, to: relayHub.address, value: relayCallArgs.value, data: encodedCall }, { common }) eip2930Transaction = AccessListEIP2930Transaction.fromTxData(legacyTx, { common }) eip1559Transaction = FeeMarketEIP1559Transaction.fromTxData({ nonce: relayCallArgs.nonce, gasLimit: relayCallArgs.gasLimit, to: relayHub.address, value: relayCallArgs.value, data: encodedCall }, { common }) }) beforeEach(async function () { describeSnapshotId = (await snapshot()).result }) afterEach(async function () { await revert(describeSnapshotId) }) describe('#decodeTransaction', function () { it('should decode TransactionType1 tx', async function () { const input = [bnToRlp(eip2930Transaction.chainId), bnToRlp(eip2930Transaction.nonce), bnToRlp(eip2930Transaction.gasPrice), bnToRlp(eip2930Transaction.gasLimit), eip2930Transaction.to!.toBuffer(), bnToRlp(eip2930Transaction.value), eip2930Transaction.data, eip2930Transaction.accessList] const penalizableTxData = `0x01${encode(input).toString('hex')}` const decodedTx = await penalizer.decodeTransaction(penalizableTxData) // @ts-ignore validateDecodedTx(decodedTx, eip2930Transaction) }) it('should decode new TransactionType2 tx', async function () { const input = [bnToRlp(eip1559Transaction.chainId), bnToRlp(eip1559Transaction.nonce), bnToRlp(eip1559Transaction.maxPriorityFeePerGas), bnToRlp(eip1559Transaction.maxFeePerGas), bnToRlp(eip1559Transaction.gasLimit), eip1559Transaction.to!.toBuffer(), bnToRlp(eip1559Transaction.value), eip1559Transaction.data, eip1559Transaction.accessList] const penalizableTxData = `0x02${encode(input).toString('hex')}` const decodedTx = await penalizer.decodeTransaction(penalizableTxData) // @ts-ignore validateDecodedTx(decodedTx, eip1559Transaction) }) it('should decode legacy tx', async function () { const input = [bnToRlp(legacyTx.nonce), bnToRlp(legacyTx.gasPrice), bnToRlp(legacyTx.gasLimit), legacyTx.to!.toBuffer(), bnToRlp(legacyTx.value), legacyTx.data] const penalizableTxData = `0x${encode(input).toString('hex')}` const decodedTx = await penalizer.decodeTransaction(penalizableTxData) // @ts-ignore validateDecodedTx(decodedTx, legacyTx) }) }) it('should not penalize TransactionType1 tx', async function () { const signedTx = eip2930Transaction.sign(relayCallArgs.privateKey) const input = [bnToRlp(eip2930Transaction.chainId), bnToRlp(eip2930Transaction.nonce), bnToRlp(eip2930Transaction.gasPrice), bnToRlp(eip2930Transaction.gasLimit), eip2930Transaction.to!.toBuffer(), bnToRlp(eip2930Transaction.value), eip2930Transaction.data, eip2930Transaction.accessList] const penalizableTxData = `0x01${encode(input).toString('hex')}` const newV = (signedTx.v!.toNumber() + 27) const penalizableTxSignature = signatureRSV2Hex(signedTx.r!, signedTx.s!, newV) const request = penalizer.contract.methods.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x').encodeABI() // eslint-disable-next-line const commitHash = web3.utils.keccak256(web3.utils.keccak256(request) + committer.slice(2)) await penalizer.commit(commitHash, { from: committer }) await evmMineMany(10) await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x', { from: committer }), 'Legal relay transaction' ) }) it('should not penalize TransactionType2 tx', async function () { const signedTx = eip1559Transaction.sign(relayCallArgs.privateKey) const input = [bnToRlp(eip1559Transaction.chainId), bnToRlp(eip1559Transaction.nonce), bnToRlp(eip1559Transaction.maxPriorityFeePerGas), bnToRlp(eip1559Transaction.maxFeePerGas), bnToRlp(eip1559Transaction.gasLimit), eip1559Transaction.to!.toBuffer(), bnToRlp(eip1559Transaction.value), eip1559Transaction.data, eip1559Transaction.accessList] const penalizableTxData = `0x02${encode(input).toString('hex')}` const newV = (signedTx.v!.toNumber() + 27) const penalizableTxSignature = signatureRSV2Hex(signedTx.r!, signedTx.s!, newV) const request = penalizer.contract.methods.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x').encodeABI() // eslint-disable-next-line const commitHash = web3.utils.keccak256(web3.utils.keccak256(request) + committer.slice(2)) await penalizer.commit(commitHash, { from: committer }) await evmMineMany(10) await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x', { from: committer }), 'Legal relay transaction' ) }); // legacy tx first byte is in [0xc0, 0xfe] ['bf', 'ff'].forEach(byteToSign => { it('should penalize any non legacy tx format signed bytes', async function () { const bufferToSign = Buffer.from(byteToSign, 'hex') const msgHash = keccak256(bufferToSign) const sig = ecsign(msgHash, relayWorkerPrivateKey) const penalizableTxSignature = signatureRSV2Hex(sig.r, sig.s, sig.v) const request = penalizer.contract.methods.penalizeIllegalTransaction(bufferToSign, penalizableTxSignature, relayHub.address, '0x').encodeABI() // eslint-disable-next-line const commitHash = web3.utils.keccak256(web3.utils.keccak256(request) + committer.slice(2)) await penalizer.commit(commitHash, { from: committer }) await evmMineMany(10) const res = await penalizer.penalizeIllegalTransaction(bufferToHex(bufferToSign), penalizableTxSignature, relayHub.address, '0x', { from: committer }) expectEvent(res, 'StakePenalized', { relayManager: relayManager, beneficiary: committer, reward: stake.divn(2) }) }) }) }) before('register reporter as relayer', async function () { await testToken.mint(stake, { from: relayOwner }) await testToken.approve(stakeManager.address, stake, { from: relayOwner }) await stakeManager.setRelayManagerOwner(relayOwner, { from: reporterRelayManager }) await stakeManager.stakeForRelayManager(testToken.address, reporterRelayManager, 15000, stake, { from: relayOwner }) await stakeManager.authorizeHubByOwner(reporterRelayManager, relayHub.address, { from: relayOwner }) }) async function commitPenalizationAndReturnMethod (method: any, ...args: any[]): Promise<any> { const methodInvoked = method(...args, '0x00000000') const penalizeMsgData = methodInvoked.encodeABI() const defaultOptions: Truffle.TransactionDetails = { from: reporterRelayManager, gasPrice: 1e9 } // commit to penalization and mine some blocks // eslint-disable-next-line @typescript-eslint/restrict-template-expressions // @ts-ignore const commitHash = web3.utils.keccak256(`${web3.utils.keccak256(penalizeMsgData)}${defaultOptions.from.slice(2).toLowerCase()}`) await penalizer.commit(commitHash, defaultOptions) await evmMineMany(6) return methodInvoked } // Receives a function that will penalize the relay and tests that call for a penalization, including checking the // emitted event and penalization reward transfer. Returns the transaction receipt. async function expectPenalization (methodInvoked: any, overrideOptions: Truffle.TransactionDetails = {}): Promise<any> { const defaultOptions: Truffle.TransactionDetails = { from: reporterRelayManager, gas: '1000000', gasPrice: 1e9 } const reporterBalanceTracker = await balanceTrackerErc20(testToken.address, defaultOptions.from!) const stakeManagerBalanceTracker = await balanceTrackerErc20(testToken.address, stakeManager.address) const stakeInfo = await stakeManager.stakes(relayManager) // @ts-ignore (names) const stake = stakeInfo.stake // A gas price of zero makes checking the balance difference simpler const mergedOptions: Truffle.TransactionDetails = Object.assign({}, defaultOptions, overrideOptions) const receipt = await new Promise( (resolve: any, reject: any) => methodInvoked.send(mergedOptions) .then(function (receipt: any) { resolve(receipt) }) .catch(function (reason: any) { reject(reason) }) ) /* * TODO: abiDecoder is needed to decode raw Web3.js transactions await expectEvent.inTransaction(rec, Penalizer, { relayManager: relayManager, beneficiary: reporterRelayManager, reward: expectedReward }) */ // The reporter gets half of the stake expect(await reporterBalanceTracker.delta()).to.be.bignumber.equals(stake.divn(2)) // The other half is burned, so StakeManager's balance is decreased by the full stake expect(await stakeManagerBalanceTracker.delta()).to.be.bignumber.equals(stake.neg()) return receipt } describe('penalize with commit/reveal', function () { let request: string let penalizableTxData: string let penalizableTxSignature: string before(async function () { const receipt = await web3.eth.sendTransaction({ from: anotherRelayWorker, to: other, value: ether('0.5'), gasPrice: 1e9 }); ({ data: penalizableTxData, signature: penalizableTxSignature } = await getDataAndSignatureFromHash(receipt.transactionHash, chainId)) request = penalizer.contract.methods.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x').encodeABI() // eslint-disable-next-line @typescript-eslint/restrict-template-expressions const commitHash = web3.utils.keccak256(`${web3.utils.keccak256(request)}${committer.slice(2)}`) await penalizer.commit(commitHash, { from: committer }) }) it('should fail to penalize too soon after commit', async () => { await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x', { from: committer }), 'reveal penalize too soon' ) }) it('should fail to penalize too late after commit', async () => { const id = (await snapshot()).result await evmMineMany(50) await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x', { from: committer }), 'reveal penalize too late' ) await revert(id) }) it('should fail to penalize with incorrect randomValue', async () => { const id = (await snapshot()).result request = penalizer.contract.methods.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0xcafef00d').encodeABI() // eslint-disable-next-line @typescript-eslint/restrict-template-expressions const commitHash = web3.utils.keccak256(`${web3.utils.keccak256(request)}${committer.slice(2)}`) await penalizer.commit(commitHash, { from: committer }) await evmMineMany(10) await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0xdeadbeef', { from: committer }), 'no commit' ) // this is not a failure: it passes the Penalizer modifier test (commit test), // it then reverts inside the RelayHub (since we didn't fully initialize this relay/worker) await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0xcafef00d', { from: committer }), 'Unknown relay worker' ) await revert(id) }) it('should reject penalize if method call differs', async () => { await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature + '00', relayHub.address, '0x', { from: committer }), 'no commit' ) }) it('should reject penalize if commit called from another account', async () => { await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x', { from: nonCommitter }), 'no commit' ) }) it('should allow penalize after commit', async () => { await evmMineMany(10) // this is not a failure: it passes the Penalizer modifier test (commit test), // it then reverts inside the RelayHub (since we didn't fully initialize this relay/worker) await expectRevert( penalizer.penalizeIllegalTransaction(penalizableTxData, penalizableTxSignature, relayHub.address, '0x', { from: committer }), 'Unknown relay worker' ) }) it('penalizeRepeatedNonce', async function () { const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeRepeatedNonce, penalizableTxData, penalizableTxSignature, penalizableTxData, penalizableTxSignature, relayHub.address) await expectRevert( method.send({ from: other }), 'no commit' ) // this is not a failure: it passes the Penalizer modifier test (commit test), // it then reverts on a transaction validity test await expectRevert( method.send({ from: reporterRelayManager }), 'tx is equal' ) }) }) describe('penalizable behaviors', function () { before(function () { // @ts-ignore expect(privateToAddress(relayCallArgs.privateKey).toString('hex')).to.equal(relayWorker.toLowerCase()) }) beforeEach('staking for relay', async function () { await testToken.mint(stake, { from: relayOwner }) await testToken.approve(stakeManager.address, stake, { from: relayOwner }) await stakeManager.stakeForRelayManager(testToken.address, relayManager, 15000, stake, { from: relayOwner }) await stakeManager.authorizeHubByOwner(relayManager, relayHub.address, { from: relayOwner }) }) describe('repeated relay nonce', function () { it('penalizes transactions with same nonce and different data', async function () { const txDataSigA = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, relayCallArgs), chainId) const txDataSigB = getDataAndSignature(encodeRelayCallEIP155(Object.assign({}, encodedCallArgs, { data: '0xabcd' }), relayCallArgs), chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeRepeatedNonce, txDataSigA.data, txDataSigA.signature, txDataSigB.data, txDataSigB.signature, relayHub.address ) await expectPenalization(method) }) it('penalizes transactions with same nonce and different gas limit', async function () { const txDataSigA = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, relayCallArgs), chainId) const txDataSigB = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, Object.assign({}, relayCallArgs, { gasLimit: 100 })), chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeRepeatedNonce, txDataSigA.data, txDataSigA.signature, txDataSigB.data, txDataSigB.signature, relayHub.address) await expectPenalization(method) }) it('penalizes transactions with same nonce and different value', async function () { const txDataSigA = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, relayCallArgs), chainId) const txDataSigB = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, Object.assign({}, relayCallArgs, { value: 100 })), chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeRepeatedNonce, txDataSigA.data, txDataSigA.signature, txDataSigB.data, txDataSigB.signature, relayHub.address) await expectPenalization(method) }) it('does not penalize transactions with same nonce and data, value, gasLimit, destination', async function () { const txDataSigA = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, relayCallArgs), chainId) const txDataSigB = getDataAndSignature(encodeRelayCallEIP155( encodedCallArgs, Object.assign({}, relayCallArgs, { gasPrice: 70 }) // only gasPrice may be different ), chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeRepeatedNonce, txDataSigA.data, txDataSigA.signature, txDataSigB.data, txDataSigB.signature, relayHub.address) await expectRevert( method.send({ from: reporterRelayManager, gas: 5e5 }), 'tx is equal' ) }) it('does not penalize transactions with different nonces', async function () { const txDataSigA = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, relayCallArgs), chainId) const txDataSigB = getDataAndSignature(encodeRelayCallEIP155( encodedCallArgs, Object.assign({}, relayCallArgs, { nonce: 1 }) ), chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeRepeatedNonce, txDataSigA.data, txDataSigA.signature, txDataSigB.data, txDataSigB.signature, relayHub.address) await expectRevert( method.send({ from: reporterRelayManager, gas: 5e5 }), 'Different nonce' ) }) it('does not penalize transactions with same nonce from different relays', async function () { const txDataSigA = getDataAndSignature(encodeRelayCallEIP155(encodedCallArgs, relayCallArgs), chainId) const txDataSigB = getDataAndSignature(encodeRelayCallEIP155( encodedCallArgs, Object.assign({}, relayCallArgs, { privateKey: Buffer.from('0123456789012345678901234567890123456789012345678901234567890123', 'hex') }) ), chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeRepeatedNonce, txDataSigA.data, txDataSigA.signature, txDataSigB.data, txDataSigB.signature, relayHub.address) await expectRevert( method.send({ from: reporterRelayManager }), 'Different signer' ) }) }) describe('illegal call', function () { // TODO: this tests are excessive, and have a lot of tedious build-up it('penalizes relay transactions to addresses other than RelayHub', async function () { // Relay sending ether to another account const receipt = await web3.eth.sendTransaction({ from: relayWorker, to: other, value: ether('0.5'), gasPrice: 1e9 }) const { data, signature } = await getDataAndSignatureFromHash(receipt.transactionHash, chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeIllegalTransaction, data, signature, relayHub.address) await expectPenalization(method) }) it('penalizes relay worker transactions to illegal RelayHub functions (stake)', async function () { await stakeManager.setRelayManagerOwner(relayWorker, { from: other }) await testToken.mint(stake, { from: relayWorker }) await testToken.approve(stakeManager.address, stake, { from: relayWorker }) // Relay staking for a second relay const { tx } = await stakeManager.stakeForRelayManager(testToken.address, other, 15000, stake, { from: relayWorker }) const { data, signature } = await getDataAndSignatureFromHash(tx, chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeIllegalTransaction, data, signature, relayHub.address) await expectPenalization(method) }) it('should penalize even after the relayer unlocked stake', async function () { const id = (await snapshot()).result await relayHub.depositFor(paymaster.address, { from: other, value: ether('1') }) // Relay sending ether to another account const gasPrice = 1e9 const receipt = await web3.eth.sendTransaction({ from: relayWorker, to: other, value: ether('0.5'), gasPrice }) const res = await stakeManager.unlockStake(relayManager, { from: relayOwner }) expectEvent(res, StakeUnlocked, { relayManager, owner: relayOwner }) const relayCallTxDataSig = await getDataAndSignatureFromHash(receipt.transactionHash, chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeIllegalTransaction, relayCallTxDataSig.data, relayCallTxDataSig.signature, relayHub.address) await expectPenalization(method) await revert(id) }) it('does not penalize legal relay transactions', async function () { // relayCall is a legal transaction const baseFee = new BN('300') const fee = new BN('10') const gasPrice = new BN(1e9) const maxFeePerGas = new BN(1e9) const maxPriorityFeePerGas = new BN(1e9) const gasLimit = new BN('1000000') const senderNonce = new BN('0') const txData = recipient.contract.methods.emitMessage('').encodeABI() const relayRequest: RelayRequest = { request: { to: recipient.address, data: txData, from: sender, nonce: senderNonce.toString(), value: '0', gas: gasLimit.toString(), validUntilTime: '0' }, relayData: { maxFeePerGas: maxFeePerGas.toString(), maxPriorityFeePerGas: maxPriorityFeePerGas.toString(), baseRelayFee: baseFee.toString(), pctRelayFee: fee.toString(), transactionCalldataGasUsed: '0', relayWorker, forwarder, paymaster: paymaster.address, paymasterData, clientId } } const dataToSign = new TypedRequestData( chainId, forwarder, relayRequest ) const signature = await getEip712Signature( web3, dataToSign ) await relayHub.depositFor(paymaster.address, { from: other, value: ether('1') }) const externalGasLimit = gasLimit.add(new BN(1e6)) const relayCallTx = await relayHub.relayCall(10e6, relayRequest, signature, '0x', { from: relayWorker, gas: externalGasLimit, gasPrice }) const relayCallTxDataSig = await getDataAndSignatureFromHash(relayCallTx.tx, chainId) const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeIllegalTransaction, relayCallTxDataSig.data, relayCallTxDataSig.signature, relayHub.address) await expectRevert( method.send({ from: reporterRelayManager }), 'Legal relay transaction' ) }) }) }) describe('penalizable relay states', function () { context('with penalizable transaction', function () { let penalizableTxData: string let penalizableTxSignature: string beforeEach(async function () { // Relays are not allowed to transfer Ether const receipt = await web3.eth.sendTransaction({ from: anotherRelayWorker, to: other, value: ether('0.5'), gasPrice: 1e9 }); ({ data: penalizableTxData, signature: penalizableTxSignature } = await getDataAndSignatureFromHash(receipt.transactionHash, chainId)) }) // All of these tests use the same penalization function (we one we set up in the beforeEach block) async function penalize (): Promise<void> { const method = await commitPenalizationAndReturnMethod( penalizer.contract.methods.penalizeIllegalTransaction, penalizableTxData, penalizableTxSignature, relayHub.address) return await expectPenalization(method) } context('with not owned relay worker', function () { it('account cannot be penalized', async function () { await expectRevert(penalize(), 'Unknown relay worker') }) }) context('with staked and locked relay manager and ', function () { beforeEach(async function () { await testToken.mint(stake, { from: relayOwner }) await testToken.approve(stakeManager.address, stake, { from: relayOwner }) await stakeManager.stakeForRelayManager(testToken.address, relayManager, 15000, stake, { from: relayOwner }) }) before(async function () { await stakeManager.authorizeHubByOwner(relayManager, relayHub.address, { from: relayOwner }) await relayHub.addRelayWorkers([anotherRelayWorker], { from: relayManager }) }) it('relay can be penalized', async function () { await penalize() }) it('relay cannot be penalized twice', async function () { await penalize() await expectRevert(penalize(), 'relay manager not staked') }) }) }) }) function encodeRelayCallEIP155 (encodedCallArgs: any, relayCallArgs: any): Transaction { const relayWorker = privateToAddress(relayCallArgs.privateKey).toString('hex') // TODO: 'encodedCallArgs' is no longer needed. just keep the RelayRequest in test const relayRequest: RelayRequest = { request: { to: encodedCallArgs.recipient, data: encodedCallArgs.data, from: encodedCallArgs.sender, nonce: encodedCallArgs.nonce.toString(), value: '0', gas: encodedCallArgs.gasLimit.toString(), validUntilTime: '0' }, relayData: { baseRelayFee: encodedCallArgs.baseFee.toString(), pctRelayFee: encodedCallArgs.fee.toString(), maxFeePerGas: encodedCallArgs.maxFeePerGas.toString(), maxPriorityFeePerGas: encodedCallArgs.maxPriorityFeePerGas.toString(), transactionCalldataGasUsed: '0', relayWorker, forwarder, paymaster: encodedCallArgs.paymaster, paymasterData, clientId } } const encodedCall = relayHub.contract.methods.relayCall(10e6, relayRequest, '0xabcdef123456', '0x').encodeABI() const transaction = Transaction.fromTxData({ nonce: relayCallArgs.nonce, gasLimit: relayCallArgs.gasLimit, gasPrice: relayCallArgs.gasPrice, to: relayHub.address, value: relayCallArgs.value, data: encodedCall }, transactionOptions) const signedTx = transaction.sign(relayCallArgs.privateKey) return signedTx } async function getDataAndSignatureFromHash (txHash: string, chainId: number): Promise<{ data: string, signature: string }> { const rpcTx: any = await web3.eth.getTransaction(txHash) const vInteger = parseInt(rpcTx.v, 16) if (chainId == null && vInteger > 28) { throw new Error('Missing ChainID for EIP-155 signature') } if (chainId == null && vInteger <= 28) { throw new Error('Passed ChainID for non-EIP-155 signature') } const tx = new Transaction({ nonce: new BN(rpcTx.nonce), gasPrice: new BN(rpcTx.gasPrice), gasLimit: new BN(rpcTx.gas), to: rpcTx.to, value: new BN(rpcTx.value), data: rpcTx.input, v: rpcTx.v, r: rpcTx.r, s: rpcTx.s }, transactionOptions) return getDataAndSignature(tx, chainId) } function validateDecodedTx (decodedTx: { nonce: string, gasPrice: string, gasLimit: string, to: string, value: string, data: string }, originalTx: AccessListEIP2930Transaction | Transaction): void { assert.equal(decodedTx.nonce, originalTx.nonce.toString()) assert.equal(decodedTx.gasLimit, originalTx.gasLimit.toString()) assert.equal(removeHexPrefix(decodedTx.data), originalTx.data.toString('hex')) assert.equal(decodedTx.to.toLowerCase(), originalTx.to!.toString().toLowerCase()) assert.equal(decodedTx.value, originalTx.value.toString()) } }) })
the_stack
import { EXMLConfig, NS_S, NS_W } from "./EXMLConfig2"; import XMLParser = require("../xml/index"); import { EXAddItems, EXBinding, EXClass, EXFunction, EXSetProperty, EXState, EXVariable, EXSetStateProperty } from "./CodeFactory"; let DEBUG = false; import { egretbridge } from "./egretbridge"; import { jsonFactory } from './JSONClass' import utils = require('../../lib/utils'); import { isOneByOne } from "../../actions/exml"; export const eui = jsonFactory; /** * @private * EXML配置管理器实例 */ export let exmlConfig: EXMLConfig; export let isError: boolean = false; let exmlParserPool: JSONParser[] = []; let innerClassCount = 1; let HOST_COMPONENT = "hostComponent"; let DECLARATIONS = "Declarations"; let TYPE_CLASS = "Class"; let TYPE_ARRAY = "Array"; let TYPE_PERCENTAGE = "Percentage"; let TYPE_STexture = "string | Texture"; let TYPE_STATE = "State[]"; let ELEMENTS_CONTENT = "elementsContent"; let basicTypes: string[] = [TYPE_ARRAY, TYPE_STexture, "boolean", "string", "number"]; let wingKeys: string[] = ["id", "locked", "includeIn", "excludeFrom"]; let htmlEntities: string[][] = [["<", "&lt;"], [">", "&gt;"], ["&", "&amp;"], ["\"", "&quot;"], ["'", "&apos;"]]; let jsKeyWords: string[] = ["null", "NaN", "undefined", "true", "false"]; /** 常用的关键字进行缩短设置,压缩体积6% */ let euiShorten = { "eui.BitmapLabel": "$eBL", "eui.Button": "$eB", "eui.CheckBox": "$eCB", "eui.Component": "$eC", "eui.DataGroup": "$eDG", "eui.EditableText": "$eET", "eui.Group": "$eG", "eui.HorizontalLayout": "$eHL", "eui.HScrollBar": "$eHSB", "eui.HSlider": "$eHS", "eui.Image": "$eI", "eui.Label": "$eL", "eui.List": "$eLs", "eui.Panel": "$eP", "eui.ProgressBar": "$ePB", "eui.RadioButton": "$eRB", "eui.RadioButtonGroup": "$eRBG", "eui.Range": "$eRa", "eui.Rect": "$eR", "eui.RowAlign": "$eRAl", "eui.Scroller": "$eS", "eui.TabBar": "$eT", "eui.TextInput": "$eTI", "eui.TileLayout": "$eTL", "eui.ToggleButton": "$eTB", "eui.ToggleSwitch": "$eTS", "eui.VerticalLayout": "$eVL", "eui.ViewStack": "$eV", "eui.VScrollBar": "$eVSB", "eui.VSlider": "$eVS", "eui.Skin": "$eSk" } /** * @private */ export class JSONParser { /** * @private */ public constructor() { } private _topNode: egretbridge.XML; public get topNode(): egretbridge.XML { return this._topNode; } private _className: string; public get className(): string { return this._className; } /** * @private */ private repeatedIdMap: any; /** * @private * 当前类 */ private currentClass: EXClass; /** * @private * 当前编译的类名 */ private currentClassName: string; /** * @private * 当前要编译的EXML文件 */ private currentXML: egretbridge.XML; /** * @private * id缓存字典 */ private idDic: any; /** * @private * 状态代码列表 */ private stateCode: EXState[]; /** * @private */ private stateNames: string[]; /** * @private * 需要单独创建的实例id列表 */ private stateIds: string[]; /** * @private */ private skinParts: string[]; /** * @private */ private bindings: EXBinding[]; /** * @private */ private declarations: any; /** * @private * 编译指定的XML对象为json。 * @param xmlData 要编译的EXML文件内容 * */ public parse(text: string, path?: string): { className: string, json?: string } { if (DEBUG) { if (!text) { egretbridge.$error(1003, "text"); } } let xmlData: any = null; /** 解析exml文件 */ if (DEBUG) { try { xmlData = XMLParser.parse(text); } catch (e) { egretbridge.$error(2002, text + "\n" + e.message); } } else { xmlData = XMLParser.parse(text); } this._topNode = xmlData; let className: string = ""; if (xmlData.attributes["class"]) { className = xmlData.attributes["class"]; delete xmlData.attributes["class"]; } else { className = "$exmlClass" + innerClassCount++; } this._className = className; if (jsonFactory.hasClassName(className)) { console.log(utils.tr(2104, path, className)); isError = true; } if (path) { jsonFactory.addContent(path, this.className, "$path"); } this.parseClass(xmlData, className); if (isOneByOne) { let json = eui.toCode(); eui.clear(); return { className, json }; } else { return { className }; } } /** * @private * 编译指定的XML对象为CpClass对象。 */ private parseClass(xmlData: egretbridge.XML, className: string) { if (!exmlConfig) { exmlConfig = new EXMLConfig(); } exmlConfig.dirPath = egret.args.projectDir; this.currentXML = xmlData; this.currentClassName = className; this.idDic = {}; this.stateCode = []; this.stateNames = []; this.skinParts = []; this.bindings = []; this.declarations = null; this.currentClass = new EXClass(); this.currentClass.allName = this.currentClassName; this.stateIds = []; let index = className.lastIndexOf("."); if (index != -1) { this.currentClass.className = className.substring(index + 1); } else { this.currentClass.className = className; } this.startCompile(); } /** * @private * 开始编译 */ private startCompile(): void { if (DEBUG) { let result = this.getRepeatedIds(this.currentXML); if (result.length > 0) { egretbridge.$error(2004, this.currentClassName, result.join("\n")); } } let superClass = this.getClassNameOfNode(this.currentXML); this.currentClass.superClass = superClass; this.getStateNames(); let children = this.currentXML.children; if (children) { let length = children.length; for (let i = 0; i < length; i++) { let node: any = children[i]; if (node.nodeType === 1 && node.namespace == NS_W && node.localName == DECLARATIONS) { this.declarations = node; break; } } } if (DEBUG) { let list: string[] = []; this.checkDeclarations(this.declarations, list); if (list.length > 0) { egretbridge.$error(2020, this.currentClassName, list.join("\n")); } } if (!this.currentXML.namespace) { if (DEBUG) { egretbridge.$error(2017, this.currentClassName, this.toXMLString(this.currentXML)); } return; } this.addIds(this.currentXML.children); this.addBaseConfig(); } /** * @private * 添加必须的id */ private addIds(items: any): void { if (!items) { return; } let length = items.length; for (let i = 0; i < length; i++) { let node: egretbridge.XML = items[i]; if (node.nodeType != 1) { continue; } if (!node.namespace) { if (DEBUG) { egretbridge.$error(2017, this.currentClassName, this.toXMLString(node)); } continue; } if (this.isInnerClass(node)) { continue; } this.addIds(node.children); if (node.namespace == NS_W || !node.localName) { } else if (this.isProperty(node)) { let prop = node.localName; let index = prop.indexOf("."); let children: Array<any> = node.children; if (index == -1 || !children || children.length == 0) { continue; } let firstChild: egretbridge.XML = children[0]; this.stateIds.push(firstChild.attributes.id); } else if (node.nodeType === 1) { let id = node.attributes["id"]; let stateGroups = node.attributes["stateGroups"]; if (id && stateGroups == undefined) {//区分是组件的id还是stateGroup的id let e = new RegExp("^[a-zA-Z_$]{1}[a-z0-9A-Z_$]*"); if (id.match(e) == null) { egretbridge.$warn(2022, id); } if (id.match(new RegExp(/ /g)) != null) { egretbridge.$warn(2022, id); } if (this.skinParts.indexOf(id) == -1) { this.skinParts.push(id); } this.createVarForNode(node); if (this.isStateNode(node))//检查节点是否只存在于一个状态里,需要单独实例化 this.stateIds.push(id); } else { this.createIdForNode(node); if (this.isStateNode(node)) this.stateIds.push(node.attributes.id); } } } } /** * @private * 是否为内部类。 */ private isInnerClass(node: egretbridge.XML): boolean { if (node.hasOwnProperty("isInnerClass")) { return node["isInnerClass"]; } let result = (node.localName == "Skin" && node.namespace == NS_S); if (!result) { if (this.isProperty(node)) { result = false; } else { let prop: string; let parent = node.parent; if (this.isProperty(parent)) { prop = parent.localName; let index = prop.indexOf("."); if (index != -1) { prop = prop.substring(0, index); } parent = parent.parent; } else { prop = exmlConfig.getDefaultPropById(parent.localName, parent.namespace); } let className = exmlConfig.getClassNameById(parent.localName, parent.namespace); result = (exmlConfig.getPropertyType(prop, className) == TYPE_CLASS); } } node["isInnerClass"] = result; return result; } /** * @private * 检测指定节点的属性是否含有视图状态 */ private containsState(node: egretbridge.XML): boolean { let attributes = node.attributes; if (attributes["includeIn"] || attributes["excludeFrom"]) { return true; } let keys = Object.keys(attributes); let length = keys.length; for (let i = 0; i < length; i++) { let name = keys[i]; if (name.indexOf(".") != -1) { return true; } } return false; } /** * @private * 为指定节点创建id属性 */ private createIdForNode(node: egretbridge.XML): void { let idName = this.getNodeId(node); if (!this.idDic[idName]) { this.idDic[idName] = 1; } else { this.idDic[idName]++; } idName += this.idDic[idName]; node.attributes.id = idName; } /** * @private * 获取节点ID */ private getNodeId(node: egretbridge.XML): string { if (node.attributes["id"]) { return node.attributes.id; } return "_" + node.localName; } /** * @private * 为指定节点创建变量 */ private createVarForNode(node: egretbridge.XML): void { let moduleName = this.getClassNameOfNode(node); if (moduleName == "") { return; } if (!this.currentClass.getVariableByName(node.attributes.id)) { this.currentClass.addVariable(new EXVariable(node.attributes.id)); } } /** * @private * 对子节点进行config的提取,返回节点名字id */ private addNodeConfig(node: egretbridge.XML): string { let className = node.localName; let isBasicType = this.isBasicTypeData(className); if (isBasicType) { return this.createBasicTypeForNode(node); } let moduleName = this.getClassNameOfNode(node); let func = new EXFunction(); let id = node.attributes.id; func.name = id; //保存的名字 let configName = func.name; let config = {}; for (let i in node.attributes) { if (i != "id") { let value = node.attributes[i]; config[i] = value; } } let name = exmlConfig.getClassNameById(node.localName, node.namespace); config["$t"] = euiShorten[name] == undefined ? name : euiShorten[name]; jsonFactory.addContent(config, this.currentClassName, func.name); // 赋值skin的属性 this.addConfig(node, configName, moduleName); this.initlizeChildNode(node, func.name); return func.name; } /** * @private * 检查目标类名是否是基本数据类型 */ private isBasicTypeData(className: string): boolean { return basicTypes.indexOf(className) != -1; } /** * @private * 为指定基本数据类型节点实例化,返回实例化后的值。 */ private createBasicTypeForNode(node: egretbridge.XML): string { let className = node.localName; let returnValue = ""; let varItem = this.currentClass.getVariableByName(node.attributes.id); let children: any[] = node.children; let text = ""; if (children && children.length > 0) { let firstChild: egretbridge.XMLText = children[0]; if (firstChild.nodeType == 3) { text = firstChild.text.trim(); } } switch (className) { case TYPE_ARRAY: let values = []; if (children) { let length = children.length; for (let i = 0; i < length; i++) { let child: egretbridge.XML = children[i]; if (child.nodeType == 1) { values.push(this.addNodeConfig(child)); } } } returnValue = "[" + values.join(",") + "]"; break; case "boolean": returnValue = (text == "false" || !text) ? "false" : "true"; break; case "number": returnValue = text; if (returnValue.indexOf("%") != -1) { returnValue = returnValue.substring(0, returnValue.length - 1); } break; } if (varItem) varItem.defaultValue = returnValue; return returnValue; } /** * @private * 将节点属性赋值语句添加到代码块 */ private addConfig(node: egretbridge.XML, configName: string, type?: string): void { let key: string; let value: string; let attributes = node.attributes; let jsonProperty = {}; let keyList: string[] = Object.keys(attributes); keyList.sort();//排序一下防止出现随机顺序 //对 style 属性先行赋值 let styleIndex = keyList.indexOf("style"); if (styleIndex > 0) { keyList.splice(styleIndex, 1); keyList.unshift("style"); } let length = keyList.length; for (let i = 0; i < length; i++) { key = keyList[i]; if (!this.isNormalKey(key)) { continue; } value = attributes[key]; key = this.formatKey(key, value); value = this.formatValue(key, value, node); jsonProperty[key] = value; } if (type) { jsonProperty["$t"] = euiShorten[type] == undefined ? type : euiShorten[type]; } jsonFactory.addContent(jsonProperty, this.currentClassName, configName == undefined ? "$bs" : configName); } /** * @private * 初始化子项 */ private initlizeChildNode(node: egretbridge.XML, varName: string): void { let children: Array<any> = node.children; if (!children || children.length == 0) { return; } let className = exmlConfig.getClassNameById(node.localName, node.namespace); let directChild: egretbridge.XML[] = []; let length = children.length; let propList: string[] = []; let errorInfo: any; for (let i = 0; i < length; i++) { let child: egretbridge.XML = children[i]; if (child.nodeType != 1 || child.namespace == NS_W) { continue; } if (this.isInnerClass(child)) { if (child.localName == "Skin") { let innerClassName = this.parseInnerClass(child); jsonFactory.addContent(innerClassName, this.currentClassName + "/" + this.getNodeId(node), "skinName") } continue; } let prop = child.localName; if (this.isProperty(child)) { if (!this.isNormalKey(prop)) { continue; } let type = exmlConfig.getPropertyType(child.localName, className); if (!type) { if (DEBUG) { egretbridge.$error(2005, this.currentClassName, child.localName, this.getPropertyStr(child)); } continue; } if (!child.children || child.children.length == 0) { if (DEBUG) { egretbridge.$warn(2102, this.currentClassName, this.getPropertyStr(child)); } continue; } if (DEBUG) { errorInfo = this.getPropertyStr(child); } this.addChildrenToProp(child.children, type, prop, varName, errorInfo, propList, node); } else { directChild.push(child); } } if (directChild.length == 0) return; let defaultProp = exmlConfig.getDefaultPropById(node.localName, node.namespace); let defaultType = exmlConfig.getPropertyType(defaultProp, className); if (DEBUG) { errorInfo = this.getPropertyStr(directChild[0]); } if (!defaultProp || !defaultType) { if (DEBUG) { egretbridge.$error(2012, this.currentClassName, errorInfo); } return; } this.addChildrenToProp(directChild, defaultType, defaultProp, varName, errorInfo, propList, node); } /** * @private * 解析内部类节点,并返回类名。 */ private parseInnerClass(node: egretbridge.XML): string { let parser = exmlParserPool.pop(); if (!parser) { parser = new JSONParser(); } let innerClassName = this.currentClassName + "$" + node.localName + innerClassCount++; parser.parseClass(node, innerClassName); exmlParserPool.push(parser); return innerClassName; } /** * @private * 添加多个子节点到指定的属性 */ private addChildrenToProp(children: Array<any>, type: string, prop: string, varName: string, errorInfo: string, propList: string[], node: egretbridge.XML): void { let nodeName = ""; let childLength = children.length; let elementsContentForJson; if (childLength > 1) { if (type != TYPE_ARRAY) { if (DEBUG) { egretbridge.$error(2011, this.currentClassName, prop, errorInfo); } return; } if (prop == ELEMENTS_CONTENT) { let values: string[] = []; for (let j = 0; j < childLength; j++) { let item: egret.XML = children[j]; if (item.nodeType != 1) { continue; } nodeName = this.addToCodeBlockForNode(item); if (!this.isStateNode(item)) values.push(nodeName); } elementsContentForJson = values; prop = "$eleC"; } else { let values: string[] = []; for (let j = 0; j < childLength; j++) { let item: egret.XML = children[j]; if (item.nodeType != 1) { continue; } nodeName = this.addNodeConfig(item); if (!this.isStateNode(item)) values.push(nodeName); } elementsContentForJson = values; } } else { let firstChild: egretbridge.XML = children[0]; if (type == TYPE_ARRAY) { if (firstChild.localName == TYPE_ARRAY) { let values = []; if (firstChild.children) { let len = firstChild.children.length; for (let k = 0; k < len; k++) { let item = <any>firstChild.children[k]; if (item.nodeType != 1) { continue; } nodeName = this.addNodeConfig(item); this.getClassNameOfNode(item); if (!this.isStateNode(item)) values.push(nodeName); } } elementsContentForJson = values; } else { if (prop == ELEMENTS_CONTENT && !this.isStateNode(firstChild)) { nodeName = this.addToCodeBlockForNode(firstChild); this.getClassNameOfNode(firstChild); elementsContentForJson = [nodeName]; prop = "$eleC"; } else { nodeName = this.addNodeConfig(firstChild); this.getClassNameOfNode(firstChild); if (!this.isStateNode(firstChild)) { elementsContentForJson = [nodeName]; } } } } else if (firstChild.nodeType == 1) { if (type == TYPE_CLASS) { if (childLength > 1) { if (DEBUG) { egretbridge.$error(2011, this.currentClassName, prop, errorInfo); } return; } nodeName = this.parseInnerClass(children[0]); elementsContentForJson = nodeName; } else { this.getClassNameOfNode(firstChild); nodeName = this.addNodeConfig(firstChild); elementsContentForJson = nodeName; } } else { nodeName = this.formatValue(prop, (<egretbridge.XMLText><any>firstChild).text, node); elementsContentForJson = nodeName; } } if (nodeName != "") { if (nodeName.indexOf("()") == -1) prop = this.formatKey(prop, nodeName); if (propList.indexOf(prop) == -1) { propList.push(prop); } else if (DEBUG) { egretbridge.$warn(2103, this.currentClassName, prop, errorInfo); } let tar = varName == "this" ? "$bs" : varName; jsonFactory.addContent(elementsContentForJson, this.currentClassName + "/" + tar, prop); } } private addToCodeBlockForNode(node: egret.XML): string { let moduleName = this.getClassNameOfNode(node); let id = node.attributes.id; let varName: string = id; //赋值基本属性 this.addConfig(node, varName, moduleName); this.initlizeChildNode(node, varName); return varName; } /** * @private * 指定节点是否是属性节点 */ private isProperty(node: egretbridge.XML): boolean { if (node.hasOwnProperty("isProperty")) { return node["isProperty"]; } let result: boolean; let name = node.localName; if (!name || node.nodeType !== 1 || !node.parent || this.isBasicTypeData(name)) { result = false; } else { let parent = node.parent; let index = name.indexOf(".") if (index != -1) { name = name.substr(0, index); } let className = exmlConfig.getClassNameById(parent.localName, parent.namespace); result = !!exmlConfig.getPropertyType(name, className); } node["isProperty"] = result; return result; } /** * @private * 是否是普通赋值的key */ private isNormalKey(key: string): boolean { if (!key || key.indexOf(".") != -1 || key.indexOf(":") != -1 || wingKeys.indexOf(key) != -1) { return false; } return true; } /** * @private * 格式化key */ private formatKey(key: string, value: string): string { if (value.indexOf("%") != -1) { if (key == "height") { key = "percentHeight"; } else if (key == "width") { key = "percentWidth"; } } return key; } /** * @private * 格式化值 * * $$$$$$ 这里需要注意,在skin的基本属性和动画都要在这里格式化值, * 主要是对数字的一些操作,色号还有百分比之类的进行换算 */ private formatValue(key: string, value: any, node: egretbridge.XML): any { if (!value) { value = ""; } value = value.trim(); let className = this.getClassNameOfNode(node); let type: string = exmlConfig.getPropertyType(key, className); if (DEBUG && !type) { egretbridge.$error(2005, this.currentClassName, key, this.toXMLString(node)); } let bindingValue = this.formatBinding(value); if (bindingValue) { this.checkIdForState(node); let target = "this"; if (node !== this.currentXML) { target = node.attributes["id"]; } this.bindings.push(new EXBinding(target, key, bindingValue.templates, bindingValue.chainIndex)); value = ""; } else if (type == TYPE_PERCENTAGE) { if (value.indexOf("%") != -1) { value = this.unescapeHTMLEntity(value); } if (key == "percentHeight" || key == "percentWidth" || !value.includes("%")) value = parseFloat(value); } else { switch (type) { case "number": if (value.indexOf("#") == 0) { if (DEBUG && isNaN(<any>value.substring(1))) { egretbridge.$warn(2021, this.currentClassName, key, value); } value = "0x" + value.substring(1); value = parseInt(value, 0); } else if (value.indexOf("%") != -1) { if (DEBUG && isNaN(<any>value.substr(0, value.length - 1))) { egretbridge.$warn(2021, this.currentClassName, key, value); } value = parseFloat(value.substr(0, value.length - 1)); } else if (DEBUG && isNaN(<any>value)) { egretbridge.$warn(2021, this.currentClassName, key, value); } else if (value.indexOf("x") != -1 || value.indexOf("X") != -1) { value = parseInt(value, 0); } else { value = parseFloat(value); } break; case "boolean": value = (value == "false" || !value) ? false : true; break; default: if (DEBUG) { egretbridge.$error(2008, this.currentClassName, "string", key + ":" + type, this.toXMLString(node)); } break; } } return value; } private formatBinding(value: string): { templates: string[], chainIndex: number[] } { if (!value) { return null; } value = value.trim(); if (value.charAt(0) != "{" || value.charAt(value.length - 1) != "}") { return null; } value = value.substring(1, value.length - 1).trim(); let templates = value.indexOf("+") == -1 ? [value] : this.parseTemplates(value); let chainIndex: number[] = []; let length = templates.length; for (let i = 0; i < length; i++) { let item = templates[i].trim(); if (!item) { templates.splice(i, 1); i--; length--; continue; } var first = item.charAt(0); if (first == "'" || first == "\"") { continue; } //在动画或是绑定数据的时候进行类型转换 if (first >= "0" && first <= "9" || first == "-") { templates[i] = parseFloat(templates[i]) as any; continue; } if (item.indexOf(".") == -1 && jsKeyWords.indexOf(item) != -1) { continue; } if (item.indexOf("this.") == 0) { item = item.substring(5); } let firstKey = item.split(".")[0]; if (firstKey != HOST_COMPONENT && this.skinParts.indexOf(firstKey) == -1) { item = HOST_COMPONENT + "." + item; } templates[i] = item; chainIndex.push(i); } return { templates: templates, chainIndex: chainIndex }; } private parseTemplates(value: string): string[] { //仅仅是表达式相加 如:{a.b+c.d} if (value.indexOf("'") == -1) { return value.split("+"); } //包含文本的需要提取文本并对文本进行处理 let isSingleQuoteLeak = false;//是否缺失单引号 let trimText = ""; value = value.split("\\\'").join("\v0\v"); while (value.length > 0) { //'成对出现 这是第一个 let index = value.indexOf("'"); if (index == -1) { trimText += value; break; } trimText += value.substring(0, index + 1); value = value.substring(index + 1); //'成对出现 这是第二个 index = value.indexOf("'"); if (index == -1) { index = value.length - 1; isSingleQuoteLeak = true; } let quote = value.substring(0, index + 1); trimText += quote.split("+").join("\v1\v"); value = value.substring(index + 1); } value = trimText.split("\v0\v").join("\\\'"); //补全缺失的单引号 if (isSingleQuoteLeak) { value += "'"; } let templates = value.split("+"); let length = templates.length; for (let i = 0; i < length; i++) { templates[i] = templates[i].split("\v1\v").join("+"); } return templates; } /** * @private /** * 转换HTML实体字符为普通字符 */ private unescapeHTMLEntity(str: string): string { if (!str) { return ""; } let length = htmlEntities.length; for (let i: number = 0; i < length; i++) { let arr = htmlEntities[i]; let key: string = arr[0]; let value: string = arr[1]; str = str.split(value).join(key); } return str; } /** * @private * 复制基本属性 * */ private addBaseConfig(): void { let varName: string = "this"; this.addConfig(this.currentXML, "$bs"); if (this.declarations) { let children: Array<any> = this.declarations.children; if (children && children.length > 0) { let length = children.length; for (let i = 0; i < length; i++) { let decl: egretbridge.XML = children[i]; if (decl.nodeType != 1) { continue; } this.addNodeConfig(decl); } } } this.initlizeChildNode(this.currentXML, varName); var stateIds = this.stateIds; if (stateIds.length > 0) { jsonFactory.addContent(stateIds, this.currentClassName + "/$bs", "$sId"); } let skinConfig = this.skinParts; if (skinConfig.length > 0) { jsonFactory.addContent(skinConfig, this.currentClassName, "$sP"); } this.currentXML.attributes.id = ""; //生成视图状态代码 this.createStates(this.currentXML); let states: EXState[]; let node = this.currentXML; let nodeClassName = this.getClassNameOfNode(node); let attributes = node.attributes; let keys = Object.keys(attributes); let keysLength = keys.length; for (let m = 0; m < keysLength; m++) { let itemName = keys[m]; let value: string = attributes[itemName]; let index = itemName.indexOf("."); if (index != -1) { let key = itemName.substring(0, index); key = this.formatKey(key, value); let itemValue = this.formatValue(key, value, node); if (!itemValue) { continue; } let stateName = itemName.substr(index + 1); states = this.getStateByName(stateName, node); let stateLength = states.length; if (stateLength > 0) { for (let i = 0; i < stateLength; i++) { let state = states[i]; state.addOverride(new EXSetProperty("", key, itemValue)); } } } } //生成视图配置 let stateCode = this.stateCode; let length = stateCode.length; if (length > 0) { let stateConfig = {}; for (let i = 0; i < length; i++) { let setPropertyConfig = []; for (let property of stateCode[i].setProperty) { let tempProp = {}; for (let prop in property) { if (prop == "indent") { } else if (prop == "target") { if (property[prop].search("this.") > -1) { let temp = property[prop].slice("this.".length, property[prop].length) tempProp[prop] = temp; } else tempProp[prop] = property[prop]; } else tempProp[prop] = property[prop]; } setPropertyConfig.push(tempProp); } let addItemsConfig = []; for (let property of stateCode[i].addItems) { let tempProp = {}; for (let prop in property) { if (prop != "indent") { tempProp[prop] = property[prop]; } } addItemsConfig.push(tempProp); } stateConfig[stateCode[i].name] = {}; if (setPropertyConfig.length > 0) stateConfig[stateCode[i].name]["$ssP"] = setPropertyConfig; if (addItemsConfig.length > 0) stateConfig[stateCode[i].name]["$saI"] = addItemsConfig; } jsonFactory.addContent(stateConfig, this.currentClassName, "$s"); } //生成绑定配置 let bindings = this.bindings; length = bindings.length; let bindingConfig = []; if (length > 0) { for (let binding of bindings) { let config = {}; if (binding.templates.length == 1 && binding.chainIndex.length == 1) { config["$bd"] = binding.templates;//data config["$bt"] = binding.target;//target config["$bp"] = binding.property;//property } else { config["$bd"] = binding.templates;//data config["$bt"] = binding.target;//target config["$bc"] = binding.chainIndex;//chainIndex config["$bp"] = binding.property;//property } bindingConfig.push(config); } jsonFactory.addContent(bindingConfig, this.currentClassName, "$b"); } jsonFactory.addContent(euiShorten[nodeClassName] != undefined ? euiShorten[nodeClassName] : nodeClassName, this.currentClassName, "$sC"); } /** * @private * 是否含有includeIn和excludeFrom属性 */ private isStateNode(node: egretbridge.XML): boolean { let attributes = node.attributes; return attributes.hasOwnProperty("includeIn") || attributes.hasOwnProperty("excludeFrom"); } /** * @private * 获取视图状态名称列表 */ private getStateNames(): void { let root = this.currentXML; let className = exmlConfig.getClassNameById(root.localName, root.namespace); let type = exmlConfig.getPropertyType("states", className); if (type != TYPE_STATE) { return; } let statesValue = root.attributes["states"]; if (statesValue) { delete root.attributes["states"]; } let stateNames = this.stateNames; let stateChildren: any[]; let children: any[] = root.children; let item: egretbridge.XML; if (children) { let length = children.length; for (let i = 0; i < length; i++) { item = children[i]; if (item.nodeType == 1 && item.localName == "states") { item.namespace = NS_W; stateChildren = item.children; break; } } } if (!stateChildren && !statesValue) { return; } if (DEBUG) { if (stateChildren && stateChildren.length == 0) { egretbridge.$warn(2102, this.currentClassName, this.getPropertyStr(item)); } if (stateChildren && statesValue) { egretbridge.$warn(2103, this.currentClassName, "states", this.getPropertyStr(item)); } } if (statesValue) { let states = statesValue.split(","); let length = states.length; for (let i = 0; i < length; i++) { let stateName: string = states[i].trim(); if (!stateName) { continue; } if (stateNames.indexOf(stateName) == -1) { stateNames.push(stateName); } this.stateCode.push(new EXState(stateName)); } return; } let length = stateChildren.length; for (let i = 0; i < length; i++) { let state: egretbridge.XML = stateChildren[i]; if (state.nodeType != 1) { continue; } let stateGroups: Array<any> = []; let attributes = state.attributes; if (attributes["stateGroups"]) { let groups = attributes.stateGroups.split(","); let len = groups.length; for (let j = 0; j < len; j++) { let group = groups[j].trim(); if (group) { if (stateNames.indexOf(group) == -1) { stateNames.push(group); } stateGroups.push(group); } } } let stateName = attributes.name; if (stateNames.indexOf(stateName) == -1) { stateNames.push(stateName); } this.stateCode.push(new EXState(stateName, stateGroups)); } } /** * @private * 解析视图状态代码 */ private createStates(parentNode: egretbridge.XML): void { let items: Array<any> = parentNode.children; if (!items) { return; } let length = items.length; for (let i = 0; i < length; i++) { let node: egretbridge.XML = items[i]; if (node.nodeType != 1 || this.isInnerClass(node)) { continue; } this.createStates(node); if (node.namespace == NS_W || !node.localName) { continue; } if (this.isProperty(node)) { let prop = node.localName; let index = prop.indexOf("."); let children: Array<any> = node.children; if (index == -1 || !children || children.length == 0) { continue; } let stateName = prop.substring(index + 1); prop = prop.substring(0, index); let className = this.getClassNameOfNode(parentNode); let type = exmlConfig.getPropertyType(prop, className); if (DEBUG) { if (type == TYPE_ARRAY) { egretbridge.$error(2013, this.currentClassName, this.getPropertyStr(node)); } if (children.length > 1) { egretbridge.$error(2011, this.currentClassName, prop, this.getPropertyStr(node)); } } let firstChild: egretbridge.XML = children[0]; let value: string; if (firstChild.nodeType == 1) { this.addNodeConfig(firstChild); this.checkIdForState(firstChild); value = "this." + firstChild.attributes.id; } else { value = this.formatValue(prop, (<egretbridge.XMLText><any>firstChild).text, parentNode); } let states = this.getStateByName(stateName, node); let l = states.length; if (l > 0) { for (let j: number = 0; j < l; j++) { let state = states[j]; state.addOverride(new EXSetProperty(parentNode.attributes.id, prop, value)); } } } else if (this.containsState(node)) { let attributes = node.attributes; let id = attributes.id; this.getClassNameOfNode(node); this.checkIdForState(node); let stateName: string; let states: Array<EXState>; let state: EXState; if (this.isStateNode(node)) { let propertyName = ""; let parent: egretbridge.XML = node.parent; if (parent.localName == TYPE_ARRAY) parent = parent.parent; if (parent && parent.parent) { if (this.isProperty(parent)) parent = parent.parent; } if (parent && parent != this.currentXML) { propertyName = parent.attributes.id; this.checkIdForState(parent); } let positionObj = this.findNearNodeId(node); let stateNames: string[] = []; if (attributes.includeIn) { stateNames = attributes.includeIn.split(","); } else { let excludeNames = attributes.excludeFrom.split(","); let stateLength = excludeNames.length; for (let j = 0; j < stateLength; j++) { let name: string = excludeNames[j]; this.getStateByName(name, node);//检查exlcudeFrom是否含有未定义的视图状态名 } stateLength = this.stateCode.length; for (let j = 0; j < stateLength; j++) { state = this.stateCode[j]; if (excludeNames.indexOf(state.name) == -1) { stateNames.push(state.name); } } } let len = stateNames.length; for (let k = 0; k < len; k++) { stateName = stateNames[k]; states = this.getStateByName(stateName, node); if (states.length > 0) { let l = states.length; for (let j = 0; j < l; j++) { state = states[j]; state.addOverride(new EXAddItems(id, propertyName, positionObj.position, positionObj.relativeTo)); } } } } let names = Object.keys(attributes); let namesLength = names.length; for (let m = 0; m < namesLength; m++) { let name = names[m]; let value: string = attributes[name]; let index: number = name.indexOf("."); if (index != -1) { let key = name.substring(0, index); key = this.formatKey(key, value); let bindingValue = this.formatBinding(value); if (!bindingValue) { value = this.formatValue(key, value, node); if (value == undefined) { continue; } } stateName = name.substr(index + 1); states = this.getStateByName(stateName, node); let l = states.length; if (l > 0) { for (let j = 0; j < l; j++) { state = states[j]; if (bindingValue) { state.addOverride(new EXSetStateProperty(id, key, bindingValue.templates, bindingValue.chainIndex)); } else { state.addOverride(new EXSetProperty(id, key, value)); } } } } } } } } /** * @private * 检查指定的ID是否创建了类成员变量,若没创建则为其创建。 */ private checkIdForState(node: egretbridge.XML): void { if (!node || this.currentClass.getVariableByName(node.attributes.id)) { return; } this.createVarForNode(node); let id: string = node.attributes.id; let funcName = id; this.currentClass.getFuncByName(funcName); } /** * @private * 通过视图状态名称获取对应的视图状态 */ private getStateByName(name: string, node: egretbridge.XML): EXState[] { let states: EXState[] = []; let stateCode = this.stateCode; let length = stateCode.length; for (let i = 0; i < length; i++) { let state = stateCode[i]; if (state.name == name) { if (states.indexOf(state) == -1) states.push(state); } else if (state.stateGroups.length > 0) { let found = false; let len = state.stateGroups.length; for (let j: number = 0; j < len; j++) { let g = state.stateGroups[j]; if (g == name) { found = true; break; } } if (found) { if (states.indexOf(state) == -1) states.push(state); } } } if (DEBUG && states.length == 0) { egretbridge.$error(2006, this.currentClassName, name, this.toXMLString(node)); } return states; } /** * @private * 寻找节点的临近节点ID和位置 */ private findNearNodeId(node: egretbridge.XML): any { let parentNode: egretbridge.XML = node.parent; let targetId = ""; let position: number; let index = -1; let preItem: egretbridge.XML; let afterItem: egretbridge.XML; let found = false; let children: Array<any> = parentNode.children; let length = children.length; for (let i = 0; i < length; i++) { let item = children[i]; if (this.isProperty(item)) continue; if (item == node) { found = true; index = i; } else { if (found && !afterItem && !this.isStateNode(item)) { afterItem = item; } } if (!found && !this.isStateNode(item)) preItem = item; } if (index == 0) { position = sys.AddPosition.FIRST; return { position: position, relativeTo: targetId }; } if (index == length - 1) { position = sys.AddPosition.LAST; return { position: position, relativeTo: targetId }; } if (afterItem) { position = sys.AddPosition.BEFORE; targetId = afterItem.attributes.id; if (targetId) { this.checkIdForState(afterItem); return { position: position, relativeTo: targetId }; } } return { position: sys.AddPosition.LAST, relativeTo: targetId }; } /** * @private * 获取节点的完整类名,包括模块名 */ private getClassNameOfNode(node: egretbridge.XML): string { let className = exmlConfig.getClassNameById(node.localName, node.namespace); if (DEBUG && !className) { egretbridge.$error(2003, this.currentClassName, this.toXMLString(node)); } return className; } /** * 获取重复的ID名 */ private getRepeatedIds(xml: egretbridge.XML): string[] { let result: string[] = []; this.repeatedIdMap = {}; this.getIds(xml, result); return result; } private getIds(xml: any, result: Array<any>): void { if (xml.namespace != NS_W && xml.attributes.id) { let id: string = xml.attributes.id; if (this.repeatedIdMap[id]) { result.push(this.toXMLString(xml)); } else { this.repeatedIdMap[id] = true; } } let children: Array<any> = xml.children; if (children) { let length: number = children.length; for (let i: number = 0; i < length; i++) { let node: any = children[i]; if (node.nodeType !== 1 || this.isInnerClass(node)) { continue; } this.getIds(node, result); } } } private toXMLString(node: egretbridge.XML): string { if (!node) { return ""; } let str: string = " at <" + node.name; let attributes = node.attributes; let keys = Object.keys(attributes); let length = keys.length; for (let i = 0; i < length; i++) { let key = keys[i]; let value: string = attributes[key]; if (key == "id" && value.substring(0, 2) == "__") { continue; } str += " " + key + "=\"" + value + "\""; } if (node.children.length == 0) { str += "/>"; } else { str += ">"; } return str; } /** * 清理声明节点里的状态标志 */ private checkDeclarations(declarations: egretbridge.XML, list: string[]): void { if (!declarations) { return; } let children = declarations.children; if (children) { let length = children.length; for (let i = 0; i < length; i++) { let node: any = children[i]; if (node.nodeType != 1) { continue; } if (node.attributes.includeIn) { list.push(this.toXMLString(node)); } if (node.attributes.excludeFrom) { list.push(this.toXMLString(node)) } this.checkDeclarations(node, list); } } } private getPropertyStr(child: any): string { let parentStr = this.toXMLString(child.parent); let childStr = this.toXMLString(child).substring(5); return parentStr + "\n \t" + childStr; } } module sys { export const enum AddPosition { /** * @private * 添加父级容器的底层 */ FIRST, /** * @private * 添加在父级容器的顶层 */ LAST, /** * @private * 添加在相对对象之前 */ BEFORE, /** * @private * 添加在相对对象之后 */ AFTER } }
the_stack
import xss from 'xss'; import mongoose from 'mongoose'; import { SearchDelegatorName } from '~/interfaces/named-query'; import { IPageWithMeta } from '~/interfaces/page'; import { IFormattedSearchResult, IPageSearchMeta, ISearchResult } from '~/interfaces/search'; import loggerFactory from '~/utils/logger'; import NamedQuery from '../models/named-query'; import { SearchDelegator, SearchQueryParser, SearchResolver, ParsedQuery, SearchableData, QueryTerms, } from '../interfaces/search'; import ElasticsearchDelegator from './search-delegator/elasticsearch'; import PrivateLegacyPagesDelegator from './search-delegator/private-legacy-pages'; import { PageModel } from '../models/page'; import { serializeUserSecurely } from '../models/serializers/user-serializer'; import { ObjectIdLike } from '../interfaces/mongoose-utils'; import { SearchError } from '../models/vo/search-error'; // eslint-disable-next-line no-unused-vars const logger = loggerFactory('growi:service:search'); const nonNullable = <T>(value: T): value is NonNullable<T> => value != null; // options for filtering xss const filterXssOptions = { whiteList: { em: ['class'], }, }; const filterXss = new xss.FilterXSS(filterXssOptions); const normalizeQueryString = (_queryString: string): string => { let queryString = _queryString.trim(); queryString = queryString.replace(/\s+/g, ' '); return queryString; }; const normalizeNQName = (nqName: string): string => { return nqName.trim(); }; const findPageListByIds = async(pageIds: ObjectIdLike[], crowi: any) => { const Page = crowi.model('Page') as unknown as PageModel; const User = crowi.model('User'); const builder = new Page.PageQueryBuilder(Page.find(({ _id: { $in: pageIds } })), false); builder.addConditionToPagenate(undefined, undefined); // offset and limit are unnesessary builder.populateDataToList(User.USER_FIELDS_EXCEPT_CONFIDENTIAL); // populate lastUpdateUser builder.query = builder.query.populate({ path: 'creator', select: User.USER_FIELDS_EXCEPT_CONFIDENTIAL, }); const pages = await builder.query.clone().exec('find'); const totalCount = await builder.query.exec('count'); return { pages, totalCount, }; }; class SearchService implements SearchQueryParser, SearchResolver { crowi!: any configManager!: any isErrorOccuredOnHealthcheck: boolean | null isErrorOccuredOnSearching: boolean | null fullTextSearchDelegator: any & ElasticsearchDelegator nqDelegators: {[key in SearchDelegatorName]: SearchDelegator} constructor(crowi) { this.crowi = crowi; this.configManager = crowi.configManager; this.isErrorOccuredOnHealthcheck = null; this.isErrorOccuredOnSearching = null; try { this.fullTextSearchDelegator = this.generateFullTextSearchDelegator(); this.nqDelegators = this.generateNQDelegators(this.fullTextSearchDelegator); logger.info('Succeeded to initialize search delegators'); } catch (err) { logger.error(err); } if (this.isConfigured) { this.fullTextSearchDelegator.init(); this.registerUpdateEvent(); } } get isConfigured() { return this.fullTextSearchDelegator != null; } get isReachable() { return this.isConfigured && !this.isErrorOccuredOnHealthcheck && !this.isErrorOccuredOnSearching; } get isElasticsearchEnabled() { const uri = this.configManager.getConfig('crowi', 'app:elasticsearchUri'); return uri != null && uri.length > 0; } generateFullTextSearchDelegator() { logger.info('Initializing search delegator'); if (this.isElasticsearchEnabled) { logger.info('Elasticsearch is enabled'); return new ElasticsearchDelegator(this.configManager, this.crowi.socketIoService); } logger.info('No elasticsearch URI is specified so that full text search is disabled.'); } generateNQDelegators(defaultDelegator: ElasticsearchDelegator): {[key in SearchDelegatorName]: SearchDelegator} { return { [SearchDelegatorName.DEFAULT]: defaultDelegator, [SearchDelegatorName.PRIVATE_LEGACY_PAGES]: new PrivateLegacyPagesDelegator() as unknown as SearchDelegator, }; } registerUpdateEvent() { const pageEvent = this.crowi.event('page'); pageEvent.on('create', this.fullTextSearchDelegator.syncPageUpdated.bind(this.fullTextSearchDelegator)); pageEvent.on('update', this.fullTextSearchDelegator.syncPageUpdated.bind(this.fullTextSearchDelegator)); pageEvent.on('delete', this.fullTextSearchDelegator.syncPageDeleted.bind(this.fullTextSearchDelegator)); pageEvent.on('revert', this.fullTextSearchDelegator.syncPageDeleted.bind(this.fullTextSearchDelegator)); pageEvent.on('deleteCompletely', this.fullTextSearchDelegator.syncPageDeleted.bind(this.fullTextSearchDelegator)); pageEvent.on('syncDescendantsDelete', this.fullTextSearchDelegator.syncDescendantsPagesDeleted.bind(this.fullTextSearchDelegator)); pageEvent.on('updateMany', this.fullTextSearchDelegator.syncPagesUpdated.bind(this.fullTextSearchDelegator)); pageEvent.on('syncDescendantsUpdate', this.fullTextSearchDelegator.syncDescendantsPagesUpdated.bind(this.fullTextSearchDelegator)); pageEvent.on('addSeenUsers', this.fullTextSearchDelegator.syncPageUpdated.bind(this.fullTextSearchDelegator)); pageEvent.on('rename', () => { this.fullTextSearchDelegator.syncPageDeleted.bind(this.fullTextSearchDelegator); this.fullTextSearchDelegator.syncPageUpdated.bind(this.fullTextSearchDelegator); }); const bookmarkEvent = this.crowi.event('bookmark'); bookmarkEvent.on('create', this.fullTextSearchDelegator.syncBookmarkChanged.bind(this.fullTextSearchDelegator)); bookmarkEvent.on('delete', this.fullTextSearchDelegator.syncBookmarkChanged.bind(this.fullTextSearchDelegator)); const tagEvent = this.crowi.event('tag'); tagEvent.on('update', this.fullTextSearchDelegator.syncTagChanged.bind(this.fullTextSearchDelegator)); const commentEvent = this.crowi.event('comment'); commentEvent.on('create', this.fullTextSearchDelegator.syncCommentChanged.bind(this.fullTextSearchDelegator)); commentEvent.on('update', this.fullTextSearchDelegator.syncCommentChanged.bind(this.fullTextSearchDelegator)); commentEvent.on('delete', this.fullTextSearchDelegator.syncCommentChanged.bind(this.fullTextSearchDelegator)); } resetErrorStatus() { this.isErrorOccuredOnHealthcheck = false; this.isErrorOccuredOnSearching = false; } async reconnectClient() { logger.info('Try to reconnect...'); this.fullTextSearchDelegator.initClient(); try { await this.getInfoForHealth(); logger.info('Reconnecting succeeded.'); this.resetErrorStatus(); } catch (err) { throw err; } } async getInfo() { try { return await this.fullTextSearchDelegator.getInfo(); } catch (err) { logger.error(err); throw err; } } async getInfoForHealth() { try { const result = await this.fullTextSearchDelegator.getInfoForHealth(); this.isErrorOccuredOnHealthcheck = false; return result; } catch (err) { logger.error(err); // switch error flag, `isErrorOccuredOnHealthcheck` to be `false` this.isErrorOccuredOnHealthcheck = true; throw err; } } async getInfoForAdmin() { return this.fullTextSearchDelegator.getInfoForAdmin(); } async normalizeIndices() { return this.fullTextSearchDelegator.normalizeIndices(); } async rebuildIndex() { return this.fullTextSearchDelegator.rebuildIndex(); } async parseSearchQuery(queryString: string, nqName: string | null): Promise<ParsedQuery> { // eslint-disable-next-line no-param-reassign queryString = normalizeQueryString(queryString); const terms = this.parseQueryString(queryString); if (nqName == null) { return { queryString, terms }; } const nq = await NamedQuery.findOne({ name: normalizeNQName(nqName) }); // will delegate to full-text search if (nq == null) { logger.debug(`Delegated to full-text search since a named query document did not found. (nqName="${nqName}")`); return { queryString, terms }; } const { aliasOf, delegatorName } = nq; let parsedQuery: ParsedQuery; if (aliasOf != null) { parsedQuery = { queryString: normalizeQueryString(aliasOf), terms: this.parseQueryString(aliasOf) }; } else { parsedQuery = { queryString, terms, delegatorName }; } return parsedQuery; } async resolve(parsedQuery: ParsedQuery): Promise<[SearchDelegator, SearchableData]> { const { queryString, terms, delegatorName = SearchDelegatorName.DEFAULT } = parsedQuery; const nqDeledator = this.nqDelegators[delegatorName]; const data = { queryString, terms, }; return [nqDeledator, data]; } /** * Throws SearchError if data is corrupted. * @param {SearchableData} data * @param {SearchDelegator} delegator * @throws {SearchError} SearchError */ private validateSearchableData(delegator: SearchDelegator, data: SearchableData): void { const { terms } = data; if (delegator.isTermsNormalized(terms)) { return; } const unavailableTermsKeys = delegator.validateTerms(terms); throw new SearchError('The query string includes unavailable terms.', unavailableTermsKeys); } async searchKeyword(keyword: string, nqName: string | null, user, userGroups, searchOpts): Promise<[ISearchResult<unknown>, string | null]> { let parsedQuery: ParsedQuery; // parse try { parsedQuery = await this.parseSearchQuery(keyword, nqName); } catch (err) { logger.error('Error occurred while parseSearchQuery', err); throw err; } let delegator: SearchDelegator; let data: SearchableData; // resolve try { [delegator, data] = await this.resolve(parsedQuery); } catch (err) { logger.error('Error occurred while resolving search delegator', err); throw err; } // throws this.validateSearchableData(delegator, data); return [await delegator.search(data, user, userGroups, searchOpts), delegator.name ?? null]; } parseQueryString(queryString: string): QueryTerms { // terms const matchWords: string[] = []; const notMatchWords: string[] = []; const phraseWords: string[] = []; const notPhraseWords: string[] = []; const prefixPaths: string[] = []; const notPrefixPaths: string[] = []; const tags: string[] = []; const notTags: string[] = []; // First: Parse phrase keywords const phraseRegExp = new RegExp(/(-?"[^"]+")/g); const phrases = queryString.match(phraseRegExp); if (phrases !== null) { queryString = queryString.replace(phraseRegExp, ''); // eslint-disable-line no-param-reassign phrases.forEach((phrase) => { phrase.trim(); if (phrase.match(/^-/)) { notPhraseWords.push(phrase.replace(/^-/, '')); } else { phraseWords.push(phrase); } }); } // Second: Parse other keywords (include minus keywords) queryString.split(' ').forEach((word) => { if (word === '') { return; } // https://regex101.com/r/pN9XfK/1 const matchNegative = word.match(/^-(prefix:|tag:)?(.+)$/); // https://regex101.com/r/3qw9FQ/1 const matchPositive = word.match(/^(prefix:|tag:)?(.+)$/); if (matchNegative != null) { if (matchNegative[1] === 'prefix:') { notPrefixPaths.push(matchNegative[2]); } else if (matchNegative[1] === 'tag:') { notTags.push(matchNegative[2]); } else { notMatchWords.push(matchNegative[2]); } } else if (matchPositive != null) { if (matchPositive[1] === 'prefix:') { prefixPaths.push(matchPositive[2]); } else if (matchPositive[1] === 'tag:') { tags.push(matchPositive[2]); } else { matchWords.push(matchPositive[2]); } } }); const terms = { match: matchWords, not_match: notMatchWords, phrase: phraseWords, not_phrase: notPhraseWords, prefix: prefixPaths, not_prefix: notPrefixPaths, tag: tags, not_tag: notTags, }; return terms; } // TODO: optimize the way to check isFormattable e.g. check data schema of searchResult // So far, it determines by delegatorName passed by searchService.searchKeyword checkIsFormattable(searchResult, delegatorName: SearchDelegatorName): boolean { return delegatorName === SearchDelegatorName.DEFAULT; } /** * formatting result */ async formatSearchResult(searchResult: ISearchResult<any>, delegatorName: SearchDelegatorName, user, userGroups): Promise<IFormattedSearchResult> { if (!this.checkIsFormattable(searchResult, delegatorName)) { const data: IPageWithMeta<IPageSearchMeta>[] = searchResult.data.map((page) => { return { data: page, }; }); return { data, meta: searchResult.meta, }; } /* * Format ElasticSearch result */ const User = this.crowi.model('User'); const result = {} as IFormattedSearchResult; // get page data const pageIds = searchResult.data.map((page) => { return page._id }); const findPageResult = await findPageListByIds(pageIds, this.crowi); // set meta data result.meta = searchResult.meta; // set search result page data const pages: (IPageWithMeta<IPageSearchMeta> | null)[] = searchResult.data.map((data) => { const pageData = findPageResult.pages.find((pageData) => { return pageData.id === data._id; }); if (pageData == null) { return null; } // add tags and seenUserCount to pageData pageData._doc.tags = data._source.tag_names; pageData._doc.seenUserCount = (pageData.seenUsers && pageData.seenUsers.length) || 0; // serialize lastUpdateUser if (pageData.lastUpdateUser != null && pageData.lastUpdateUser instanceof User) { pageData.lastUpdateUser = serializeUserSecurely(pageData.lastUpdateUser); } // increment elasticSearchResult let elasticSearchResult; const highlightData = data._highlight; if (highlightData != null) { const snippet = this.canShowSnippet(pageData, user, userGroups) ? highlightData['body.en'] || highlightData['body.ja'] || highlightData['comments.en'] || highlightData['comments.ja'] : null; const pathMatch = highlightData['path.en'] || highlightData['path.ja']; const isHtmlInPath = highlightData['path.en'] != null || highlightData['path.ja'] != null; elasticSearchResult = { snippet: snippet != null && typeof snippet[0] === 'string' ? filterXss.process(snippet) : null, highlightedPath: pathMatch != null && typeof pathMatch[0] === 'string' ? filterXss.process(pathMatch) : null, isHtmlInPath, }; } // serialize creator if (pageData.creator != null && pageData.creator instanceof User) { pageData.creator = serializeUserSecurely(pageData.creator); } // generate pageMeta data const pageMeta = { bookmarkCount: data._source.bookmark_count || 0, elasticSearchResult, }; return { data: pageData, meta: pageMeta }; }); result.data = pages.filter(nonNullable); return result; } canShowSnippet(pageData, user, userGroups): boolean { const Page = mongoose.model('Page') as unknown as PageModel; const testGrant = pageData.grant; const testGrantedUser = pageData.grantedUsers?.[0]; const testGrantedGroup = pageData.grantedGroup; if (testGrant === Page.GRANT_RESTRICTED) { return false; } if (testGrant === Page.GRANT_OWNER) { if (user == null) return false; return user._id.toString() === testGrantedUser.toString(); } if (testGrant === Page.GRANT_USER_GROUP) { if (userGroups == null) return false; return userGroups.map(id => id.toString()).includes(testGrantedGroup.toString()); } return true; } } export default SearchService;
the_stack
import { getRegistryUrl, install } from '../../shared/npm'; import fs from 'fs'; import path from 'path'; import axios from 'axios'; import packageJson from '../../shared/packageJson'; import { getTag, checkoutVersion, getCurrentTag } from '../universal-pkg/repository/git'; import { download } from '../../shared/git'; import { HOOK_TYPE_ON_COMMAND_REGISTERED, LATEST_VERSION, FEFLOW_BIN, FEFLOW_LIB, NPM_PLUGIN_INFO_JSON, INVALID_VERSION, FEFLOW_PLUGIN_GIT_PREFIX, FEFLOW_PLUGIN_PREFIX, FEFLOW_PLUGIN_LOCAL_PREFIX, SILENT_ARG, DISABLE_ARG, } from '../../shared/constant'; import { Plugin } from '../universal-pkg/schema/plugin'; import Linker from '../universal-pkg/linker'; import { UniversalPkg } from '../universal-pkg/dep/pkg'; import versionImpl from '../universal-pkg/dep/version'; import applyPlugins, { resolvePlugin } from '../plugin/applyPlugins'; import { CommandPickConfig } from '../command-picker'; import { getURL } from '../../shared/url'; import { copyDir } from '../../shared/fs'; // import loggerReport from '../logger/report'; interface PkgJson { dependencies?: { [key: string]: string; }; devDependencies?: { [key: string]: string; }; } async function getRepoInfo(ctx: any, packageName: string) { const serverUrl = ctx.config?.serverUrl; const url = getURL(serverUrl, `apply/getlist?name=${packageName}`); if (!url) { return Promise.reject(`the serverUrl is invalid: ${serverUrl}`); } return axios .get(url, { proxy: false, }) .then((res) => { const data = res.data || {}; return (data.data?.length > 0 && data.data[0]) || []; }) .catch((e: any) => { ctx.logger.debug('Get repo info error', e); }); } // git@github.com:tencent/feflow.git // or http[s]://github.com/tencent/feflow.git or http[s]://user:pwd@github.com/tencent/feflow.git // to // encodeURIComponent("github.com/tencent/feflow.git") function getGitRepoName(repoUrl: string): string | undefined { const ret = /^((http:\/\/|https:\/\/)(.*?@)?|git@)/.exec(repoUrl); let repurl: string = ''; if (Array.isArray(ret) && ret.length > 0) { repurl = repoUrl.substring(ret[0].length); } return encodeURIComponent(FEFLOW_PLUGIN_GIT_PREFIX + repurl.split(':').join('/')); } function getDirRepoName(dir: string): string { return encodeURIComponent(FEFLOW_PLUGIN_LOCAL_PREFIX + dir.trim()); } function deleteDir(dirPath: string) { let files: any = []; try { const dirStats = fs.statSync(dirPath); if (!dirStats.isDirectory()) { return; } } catch (e) { return; } files = fs.readdirSync(dirPath); files.forEach((file: string) => { const curPath = `${dirPath}/${file}`; const stat = fs.statSync(curPath); if (stat.isDirectory()) { deleteDir(curPath); } else { fs.unlinkSync(curPath); } }); const stat = fs.lstatSync(dirPath); if (stat.isDirectory()) { fs.rmdirSync(dirPath); } else { fs.rmdirSync(fs.realpathSync(dirPath)); fs.unlinkSync(dirPath); } } function isGitRepo(url: string): boolean { return ( new RegExp( '^git@[a-zA-Z0-9._-]+:[a-zA-Z0-9._-]+(/[a-zA-Z0-9._-]+)+.git(@v(0|[1-9]\\d*).(0|[1-9]\\d*).(0|[1-9]\\d*))?$', ).test(url) || new RegExp( '^http(s)?://([a-zA-Z0-9._-]*?(:[a-zA-Z0-9._-]*)?@)?[a-zA-Z0-9._-]+' + '(/[a-zA-Z0-9._-]+)+.git(@v(0|[1-9]\\d*).(0|[1-9]\\d*).(0|[1-9]\\d*))?$', ).test(url) ); } async function installNpmPlugin(ctx: any, ...dependencies: string[]) { const packageManager = ctx?.config?.packageManager; const registryUrl = await getRegistryUrl(packageManager); let versionList: string[]; let needInstall: string[] = []; try { versionList = await Promise.all( dependencies.map(async (dependency: string) => { try { return await packageJson(dependency, registryUrl); } catch (e) { ctx.logger.error(`${dependency} not found on ${packageManager}, please check if it exists`); ctx.logger.debug(e); process.exit(2); } }), ); const getCurversion = () => { let json: PkgJson = {}; const installedPlugin = {}; try { const data = fs.readFileSync(ctx.rootPkg, 'utf-8'); json = JSON.parse(data); } catch (e) { ctx.logger.error(`getCurversion error: ${JSON.stringify(e)}`); } if (!json.dependencies) { return {}; } const deps = json.dependencies || json.devDependencies || {}; Object.keys(deps).forEach((name) => { if (!/^feflow-plugin-|^@[^/]+\/feflow-plugin-|^generator-|^@[^/]+\/generator-/.test(name)) { return false; } installedPlugin[name] = deps[name]; }); return installedPlugin; }; const hasInstallDep = getCurversion(); needInstall = dependencies.filter((dep, idx) => { const depList = (dep || '').split('@'); const depName = !depList[0] ? `@${depList[1]}` : depList[0]; if (hasInstallDep[depName] !== versionList[idx]) { return dep; } ctx.logger.info(`[${dep}] has installed the latest version: ${hasInstallDep[depName]}`); }); } catch (err) { ctx.logger.error(`get pkg info error ${JSON.stringify(err)}`); } if (!needInstall.length) { return Promise.resolve(); } ctx.logger.info('Installing packages. This might take a couple of minutes.'); return install(packageManager, ctx.root, packageManager === 'yarn' ? 'add' : 'install', needInstall, false).then( () => { ctx.logger.info('install success'); }, ); } function updateNpmPluginInfo(ctx: any, pluginName: string, options: any) { const { root, }: { root: string; } = ctx; const configPath = path.join(root, NPM_PLUGIN_INFO_JSON); const npmPluginInfoJson = fs.existsSync(configPath) ? require(configPath) : {}; if (options === false) { delete npmPluginInfoJson[pluginName]; } else { if (options.globalCmd) { const pluginInfo = npmPluginInfoJson[pluginName] || {}; const globalCmd = pluginInfo.globalCmd || []; pluginInfo.globalCmd = globalCmd ? Array.from(new Set<string>([...globalCmd, ...options.globalCmd])) : options.globalCmd || []; npmPluginInfoJson[pluginName] = pluginInfo; delete options.globalCmd; } npmPluginInfoJson[pluginName] = Object.assign({}, npmPluginInfoJson[pluginName] || {}, options || {}); } fs.writeFileSync(configPath, JSON.stringify(npmPluginInfoJson, null, 4)); } async function installJsPlugin(ctx: any, installPlugin: string) { const { bin, lib, logger, }: { bin: string; lib: string; logger: any; } = ctx; const isGlobal = ctx?.args.g; // install js npm plugin await installNpmPlugin(ctx, installPlugin); // if install with option -g, register as global command if (isGlobal && /^feflow-plugin-|^@[^/]+\/feflow-plugin-/.test(installPlugin)) { ctx.hook.on(HOOK_TYPE_ON_COMMAND_REGISTERED, (cmdName: string) => { if (cmdName) { logger.debug(`linking cmd [${cmdName}] registered by plugin ${installPlugin} to global`); // create symbol link to plugin, support global plugin cmd const linker = new Linker(); linker.register(bin, lib, cmdName); updateNpmPluginInfo(ctx, installPlugin, { globalCmd: [cmdName] }); logger.info(`can just type > "${cmdName} options" in terminal, equal to "fef ${cmdName} options"`); } }); return applyPlugins([installPlugin])(ctx); } } async function startInstall(ctx: any, pkgInfo: PkgInfo, repoPath: string, updateFlag: boolean, isGlobal: boolean) { const { logger, universalPkg, universalModules, bin, lib, }: { logger: any; universalPkg: UniversalPkg; universalModules: string; bin: string; lib: string; } = ctx; // start install logger.debug('install version:', pkgInfo.checkoutTag); if (pkgInfo.fromType !== PkgInfo.dir) { if (!fs.existsSync(repoPath)) { logger.info(`start download from ${pkgInfo.repoFrom}`); try { await download(pkgInfo.repoFrom, pkgInfo.checkoutTag, repoPath); } catch (e) { logger.warn(`download warn with code ${e}`); } } } else { deleteDir(repoPath); logger.info(`start copy from ${pkgInfo.repoFrom}`); await copyDir(pkgInfo.repoFrom, repoPath); } let lastRepoName = ''; const lastVersion = universalPkg.getInstalled().get(pkgInfo.repoName); if (lastVersion) { const oldRepoPath = getRepoPath(universalModules, pkgInfo.repoName, lastVersion); lastRepoName = toSimpleCommand(pkgInfo.repoName); try { const oldPlugin = resolvePlugin(ctx, oldRepoPath); if (oldPlugin.name) { lastRepoName = oldPlugin.name; } } catch (e) { } } if (pkgInfo.fromType !== PkgInfo.dir) { logger.info(`switch to version: ${pkgInfo.checkoutTag}`); await checkoutVersion(repoPath, pkgInfo.checkoutTag, pkgInfo.lastCheckoutTag); } // deal dependencies const linker = new Linker(); const oldVersion = universalPkg.getInstalled().get(pkgInfo.repoName); let oldDependencies; if (isGlobal && oldVersion) { oldDependencies = universalPkg.getDependencies(pkgInfo.repoName, oldVersion); if (oldDependencies) { oldDependencies = new Map(oldDependencies); } } const plugin = resolvePlugin(ctx, repoPath); // check the validity of the plugin before installing it await plugin.check(); logger.debug('check plugin success'); const pluginBin = path.join(repoPath, `.${FEFLOW_BIN}`); const pluginLib = path.join(repoPath, `.${FEFLOW_LIB}`); for (const depPlugin of plugin.dep.plugin) { try { const curPkgInfo = await getPkgInfo(ctx, depPlugin); if (!curPkgInfo) { throw `the dependent plugin ${depPlugin} does not belong to the universal packge`; } await installPlugin(ctx, depPlugin, false); const commandName = toSimpleCommand(curPkgInfo.repoName); if (oldDependencies?.get(curPkgInfo.repoName) === curPkgInfo.installVersion) { oldDependencies.delete(curPkgInfo.repoName); } universalPkg.depend(pkgInfo.repoName, pkgInfo.installVersion, curPkgInfo.repoName, curPkgInfo.installVersion); const pluginPath = path.join(universalModules, `${curPkgInfo.repoName}@${curPkgInfo.installVersion}`); const curPlugin = resolvePlugin(ctx, pluginPath); let useCommandName = commandName; // custom command name if (curPlugin.name) { useCommandName = curPlugin.name; } if (curPlugin.langRuntime) { const commands = curPlugin.command.getCommands(); linker.registerCustom(pluginBin, pluginLib, commands, useCommandName); } else { // call {pkg}@{version} and disable-check linker.register( pluginBin, pluginLib, `${commandName}@${curPkgInfo.installVersion} ${DISABLE_ARG} ${SILENT_ARG}`, useCommandName, ); } logger.info(`install [${curPkgInfo.showName()}] ` + `was successful and it is called using [${useCommandName}]`); } catch (e) { logger.error(`failed to install plugin dependency ${depPlugin}`); throw e; } } if (oldVersion && oldDependencies) { for (const [oldPkg, oldPkgVersion] of oldDependencies) { universalPkg.removeDepended(oldPkg, oldPkgVersion, pkgInfo.repoName, oldVersion); } } plugin.preInstall.run(); const cmdName = toSimpleCommand(pkgInfo.repoName); let useCommandName = cmdName; // custom command name if (plugin.name) { useCommandName = plugin.name; } if (plugin.langRuntime) { const commands = plugin.command.getCommands(); linker.registerCustom(bin, lib, commands, useCommandName); } else { linker.register(bin, lib, cmdName, useCommandName); } if (lastRepoName && lastRepoName !== useCommandName) { linker.remove(bin, lib, lastRepoName); } // install when global or not exists if (isGlobal || !universalPkg.isInstalled(pkgInfo.repoName)) { universalPkg.install(pkgInfo.repoName, pkgInfo.installVersion); } // the package management information is retained only when the installation is fully successful if (isGlobal) { removeInvalidPkg(ctx); } universalPkg.saveChange(); plugin.test.runLess(); if (updateFlag) { plugin.postUpgrade.runLess(); logger.info(`update [${pkgInfo.showName()}] ` + `was successful and it is called using [${useCommandName}]`); } else { plugin.postInstall.runLess(); logger.info(`install [${pkgInfo.showName()}] ` + `was successful and it is called using [${useCommandName}]`); } } function getRepoPath(universalModules: string, repoName: string, installVersion: string): string { return path.join(universalModules, `${repoName}@${installVersion}`); } async function installPlugin(ctx: any, installPluginStr: string, isGlobal: boolean) { const { logger, universalPkg, universalModules, }: { logger: any; universalPkg: UniversalPkg; universalModules: string; } = ctx; const serverUrl = ctx.config?.serverUrl; const finalInstallPluginStr = installPluginStr.trim(); if (!serverUrl) { logger.warn('please configure the serverUrl'); return installJsPlugin(ctx, finalInstallPluginStr); } const pkgInfo = await getPkgInfo(ctx, finalInstallPluginStr); if (!pkgInfo) { return installJsPlugin(ctx, finalInstallPluginStr); } if (!pkgInfo.repoName) { throw `plugin [${pkgInfo.repoFrom}] does not exist`; } // if the specified version is already installed, skip it if (universalPkg.isInstalled(pkgInfo.repoName, pkgInfo.checkoutTag, !isGlobal)) { global && logger.info(`the current version is installed`); return; } let updateFlag = false; const repoPath = getRepoPath(universalModules, pkgInfo.repoName, pkgInfo.installVersion); if (pkgInfo.installVersion === LATEST_VERSION) { if (universalPkg.isInstalled(pkgInfo.repoName, LATEST_VERSION)) { try { const currentVersion = await getCurrentTag(repoPath); if (currentVersion && pkgInfo.checkoutTag === currentVersion) { if (global) { logger.info( `[${pkgInfo.repoName}] the plugin version currently installed is the latest version: ${currentVersion}`, ); } return; } updateFlag = true; if (currentVersion) { pkgInfo.lastCheckoutTag = currentVersion; } } catch (e) { logger.error(JSON.stringify(e)); } } } if (updateFlag) { logger.info(`[${pkgInfo.showName()}] update the plugin to version ${pkgInfo.checkoutTag}`); try { resolvePlugin(ctx, repoPath).preUpgrade.runLess(); } catch (e) { } } else { logger.info(`[${pkgInfo.showName()}] installing plugin`); } await startInstall(ctx, pkgInfo, repoPath, updateFlag, isGlobal); } function toSimpleCommand(command: string): string { return command.replace(FEFLOW_PLUGIN_PREFIX, ''); } function isDir(installPluginDir: string): boolean { try { return fs.statSync(installPluginDir).isDirectory(); } catch (e) { return false; } } // when you install a universal package, return PkgInfo, otherwise return undefined export async function getPkgInfo(ctx: any, installPlugin: string): Promise<PkgInfo | undefined> { let installVersion; let checkoutTag; let repoFrom; let repoName; let fromType: number; // install from git repo if (isGitRepo(installPlugin)) { fromType = PkgInfo.git; if (installPlugin.indexOf('.git@') !== -1) { const splits = installPlugin.split('@'); const ver = splits.pop(); repoFrom = splits.join('@'); installVersion = ver || LATEST_VERSION; } else { repoFrom = installPlugin; installVersion = LATEST_VERSION; } const confirmTag = installVersion === LATEST_VERSION ? undefined : installVersion; checkoutTag = await getTag(repoFrom, confirmTag); repoName = getGitRepoName(repoFrom); } else if (isDir(installPlugin)) { fromType = PkgInfo.dir; const plugin = resolvePlugin(ctx, installPlugin); if (!plugin.name) { throw 'the [name] field must be specified in plugin.yml'; } installVersion = LATEST_VERSION; checkoutTag = INVALID_VERSION; repoFrom = installPlugin; repoName = getDirRepoName(installPlugin); } else { fromType = PkgInfo.appStore; const pluginName = installPlugin.split('@')[0]; let pluginVersion = installPlugin.split('@')[1]; const repoInfo = await getRepoInfo(ctx, pluginName); if (!repoInfo) { ctx.logger.warn( `cant found message about ${pluginName} from Feflow Application market, please check if it exists`, ); return; } repoFrom = repoInfo.repo; repoName = repoInfo.name; if (isGitRepo(repoFrom) && !repoInfo.tnpm) { if (pluginVersion) { pluginVersion = versionImpl.toFull(pluginVersion); if (!versionImpl.check(pluginVersion)) { throw `invalid version: ${pluginVersion} for ${pluginName}`; } } installVersion = pluginVersion || LATEST_VERSION; checkoutTag = await getTag(repoFrom, installVersion === LATEST_VERSION ? undefined : installVersion); } else { return; } } if (!checkoutTag) { throw `the version [${installVersion}] was not found`; } return new PkgInfo(repoName, repoFrom, installVersion, checkoutTag, fromType); } class PkgInfo { public static git = 1; public static appStore = 2; public static dir = 3; repoName: string; repoFrom: string; installVersion: string; checkoutTag: string; lastCheckoutTag = ''; fromType: number; constructor(repoName: string, repoUrl: string, installVersion: string, checkoutTag: string, fromType: number) { this.repoName = repoName; this.repoFrom = repoUrl; this.installVersion = installVersion; this.checkoutTag = checkoutTag; this.fromType = fromType; } public showName(): string { if (this.fromType !== PkgInfo.appStore) { return this.repoFrom; } return this.repoName; } } async function uninstallUniversalPlugin(ctx: any, pluginName: string) { const { logger, universalPkg, }: { logger: any; universalPkg: UniversalPkg; bin: string; lib: string; } = ctx; const version = universalPkg.getInstalled().get(pluginName); if (!version) { logger.error('this plugin is not currently installed'); return; } let plugin: Plugin | undefined; try { const repoPath = path.join(ctx.universalModules, `${pluginName}@${version}`); try { plugin = resolvePlugin(ctx, repoPath); } catch (e) { logger.debug(`resolve plugin failure, ${e}`); } plugin?.preUninstall?.run(); universalPkg.uninstall(pluginName, version); } catch (e) { logger.error(`uninstall failure, ${e}`); return; } try { removeInvalidPkg(ctx); plugin?.postUninstall?.runLess(); logger.info('uninstall success'); } catch (e) { logger.info(`uninstall succeeded, but failed to clean the data, ${e}`); } } async function uninstallNpmPlugin(ctx: any, dependencies: []) { const { logger, root, bin, lib, }: { logger: any; root: string; bin: string; lib: string; } = ctx; dependencies.forEach((pkg: string) => { const npmPluginInfoPath = path.join(root, NPM_PLUGIN_INFO_JSON); try { if (fs.existsSync(npmPluginInfoPath)) { const npmPluginInfo = require(npmPluginInfoPath); const pluginGlobalCmd = npmPluginInfo?.[pkg]?.globalCmd || []; pluginGlobalCmd.forEach((cmd: string) => { new Linker().remove(bin, lib, cmd); }); updateNpmPluginInfo(ctx, pkg, false); } } catch (e) { logger.debug(`remove plugin registered cmd link failure, ${e}`); } }); return install( ctx?.config?.packageManager, ctx.root, ctx?.config?.packageManager === 'yarn' ? 'remove' : 'uninstall', dependencies, false, ).then(() => { ctx.logger.info('uninstall success'); }); } function removePkg(ctx: any, pkg: string, version: string) { const { bin, lib, universalPkg }: { universalPkg: UniversalPkg; bin: string; lib: string } = ctx; const pluginPath = path.join(ctx.universalModules, `${pkg}@${version}`); if (fs.existsSync(pluginPath)) { let useName = toSimpleCommand(pkg); const curPlugin = resolvePlugin(ctx, pluginPath); if (curPlugin.name) { useName = curPlugin.name; } deleteDir(pluginPath); if (!universalPkg.isInstalled(pkg)) { try { new Linker().remove(bin, lib, useName); } catch (e) { ctx.logger.debug(`remove link failure, ${e}`); } } } } function removeInvalidPkg(ctx: any) { const { universalPkg }: { universalPkg: UniversalPkg } = ctx; const invalidDep = universalPkg.removeInvalidDependencies(); for (const [invalidPkg, invalidVersion] of invalidDep) { removePkg(ctx, invalidPkg, invalidVersion); } } // update only the plugins installed globally export async function updateUniversalPlugin(ctx: any, pkg: string, version: string, plugin: Plugin) { const universalPkg = ctx.universalPkg as UniversalPkg; const dependedOn = universalPkg.getDepended(pkg, version); // update parent if (dependedOn) { for (const [dependedOnPkg, dependedOnVersion] of dependedOn) { if (dependedOnVersion !== LATEST_VERSION) { continue; } await updatePlugin(ctx, dependedOnPkg, dependedOnVersion); } } const newVersion = universalPkg.getInstalled().get(pkg); if (newVersion === version && version === LATEST_VERSION && plugin.autoUpdate) { await updatePlugin(ctx, pkg, version); } } async function updatePlugin(ctx: any, pkg: string, version: string) { const { universalPkg }: { universalPkg: UniversalPkg } = ctx; const isGlobal = universalPkg.isInstalled(pkg, version); try { await installPlugin(ctx, `${pkg}@${version}`, isGlobal); } catch (e) { ctx.logger.error(`[${pkg}] update failure, ${e}`); } } module.exports = (ctx: any) => { ctx.commander.register('install', 'Install a devkit or plugin', async () => { const dependencies = ctx.args._; const installPluginStr = dependencies[0]; if (!installPluginStr) { ctx.logger.error('parameter error'); return; } try { await installPlugin(ctx, installPluginStr, true); } catch (e) { ctx.logger.error(`install error: ${JSON.stringify(e)}`); process.exit(2); } }); ctx.commander.register('uninstall', 'Uninstall a devkit or plugin', async () => { const dependencies = ctx.args._; ctx.logger.info('Uninstalling packages. This might take a couple of minutes.'); const serverUrl = ctx.config?.serverUrl; if (!serverUrl) { return uninstallNpmPlugin(ctx, dependencies); } const { universalPkg } = ctx; const installPluginStr = dependencies[0]; const pkgInfo = await getPkgInfo(ctx, installPluginStr); if (pkgInfo && universalPkg.isInstalled(pkgInfo.repoName)) { return uninstallUniversalPlugin(ctx, pkgInfo.repoName); } await uninstallNpmPlugin(ctx, dependencies); const pickerConfig = new CommandPickConfig(ctx); pickerConfig.removeCache(dependencies[0]); }); }; module.exports.installPlugin = installPlugin; module.exports.updateUniversalPlugin = updateUniversalPlugin; module.exports.getRepoInfo = getRepoInfo; module.exports.getPkgInfo = getPkgInfo;
the_stack
import * as core from '@actions/core' import { removeRef, slug, slug_cs, slugref, slugref_cs, slugurl, slugurl_cs, slugurlref, slugurlref_cs } from './slug' import {shortsha} from './short' import {get_first_part, get_second_part} from './partial' const SEPARATOR = '/' /** * Inputs environments variables keys from Github actions job * see https://docs.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables */ const GITHUB_REPOSITORY = 'GITHUB_REPOSITORY' const GITHUB_REF = 'GITHUB_REF' const GITHUB_HEAD_REF = 'GITHUB_HEAD_REF' const GITHUB_BASE_REF = 'GITHUB_BASE_REF' const GITHUB_SHA = 'GITHUB_SHA' const GITHUB_EVENT_PATH = 'GITHUB_EVENT_PATH' /** * Partial outputs environments variables keys */ const GITHUB_REPOSITORY_OWNER_PART = 'GITHUB_REPOSITORY_OWNER_PART' const GITHUB_REPOSITORY_NAME_PART = 'GITHUB_REPOSITORY_NAME_PART' /** * New environments variables keys */ const GITHUB_REF_NAME = 'GITHUB_REF_NAME' /** * Slugged outputs environments variables keys */ const GITHUB_REPOSITORY_SLUG = 'GITHUB_REPOSITORY_SLUG' const GITHUB_REPOSITORY_SLUG_CS = 'GITHUB_REPOSITORY_SLUG_CS' const GITHUB_REPOSITORY_OWNER_PART_SLUG = 'GITHUB_REPOSITORY_OWNER_PART_SLUG' const GITHUB_REPOSITORY_OWNER_PART_SLUG_CS = 'GITHUB_REPOSITORY_OWNER_PART_SLUG_CS' const GITHUB_REPOSITORY_NAME_PART_SLUG = 'GITHUB_REPOSITORY_NAME_PART_SLUG' const GITHUB_REPOSITORY_NAME_PART_SLUG_CS = 'GITHUB_REPOSITORY_NAME_PART_SLUG_CS' const GITHUB_REF_SLUG = 'GITHUB_REF_SLUG' const GITHUB_REF_SLUG_CS = 'GITHUB_REF_SLUG_CS' const GITHUB_HEAD_REF_SLUG = 'GITHUB_HEAD_REF_SLUG' const GITHUB_HEAD_REF_SLUG_CS = 'GITHUB_HEAD_REF_SLUG_CS' const GITHUB_BASE_REF_SLUG = 'GITHUB_BASE_REF_SLUG' const GITHUB_BASE_REF_SLUG_CS = 'GITHUB_BASE_REF_SLUG_CS' const GITHUB_EVENT_REF_SLUG = 'GITHUB_EVENT_REF_SLUG' const GITHUB_EVENT_REF_SLUG_CS = 'GITHUB_EVENT_REF_SLUG_CS' const GITHUB_REF_NAME_SLUG = 'GITHUB_REF_NAME_SLUG' const GITHUB_REF_NAME_SLUG_CS = 'GITHUB_REF_NAME_SLUG_CS' /** * URL-Slugged outputs environments variables keys */ const GITHUB_REPOSITORY_SLUG_URL = 'GITHUB_REPOSITORY_SLUG_URL' const GITHUB_REPOSITORY_SLUG_URL_CS = 'GITHUB_REPOSITORY_SLUG_URL_CS' const GITHUB_REPOSITORY_OWNER_PART_SLUG_URL = 'GITHUB_REPOSITORY_OWNER_PART_SLUG_URL' const GITHUB_REPOSITORY_OWNER_PART_SLUG_URL_CS = 'GITHUB_REPOSITORY_OWNER_PART_SLUG_URL_CS' const GITHUB_REPOSITORY_NAME_PART_SLUG_URL = 'GITHUB_REPOSITORY_NAME_PART_SLUG_URL' const GITHUB_REPOSITORY_NAME_PART_SLUG_URL_CS = 'GITHUB_REPOSITORY_NAME_PART_SLUG_URL_CS' const GITHUB_REF_SLUG_URL = 'GITHUB_REF_SLUG_URL' const GITHUB_REF_SLUG_URL_CS = 'GITHUB_REF_SLUG_URL_CS' const GITHUB_HEAD_REF_SLUG_URL = 'GITHUB_HEAD_REF_SLUG_URL' const GITHUB_HEAD_REF_SLUG_URL_CS = 'GITHUB_HEAD_REF_SLUG_URL_CS' const GITHUB_BASE_REF_SLUG_URL = 'GITHUB_BASE_REF_SLUG_URL' const GITHUB_BASE_REF_SLUG_URL_CS = 'GITHUB_BASE_REF_SLUG_URL_CS' const GITHUB_EVENT_REF_SLUG_URL = 'GITHUB_EVENT_REF_SLUG_URL' const GITHUB_EVENT_REF_SLUG_URL_CS = 'GITHUB_EVENT_REF_SLUG_URL_CS' const GITHUB_REF_NAME_SLUG_URL = 'GITHUB_REF_NAME_SLUG_URL' const GITHUB_REF_NAME_SLUG_URL_CS = 'GITHUB_REF_NAME_SLUG_URL_CS' /** * Shorted outputs environments variables keys */ const GITHUB_SHA_SHORT = 'GITHUB_SHA_SHORT' const GITHUB_EVENT_PULL_REQUEST_HEAD_SHA_SHORT = 'GITHUB_EVENT_PULL_REQUEST_HEAD_SHA_SHORT' async function run(): Promise<void> { try { const eventPath = process.env[GITHUB_EVENT_PATH] if (eventPath) { const eventData = await import(eventPath) if (eventData.hasOwnProperty('ref')) { core.exportVariable(GITHUB_EVENT_REF_SLUG, slugref(eventData.ref)) core.exportVariable(GITHUB_EVENT_REF_SLUG_CS, slugref_cs(eventData.ref)) core.exportVariable( GITHUB_EVENT_REF_SLUG_URL, slugurlref(eventData.ref) ) core.exportVariable( GITHUB_EVENT_REF_SLUG_URL_CS, slugurlref_cs(eventData.ref) ) } else if (eventData.hasOwnProperty('pull_request')) { core.exportVariable( GITHUB_EVENT_PULL_REQUEST_HEAD_SHA_SHORT, shortsha(eventData.pull_request.head.sha) ) } } exportFirstPart(GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_OWNER_PART) exportSecondPart(GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_NAME_PART) exportSlug(GITHUB_REPOSITORY, GITHUB_REPOSITORY_SLUG) exportSlugCS(GITHUB_REPOSITORY, GITHUB_REPOSITORY_SLUG_CS) exportFirstPartSlug( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_OWNER_PART_SLUG ) exportFirstPartSlugCS( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_OWNER_PART_SLUG_CS ) exportSecondPartSlug( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_NAME_PART_SLUG ) exportSecondPartSlugCS( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_NAME_PART_SLUG_CS ) exportSlugUrl(GITHUB_REPOSITORY, GITHUB_REPOSITORY_SLUG_URL) exportSlugUrlCS(GITHUB_REPOSITORY, GITHUB_REPOSITORY_SLUG_URL_CS) exportFirstPartSlugUrl( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_OWNER_PART_SLUG_URL ) exportFirstPartSlugUrlCS( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_OWNER_PART_SLUG_URL_CS ) exportSecondPartSlugUrl( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_NAME_PART_SLUG_URL ) exportSecondPartSlugUrlCS( GITHUB_REPOSITORY, SEPARATOR, GITHUB_REPOSITORY_NAME_PART_SLUG_URL_CS ) exportSlugRef(GITHUB_REF, GITHUB_REF_SLUG) exportSlugRefCS(GITHUB_REF, GITHUB_REF_SLUG_CS) exportSlugRef(GITHUB_HEAD_REF, GITHUB_HEAD_REF_SLUG) exportSlugRefCS(GITHUB_HEAD_REF, GITHUB_HEAD_REF_SLUG_CS) exportSlugRef(GITHUB_BASE_REF, GITHUB_BASE_REF_SLUG) exportSlugRefCS(GITHUB_BASE_REF, GITHUB_BASE_REF_SLUG_CS) exportSlugUrlRef(GITHUB_REF, GITHUB_REF_SLUG_URL) exportSlugUrlRefCS(GITHUB_REF, GITHUB_REF_SLUG_URL_CS) exportSlugUrlRef(GITHUB_HEAD_REF, GITHUB_HEAD_REF_SLUG_URL) exportSlugUrlRefCS(GITHUB_HEAD_REF, GITHUB_HEAD_REF_SLUG_URL_CS) exportSlugUrlRef(GITHUB_BASE_REF, GITHUB_BASE_REF_SLUG_URL) exportSlugUrlRefCS(GITHUB_BASE_REF, GITHUB_BASE_REF_SLUG_URL_CS) exportShortSha(GITHUB_SHA, GITHUB_SHA_SHORT) exportBranchName() } catch (error) { core.setFailed(error.message) } } function exportFirstPart( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { core.exportVariable(outputKey, get_first_part(envVar, separator)) } } function exportSecondPart( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { core.exportVariable(outputKey, get_second_part(envVar, separator)) } } function exportSlugCS(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { core.exportVariable(outputKey, slug_cs(envVar)) } } function exportSlug(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { core.exportVariable(outputKey, slug(envVar)) } } function exportFirstPartSlugCS( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_first_part(envVar, separator) core.exportVariable(outputKey, slug_cs(value)) } } function exportFirstPartSlug( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_first_part(envVar, separator) core.exportVariable(outputKey, slug(value)) } } function exportSecondPartSlugCS( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_second_part(envVar, separator) core.exportVariable(outputKey, slug_cs(value)) } } function exportSecondPartSlug( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_second_part(envVar, separator) core.exportVariable(outputKey, slug(value)) } } function exportSlugRefCS(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { exportSlugRefCSValue(envVar, outputKey) } } function exportSlugRefCSValue(envVar: string, outputKey: string): void { core.exportVariable(outputKey, slugref_cs(envVar)) } function exportSlugRef(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { exportSlugRefValue(envVar, outputKey) } } function exportSlugRefValue(envVar: string, outputKey: string): void { core.exportVariable(outputKey, slugref(envVar)) } function exportSlugUrlCS(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { core.exportVariable(outputKey, slugurl_cs(envVar)) } } function exportSlugUrl(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { core.exportVariable(outputKey, slugurl(envVar)) } } function exportFirstPartSlugUrlCS( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_first_part(envVar, separator) core.exportVariable(outputKey, slugurl_cs(value)) } } function exportFirstPartSlugUrl( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_first_part(envVar, separator) core.exportVariable(outputKey, slugurl(value)) } } function exportSecondPartSlugUrlCS( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_second_part(envVar, separator) core.exportVariable(outputKey, slugurl_cs(value)) } } function exportSecondPartSlugUrl( inputKey: string, separator: string, outputKey: string ): void { const envVar = process.env[inputKey] if (envVar) { const value = get_second_part(envVar, separator) core.exportVariable(outputKey, slugurl(value)) } } function exportSlugUrlRefCS(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { exportSlugUrlRefCSValue(envVar, outputKey) } } function exportSlugUrlRefCSValue(envVar: string, outputKey: string): void { core.exportVariable(outputKey, slugurlref_cs(envVar)) } function exportSlugUrlRef(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { exportSlugUrlRefValue(envVar, outputKey) } } function exportSlugUrlRefValue(envVar: string, outputKey: string): void { core.exportVariable(outputKey, slugurlref(envVar)) } function exportShortSha(inputKey: string, outputKey: string): void { const envVar = process.env[inputKey] if (envVar) { core.exportVariable(outputKey, shortsha(envVar)) } } function exportBranchName(): void { //GITHUB_HEAD_REF is only set for pull request events https://docs.github.com/en/actions/reference/environment-variables const isPullRequest = !!process.env.GITHUB_HEAD_REF let refName if (isPullRequest) { refName = process.env.GITHUB_HEAD_REF } else { refName = process.env.GITHUB_REF } if (refName) { core.exportVariable(GITHUB_REF_NAME, removeRef(refName)) exportSlugRefValue(refName, GITHUB_REF_NAME_SLUG) exportSlugRefCSValue(refName, GITHUB_REF_NAME_SLUG_CS) exportSlugUrlRefValue(refName, GITHUB_REF_NAME_SLUG_URL) exportSlugUrlRefCSValue(refName, GITHUB_REF_NAME_SLUG_URL_CS) } } run()
the_stack
/// <reference types="amap-js-api" /> /// <reference types="amap-js-api-place-search" /> declare namespace AMap { enum TransferPolicy { /** * 最快捷模式 */ LEAST_TIME = 0, /** * 最经济模式 */ LEAST_FEE = 1, /** * 最少换乘模式 */ LEAST_TRANSFER = 2, /** * 最少步行模式 */ LEAST_WALK = 3, /** * 最舒适模式 */ MOST_COMFORT = 4, /** * 不乘地铁模式 */ NO_SUBWAY = 5 } namespace Transfer { interface EventMap { error: Event<'error', { info: string }>; complete: Event<'complete', SearchResult>; } interface Options { /** * 公交换乘的城市,支持城市名称、城市区号、电话区号,此项为必填 */ city: string; /** * 公交换乘策略 */ policy?: TransferPolicy; /** * 是否计算夜班车,默认为不计算 */ nightflag?: boolean; /** * 终点城市,跨城公交路径规划时为必填参数 */ cityd?: string; /** * 返回结果控制, 默认值: base * base:返回基本信息 * all:返回全部信息 */ extensions?: 'all' | 'base'; /** * AMap.Map对象, 展现结果的地图实例 */ map?: Map; /** * 结果列表的HTML容器id或容器元素 */ panel?: string; /** * 设置是否隐藏路径规划的起始点图标 */ hideMarkers?: boolean; /** * 使用map属性时,绘制的规划线路是否显示描边。默认为true */ isOutline?: boolean; /** * 使用map属性时,绘制的规划线路的描边颜色。默认为'white' */ outlineColor?: string; /** * 用于控制在路径规划结束后,是否自动调整地图视野使绘制的路线处于视口的可见范围 */ autoFitView?: boolean; // internal showDir?: boolean; } interface SearchPoint { /** * 关键词 */ keyword: string; } interface SegmentCommon { /** * 此换乘段预期用时,单位:秒 */ time: number; /** * 此换乘段的文字描述 */ instruction: string; /** * 此换乘段距离 */ distance: number; } interface WalkStep { /** * 步行子路段描述 */ instruction: string; /** * 道路 */ road: string; /** * 步行子路段距离,单位:米 */ distance: number; /** * 步行子路段预计使用时间,单位:秒 */ time: number; /** * 步行子路段坐标集合 */ path: LngLat[]; /** * 本步行子路段完成后动作 */ action: string; /** * 步行子路段完成后辅助动作,一般为到达某个公交站点或目的地时返回 */ assist_action: string; } interface WalkDetails { /** * 此换乘段的步行起点 */ origin: LngLat; /** * 此换乘段的步行终点 */ destination: LngLat; /** * 此换乘段坐标集合 */ path: LngLat[]; /** * 步行子路段WalkStep列表 */ steps: WalkStep[]; } interface WalkSegment extends SegmentCommon { /** * 换乘动作类型 */ transit_mode: 'WALK'; /** * 此换乘段导航信息 */ transit: WalkDetails; } interface TaxiDetails { /** * 耗时,单位:秒 */ time: number; /** * 该方案的总距离,单位:米 */ distance: number; /** * 打车起点坐标 */ origin: LngLat; /** * 打车终点坐标 */ destination: LngLat; /** * 起点名称 */ sname: string; /** * 终点名称 */ tname: string; } interface TaxiSegment extends SegmentCommon { /** * 换乘动作类型 */ transit_mode: 'TAXI'; /** * 此换乘段导航信息 */ transit: TaxiDetails; } interface Stop { /** * 公交站点名称 */ name: string; /** * 公交站点ID */ id: string; /** * 站点经纬度信息 */ location: LngLat; segment?: TransitSegment; } interface TransitLine { /** * 公交路线名 */ name: string; /** * 公交路线ID */ id: string; /** * 公交类型 */ type: string; /** * 公交路线首班车时间 */ stime: string | never[]; /** * 公交路线末班车时间 */ etime: string | never[]; } interface SubwayEntrance { /** * 地铁口名称 */ name: string; /** * 地铁口经纬度坐标 */ location: LngLat; } interface TransitDetails { /** * 此换乘段的上车站 */ on_station: Stop; /** * 此换乘段的下车站 */ off_station: Stop; /** * 此换乘段公交部分(上车站-下车站)坐标集合 */ path: LngLat[]; /** * 途径公交站点数(不包括上车站和下车站) */ via_num: number; /** * 途径公交站点集合(不包括上车站和下车站) */ via_stops: Stop[]; /** * 此换乘段公交路线 */ lines: TransitLine[]; /** * 地铁站入口 */ entrance?: SubwayEntrance; /** * 地铁站出口 */ exit?: SubwayEntrance; } interface TransitSegment extends SegmentCommon { /** * 换乘动作类型 */ transit_mode: 'SUBWAY' | 'METRO_RAIL' | 'BUS'; /** * 此换乘段导航信息 */ transit: TransitDetails; } interface RailStop { /** * 上、下车站点所在城市的adcode */ adcode: string; /** * 上、下车站点ID */ id: string; /** * 上、下站点经纬度信息 */ location: LngLat; /** * 上、下车站点名称 */ name: string; /** * 上下车点发车时间 */ time: number; wait?: number; segment?: RailwaySegment; } interface Space { /** * 仓位编码,参考仓位级别表 */ type: string | never[]; /** * 仓位费用 */ cost: number; } interface RailwayDetailsBase { /** * 线路id编码 */ id: string; /** * 线路名称 */ name: string; /** * 线路车次号 */ trip: string; /** * 线路车次类型,参考火车路线类型列表 */ type: string; /** * 该换乘段的行车总距离 */ distance: number; /** * 该线路车段耗时 */ time: number; /** * 火车始发站信息 */ departure_stop: RailStop; /** * 火车到站信息 */ arrival_stop: RailStop; /** * 仓位及价格信息 */ spaces: Space[]; } interface Alter { /** * 备选方案ID */ id: string; /** * 备选线路名称 */ name: string; } interface ViaStop { /** * 途径车站点ID */ id: string; /** * 站点经纬度信息 */ location: LngLat; /** * 途径车站点名称 */ name: string; /** * 途径站点的进站时间,如大于24:00,则表示跨天 */ time: number; /** * 途径站点的停靠时间,单位:分钟 */ wait: number; } interface RailwayDetailsExt extends RailwayDetailsBase { /** * 途经站点信息 */ via_stops: ViaStop[]; /** * 途经站点数量 */ via_num: number; /** * 聚合的备选方案 */ alters: Alter[]; } type RailwayDetails = RailwayDetailsBase | RailwayDetailsExt; interface RailwaySegment extends SegmentCommon { /** * 换乘动作类型 */ transit_mode: 'RAILWAY'; /** * 此换乘段导航信息 */ transit: RailwayDetails; } type Segment = WalkSegment | TaxiSegment | TransitSegment | RailwaySegment; interface TransferPlan { /** * 此换乘方案价格,单位:元 */ cost: number; /** * 预期时间,单位:秒 */ time: number; /** * 是否夜间线路 */ nightLine: boolean; /** * 换乘路段列表,以每次换乘动结束作为分段点,将整个换乘方案分隔成若干 Segment(换乘路段) */ segments: Segment[]; /** * 此方案公交行驶距离,单位:米 */ transit_distance: number; /** * 此方案火车行驶距离,单位:米 */ railway_distance: number; /** * 此方案总步行距离,单位:米 */ walking_distance: number; /** * 此方案出租车行驶距离,单位:米 */ taxi_distance: number; /** * 此换乘方案全程距离,单位:米 */ distance: number; /** * 此换乘方案的路径坐标集合 */ path: LngLat[]; } interface Poi { location: LngLat; name: string; type: 'start' | 'end'; } interface SearchResultCommon { /** * 成功状态说明 */ info: string; /** * 公交换乘起点坐标 */ origin: LngLat; /** * 公交换乘终点坐标 */ destination: LngLat; /** * 出租车费用,单位:元 */ taxi_cost: number; /** * 换乘方案列表 */ plans: TransferPlan[]; } interface SearchResultBase extends SearchResultCommon { /** * 公交换乘起点 */ start?: Poi; /** * 公交换乘终点 */ end?: Poi; } interface SearchResultExt extends SearchResultCommon { /** * 公交换乘起点 */ start: PlaceSearch.PoiExt; /** * 公交换乘终点 */ end: PlaceSearch.PoiExt; /** * 公交换乘起点名称 */ originName: string; /** * 公交换乘终点名称 */ destinationName: string; } type SearchResult = SearchResultBase | SearchResultExt; type SearchStatus = 'complete' | 'error' | 'no_data'; } class Transfer extends EventEmitter { /** * 公交换乘服务 * @param options 构造函数选项 */ constructor(options: Transfer.Options); /** * 根据起点和终点坐标,进行公交换乘查询 * @param origin 起点坐标 * @param destination 终点坐标 * @param callback 查询回调 */ search( origin: LocationValue, destination: LocationValue, callback?: (status: Transfer.SearchStatus, result: string | Transfer.SearchResultBase) => void ): void; /** * 根据起点和终点坐标,进行公交换乘查询 * @param path 路径名称关键字 * @param callback 路径回调 */ search( path: [Transfer.SearchPoint, Transfer.SearchPoint], callback?: (status: Transfer.SearchStatus, result: string | Transfer.SearchResultExt) => void ): void; /** * 设置公交换乘策略 * @param policy 公交换乘策略 */ setPolicy(policy?: TransferPolicy): void; /** * 设置公交换乘查询的城市 * @param city 城市名称、城市区号、电话区号 */ setCity(city?: string): void; /** * 设置公交换乘查询的城市 * @param city 城市名称、城市区号、电话区号 */ setCityd(city?: string): void; /** * 设置公交路径规划出发时间 * @param time 时间 * @param date 日期 */ leaveAt(time?: string, date?: string): void; /** * 清除结果显示 */ clear(): void; /** * 唤起高德地图客户端公交路径规划 * @param obj 唤起参数 */ searchOnAMAP(obj: { /** * 起点坐标 */ origin: LocationValue, /** * 起点名称 */ originName?: string, /** * 终点坐标 */ destination: LocationValue, /** * 终点名称 */ destinationName?: string }): void; // internal open(): void; close(): void; } }
the_stack
import { Lambda } from 'aws-sdk'; import { REQUIRED_BY_CFN } from '../../../lib/api/hotswap/s3-bucket-deployments'; import * as setup from './hotswap-test-setup'; let mockLambdaInvoke: (params: Lambda.Types.InvocationRequest) => Lambda.Types.InvocationResponse; let hotswapMockSdkProvider: setup.HotswapMockSdkProvider; const payloadWithoutCustomResProps = { RequestType: 'Update', ResponseURL: REQUIRED_BY_CFN, PhysicalResourceId: REQUIRED_BY_CFN, StackId: REQUIRED_BY_CFN, RequestId: REQUIRED_BY_CFN, LogicalResourceId: REQUIRED_BY_CFN, }; beforeEach(() => { hotswapMockSdkProvider = setup.setupHotswapTests(); mockLambdaInvoke = jest.fn(); hotswapMockSdkProvider.setInvokeLambdaMock(mockLambdaInvoke); }); test('calls the lambdaInvoke() API when it receives only an asset difference in an S3 bucket deployment and evaluates CFN expressions in S3 Deployment Properties', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { S3Deployment: { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: 'a-lambda-arn', SourceBucketNames: ['src-bucket'], SourceObjectKeys: ['src-key-old'], DestinationBucketName: 'dest-bucket', DestinationBucketKeyPrefix: 'my-key/some-old-prefix', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { S3Deployment: { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: 'a-lambda-arn', SourceBucketNames: ['src-bucket'], SourceObjectKeys: { 'Fn::Split': [ '-', 'key1-key2-key3', ], }, DestinationBucketName: 'dest-bucket', DestinationBucketKeyPrefix: 'my-key/some-new-prefix', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockLambdaInvoke).toHaveBeenCalledWith({ FunctionName: 'a-lambda-arn', Payload: JSON.stringify({ ...payloadWithoutCustomResProps, ResourceProperties: { SourceBucketNames: ['src-bucket'], SourceObjectKeys: ['key1', 'key2', 'key3'], DestinationBucketName: 'dest-bucket', DestinationBucketKeyPrefix: 'my-key/some-new-prefix', }, }), }); }); test('does not call the invoke() API when a resource with type that is not Custom::CDKBucketDeployment but has the same properties is changed', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { S3Deployment: { Type: 'Custom::NotCDKBucketDeployment', Properties: { SourceObjectKeys: ['src-key-old'], }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { S3Deployment: { Type: 'Custom::NotCDKBucketDeployment', Properties: { SourceObjectKeys: ['src-key-new'], }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockLambdaInvoke).not.toHaveBeenCalled(); }); test('does not call the invokeLambda() api if the updated Policy has no Roles', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Parameters: { WebsiteBucketParamOld: { Type: 'String' }, WebsiteBucketParamNew: { Type: 'String' }, }, Resources: { S3Deployment: { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: 'a-lambda-arn', SourceObjectKeys: ['src-key-old'], }, }, Policy: { Type: 'AWS::IAM::Policy', Properties: { PolicyName: 'my-policy', PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { Ref: 'WebsiteBucketParamOld', }, }, ], }, }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Parameters: { WebsiteBucketParamOld: { Type: 'String' }, WebsiteBucketParamNew: { Type: 'String' }, }, Resources: { S3Deployment: { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: 'a-lambda-arn', SourceObjectKeys: ['src-key-new'], }, }, Policy: { Type: 'AWS::IAM::Policy', Properties: { PolicyName: 'my-policy', PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { Ref: 'WebsiteBucketParamNew', }, }, ], }, }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockLambdaInvoke).not.toHaveBeenCalled(); }); test('throws an error when the serviceToken fails evaluation in the template', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { S3Deployment: { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: { Ref: 'BadLamba', }, SourceBucketNames: ['src-bucket'], SourceObjectKeys: ['src-key-old'], DestinationBucketName: 'dest-bucket', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { S3Deployment: { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: { Ref: 'BadLamba', }, SourceBucketNames: ['src-bucket'], SourceObjectKeys: ['src-key-new'], DestinationBucketName: 'dest-bucket', }, }, }, }, }); // WHEN await expect(() => hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact), ).rejects.toThrow(/Parameter or resource 'BadLamba' could not be found for evaluation/); expect(mockLambdaInvoke).not.toHaveBeenCalled(); }); describe('old-style synthesis', () => { const parameters = { WebsiteBucketParamOld: { Type: 'String' }, WebsiteBucketParamNew: { Type: 'String' }, DifferentBucketParamNew: { Type: 'String' }, }; const serviceRole = { Type: 'AWS::IAM::Role', Properties: { AssumeRolePolicyDocument: { Statement: [ { Action: 'sts:AssumeRole', Effect: 'Allow', Principal: { Service: 'lambda.amazonaws.com', }, }, ], Version: '2012-10-17', }, }, }; const policyOld = { Type: 'AWS::IAM::Policy', Properties: { PolicyName: 'my-policy-old', Roles: [ { Ref: 'ServiceRole' }, ], PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { Ref: 'WebsiteBucketParamOld', }, }, ], }, }, }; const policyNew = { Type: 'AWS::IAM::Policy', Properties: { PolicyName: 'my-policy-new', Roles: [ { Ref: 'ServiceRole' }, ], PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { Ref: 'WebsiteBucketParamNew', }, }, ], }, }, }; const policy2Old = { Type: 'AWS::IAM::Policy', Properties: { PolicyName: 'my-policy-old-2', Roles: [ { Ref: 'ServiceRole' }, ], PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { Ref: 'WebsiteBucketParamOld', }, }, ], }, }, }; const policy2New = { Type: 'AWS::IAM::Policy', Properties: { PolicyName: 'my-policy-new-2', Roles: [ { Ref: 'ServiceRole2' }, ], PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { Ref: 'DifferentBucketParamOld', }, }, ], }, }, }; const deploymentLambda = { Type: 'AWS::Lambda::Function', Role: { 'Fn::GetAtt': [ 'ServiceRole', 'Arn', ], }, }; const s3DeploymentOld = { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: { 'Fn::GetAtt': [ 'S3DeploymentLambda', 'Arn', ], }, SourceBucketNames: ['src-bucket-old'], SourceObjectKeys: ['src-key-old'], DestinationBucketName: 'WebsiteBucketOld', }, }; const s3DeploymentNew = { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: { 'Fn::GetAtt': [ 'S3DeploymentLambda', 'Arn', ], }, SourceBucketNames: ['src-bucket-new'], SourceObjectKeys: ['src-key-new'], DestinationBucketName: 'WebsiteBucketNew', }, }; beforeEach(() => { setup.pushStackResourceSummaries( setup.stackSummaryOf('S3DeploymentLambda', 'AWS::Lambda::Function', 'my-deployment-lambda'), setup.stackSummaryOf('ServiceRole', 'AWS::IAM::Role', 'my-service-role'), ); }); test('calls the lambdaInvoke() API when it receives an asset difference in an S3 bucket deployment and an IAM Policy difference using old-style synthesis', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { Parameters: parameters, ServiceRole: serviceRole, Policy: policyOld, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentOld, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { Parameters: parameters, ServiceRole: serviceRole, Policy: policyNew, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentNew, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact, { WebsiteBucketParamOld: 'WebsiteBucketOld', WebsiteBucketParamNew: 'WebsiteBucketNew' }); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockLambdaInvoke).toHaveBeenCalledWith({ FunctionName: 'arn:aws:lambda:here:123456789012:function:my-deployment-lambda', Payload: JSON.stringify({ ...payloadWithoutCustomResProps, ResourceProperties: { SourceBucketNames: ['src-bucket-new'], SourceObjectKeys: ['src-key-new'], DestinationBucketName: 'WebsiteBucketNew', }, }), }); }); test('does not call the lambdaInvoke() API when the difference in the S3 deployment is referred to in one IAM policy change but not another', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { ServiceRole: serviceRole, Policy1: policyOld, Policy2: policy2Old, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentOld, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { ServiceRole: serviceRole, Policy1: policyNew, Policy2: { Properties: { Roles: [ { Ref: 'ServiceRole' }, 'different-role', ], PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ 'DifferentBucketNew', 'Arn', ], }, }, ], }, }, }, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentNew, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockLambdaInvoke).not.toHaveBeenCalled(); }); test('does not call the lambdaInvoke() API when the lambda that references the role is referred to by something other than an S3 deployment', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { ServiceRole: serviceRole, Policy: policyOld, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentOld, Endpoint: { Type: 'AWS::Lambda::Permission', Properties: { Action: 'lambda:InvokeFunction', FunctionName: { 'Fn::GetAtt': [ 'S3DeploymentLambda', 'Arn', ], }, Principal: 'apigateway.amazonaws.com', }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { ServiceRole: serviceRole, Policy: policyNew, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentNew, Endpoint: { Type: 'AWS::Lambda::Permission', Properties: { Action: 'lambda:InvokeFunction', FunctionName: { 'Fn::GetAtt': [ 'S3DeploymentLambda', 'Arn', ], }, Principal: 'apigateway.amazonaws.com', }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockLambdaInvoke).not.toHaveBeenCalled(); }); test('calls the lambdaInvoke() API when it receives an asset difference in two S3 bucket deployments and IAM Policy differences using old-style synthesis', async () => { // GIVEN const s3Deployment2Old = { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: { 'Fn::GetAtt': [ 'S3DeploymentLambda2', 'Arn', ], }, SourceBucketNames: ['src-bucket-old'], SourceObjectKeys: ['src-key-old'], DestinationBucketName: 'DifferentBucketOld', }, }; const s3Deployment2New = { Type: 'Custom::CDKBucketDeployment', Properties: { ServiceToken: { 'Fn::GetAtt': [ 'S3DeploymentLambda2', 'Arn', ], }, SourceBucketNames: ['src-bucket-new'], SourceObjectKeys: ['src-key-new'], DestinationBucketName: 'DifferentBucketNew', }, }; setup.setCurrentCfnStackTemplate({ Resources: { ServiceRole: serviceRole, ServiceRole2: serviceRole, Policy1: policyOld, Policy2: policy2Old, S3DeploymentLambda: deploymentLambda, S3DeploymentLambda2: deploymentLambda, S3Deployment: s3DeploymentOld, S3Deployment2: s3Deployment2Old, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { Parameters: parameters, ServiceRole: serviceRole, ServiceRole2: serviceRole, Policy1: policyNew, Policy2: policy2New, S3DeploymentLambda: deploymentLambda, S3DeploymentLambda2: deploymentLambda, S3Deployment: s3DeploymentNew, S3Deployment2: s3Deployment2New, }, }, }); // WHEN setup.pushStackResourceSummaries( setup.stackSummaryOf('S3DeploymentLambda2', 'AWS::Lambda::Function', 'my-deployment-lambda-2'), setup.stackSummaryOf('ServiceRole2', 'AWS::IAM::Role', 'my-service-role-2'), ); const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact, { WebsiteBucketParamOld: 'WebsiteBucketOld', WebsiteBucketParamNew: 'WebsiteBucketNew', DifferentBucketParamNew: 'WebsiteBucketNew', }); // THEN expect(deployStackResult).not.toBeUndefined(); expect(mockLambdaInvoke).toHaveBeenCalledWith({ FunctionName: 'arn:aws:lambda:here:123456789012:function:my-deployment-lambda', Payload: JSON.stringify({ ...payloadWithoutCustomResProps, ResourceProperties: { SourceBucketNames: ['src-bucket-new'], SourceObjectKeys: ['src-key-new'], DestinationBucketName: 'WebsiteBucketNew', }, }), }); expect(mockLambdaInvoke).toHaveBeenCalledWith({ FunctionName: 'arn:aws:lambda:here:123456789012:function:my-deployment-lambda-2', Payload: JSON.stringify({ ...payloadWithoutCustomResProps, ResourceProperties: { SourceBucketNames: ['src-bucket-new'], SourceObjectKeys: ['src-key-new'], DestinationBucketName: 'DifferentBucketNew', }, }), }); }); test('does not call the lambdaInvoke() API when it receives an asset difference in an S3 bucket deployment that references two different policies', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { ServiceRole: serviceRole, Policy1: policyOld, Policy2: policy2Old, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentOld, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { ServiceRole: serviceRole, Policy1: policyNew, Policy2: { Properties: { Roles: [ { Ref: 'ServiceRole' }, ], PolicyDocument: { Statement: [ { Action: ['s3:GetObject*'], Effect: 'Allow', Resource: { 'Fn::GetAtt': [ 'DifferentBucketNew', 'Arn', ], }, }, ], }, }, }, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentNew, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockLambdaInvoke).not.toHaveBeenCalled(); }); test('does not call the lambdaInvoke() API when a policy is referenced by a resource that is not an S3 deployment', async () => { // GIVEN setup.setCurrentCfnStackTemplate({ Resources: { ServiceRole: serviceRole, Policy1: policyOld, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentOld, NotADeployment: { Type: 'AWS::Not::S3Deployment', Properties: { Prop: { Ref: 'ServiceRole', }, }, }, }, }); const cdkStackArtifact = setup.cdkStackArtifactOf({ template: { Resources: { ServiceRole: serviceRole, Policy1: policyNew, S3DeploymentLambda: deploymentLambda, S3Deployment: s3DeploymentNew, NotADeployment: { Type: 'AWS::Not::S3Deployment', Properties: { Prop: { Ref: 'ServiceRole', }, }, }, }, }, }); // WHEN const deployStackResult = await hotswapMockSdkProvider.tryHotswapDeployment(cdkStackArtifact); // THEN expect(deployStackResult).toBeUndefined(); expect(mockLambdaInvoke).not.toHaveBeenCalled(); }); });
the_stack
import { Production } from '../production'; import { WorldInterface } from './worldInterface'; import { Unit } from '../units/unit'; import { GameModel } from '../gameModel'; import { BuyAction, BuyAndUnlockAction, UpAction, UpHire, UpSpecial } from '../units/action'; import { Cost } from '../cost'; import { TypeList } from '../typeList'; import { World } from '../world'; import { TogableProduction } from '../units/togableProductions'; export class Machine implements WorldInterface { // Machinery composterStation: Unit refineryStation: Unit laserStation: Unit hydroFarm: Unit plantingMachine: Unit mine: Unit sandDigger: Unit loggingMachine: Unit honeyMaker: Unit burningGlass: Unit iceCollector: Unit iceCompacter: Unit listMachinery = new Array<Unit>() machineryProd = new Decimal(500) machineryCost = new Decimal(-150) price1 = new Decimal(1E5) price2 = new Decimal(6E4) price3 = new Decimal(3E4) constructor(public game: GameModel) { } public declareStuff() { this.composterStation = new Unit(this.game, "composterStation", "Composter Station", "Turn wood into soil.") this.refineryStation = new Unit(this.game, "refineryStation", "Refinery Station", "Turn soil into sand.") this.laserStation = new Unit(this.game, "laserStation", "Laser Station", "Yield crystal.") this.hydroFarm = new Unit(this.game, "hydroFarm", "Hydroponic Farm", "Yield fungus.") this.plantingMachine = new Unit(this.game, "plantingMac", "Planting Machine", "Yield wood.") this.sandDigger = new Unit(this.game, "sandDigger", "Sand Digger", "Yield sand.") this.loggingMachine = new Unit(this.game, "loggingMachine", "Logging Machine", "Yield wood.") this.mine = new Unit(this.game, "mine", "Mine", "Yield crystal.") this.honeyMaker = new Unit(this.game, "honeyMaker", "Honey Maker", "Automate the making of honey. Only bees know how it works.") this.iceCompacter = new Unit(this.game, "iceC", "Ice Compacter", "Ice Compacter is a machine that compacts ice into crystal.") this.iceCollector = new Unit(this.game, "iceK", "Water Tank", "A tank of water.") this.burningGlass = new Unit(this.game, "burningGlass", "Burning Lens", "A large convex lens used to concentrate sun's rays. This machine melts ice faster than anything else.") this.listMachinery = new Array<Unit>() this.listMachinery.push(this.composterStation) this.listMachinery.push(this.refineryStation) this.listMachinery.push(this.laserStation) this.listMachinery.push(this.hydroFarm) this.listMachinery.push(this.plantingMachine) this.listMachinery.push(this.sandDigger) this.listMachinery.push(this.loggingMachine) this.listMachinery.push(this.mine) this.listMachinery.push(this.honeyMaker) this.listMachinery.push(this.iceCompacter) this.listMachinery.push(this.iceCollector) this.listMachinery.push(this.burningGlass) this.game.lists.push(new TypeList("Machinery", this.listMachinery)) } public initStuff() { // Composter // this.composterStation.types = [Type.Machinery] this.composterStation.actions.push(new BuyAction(this.game, this.composterStation, [ new Cost(this.game.baseWorld.wood, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.fungus, this.price2, this.game.buyExp), new Cost(this.game.baseWorld.crystal, this.price3, this.game.buyExp) ] )) this.game.baseWorld.soil.addProductor(new Production(this.composterStation, this.machineryProd)) this.game.baseWorld.wood.addProductor(new Production(this.composterStation, this.machineryCost)) // Refinery // this.refineryStation.types = [Type.Machinery] this.refineryStation.actions.push(new BuyAction(this.game, this.refineryStation, [ new Cost(this.game.baseWorld.soil, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.wood, this.price2, this.game.buyExp), new Cost(this.game.baseWorld.fungus, this.price3, this.game.buyExp) ] )) this.game.baseWorld.sand.addProductor(new Production(this.refineryStation, this.machineryProd)) this.game.baseWorld.soil.addProductor(new Production(this.refineryStation, this.machineryCost)) // Laser // this.laserStation.types = [Type.Machinery] this.laserStation.actions.push(new BuyAction(this.game, this.laserStation, [ new Cost(this.game.baseWorld.sand, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.soil, this.price2, this.game.buyExp), new Cost(this.game.baseWorld.wood, this.price3, this.game.buyExp) ] )) this.game.baseWorld.crystal.addProductor(new Production(this.laserStation, this.machineryProd)) this.game.baseWorld.sand.addProductor(new Production(this.laserStation, this.machineryCost)) // Hydroponic Farm // this.hydroFarm.types = [Type.Machinery] this.hydroFarm.actions.push(new BuyAction(this.game, this.hydroFarm, [ new Cost(this.game.baseWorld.crystal, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.sand, this.price2, this.game.buyExp), new Cost(this.game.baseWorld.soil, this.price3, this.game.buyExp) ] )) this.game.baseWorld.fungus.addProductor(new Production(this.hydroFarm, this.machineryProd)) this.game.baseWorld.crystal.addProductor(new Production(this.hydroFarm, this.machineryCost)) // Planting Machine // this.plantingMachine.types = [Type.Machinery] this.plantingMachine.actions.push(new BuyAction(this.game, this.plantingMachine, [ new Cost(this.game.baseWorld.fungus, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.crystal, this.price2, this.game.buyExp), new Cost(this.game.baseWorld.sand, this.price3, this.game.buyExp) ] )) this.game.baseWorld.wood.addProductor(new Production(this.plantingMachine, this.machineryProd)) this.game.baseWorld.fungus.addProductor(new Production(this.plantingMachine, this.machineryCost)) // Not always avaiable const machineryProd2 = this.machineryProd.div(2) // Sand digger this.sandDigger.avabileBaseWorld = false // this.sandDigger.types = [Type.Machinery] this.sandDigger.actions.push(new BuyAction(this.game, this.sandDigger, [ new Cost(this.game.baseWorld.wood, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.crystal, this.price2, this.game.buyExp) ] )) this.game.baseWorld.sand.addProductor(new Production(this.sandDigger, machineryProd2)) // Wood this.loggingMachine.avabileBaseWorld = false // this.loggingMachine.types = [Type.Machinery] this.loggingMachine.actions.push(new BuyAction(this.game, this.loggingMachine, [ new Cost(this.game.baseWorld.wood, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.crystal, this.price2, this.game.buyExp) ] )) this.game.baseWorld.wood.addProductor(new Production(this.loggingMachine, machineryProd2)) // Mine this.mine.avabileBaseWorld = false // this.mine.types = [Type.Machinery] this.mine.actions.push(new BuyAction(this.game, this.mine, [ new Cost(this.game.baseWorld.wood, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.soil, this.price2, this.game.buyExp) ] )) this.game.baseWorld.crystal.addProductor(new Production(this.mine, machineryProd2)) // Honey this.honeyMaker.avabileBaseWorld = false // this.honeyMaker.types = [Type.Machinery] this.honeyMaker.actions.push(new BuyAction(this.game, this.honeyMaker, [ new Cost(this.game.baseWorld.nectar, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.honey, this.price2, this.game.buyExp) ] )) this.game.baseWorld.honey.addProductor(new Production(this.honeyMaker, this.machineryProd)) this.game.baseWorld.nectar.addProductor(new Production(this.honeyMaker, this.machineryCost)) // Ice Compacter this.iceCompacter.avabileBaseWorld = false // this.iceCompacter.types = [Type.Machinery] this.iceCompacter.actions.push(new BuyAction(this.game, this.iceCompacter, [ new Cost(this.game.baseWorld.crystal, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.wood, this.price2, this.game.buyExp), new Cost(this.game.baseWorld.soil, this.price3, this.game.buyExp) ] )) this.game.baseWorld.crystal.addProductor(new Production(this.iceCompacter, this.machineryProd)) this.game.baseWorld.ice.addProductor(new Production(this.iceCompacter, this.machineryCost)) // Ice Collector this.iceCollector.avabileBaseWorld = false // this.iceCollector.types = [Type.Machinery] this.iceCollector.actions.push(new BuyAction(this.game, this.iceCollector, [ new Cost(this.game.baseWorld.wood, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.soil, this.price2, this.game.buyExp) ] )) this.game.baseWorld.crystal.addProductor(new Production(this.iceCollector, machineryProd2)) // Ice Burning Glass this.burningGlass.avabileBaseWorld = false // this.burningGlass.types = [Type.Machinery] this.burningGlass.actions.push(new BuyAction(this.game, this.burningGlass, [ new Cost(this.game.baseWorld.crystal, this.price1, this.game.buyExp), new Cost(this.game.baseWorld.wood, this.price2, this.game.buyExp) ] )) this.game.baseWorld.ice.addProductor(new Production(this.burningGlass, machineryProd2.times(-10))) } public addWorld() { World.worldPrefix.push( new World(this.game, "Mechanized", "", [], [], [], [], [], [ [this.composterStation, new Decimal(0.2)], [this.refineryStation, new Decimal(0.2)], [this.laserStation, new Decimal(0.2)], [this.hydroFarm, new Decimal(0.2)], [this.plantingMachine, new Decimal(0.2)] ], new Decimal(1) )) World.worldSuffix.push( new World(this.game, "of Machine", "", [], [], [], [], [], [ [this.composterStation, new Decimal(0.2)], [this.refineryStation, new Decimal(0.2)], [this.laserStation, new Decimal(0.2)], [this.hydroFarm, new Decimal(0.2)], [this.plantingMachine, new Decimal(0.2)] ], new Decimal(1) )) } }
the_stack
import Point from "@mapbox/point-geometry"; import UnitBezier from "@mapbox/unitbezier"; // @ts-ignore import polylabel from "polylabel"; import { ArrayAttr, AttrOption, FontAttr, FontAttrOptions, NumberAttr, StringAttr, TextAttr, TextAttrOptions, } from "./attribute"; import { Label, Layout } from "./labeler"; import { lineCells, simpleLabel } from "./line"; import { linebreak } from "./text"; import { Bbox, Feature, GeomType } from "./tilecache"; // https://bugs.webkit.org/show_bug.cgi?id=230751 const MAX_VERTICES_PER_DRAW_CALL = 5400; export interface PaintSymbolizer { before?(ctx: CanvasRenderingContext2D, z: number): void; draw( ctx: CanvasRenderingContext2D, geom: Point[][], z: number, feature: Feature ): void; } export enum Justify { Left = 1, Center = 2, Right = 3, } export enum TextPlacements { N = 1, NE = 2, E = 3, SE = 4, S = 5, SW = 6, W = 7, NW = 8, } export interface DrawExtra { justify: Justify; } export interface LabelSymbolizer { /* the symbolizer can, but does not need to, inspect index to determine the right position * if return undefined, no label is added * return a label, but if the label collides it is not added */ place(layout: Layout, geom: Point[][], feature: Feature): Label[] | undefined; } export const createPattern = ( width: number, height: number, fn: (canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D) => void ) => { const canvas = document.createElement("canvas"); const ctx = canvas.getContext("2d"); canvas.width = width; canvas.height = height; if (ctx !== null) fn(canvas, ctx); return canvas; }; export class PolygonSymbolizer implements PaintSymbolizer { pattern?: CanvasImageSource; fill: StringAttr; opacity: NumberAttr; stroke: StringAttr; width: NumberAttr; per_feature: boolean; do_stroke: boolean; constructor(options: { pattern?: CanvasImageSource; fill?: AttrOption<string>; opacity?: AttrOption<number>; stroke?: AttrOption<string>; width?: AttrOption<number>; per_feature?: boolean; }) { this.pattern = options.pattern; this.fill = new StringAttr(options.fill, "black"); this.opacity = new NumberAttr(options.opacity, 1); this.stroke = new StringAttr(options.stroke, "black"); this.width = new NumberAttr(options.width, 0); this.per_feature = (this.fill.per_feature || this.opacity.per_feature || this.stroke.per_feature || this.width.per_feature || options.per_feature) ?? false; this.do_stroke = false; } public before(ctx: CanvasRenderingContext2D, z: number) { if (!this.per_feature) { ctx.globalAlpha = this.opacity.get(z); ctx.fillStyle = this.fill.get(z); ctx.strokeStyle = this.stroke.get(z); let width = this.width.get(z); if (width > 0) this.do_stroke = true; ctx.lineWidth = width; } if (this.pattern) { const patten = ctx.createPattern(this.pattern, "repeat"); if (patten) ctx.fillStyle = patten; } } public draw( ctx: CanvasRenderingContext2D, geom: Point[][], z: number, f: Feature ) { var do_stroke = false; if (this.per_feature) { ctx.globalAlpha = this.opacity.get(z, f); ctx.fillStyle = this.fill.get(z, f); var width = this.width.get(z, f); if (width) { do_stroke = true; ctx.strokeStyle = this.stroke.get(z, f); ctx.lineWidth = width; } } let drawPath = () => { ctx.fill(); if (do_stroke || this.do_stroke) { ctx.stroke(); } }; var vertices_in_path = 0; ctx.beginPath(); for (var poly of geom) { if (vertices_in_path + poly.length > MAX_VERTICES_PER_DRAW_CALL) { drawPath(); vertices_in_path = 0; ctx.beginPath(); } for (var p = 0; p < poly.length - 1; p++) { let pt = poly[p]; if (p == 0) ctx.moveTo(pt.x, pt.y); else ctx.lineTo(pt.x, pt.y); } vertices_in_path += poly.length; } if (vertices_in_path > 0) drawPath(); } } export function arr(base: number, a: number[]): (z: number) => number { return (z) => { let b = z - base; if (b >= 0 && b < a.length) { return a[b]; } return 0; }; } function getStopIndex(input: number, stops: number[][]): number { let idx = 0; while (stops[idx + 1][0] < input) idx++; return idx; } function interpolate(factor: number, start: number, end: number): number { return factor * (end - start) + start; } function computeInterpolationFactor( z: number, idx: number, base: number, stops: number[][] ): number { const difference = stops[idx + 1][0] - stops[idx][0]; const progress = z - stops[idx][0]; if (difference === 0) return 0; else if (base === 1) return progress / difference; else return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1); } export function exp(base: number, stops: number[][]): (z: number) => number { return (z) => { if (stops.length < 1) return 0; if (z <= stops[0][0]) return stops[0][1]; if (z >= stops[stops.length - 1][0]) return stops[stops.length - 1][1]; const idx = getStopIndex(z, stops); const factor = computeInterpolationFactor(z, idx, base, stops); return interpolate(factor, stops[idx][1], stops[idx + 1][1]); }; } export type Stop = [number, number] | [number, string] | [number, boolean]; export function step( output0: number | string | boolean, stops: Stop[] ): (z: number) => number | string | boolean { // Step computes discrete results by evaluating a piecewise-constant // function defined by stops. // Returns the output value of the stop with a stop input value just less than // the input one. If the input value is less than the input of the first stop, // output0 is returned return (z) => { if (stops.length < 1) return 0; let retval = output0; for (let i = 0; i < stops.length; i++) { if (z >= stops[i][0]) retval = stops[i][1]; } return retval; }; } export function linear(stops: number[][]): (z: number) => number { return exp(1, stops); } export function cubicBezier( x1: number, y1: number, x2: number, y2: number, stops: number[][] ): (z: number) => number { return (z) => { if (stops.length < 1) return 0; const bezier = new UnitBezier(x1, y1, x2, y2); const idx = getStopIndex(z, stops); const factor = bezier.solve(computeInterpolationFactor(z, idx, 1, stops)); return interpolate(factor, stops[idx][1], stops[idx + 1][1]); }; } function isFunction(obj: any) { return !!(obj && obj.constructor && obj.call && obj.apply); } export class LineSymbolizer implements PaintSymbolizer { color: StringAttr; width: NumberAttr; opacity: NumberAttr; dash: ArrayAttr<number> | null; dashColor: StringAttr; dashWidth: NumberAttr; skip: boolean; per_feature: boolean; lineCap: StringAttr<CanvasLineCap>; lineJoin: StringAttr<CanvasLineJoin>; constructor(options: { color?: AttrOption<string>; width?: AttrOption<number>; opacity?: AttrOption<number>; dash?: number[]; dashColor?: AttrOption<string>; dashWidth?: AttrOption<number>; skip?: boolean; per_feature?: boolean; lineCap?: AttrOption<CanvasLineCap>; lineJoin?: AttrOption<CanvasLineJoin>; }) { this.color = new StringAttr(options.color, "black"); this.width = new NumberAttr(options.width); this.opacity = new NumberAttr(options.opacity); this.dash = options.dash ? new ArrayAttr(options.dash) : null; this.dashColor = new StringAttr(options.dashColor, "black"); this.dashWidth = new NumberAttr(options.dashWidth, 1.0); this.lineCap = new StringAttr(options.lineCap, "butt"); this.lineJoin = new StringAttr(options.lineJoin, "miter"); this.skip = false; this.per_feature = !!( this.dash?.per_feature || this.color.per_feature || this.opacity.per_feature || this.width.per_feature || this.lineCap.per_feature || this.lineJoin.per_feature || options.per_feature ); } public before(ctx: CanvasRenderingContext2D, z: number) { if (!this.per_feature) { ctx.strokeStyle = this.color.get(z); ctx.lineWidth = this.width.get(z); ctx.globalAlpha = this.opacity.get(z); ctx.lineCap = this.lineCap.get(z); ctx.lineJoin = this.lineJoin.get(z); } } public draw( ctx: CanvasRenderingContext2D, geom: Point[][], z: number, f: Feature ) { if (this.skip) return; let strokePath = () => { if (this.per_feature) { ctx.globalAlpha = this.opacity.get(z, f); ctx.lineCap = this.lineCap.get(z, f); ctx.lineJoin = this.lineJoin.get(z, f); } if (this.dash) { ctx.save(); if (this.per_feature) { ctx.lineWidth = this.dashWidth.get(z, f); ctx.strokeStyle = this.dashColor.get(z, f); ctx.setLineDash(this.dash.get(z, f)); } else { ctx.setLineDash(this.dash.get(z)); } ctx.stroke(); ctx.restore(); } else { ctx.save(); if (this.per_feature) { ctx.lineWidth = this.width.get(z, f); ctx.strokeStyle = this.color.get(z, f); } ctx.stroke(); ctx.restore(); } }; var vertices_in_path = 0; ctx.beginPath(); for (var ls of geom) { if (vertices_in_path + ls.length > MAX_VERTICES_PER_DRAW_CALL) { strokePath(); vertices_in_path = 0; ctx.beginPath(); } for (var p = 0; p < ls.length; p++) { let pt = ls[p]; if (p == 0) ctx.moveTo(pt.x, pt.y); else ctx.lineTo(pt.x, pt.y); } vertices_in_path += ls.length; } if (vertices_in_path > 0) strokePath(); } } interface Sprite { canvas: CanvasImageSource; x: number; y: number; w: number; h: number; } export interface IconSymbolizerOptions { name: string; sprites?: Map<string, Sprite>; } export class IconSymbolizer implements LabelSymbolizer { name: string; sprites: Map<string, Sprite>; constructor(options: IconSymbolizerOptions) { this.name = options.name; this.sprites = options.sprites ?? new Map(); } public place(layout: Layout, geom: Point[][], feature: Feature) { let pt = geom[0]; let a = new Point(geom[0][0].x, geom[0][0].y); let bbox = { minX: a.x - 32, minY: a.y - 32, maxX: a.x + 32, maxY: a.y + 32, }; let draw = (ctx: CanvasRenderingContext2D) => { ctx.globalAlpha = 1; let r = this.sprites.get(this.name); if (r) ctx.drawImage(r.canvas, r.x, r.y, r.w, r.h, -8, -8, r.w, r.h); }; return [{ anchor: a, bboxes: [bbox], draw: draw }]; } } export class CircleSymbolizer implements LabelSymbolizer, PaintSymbolizer { radius: NumberAttr; fill: StringAttr; stroke: StringAttr; width: NumberAttr; opacity: NumberAttr; constructor(options: { radius?: AttrOption<number>; fill?: AttrOption<string>; stroke?: AttrOption<string>; width?: AttrOption<number>; opacity?: AttrOption<number>; }) { this.radius = new NumberAttr(options.radius, 3); this.fill = new StringAttr(options.fill, "black"); this.stroke = new StringAttr(options.stroke, "white"); this.width = new NumberAttr(options.width, 0); this.opacity = new NumberAttr(options.opacity); } public draw( ctx: CanvasRenderingContext2D, geom: Point[][], z: number, f: Feature ) { ctx.globalAlpha = this.opacity.get(z, f); let radius = this.radius.get(z, f); let width = this.width.get(z, f); if (width > 0) { ctx.fillStyle = this.stroke.get(z, f); ctx.beginPath(); ctx.arc(geom[0][0].x, geom[0][0].y, radius + width, 0, 2 * Math.PI); ctx.fill(); } ctx.fillStyle = this.fill.get(z, f); ctx.beginPath(); ctx.arc(geom[0][0].x, geom[0][0].y, radius, 0, 2 * Math.PI); ctx.fill(); } public place(layout: Layout, geom: Point[][], feature: Feature) { let pt = geom[0]; let a = new Point(geom[0][0].x, geom[0][0].y); let radius = this.radius.get(layout.zoom, feature); let bbox = { minX: a.x - radius, minY: a.y - radius, maxX: a.x + radius, maxY: a.y + radius, }; let draw = (ctx: CanvasRenderingContext2D) => { this.draw(ctx, [[new Point(0, 0)]], layout.zoom, feature); }; return [{ anchor: a, bboxes: [bbox], draw }]; } } export class ShieldSymbolizer implements LabelSymbolizer { font: FontAttr; text: TextAttr; background: StringAttr; fill: StringAttr; padding: NumberAttr; constructor( options: { fill?: AttrOption<string>; background?: AttrOption<string>; padding?: AttrOption<number>; } & FontAttrOptions & TextAttrOptions ) { this.font = new FontAttr(options); this.text = new TextAttr(options); this.fill = new StringAttr(options.fill, "black"); this.background = new StringAttr(options.background, "white"); this.padding = new NumberAttr(options.padding, 0); // TODO check falsy } public place(layout: Layout, geom: Point[][], f: Feature) { let property = this.text.get(layout.zoom, f); if (!property) return undefined; let font = this.font.get(layout.zoom, f); layout.scratch.font = font; let metrics = layout.scratch.measureText(property); let width = metrics.width; let ascent = metrics.actualBoundingBoxAscent; let descent = metrics.actualBoundingBoxDescent; let pt = geom[0]; let a = new Point(geom[0][0].x, geom[0][0].y); let p = this.padding.get(layout.zoom, f); let bbox = { minX: a.x - width / 2 - p, minY: a.y - ascent - p, maxX: a.x + width / 2 + p, maxY: a.y + descent + p, }; let draw = (ctx: CanvasRenderingContext2D) => { ctx.globalAlpha = 1; ctx.fillStyle = this.background.get(layout.zoom, f); ctx.fillRect( -width / 2 - p, -ascent - p, width + 2 * p, ascent + descent + 2 * p ); ctx.fillStyle = this.fill.get(layout.zoom, f); ctx.font = font; ctx.fillText(property!, -width / 2, 0); }; return [{ anchor: a, bboxes: [bbox], draw: draw }]; } } // TODO make me work with multiple anchors export class FlexSymbolizer implements LabelSymbolizer { list: LabelSymbolizer[]; constructor(list: LabelSymbolizer[]) { this.list = list; } public place(layout: Layout, geom: Point[][], feature: Feature) { var labels = this.list[0].place(layout, geom, feature); if (!labels) return undefined; var label = labels[0]; let anchor = label.anchor; let bbox = label.bboxes[0]; let height = bbox.maxY - bbox.minY; let draws = [{ draw: label.draw, translate: { x: 0, y: 0 } }]; let newGeom = [[{ x: geom[0][0].x, y: geom[0][0].y + height }]]; for (let i = 1; i < this.list.length; i++) { labels = this.list[i].place(layout, newGeom, feature); if (labels) { label = labels[0]; bbox = mergeBbox(bbox, label.bboxes[0]); draws.push({ draw: label.draw, translate: { x: 0, y: height } }); } } let draw = (ctx: CanvasRenderingContext2D) => { for (let sub of draws) { ctx.save(); ctx.translate(sub.translate.x, sub.translate.y); sub.draw(ctx); ctx.restore(); } }; return [{ anchor: anchor, bboxes: [bbox], draw: draw }]; } } const mergeBbox = (b1: Bbox, b2: Bbox) => { return { minX: Math.min(b1.minX, b2.minX), minY: Math.min(b1.minY, b2.minY), maxX: Math.max(b1.maxX, b2.maxX), maxY: Math.max(b1.maxY, b2.maxY), }; }; export class GroupSymbolizer implements LabelSymbolizer { list: LabelSymbolizer[]; constructor(list: LabelSymbolizer[]) { this.list = list; } public place(layout: Layout, geom: Point[][], feature: Feature) { let first = this.list[0]; if (!first) return undefined; var labels = first.place(layout, geom, feature); if (!labels) return undefined; var label = labels[0]; let anchor = label.anchor; let bbox = label.bboxes[0]; let draws = [label.draw]; for (let i = 1; i < this.list.length; i++) { labels = this.list[i].place(layout, geom, feature); if (!labels) return undefined; label = labels[0]; bbox = mergeBbox(bbox, label.bboxes[0]); draws.push(label.draw); } let draw = (ctx: CanvasRenderingContext2D) => { draws.forEach((d) => d(ctx)); }; return [{ anchor: anchor, bboxes: [bbox], draw: draw }]; } } export class CenteredSymbolizer implements LabelSymbolizer { symbolizer: LabelSymbolizer; constructor(symbolizer: LabelSymbolizer) { this.symbolizer = symbolizer; } public place(layout: Layout, geom: Point[][], feature: Feature) { let a = geom[0][0]; let placed = this.symbolizer.place(layout, [[new Point(0, 0)]], feature); if (!placed || placed.length == 0) return undefined; let first_label = placed[0]; let bbox = first_label.bboxes[0]; let width = bbox.maxX - bbox.minX; let height = bbox.maxY - bbox.minY; let centered = { minX: a.x - width / 2, maxX: a.x + width / 2, minY: a.y - height / 2, maxY: a.y + height / 2, }; let draw = (ctx: CanvasRenderingContext2D) => { ctx.translate(-width / 2, height / 2 - bbox.maxY); first_label.draw(ctx, { justify: Justify.Center }); }; return [{ anchor: a, bboxes: [centered], draw: draw }]; } } export class Padding implements LabelSymbolizer { symbolizer: LabelSymbolizer; padding: NumberAttr; constructor(padding: number, symbolizer: LabelSymbolizer) { this.padding = new NumberAttr(padding, 0); this.symbolizer = symbolizer; } public place(layout: Layout, geom: Point[][], feature: Feature) { let placed = this.symbolizer.place(layout, geom, feature); if (!placed || placed.length == 0) return undefined; let padding = this.padding.get(layout.zoom, feature); for (var label of placed) { for (var bbox of label.bboxes) { bbox.minX -= padding; bbox.minY -= padding; bbox.maxX += padding; bbox.maxY += padding; } } return placed; } } export interface TextSymbolizerOptions extends FontAttrOptions, TextAttrOptions { fill?: AttrOption<string>; stroke?: AttrOption<string>; width?: AttrOption<number>; lineHeight?: AttrOption<number>; letterSpacing?: AttrOption<number>; maxLineChars?: AttrOption<number>; justify?: Justify; } export class TextSymbolizer implements LabelSymbolizer { font: FontAttr; text: TextAttr; fill: StringAttr; stroke: StringAttr; width: NumberAttr; lineHeight: NumberAttr; // in ems letterSpacing: NumberAttr; // in px maxLineCodeUnits: NumberAttr; justify?: Justify; constructor(options: TextSymbolizerOptions) { this.font = new FontAttr(options); this.text = new TextAttr(options); this.fill = new StringAttr(options.fill, "black"); this.stroke = new StringAttr(options.stroke, "black"); this.width = new NumberAttr(options.width, 0); this.lineHeight = new NumberAttr(options.lineHeight, 1); this.letterSpacing = new NumberAttr(options.letterSpacing, 0); this.maxLineCodeUnits = new NumberAttr(options.maxLineChars, 15); this.justify = options.justify; } public place(layout: Layout, geom: Point[][], feature: Feature) { let property = this.text.get(layout.zoom, feature); if (!property) return undefined; let font = this.font.get(layout.zoom, feature); layout.scratch.font = font; let letterSpacing = this.letterSpacing.get(layout.zoom, feature); // line breaking let lines = linebreak( property, this.maxLineCodeUnits.get(layout.zoom, feature) ); var longestLine; var longestLineLen = 0; for (let line of lines) { if (line.length > longestLineLen) { longestLineLen = line.length; longestLine = line; } } let metrics = layout.scratch.measureText(longestLine); let width = metrics.width + letterSpacing * (longestLineLen - 1); let ascent = metrics.actualBoundingBoxAscent; let descent = metrics.actualBoundingBoxDescent; let lineHeight = (ascent + descent) * this.lineHeight.get(layout.zoom, feature); let a = new Point(geom[0][0].x, geom[0][0].y); let bbox = { minX: a.x, minY: a.y - ascent, maxX: a.x + width, maxY: a.y + descent + (lines.length - 1) * lineHeight, }; // inside draw, the origin is the anchor // and the anchor is the typographic baseline of the first line let draw = (ctx: CanvasRenderingContext2D, extra?: DrawExtra) => { ctx.globalAlpha = 1; ctx.font = font; ctx.fillStyle = this.fill.get(layout.zoom, feature); let textStrokeWidth = this.width.get(layout.zoom, feature); var y = 0; for (let line of lines) { var startX = 0; if ( this.justify == Justify.Center || (extra && extra.justify == Justify.Center) ) { startX = (width - ctx.measureText(line).width) / 2; } else if ( this.justify == Justify.Right || (extra && extra.justify == Justify.Right) ) { startX = width - ctx.measureText(line).width; } if (textStrokeWidth) { ctx.lineWidth = textStrokeWidth * 2; // centered stroke ctx.strokeStyle = this.stroke.get(layout.zoom, feature); if (letterSpacing > 0) { var xPos = startX; for (var letter of line) { ctx.strokeText(letter, xPos, y); xPos += ctx.measureText(letter).width + letterSpacing; } } else { ctx.strokeText(line, startX, y); } } if (letterSpacing > 0) { var xPos = startX; for (var letter of line) { ctx.fillText(letter, xPos, y); xPos += ctx.measureText(letter).width + letterSpacing; } } else { ctx.fillText(line, startX, y); } y += lineHeight; } }; return [{ anchor: a, bboxes: [bbox], draw: draw }]; } } export class CenteredTextSymbolizer implements LabelSymbolizer { centered: LabelSymbolizer; constructor(options: TextSymbolizerOptions) { this.centered = new CenteredSymbolizer(new TextSymbolizer(options)); } public place(layout: Layout, geom: Point[][], feature: Feature) { return this.centered.place(layout, geom, feature); } } export interface OffsetSymbolizerValues { offsetX?: number; offsetY?: number; placements?: TextPlacements[]; justify?: Justify; } export type DataDrivenOffsetSymbolizer = ( zoom: number, feature: Feature ) => OffsetSymbolizerValues; export interface OffsetSymbolizerOptions { offsetX?: AttrOption<number>; offsetY?: AttrOption<number>; justify?: Justify; placements?: TextPlacements[]; ddValues?: DataDrivenOffsetSymbolizer; } export class OffsetSymbolizer implements LabelSymbolizer { symbolizer: LabelSymbolizer; offsetX: NumberAttr; offsetY: NumberAttr; justify?: Justify; placements: TextPlacements[]; ddValues: DataDrivenOffsetSymbolizer; constructor(symbolizer: LabelSymbolizer, options: OffsetSymbolizerOptions) { this.symbolizer = symbolizer; this.offsetX = new NumberAttr(options.offsetX, 0); this.offsetY = new NumberAttr(options.offsetY, 0); this.justify = options.justify ?? undefined; this.placements = options.placements ?? [ TextPlacements.NE, TextPlacements.SW, TextPlacements.NW, TextPlacements.SE, TextPlacements.N, TextPlacements.E, TextPlacements.S, TextPlacements.W, ]; this.ddValues = options.ddValues ?? (() => { return {}; }); } public place(layout: Layout, geom: Point[][], feature: Feature) { if (feature.geomType !== GeomType.Point) return undefined; let anchor = geom[0][0]; let placed = this.symbolizer.place(layout, [[new Point(0, 0)]], feature); if (!placed || placed.length == 0) return undefined; let first_label = placed[0]; let fb = first_label.bboxes[0]; // Overwrite options values via the data driven function if exists let offsetXValue = this.offsetX; let offsetYValue = this.offsetY; let justifyValue = this.justify; let placements = this.placements; const { offsetX: ddOffsetX, offsetY: ddOffsetY, justify: ddJustify, placements: ddPlacements, } = this.ddValues(layout.zoom, feature) || {}; if (ddOffsetX) offsetXValue = new NumberAttr(ddOffsetX, 0); if (ddOffsetY) offsetYValue = new NumberAttr(ddOffsetY, 0); if (ddJustify) justifyValue = ddJustify; if (ddPlacements) placements = ddPlacements; const offsetX = offsetXValue.get(layout.zoom, feature); const offsetY = offsetYValue.get(layout.zoom, feature); let getBbox = (a: Point, o: Point) => { return { minX: a.x + o.x + fb.minX, minY: a.y + o.y + fb.minY, maxX: a.x + o.x + fb.maxX, maxY: a.y + o.y + fb.maxY, }; }; var origin = new Point(offsetX, offsetY); var justify: Justify; let draw = (ctx: CanvasRenderingContext2D) => { ctx.translate(origin.x, origin.y); first_label.draw(ctx, { justify: justify }); }; const placeLabelInPoint = (a: Point, o: Point) => { const bbox = getBbox(a, o); if (!layout.index.bboxCollides(bbox, layout.order)) return [{ anchor: anchor, bboxes: [bbox], draw: draw }]; }; for (let placement of placements) { const xAxisOffset = this.computeXAxisOffset(offsetX, fb, placement); const yAxisOffset = this.computeYAxisOffset(offsetY, fb, placement); justify = this.computeJustify(justifyValue, placement); origin = new Point(xAxisOffset, yAxisOffset); return placeLabelInPoint(anchor, origin); } return undefined; } computeXAxisOffset(offsetX: number, fb: Bbox, placement: TextPlacements) { const labelWidth = fb.maxX; const labelHalfWidth = labelWidth / 2; if ([TextPlacements.N, TextPlacements.S].includes(placement)) return offsetX - labelHalfWidth; if ( [TextPlacements.NW, TextPlacements.W, TextPlacements.SW].includes( placement ) ) return offsetX - labelWidth; return offsetX; } computeYAxisOffset(offsetY: number, fb: Bbox, placement: TextPlacements) { const labelHalfHeight = Math.abs(fb.minY); const labelBottom = fb.maxY; const labelCenterHeight = (fb.minY + fb.maxY) / 2; if ([TextPlacements.E, TextPlacements.W].includes(placement)) return offsetY - labelCenterHeight; if ( [TextPlacements.NW, TextPlacements.NE, TextPlacements.N].includes( placement ) ) return offsetY - labelBottom; if ( [TextPlacements.SW, TextPlacements.SE, TextPlacements.S].includes( placement ) ) return offsetY + labelHalfHeight; return offsetY; } computeJustify(fixedJustify: Justify | undefined, placement: TextPlacements) { if (fixedJustify) return fixedJustify; if ([TextPlacements.N, TextPlacements.S].includes(placement)) return Justify.Center; if ( [TextPlacements.NE, TextPlacements.E, TextPlacements.SE].includes( placement ) ) return Justify.Left; return Justify.Right; } } export class OffsetTextSymbolizer implements LabelSymbolizer { symbolizer: LabelSymbolizer; constructor(options: OffsetSymbolizerOptions & TextSymbolizerOptions) { this.symbolizer = new OffsetSymbolizer( new TextSymbolizer(options), options ); } public place(layout: Layout, geom: Point[][], feature: Feature) { return this.symbolizer.place(layout, geom, feature); } } export enum LineLabelPlacement { Above = 1, Center = 2, Below = 3, } export class LineLabelSymbolizer implements LabelSymbolizer { font: FontAttr; text: TextAttr; fill: StringAttr; stroke: StringAttr; width: NumberAttr; offset: NumberAttr; position: LineLabelPlacement; maxLabelCodeUnits: NumberAttr; repeatDistance: NumberAttr; constructor( options: { radius?: AttrOption<number>; fill?: AttrOption<string>; stroke?: AttrOption<string>; width?: AttrOption<number>; offset?: AttrOption<number>; maxLabelChars?: AttrOption<number>; repeatDistance?: AttrOption<number>; position?: LineLabelPlacement; } & TextAttrOptions & FontAttrOptions ) { this.font = new FontAttr(options); this.text = new TextAttr(options); this.fill = new StringAttr(options.fill, "black"); this.stroke = new StringAttr(options.stroke, "black"); this.width = new NumberAttr(options.width, 0); this.offset = new NumberAttr(options.offset, 0); this.position = options.position ?? LineLabelPlacement.Above; this.maxLabelCodeUnits = new NumberAttr(options.maxLabelChars, 40); this.repeatDistance = new NumberAttr(options.repeatDistance, 250); } public place(layout: Layout, geom: Point[][], feature: Feature) { let name = this.text.get(layout.zoom, feature); if (!name) return undefined; if (name.length > this.maxLabelCodeUnits.get(layout.zoom, feature)) return undefined; let MIN_LABELABLE_DIM = 20; let fbbox = feature.bbox; if ( fbbox.maxY - fbbox.minY < MIN_LABELABLE_DIM && fbbox.maxX - fbbox.minX < MIN_LABELABLE_DIM ) return undefined; let font = this.font.get(layout.zoom, feature); layout.scratch.font = font; let metrics = layout.scratch.measureText(name); let width = metrics.width; let height = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent; var repeatDistance = this.repeatDistance.get(layout.zoom, feature); if (layout.overzoom > 4) repeatDistance *= 1 << (layout.overzoom - 4); let cell_size = height * 2; let label_candidates = simpleLabel(geom, width, repeatDistance, cell_size); if (label_candidates.length == 0) return undefined; let labels = []; for (let candidate of label_candidates) { let dx = candidate.end.x - candidate.start.x; let dy = candidate.end.y - candidate.start.y; let cells = lineCells( candidate.start, candidate.end, width, cell_size / 2 ); let bboxes = cells.map((c) => { return { minX: c.x - cell_size / 2, minY: c.y - cell_size / 2, maxX: c.x + cell_size / 2, maxY: c.y + cell_size / 2, }; }); let draw = (ctx: CanvasRenderingContext2D) => { ctx.globalAlpha = 1; // ctx.beginPath(); // ctx.moveTo(0, 0); // ctx.lineTo(dx, dy); // ctx.strokeStyle = "red"; // ctx.stroke(); ctx.rotate(Math.atan2(dy, dx)); if (dx < 0) { ctx.scale(-1, -1); ctx.translate(-width, 0); } let heightPlacement = 0; if (this.position === LineLabelPlacement.Below) heightPlacement += height; else if (this.position === LineLabelPlacement.Center) heightPlacement += height / 2; ctx.translate( 0, heightPlacement - this.offset.get(layout.zoom, feature) ); ctx.font = font; let lineWidth = this.width.get(layout.zoom, feature); if (lineWidth) { ctx.lineWidth = lineWidth; ctx.strokeStyle = this.stroke.get(layout.zoom, feature); ctx.strokeText(name!, 0, 0); } ctx.fillStyle = this.fill.get(layout.zoom, feature); ctx.fillText(name!, 0, 0); }; labels.push({ anchor: candidate.start, bboxes: bboxes, draw: draw, deduplicationKey: name, deduplicationDistance: repeatDistance, }); } return labels; } } export class PolygonLabelSymbolizer implements LabelSymbolizer { symbolizer: LabelSymbolizer; constructor(options: TextSymbolizerOptions) { this.symbolizer = new TextSymbolizer(options); } public place(layout: Layout, geom: Point[][], feature: Feature) { let fbbox = feature.bbox; let area = (fbbox.maxY - fbbox.minY) * (fbbox.maxX - fbbox.minX); // TODO needs to be based on zoom level/overzooming if (area < 20000) return undefined; let placed = this.symbolizer.place(layout, [[new Point(0, 0)]], feature); if (!placed || placed.length == 0) return undefined; let first_label = placed[0]; let fb = first_label.bboxes[0]; let first_poly = geom[0]; let found = polylabel([first_poly.map((c) => [c.x, c.y])]); let a = new Point(found[0], found[1]); let bbox = { minX: a.x - (fb.maxX - fb.minX) / 2, minY: a.y - (fb.maxY - fb.minY) / 2, maxX: a.x + (fb.maxX - fb.minX) / 2, maxY: a.y + (fb.maxY - fb.minY) / 2, }; let draw = (ctx: CanvasRenderingContext2D) => { ctx.translate( first_label.anchor.x - (fb.maxX - fb.minX) / 2, first_label.anchor.y ); first_label.draw(ctx); }; return [{ anchor: a, bboxes: [bbox], draw: draw }]; } }
the_stack
import { ErrorTypes, ErrorMessages, TypeAssertionErrorMessageConstraints, TypeAssertion, RepeatedAssertion, SpreadAssertion, OptionalAssertion, ValidationContext } from '../types'; import { escapeString } from './escape'; import { nvl } from './util'; export const errorTypeNames = [ '', 'InvalidDefinition', 'Required', 'TypeUnmatched', 'AdditionalPropUnmatched', 'RepeatQtyUnmatched', 'SequenceUnmatched', 'ValueRangeUnmatched', 'ValuePatternUnmatched', 'ValueLengthUnmatched', 'ValueUnmatched', ]; export const defaultMessages: ErrorMessages = { invalidDefinition: '"%{name}" of "%{parentType}" type definition is invalid.', required: '"%{name}" of "%{parentType}" is required.', typeUnmatched: '"%{name}" of "%{parentType}" should be type "%{expectedType}".', additionalPropUnmatched: '"%{addtionalProps}" of "%{parentType}" are not matched to additional property patterns.', repeatQtyUnmatched: '"%{name}" of "%{parentType}" should repeat %{repeatQty} times.', sequenceUnmatched: '"%{name}" of "%{parentType}" sequence is not matched', valueRangeUnmatched: '"%{name}" of "%{parentType}" value should be in the range %{minValue} to %{maxValue}.', valuePatternUnmatched: '"%{name}" of "%{parentType}" value should be matched to pattern "%{pattern}"', valueLengthUnmatched: '"%{name}" of "%{parentType}" length should be in the range %{minLength} to %{maxLength}.', valueUnmatched: '"%{name}" of "%{parentType}" value should be "%{expectedValue}".', }; type TopRepeatable = RepeatedAssertion | SpreadAssertion | OptionalAssertion | null; interface ReportErrorArguments { ctx: ValidationContext; substitutions?: [[string, string]]; // addtional or overwritten substitution values } function getErrorMessage(errType: ErrorTypes, ...messages: ErrorMessages[]) { for (const m of messages) { switch (errType) { case ErrorTypes.InvalidDefinition: if (m.invalidDefinition) { return m.invalidDefinition; } break; case ErrorTypes.Required: if (m.required) { return m.required; } break; case ErrorTypes.TypeUnmatched: if (m.typeUnmatched) { return m.typeUnmatched; } break; case ErrorTypes.AdditionalPropUnmatched: if (m.additionalPropUnmatched) { return m.additionalPropUnmatched; } break; case ErrorTypes.RepeatQtyUnmatched: if (m.repeatQtyUnmatched) { return m.repeatQtyUnmatched; } break; case ErrorTypes.SequenceUnmatched: if (m.sequenceUnmatched) { return m.sequenceUnmatched; } break; case ErrorTypes.ValueRangeUnmatched: if (m.valueRangeUnmatched) { return m.valueRangeUnmatched; } break; case ErrorTypes.ValuePatternUnmatched: if (m.valuePatternUnmatched) { return m.valuePatternUnmatched; } break; case ErrorTypes.ValueLengthUnmatched: if (m.valueLengthUnmatched) { return m.valueLengthUnmatched; } break; case ErrorTypes.ValueUnmatched: if (m.valueUnmatched) { return m.valueUnmatched; } break; } } return ''; } function findTopRepeatableAssertion(ctx: ValidationContext): TopRepeatable { const ret = ctx.typeStack .slice() .reverse() .map(x => Array.isArray(x) ? x[0] : x) .find(x => x.kind === 'repeated' || x.kind === 'spread' || x.kind === 'optional' ) as RepeatedAssertion | SpreadAssertion | OptionalAssertion || null; return ret; } function getExpectedType(ty: TypeAssertion): string { switch (ty.kind) { case 'repeated': return `(repeated ${getExpectedType(ty.repeated)})`; case 'spread': return getExpectedType(ty.spread); case 'sequence': return '(sequence)'; case 'primitive': return ty.primitiveName; case 'primitive-value': return `(value ${ typeof ty.value === 'string' ? `'${String(ty.value)}'` : String(ty.value)})`; case 'optional': return getExpectedType(ty.optional); case 'one-of': return `(one of ${ty.oneOf.map(x => getExpectedType(x)).join(', ')})`; case 'never': case 'any': case 'unknown': return ty.kind; case 'symlink': return ty.symlinkTargetName; default: return ty.typeName ? ty.typeName : '?'; } } export function formatErrorMessage( msg: string, data: any, ty: TypeAssertion, args: ReportErrorArguments, values: {dataPath: string, topRepeatable: TopRepeatable, parentType: string, entryName: string}) { let ret = msg; // TODO: complex type object members' custom error messages are not displayed? // TODO: escapeString() is needed? const tr = values.topRepeatable; const dict = new Map<string, string>([ ['expectedType', ty.stereotype ? ty.stereotype : escapeString(getExpectedType(ty))], ['type', escapeString(typeof data)], ['expectedValue', escapeString( ty.kind === 'primitive-value' ? String(ty.value) : ty.kind === 'enum' ? ty.typeName ? `enum member of ${ty.typeName}` : '?' : '?')], ['value', escapeString(String(data))], ['repeatQty', escapeString( tr ? tr.kind !== 'optional' ? `${ nvl(tr.min, '')}${ (tr.min !== null && tr.min !== void 0) || (tr.max !== null && tr.max !== void 0) ? '..' : ''}${ nvl(tr.max, '')}` : '0..1' : '?')], ['minValue', escapeString( ty.kind === 'primitive' ? `${nvl(ty.minValue, nvl(ty.greaterThanValue, '(smallest)'))}` : '?')], ['maxValue', escapeString( ty.kind === 'primitive' ? `${nvl(ty.maxValue, nvl(ty.lessThanValue, '(biggest)'))}` : '?')], ['pattern', escapeString( ty.kind === 'primitive' ? `${ty.pattern ? `/${ty.pattern.source}/${ty.pattern.flags}` : '(pattern)'}` : '?')], ['minLength', escapeString( ty.kind === 'primitive' ? `${nvl(ty.minLength, '0')}` : '?')], ['maxLength', escapeString( ty.kind === 'primitive' ? `${nvl(ty.maxLength, '(biggest)')}` : '?')], ['name', escapeString( `${ty.kind !== 'repeated' && values.dataPath.endsWith('repeated)') ? 'repeated item of ' : ty.kind !== 'sequence' && values.dataPath.endsWith('sequence)') ? 'sequence item of ' : ''}${ values.entryName || '?'}`)], ['parentType', escapeString( values.parentType || '?')], ['dataPath', values.dataPath], ...(args.substitutions || []), ]); for (const ent of dict.entries()) { ret = ret.replace(new RegExp(`%{${ent[0]}}`), ent[1]); } return ret; } interface DataPathEntry { name: string; kind: 'type' | 'key' | 'index'; } export function reportError( errType: ErrorTypes, data: any, ty: TypeAssertion, args: ReportErrorArguments) { const messages: ErrorMessages[] = []; if (ty.messages) { messages.push(ty.messages); } if (args.ctx.errorMessages) { messages.push(args.ctx.errorMessages); } messages.push(defaultMessages); const dataPathEntryArray: DataPathEntry[] = []; for (let i = 0; i < args.ctx.typeStack.length; i++) { const p = args.ctx.typeStack[i]; const next = args.ctx.typeStack[i + 1]; const pt = Array.isArray(p) ? p[0] : p; const pi = Array.isArray(next) ? next[1] : void 0; let isSet = false; if (pt.kind === 'repeated') { if (i !== args.ctx.typeStack.length - 1) { if (pt.name) { dataPathEntryArray.push({kind: 'key', name: pt.name}); } dataPathEntryArray.push({kind: 'index', name: `(${pi !== void 0 ? `${pi}:` : ''}repeated)`}); isSet = true; } } else if (pt.kind === 'sequence') { if (i !== args.ctx.typeStack.length - 1) { if (pt.name) { dataPathEntryArray.push({kind: 'key', name: pt.name}); } dataPathEntryArray.push({kind: 'index', name: `(${pi !== void 0 ? `${pi}:` : ''}sequence)`}); isSet = true; } } if (! isSet) { if (pt.name) { if (i === 0) { if (pt.typeName) { dataPathEntryArray.push({kind: 'type', name: pt.typeName}); } else { dataPathEntryArray.push({kind: 'key', name: pt.name}); } } else { const len = dataPathEntryArray.length; if (len && dataPathEntryArray[len - 1].kind === 'type') { if (pt.kind === 'object' && next && pt.typeName) { dataPathEntryArray.push({kind: 'type', name: pt.typeName}); } else { dataPathEntryArray.push({kind: 'key', name: pt.name as string}); // NOTE: type inference failed } } else { if (pt.typeName) { dataPathEntryArray.push({kind: 'type', name: pt.typeName}); } else { dataPathEntryArray.push({kind: 'key', name: pt.name}); } } } } else if (pt.typeName) { dataPathEntryArray.push({kind: 'type', name: pt.typeName}); } } } let dataPath = ''; for (let i = 0; i < dataPathEntryArray.length; i++) { const p = dataPathEntryArray[i]; dataPath += p.name; if (i + 1 === dataPathEntryArray.length) { break; } dataPath += p.kind === 'type' ? ':' : '.'; } let parentType = ''; let entryName = ''; for (let i = dataPathEntryArray.length - 1; 0 <= i; i--) { const p = dataPathEntryArray[i]; if (p.kind === 'type') { if (i !== 0 && i === dataPathEntryArray.length - 1) { const q = dataPathEntryArray[i - 1]; if (q.kind === 'index') { continue; // e.g.: "File:acl.(0:repeated).ACL" } } // else: "File:acl.(0:repeated).ACL:target" parentType = p.name; for (let j = i + 1; j < dataPathEntryArray.length; j++) { const q = dataPathEntryArray[j]; if (q.kind === 'key') { entryName = q.name; break; } } break; } } if (! parentType) { for (let i = args.ctx.typeStack.length - 1; 0 <= i; i--) { const p = args.ctx.typeStack[i]; const pt = Array.isArray(p) ? p[0] : p; if (pt.typeName) { parentType = pt.typeName; } } } const topRepeatable: TopRepeatable = findTopRepeatableAssertion(args.ctx); const values = {dataPath, topRepeatable, parentType, entryName}; const constraints: TypeAssertionErrorMessageConstraints = {}; const cSrces: TypeAssertionErrorMessageConstraints[] = [ty as any]; if (errType === ErrorTypes.RepeatQtyUnmatched && topRepeatable) { cSrces.unshift(topRepeatable as any); } for (const cSrc of cSrces) { if (nvl(cSrc.minValue, false)) { constraints.minValue = cSrc.minValue; } if (nvl(cSrc.maxValue, false)) { constraints.maxValue = cSrc.maxValue; } if (nvl(cSrc.greaterThanValue, false)) { constraints.greaterThanValue = cSrc.greaterThanValue; } if (nvl(cSrc.lessThanValue, false)) { constraints.lessThanValue = cSrc.lessThanValue; } if (nvl(cSrc.minLength, false)) { constraints.minLength = cSrc.minLength; } if (nvl(cSrc.maxLength, false)) { constraints.maxLength = cSrc.maxLength; } if (nvl(cSrc.pattern, false)) { const pat = cSrc.pattern as any as RegExp; constraints.pattern = `/${pat.source}/${pat.flags}`; } if (nvl(cSrc.min, false)) { constraints.min = cSrc.min; } if (nvl(cSrc.max, false)) { constraints.max = cSrc.max; } } const val: {value?: any} = {}; switch (typeof data) { case 'number': case 'bigint': case 'string': case 'boolean': case 'undefined': val.value = data; break; case 'object': if (data === null) { val.value = data; } } if (ty.messageId) { args.ctx.errors.push({ code: `${ty.messageId}-${errorTypeNames[errType]}`, message: formatErrorMessage(ty.message ? ty.message : getErrorMessage(errType, ...messages), data, ty, args, values), dataPath, constraints, ...val, }); } else if (ty.message) { args.ctx.errors.push({ code: `${errorTypeNames[errType]}`, message: formatErrorMessage(ty.message, data, ty, args, values), dataPath, constraints, ...val, }); } else { args.ctx.errors.push({ code: `${errorTypeNames[errType]}`, message: formatErrorMessage(getErrorMessage(errType, ...messages), data, ty, args, values), dataPath, constraints, ...val, }); } } export function reportErrorWithPush( errType: ErrorTypes, data: any, tyidx: [TypeAssertion, number | string | undefined], args: ReportErrorArguments) { try { args.ctx.typeStack.push(tyidx); reportError(errType, data, tyidx[0], args); } finally { args.ctx.typeStack.pop(); } }
the_stack
import { Address, Algorithm, ChainId, isBlockInfoPending, isFailedTransaction, isSendTransaction, PubkeyBytes, SendTransaction, TokenTicker, TransactionState, } from "@iov/bcp"; import { Secp256k1 } from "@iov/crypto"; import { fromBase64, toHex } from "@iov/encoding"; import { HdPaths, Secp256k1HdWallet, UserProfile } from "@iov/keycontrol"; import { cosmosHubCodec } from "./cosmoshubcodec"; import { CosmosHubConnection } from "./cosmoshubconnection"; function pendingWithoutCosmosHub(): void { if (!process.env.COSMOSHUB_ENABLED) { return pending("Set COSMOSHUB_ENABLED to enable Cosmos node-based tests"); } } describe("CosmosHubConnection", () => { const atom = "ATOM" as TokenTicker; const httpUrl = "http://localhost:1317"; const defaultChainId = "cosmos:testing" as ChainId; const defaultEmptyAddress = "cosmos1h806c7khnvmjlywdrkdgk2vrayy2mmvf9rxk2r" as Address; const defaultAddress = "cosmos1pkptre7fdkl6gfrzlesjjvhxhlc3r4gmmk8rs6" as Address; const defaultPubkey = { algo: Algorithm.Secp256k1, data: fromBase64("A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ") as PubkeyBytes, }; const faucetMnemonic = "economy stock theory fatal elder harbor betray wasp final emotion task crumble siren bottom lizard educate guess current outdoor pair theory focus wife stone"; const faucetPath = HdPaths.cosmosHub(0); const defaultRecipient = "cosmos1t70qnpr0az8tf7py83m4ue5y89w58lkjmx0yq2" as Address; describe("establish", () => { it("can connect to cosmoshub via http", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); expect(connection).toBeTruthy(); connection.disconnect(); }); }); describe("chainId", () => { it("displays the chain ID", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); expect(connection.chainId).toEqual(defaultChainId); connection.disconnect(); }); }); describe("height", () => { it("displays the current height", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const height = await connection.height(); expect(height).toBeGreaterThan(0); connection.disconnect(); }); }); describe("getToken", () => { it("displays a given token", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const token = await connection.getToken("ATOM" as TokenTicker); expect(token).toEqual({ fractionalDigits: 6, tokenName: "Atom", tokenTicker: "ATOM" as TokenTicker, }); connection.disconnect(); }); it("resolves to undefined if the token is not supported", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const token = await connection.getToken("whatever" as TokenTicker); expect(token).toBeUndefined(); connection.disconnect(); }); }); describe("getAllTokens", () => { it("resolves to a list of all supported tokens", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const tokens = await connection.getAllTokens(); expect(tokens).toEqual([ { fractionalDigits: 6, tokenName: "Atom", tokenTicker: "ATOM" as TokenTicker, }, ]); connection.disconnect(); }); }); describe("getAccount", () => { it("gets an empty account by address", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const account = await connection.getAccount({ address: defaultEmptyAddress }); expect(account).toBeUndefined(); connection.disconnect(); }); it("gets an account by address", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const account = await connection.getAccount({ address: defaultAddress }); if (account === undefined) { throw new Error("Expected account not to be undefined"); } expect(account.address).toEqual(defaultAddress); expect(account.pubkey).toEqual(defaultPubkey); // Unsupported coins are filtered out expect(account.balance.length).toEqual(1); connection.disconnect(); }); it("gets an account by pubkey", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const account = await connection.getAccount({ pubkey: defaultPubkey }); if (account === undefined) { throw new Error("Expected account not to be undefined"); } expect(account.address).toEqual(defaultAddress); expect(account.pubkey).toEqual({ algo: Algorithm.Secp256k1, data: fromBase64("A08EGB7ro1ORuFhjOnZcSgwYlpe0DSFjVNUIkNNQxwKQ"), }); // Unsupported coins are filtered out expect(account.balance.length).toEqual(1); connection.disconnect(); }); }); describe("integration tests", () => { it("can post and get a transaction", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const profile = new UserProfile(); const wallet = profile.addWallet(Secp256k1HdWallet.fromMnemonic(faucetMnemonic)); const faucet = await profile.createIdentity(wallet.id, defaultChainId, faucetPath); const faucetAddress = cosmosHubCodec.identityToAddress(faucet); const unsigned = await connection.withDefaultFee<SendTransaction>({ kind: "bcp/send", chainId: defaultChainId, sender: faucetAddress, recipient: defaultRecipient, memo: "My first payment", amount: { quantity: "75000", fractionalDigits: 6, tokenTicker: atom, }, }); const nonce = await connection.getNonce({ address: faucetAddress }); const signed = await profile.signTransaction(faucet, unsigned, cosmosHubCodec, nonce); const postableBytes = cosmosHubCodec.bytesToPost(signed); const response = await connection.postTx(postableBytes); const { transactionId } = response; const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); const getResponse = await connection.getTx(transactionId); expect(getResponse).toBeTruthy(); expect(getResponse.transactionId).toEqual(transactionId); if (isFailedTransaction(getResponse)) { throw new Error("Expected transaction to succeed"); } expect(getResponse.log).toMatch(/success/i); const { transaction, signatures } = getResponse; if (!isSendTransaction(transaction)) { throw new Error("Expected send transaction"); } expect(transaction.kind).toEqual(unsigned.kind); expect(transaction.sender).toEqual(unsigned.sender); expect(transaction.recipient).toEqual(unsigned.recipient); expect(transaction.memo).toEqual(unsigned.memo); expect(transaction.amount).toEqual(unsigned.amount); expect(transaction.chainId).toEqual(unsigned.chainId); expect(signatures.length).toEqual(1); expect(signatures[0].nonce).toEqual(signed.signatures[0].nonce); expect(signatures[0].pubkey.algo).toEqual(signed.signatures[0].pubkey.algo); expect(toHex(signatures[0].pubkey.data)).toEqual( toHex(Secp256k1.compressPubkey(signed.signatures[0].pubkey.data)), ); expect(toHex(signatures[0].signature)).toEqual( toHex(Secp256k1.trimRecoveryByte(signed.signatures[0].signature)), ); connection.disconnect(); }); it("can post and search for a transaction", async () => { pendingWithoutCosmosHub(); const connection = await CosmosHubConnection.establish(httpUrl); const profile = new UserProfile(); const wallet = profile.addWallet(Secp256k1HdWallet.fromMnemonic(faucetMnemonic)); const faucet = await profile.createIdentity(wallet.id, defaultChainId, faucetPath); const faucetAddress = cosmosHubCodec.identityToAddress(faucet); const unsigned = await connection.withDefaultFee<SendTransaction>({ kind: "bcp/send", chainId: defaultChainId, sender: faucetAddress, recipient: defaultRecipient, memo: "My first payment", amount: { quantity: "75000", fractionalDigits: 6, tokenTicker: atom, }, }); const nonce = await connection.getNonce({ address: faucetAddress }); const signed = await profile.signTransaction(faucet, unsigned, cosmosHubCodec, nonce); const postableBytes = cosmosHubCodec.bytesToPost(signed); const response = await connection.postTx(postableBytes); const { transactionId } = response; const blockInfo = await response.blockInfo.waitFor((info) => !isBlockInfoPending(info)); expect(blockInfo.state).toEqual(TransactionState.Succeeded); // search by id const idSearchResponse = await connection.searchTx({ id: transactionId }); expect(idSearchResponse).toBeTruthy(); expect(idSearchResponse.length).toEqual(1); const idResult = idSearchResponse[0]; expect(idResult.transactionId).toEqual(transactionId); if (isFailedTransaction(idResult)) { throw new Error("Expected transaction to succeed"); } expect(idResult.log).toMatch(/success/i); const { transaction: idTransaction } = idResult; if (!isSendTransaction(idTransaction)) { throw new Error("Expected send transaction"); } expect(idTransaction.kind).toEqual(unsigned.kind); expect(idTransaction.sender).toEqual(unsigned.sender); expect(idTransaction.recipient).toEqual(unsigned.recipient); expect(idTransaction.memo).toEqual(unsigned.memo); expect(idTransaction.amount).toEqual(unsigned.amount); // search by sender address const senderAddressSearchResponse = await connection.searchTx({ sentFromOrTo: faucetAddress }); expect(senderAddressSearchResponse).toBeTruthy(); expect(senderAddressSearchResponse.length).toBeGreaterThanOrEqual(1); const senderAddressResult = senderAddressSearchResponse[senderAddressSearchResponse.length - 1]; expect(senderAddressResult.transactionId).toEqual(transactionId); if (isFailedTransaction(senderAddressResult)) { throw new Error("Expected transaction to succeed"); } expect(senderAddressResult.log).toMatch(/success/i); const { transaction: senderAddressTransaction } = senderAddressResult; if (!isSendTransaction(senderAddressTransaction)) { throw new Error("Expected send transaction"); } expect(senderAddressTransaction.kind).toEqual(unsigned.kind); expect(senderAddressTransaction.sender).toEqual(unsigned.sender); expect(senderAddressTransaction.recipient).toEqual(unsigned.recipient); expect(senderAddressTransaction.memo).toEqual(unsigned.memo); expect(senderAddressTransaction.amount).toEqual(unsigned.amount); // search by recipient address // TODO: Support searching by recipient // const recipientAddressSearchResponse = await connection.searchTx({ sentFromOrTo: defaultRecipient }); // expect(recipientAddressSearchResponse).toBeTruthy(); // expect(recipientAddressSearchResponse.length).toBeGreaterThanOrEqual(1); // const recipientAddressResult = // recipientAddressSearchResponse[recipientAddressSearchResponse.length - 1]; // expect(recipientAddressResult.transactionId).toEqual(transactionId); // if (isFailedTransaction(recipientAddressResult)) { // throw new Error("Expected transaction to succeed"); // } // expect(recipientAddressResult.log).toMatch(/success/i); // const { transaction: recipientAddressTransaction } = recipientAddressResult; // if (!isSendTransaction(recipientAddressTransaction)) { // throw new Error("Expected send transaction"); // } // expect(recipientAddressTransaction.kind).toEqual(unsigned.kind); // expect(recipientAddressTransaction.sender).toEqual(unsigned.sender); // expect(recipientAddressTransaction.recipient).toEqual(unsigned.recipient); // expect(recipientAddressTransaction.memo).toEqual(unsigned.memo); // expect(recipientAddressTransaction.amount).toEqual(unsigned.amount); // search by height const heightSearchResponse = await connection.searchTx({ height: idResult.height }); expect(heightSearchResponse).toBeTruthy(); expect(heightSearchResponse.length).toEqual(1); const heightResult = heightSearchResponse[0]; expect(heightResult.transactionId).toEqual(transactionId); if (isFailedTransaction(heightResult)) { throw new Error("Expected transaction to succeed"); } expect(heightResult.log).toMatch(/success/i); const { transaction: heightTransaction } = heightResult; if (!isSendTransaction(heightTransaction)) { throw new Error("Expected send transaction"); } expect(heightTransaction.kind).toEqual(unsigned.kind); expect(heightTransaction.sender).toEqual(unsigned.sender); expect(heightTransaction.recipient).toEqual(unsigned.recipient); expect(heightTransaction.memo).toEqual(unsigned.memo); expect(heightTransaction.amount).toEqual(unsigned.amount); connection.disconnect(); }); }); });
the_stack
import {ComponentFixture, fakeAsync, flushMicrotasks, TestBed} from '@angular/core/testing'; import {FormsModule, ReactiveFormsModule} from '@angular/forms'; import {MatDialogModule} from '@angular/material/dialog'; import {BrowserAnimationsModule} from '@angular/platform-browser/animations'; import {RouterTestingModule} from '@angular/router/testing'; import {of} from 'rxjs'; import {Template} from '../../models/template'; import {DialogsModule} from '../../services/dialog'; import {Dialog} from '../../services/dialog'; import {TemplateService} from '../../services/template'; import {TemplateServiceMock} from '../../testing/mocks'; import {EmailTemplate, EmailTemplateModule} from './index'; describe('EmailTemplateComponent', () => { let fixture: ComponentFixture<EmailTemplate>; let emailTemplate: EmailTemplate; let dialogService: Dialog; beforeEach(fakeAsync(() => { TestBed .configureTestingModule({ imports: [ BrowserAnimationsModule, DialogsModule, EmailTemplateModule, FormsModule, MatDialogModule, ReactiveFormsModule, RouterTestingModule, ], providers: [ {provide: TemplateService, useClass: TemplateServiceMock}, Dialog ] }) .compileComponents(); flushMicrotasks(); fixture = TestBed.createComponent(EmailTemplate); dialogService = TestBed.get(Dialog); emailTemplate = fixture.debugElement.componentInstance; fixture.detectChanges(); })); afterEach(() => { emailTemplate.showNewView = false; }); // Create reusable function for a dry spec. function updateForm(name: string, body: string, title: string) { const updateFormTemplate = new Template({name, body, title}); emailTemplate.templatesForm.controls['template'].setValue( updateFormTemplate); } // Create reusable function for a dry spec. function updateTemplateSelected(name: string, body: string, title: string) { const updateFormTemplate = new Template({name, body, title}); emailTemplate.selectedTemplate.setValue(updateFormTemplate); } it('should render', () => { expect(emailTemplate).toBeTruthy(); }); it('onInit calls getTemplateList and sets selectedTemplate', () => { spyOn(emailTemplate, 'getTemplateList').and.callThrough(); emailTemplate.ngOnInit(); fixture.detectChanges(); expect(emailTemplate.getTemplateList).toHaveBeenCalledTimes(1); emailTemplate.selectedTemplate.valueChanges.subscribe(() => { expect(emailTemplate.template.value).toEqual({ name: 'test_email_template_1', title: 'test_title', body: 'hello world' }); }); }); describe('addNewView', () => { it('sets showNewView prop and resets form', () => { spyOn(emailTemplate.templatesForm, 'reset').and.callThrough(); emailTemplate.addNewView(); fixture.detectChanges(); expect(emailTemplate.showNewView).toBe(true); expect(emailTemplate.templatesForm.reset).toHaveBeenCalledTimes(1); }); it('clicking button opens add new template view', () => { const compiled = fixture.debugElement.nativeElement; const addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); const addNewButton = compiled.querySelector('button[name="add-new-template"]'); spyOn(emailTemplate, 'addNewView').and.callThrough(); expect(addNewViewButton).toBeDefined(); addNewViewButton.click(); expect(emailTemplate.addNewView).toHaveBeenCalledTimes(1); fixture.detectChanges(); expect(emailTemplate.showNewView).toEqual(true); expect(addNewButton).toBeDefined(); }); }); describe('addTemplate', () => { it('calls TemplateService.create and calls goBackToEditView', () => { const templateService = TestBed.get(TemplateService); updateForm('testName', 'testBody', 'testTitle'); spyOn(templateService, 'create').and.callThrough(); spyOn(emailTemplate, 'goBackToEditView').withArgs(true).and.callThrough(); emailTemplate.addTemplate(); fixture.detectChanges(); expect(templateService.create).toHaveBeenCalledTimes(1); templateService.create(new Template(emailTemplate.template.value)) .subscribe(() => { expect(emailTemplate.goBackToEditView).toHaveBeenCalledWith(true); }); }); it('clicking button creates Template and goes back to edit view', () => { const templateNameInput = emailTemplate.templatesForm.get(['template', 'name']); const compiled = fixture.debugElement.nativeElement; let addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); const templateService = TestBed.get(TemplateService); spyOn(templateService, 'create').and.callThrough(); spyOn(emailTemplate, 'addTemplate').and.callThrough(); spyOn(emailTemplate, 'goBackToEditView').and.callThrough(); spyOn(emailTemplate, 'goBack').and.callThrough(); addNewViewButton.click(); fixture.detectChanges(); let addNewTemplateButton = compiled.querySelector('button[name="add-new-template"]'); addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); expect(addNewTemplateButton).toBeTruthy(); expect(addNewViewButton).toBeFalsy(); templateNameInput!.setValue('test'); expect(emailTemplate.templatesForm.valid).toBeTruthy(); addNewTemplateButton.click(); fixture.detectChanges(); templateService.create(new Template(emailTemplate.template.value)) .subscribe(() => { expect(emailTemplate.addTemplate).toHaveBeenCalledTimes(1); expect(templateService.create).toHaveBeenCalledTimes(1); expect(emailTemplate.goBackToEditView).toHaveBeenCalledTimes(1); expect(emailTemplate.goBack).toHaveBeenCalledTimes(1); const addViewNewButtonShow = compiled.querySelector('button[name="show-new-template-view"]'); addNewTemplateButton = compiled.querySelector('button[name="back-to-edit-template"]'); expect(addViewNewButtonShow).toBeTruthy(); expect(addNewTemplateButton).toBeFalsy(); }); }); }); it('getTemplateList fetches template list and sets selectedTemplate', () => { const templateService = TestBed.get(TemplateService); spyOn(templateService, 'list').and.callThrough(); emailTemplate.getTemplateList(); fixture.detectChanges(); templateService.list().subscribe(() => { expect(emailTemplate.templates.length).toEqual(2); const mockTemplate = new Template({ name: 'test_email_template_1', body: 'hello world', title: 'test_title' }); expect(emailTemplate.selectedTemplate.value).toEqual(mockTemplate); }); }); it('goBack sets showNewView, resets form, and calls GetTemplateList', () => { fixture.detectChanges(); spyOn(emailTemplate.templatesForm, 'reset').and.callThrough(); spyOn(emailTemplate, 'getTemplateList').and.callThrough(); emailTemplate.goBack(); fixture.detectChanges(); expect(emailTemplate.showNewView).toBe(false); expect(emailTemplate.getTemplateList).toHaveBeenCalledTimes(1); expect(emailTemplate.templatesForm.reset).toHaveBeenCalledTimes(1); }); describe('goBackToEditView', () => { it('param true calls goBack once', () => { spyOn(emailTemplate, 'goBack').and.callThrough(); emailTemplate.goBackToEditView(true); fixture.detectChanges(); expect(emailTemplate.goBack).toHaveBeenCalledTimes(1); }); it('confirm Yes returns to Edit View', () => { const compiled = fixture.debugElement.nativeElement; let addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); spyOn(emailTemplate, 'goBackToEditView').and.callThrough(); spyOn(emailTemplate, 'goBack').and.callThrough(); spyOn(dialogService, 'confirm') .and.returnValue(of(true)) .and.callThrough(); addNewViewButton.click(); fixture.detectChanges(); let goBackButton = compiled.querySelector('button[name="back-to-edit-template"]'); addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); expect(goBackButton).toBeTruthy(); expect(addNewViewButton).toBeFalsy(); goBackButton.click(); expect(emailTemplate.goBackToEditView).toHaveBeenCalledTimes(1); expect(dialogService.confirm).toHaveBeenCalledTimes(1); fixture.detectChanges(); dialogService.confirm('', '').subscribe(() => { expect(emailTemplate.goBack).toHaveBeenCalledTimes(1); const addViewNewButtonShow = compiled.querySelector('button[name="show-new-template-view"]'); goBackButton = compiled.querySelector('button[name="back-to-edit-template"]'); expect(addViewNewButtonShow).toBeTruthy(); expect(goBackButton).toBeFalsy(); }); }); it('confirm cancel keeps Add New View', () => { const compiled = fixture.debugElement.nativeElement; let addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); spyOn(emailTemplate, 'goBackToEditView').and.callThrough(); spyOn(emailTemplate, 'goBack').and.callThrough(); spyOn(dialogService, 'confirm') .and.returnValue(of(false)) .and.callThrough(); addNewViewButton.click(); fixture.detectChanges(); let goBackButton = compiled.querySelector('button[name="back-to-edit-template"]'); addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); expect(goBackButton).toBeTruthy(); expect(addNewViewButton).toBeFalsy(); goBackButton.click(); expect(emailTemplate.goBackToEditView).toHaveBeenCalledTimes(1); expect(dialogService.confirm).toHaveBeenCalledTimes(1); fixture.detectChanges(); dialogService.confirm('', '').subscribe(() => { expect(emailTemplate.goBack).toHaveBeenCalledTimes(0); const addViewNewButtonShow = compiled.querySelector('button[name="show-new-template-view"]'); goBackButton = compiled.querySelector('button[name="back-to-edit-template"]'); expect(addViewNewButtonShow).toBeFalsy(); expect(goBackButton).toBeTruthy(); // }); }); describe('removeTemplate', () => { it('calls TemplateService.remove and calls goBack', () => { const templateService = TestBed.get(TemplateService); updateForm('testName', 'testBody', 'testTitle'); spyOn(templateService, 'remove').and.callThrough(); spyOn(emailTemplate, 'removeTemplate').and.callThrough(); spyOn(emailTemplate, 'goBack').and.callThrough(); spyOn(dialogService, 'confirm') .and.returnValue(of(true)) .and.callThrough(); emailTemplate.removeTemplate(); fixture.detectChanges(); expect(dialogService.confirm).toHaveBeenCalledTimes(1); dialogService.confirm('', '').subscribe(() => { expect(emailTemplate.removeTemplate).toHaveBeenCalledTimes(1); expect(templateService.remove).toHaveBeenCalledTimes(1); templateService.remove(new Template(emailTemplate.template.value)) .subscribe(() => { expect(emailTemplate.goBack).toHaveBeenCalledTimes(1); }); }); }); it('button click and confirm Yes stays on Edit View', () => { const compiled = fixture.debugElement.nativeElement; const templateService = TestBed.get(TemplateService); spyOn(templateService, 'remove').and.callThrough(); spyOn(emailTemplate, 'removeTemplate').and.callThrough(); spyOn(emailTemplate, 'goBack').and.callThrough(); spyOn(dialogService, 'confirm') .and.returnValue(of(true)) .and.callThrough(); let removeButton = compiled.querySelector('button[name="remove-template"]'); let addNewTemplateButton = compiled.querySelector('button[name="add-new-template"]'); expect(removeButton).toBeTruthy(); expect(addNewTemplateButton).toBeFalsy(); removeButton.click(); fixture.detectChanges(); expect(emailTemplate.removeTemplate).toHaveBeenCalledTimes(1); expect(dialogService.confirm).toHaveBeenCalledTimes(1); dialogService.confirm('', '').subscribe(() => { expect(templateService.remove).toHaveBeenCalledTimes(1); templateService.remove(new Template(emailTemplate.template.value)) .subscribe(() => { expect(emailTemplate.goBack).toHaveBeenCalledTimes(1); removeButton = compiled.querySelector('button[name="remove-template"]'); addNewTemplateButton = compiled.querySelector('button[name="add-new-template"]'); expect(removeButton).toBeTruthy(); expect(addNewTemplateButton).toBeFalsy(); }); }); }); it('button click and confirm cancel does not remove template', () => { const compiled = fixture.debugElement.nativeElement; const templateService = TestBed.get(TemplateService); spyOn(templateService, 'remove').and.callThrough(); spyOn(emailTemplate, 'removeTemplate').and.callThrough(); spyOn(emailTemplate, 'goBack').and.callThrough(); spyOn(dialogService, 'confirm') .and.returnValue(of(false)) .and.callThrough(); let removeButton = compiled.querySelector('button[name="remove-template"]'); let addNewTemplateButton = compiled.querySelector('button[name="add-new-template"]'); expect(removeButton).toBeTruthy(); expect(addNewTemplateButton).toBeFalsy(); removeButton.click(); fixture.detectChanges(); expect(emailTemplate.removeTemplate).toHaveBeenCalledTimes(1); expect(dialogService.confirm).toHaveBeenCalledTimes(1); dialogService.confirm('', '').subscribe(() => { expect(templateService.remove).toHaveBeenCalledTimes(0); expect(emailTemplate.goBack).toHaveBeenCalledTimes(1); removeButton = compiled.querySelector('button[name="remove-template"]'); addNewTemplateButton = compiled.querySelector('button[name="add-new-template"]'); expect(removeButton).toBeTruthy(); expect(addNewTemplateButton).toBeFalsy(); }); }); }); describe('saveTemplate', () => { it('saves updated props and calls getTemplateList', () => { updateTemplateSelected('testName', 'testBody', 'testTitle'); updateForm('testName', 'updateBody', 'updateTitle'); const templateService = TestBed.get(TemplateService); spyOn(templateService, 'update').and.callThrough(); spyOn(emailTemplate, 'getTemplateList').and.callThrough(); emailTemplate.saveTemplate(); fixture.detectChanges(); expect(templateService.update).toHaveBeenCalledTimes(1); const updateTemplate = new Template(emailTemplate.template.value); templateService.update(updateTemplate).subscribe(() => { expect(emailTemplate.getTemplateList).toHaveBeenCalledTimes(1); const selectIndex = emailTemplate.templates.findIndex( item => item.name === updateTemplate.name); expect(emailTemplate.getTemplateList) .toHaveBeenCalledWith(selectIndex); }); }); it('button click saves template and calls getTemplateList', () => { const compiled = fixture.debugElement.nativeElement; const saveTemplateButton = compiled.querySelector('button[name="save-template"]'); emailTemplate.selectedTemplate.setValue( emailTemplate.templates[1], {onlySelf: true}); const templateBodyInput = emailTemplate.templatesForm.get(['template', 'body']); const templateBodyTitle = emailTemplate.templatesForm.get(['template', 'title']); const templateService = TestBed.get(TemplateService); spyOn(templateService, 'update').and.callThrough(); spyOn(emailTemplate, 'getTemplateList').and.callThrough(); templateBodyInput!.setValue('test body'); templateBodyTitle!.setValue('test title'); saveTemplateButton.click(); fixture.detectChanges(); expect(templateService.update).toHaveBeenCalledTimes(1); templateService.update(emailTemplate.selectedTemplate.value) .subscribe(() => { expect(emailTemplate.getTemplateList).toHaveBeenCalledTimes(1); const selectIndex = emailTemplate.templates.findIndex( item => item.name === emailTemplate.selectedTemplate.value.name); expect(emailTemplate.getTemplateList) .toHaveBeenCalledWith(selectIndex); }); }); }); }); describe('formValidation', () => { it('edit view form valid with expect body and title', () => { const templateBodyInput = emailTemplate.templatesForm.get(['template', 'body']); const templateBodyTitle = emailTemplate.templatesForm.get(['template', 'title']); templateBodyInput!.setValue(''); templateBodyTitle!.setValue(''); expect(emailTemplate.templatesForm.valid).toBeTruthy(); }); it('add new view form invalid with empty name field', () => { const compiled = fixture.debugElement.nativeElement; const addNewViewButton = compiled.querySelector('button[name="show-new-template-view"]'); const templateService = TestBed.get(TemplateService); spyOn(templateService, 'create').and.callThrough(); spyOn(emailTemplate, 'addTemplate').and.callThrough(); spyOn(emailTemplate, 'goBackToEditView').and.callThrough(); spyOn(emailTemplate, 'goBack').and.callThrough(); addNewViewButton.click(); fixture.detectChanges(); const templateNameInput = emailTemplate.templatesForm.get(['template', 'name']); const errors = templateNameInput!.errors; expect(errors!['required']).toBeTruthy(); expect(emailTemplate.templatesForm.valid).toBeFalsy(); }); }); });
the_stack
import {BaseConsoleView} from "./BaseConsoleView"; import { EngineAdapter, TickerEvent, IObjectUnderPointVO, ITextWrapper, DisplayObjectWrapperMouseEvent, IDisplayObjectWrapper } from "fgraphics/dist/index"; import {Point, KeyboardTools, KeyCodes} from "fcore/dist/index"; import {InputManager, InputManagerEvent, InputManagerEventData} from "flibs/dist/index"; import {BaseConsoleButton} from "./BaseConsoleButton"; import {FC} from "../FC"; export class DisplayListView extends BaseConsoleView { private static ARROW_KEY_CODES:number[] = [KeyCodes.LEFT_ARROW, KeyCodes.RIGHT_ARROW, KeyCodes.UP_ARROW, KeyCodes.DOWN_ARROW]; private lastCheckedPos:Point; private displayListField:ITextWrapper; private closeBtn:BaseConsoleButton; private lastUnderPointData:IObjectUnderPointVO; private lastAllObjectsUnderPointList:any[]; private forceUpdateUnderPointView:boolean; protected additionalInfoBtn:BaseConsoleButton; private _isAdditionalInfoEnabled:boolean; protected moveHelperBtn:BaseConsoleButton; private _isMoveHelperEnabled:boolean; private moveObjectWrapper:IDisplayObjectWrapper; private prevMoveObject:any; private moveObjectIndex:number; constructor() { super(); } protected construction():void { super.construction(); this.captureVisible = true; this.lastCheckedPos = new Point(); this.moveObjectIndex = -1; this.moveObjectWrapper = EngineAdapter.instance.createDisplayObjectWrapper(); this.titleLabel.text = FC.config.localization.displayListTitle; this.insideContentCont.visible = true; this.additionalInfoBtn = new BaseConsoleButton(); this.insideContentCont.addChild(this.additionalInfoBtn.view); this.additionalInfoBtn.tooltipData = { title: FC.config.localization.additionalInfoBtnTooltipTitle, text: FC.config.localization.additionalInfoBtnTooltipText }; this.additionalInfoBtn.field.size = FC.config.btnSettings.smallSize; // this.additionalInfoBtn.view.y = 5; this.moveHelperBtn = new BaseConsoleButton(); this.insideContentCont.addChild(this.moveHelperBtn.view); this.moveHelperBtn.tooltipData = { title: FC.config.localization.moveHelperTooltipTitle, text: FC.config.localization.moveHelperTooltipText }; this.moveHelperBtn.field.size = FC.config.btnSettings.smallSize; // this.moveHelperBtn.view.y = this.additionalInfoBtn.view.y + this.additionalInfoBtn.view.height; this.displayListField = EngineAdapter.instance.createTextWrapper(); this.insideContentCont.addChild(this.displayListField); this.displayListField.color = FC.config.displayListSettings.hierarchyLabelColor; this.displayListField.size = FC.config.displayListSettings.hierarchyLabelSize; // this.displayListField.y = this.moveHelperBtn.view.y + this.moveHelperBtn.view.height + 5; this.closeBtn = this.createTitleBtn( "X", {title: FC.config.localization.closeBtnTooltipTitle} ); this.captureBtn.tooltipData.text = FC.config.localization.displayListCapturedKeyText; } public destruction():void { super.destruction(); this.lastUnderPointData = null; this.lastAllObjectsUnderPointList = null; if (this.moveObjectWrapper) { this.moveObjectWrapper.destruction(); this.moveObjectWrapper = null; } this.prevMoveObject = null; } protected addListeners():void { super.addListeners(); this.eventListenerHelper.addEventListener( EngineAdapter.instance.mainTicker, TickerEvent.TICK, this.onTick ); this.eventListenerHelper.addEventListener( this.closeBtn.view, DisplayObjectWrapperMouseEvent.CLICK, this.onClose ); this.eventListenerHelper.addEventListener( this.additionalInfoBtn.view, DisplayObjectWrapperMouseEvent.CLICK, this.onAdditionalInfo ); this.eventListenerHelper.addEventListener( this.moveHelperBtn.view, DisplayObjectWrapperMouseEvent.CLICK, this.onMoveHelper ); this.eventListenerHelper.addEventListener( InputManager.instance, InputManagerEvent.KEY_DOWN, this.onKeyDown ); } private onTick():void { if (this.visible) { /*if (this.lastCheckedPos.x != EngineAdapter.instance.globalMouseX || this.lastCheckedPos.y != EngineAdapter.instance.globalMouseY) {*/ this.lastCheckedPos.x = EngineAdapter.instance.globalMouseX; this.lastCheckedPos.y = EngineAdapter.instance.globalMouseY; let underPointData:IObjectUnderPointVO = EngineAdapter.instance.getNativeObjectsUnderPoint( EngineAdapter.instance.stage.object, EngineAdapter.instance.globalMouseX, EngineAdapter.instance.globalMouseY ); if (this.forceUpdateUnderPointView || !this.checkUnderPointDataEqual(underPointData, this.lastUnderPointData)) { this.forceUpdateUnderPointView = false; this.lastUnderPointData = underPointData; this.lastAllObjectsUnderPointList = []; this.parseUnderPointDataToSingleList(this.lastUnderPointData, this.lastAllObjectsUnderPointList); let listText:string = this.parseUnderPointData(underPointData); this.displayListField.text = listText; this.arrange(); } // } } } protected onCaptureKey():void { super.onCaptureKey(); let underPointData:IObjectUnderPointVO = EngineAdapter.instance.getNativeObjectsUnderPoint( EngineAdapter.instance.stage.object, EngineAdapter.instance.globalMouseX, EngineAdapter.instance.globalMouseY ); // Log the parsed structure console.group("Display list structure:"); this.groupLogUnderPointData(underPointData); console.groupEnd(); } protected onAdditionalInfo():void { this.isAdditionalInfoEnabled = !this.isAdditionalInfoEnabled; } protected onMoveHelper():void { this.isMoveHelperEnabled = !this.isMoveHelperEnabled; } protected onKeyDown(data:InputManagerEventData):void { if (this.isMoveHelperEnabled) { let tempCode:number = KeyboardTools.getCharCodeFromKeyPressEvent(data.nativeEvent); if (tempCode == KeyCodes.CONTROL) { this.moveObjectIndex--; this.commitData(); } else if (DisplayListView.ARROW_KEY_CODES.indexOf(tempCode) != -1) { if (this.moveObjectWrapper.object) { let tempChangeX:number = 0; let tempChangeY:number = 0; if (tempCode == KeyCodes.LEFT_ARROW) { tempChangeX = -1; } else if (tempCode == KeyCodes.RIGHT_ARROW) { tempChangeX = 1; } if (tempCode == KeyCodes.UP_ARROW) { tempChangeY = -1; } else if (tempCode == KeyCodes.DOWN_ARROW) { tempChangeY = 1; } if (InputManager.instance.checkIfKeyDown(KeyCodes.SHIFT)) { tempChangeX *= 10; tempChangeY *= 10; } this.moveObjectWrapper.x += tempChangeX; this.moveObjectWrapper.y += tempChangeY; console.log("Movable object: ", this.moveObjectWrapper.object); console.log("x: " + this.moveObjectWrapper.x + ", y: " + this.moveObjectWrapper.y); } } } } private parseUnderPointData(data:IObjectUnderPointVO, prefix:string = "∟"):string { let result:string = ""; if (data && data.object) { let tempName:string = data.object.toString(); if (data.object.constructor) { tempName = data.object.constructor.name; } result += prefix + " " + tempName; if (FC.config.displayListSettings.nameParamName) { if (data.object[FC.config.displayListSettings.nameParamName]) { result += " (" + data.object[FC.config.displayListSettings.nameParamName] + ")"; } } if (this.isMoveHelperEnabled) { if (data.object == this.moveObjectWrapper.object) { result += " " + FC.config.localization.movableObjectText; } } if (this.isAdditionalInfoEnabled) { if (FC.config.displayListSettings.additionalInfoParams) { result += " - { "; let parsedData; let tempParamConfig; let keys:string[] = Object.keys(FC.config.displayListSettings.additionalInfoParams); let tempKey:string; let tempVisualKey:string; let keysCount:number = keys.length; for (let keyIndex:number = 0; keyIndex < keysCount; keyIndex++) { tempKey = keys[keyIndex]; if (data.object[tempKey] !== undefined) { if (keyIndex > 0) { result += ", " } parsedData = data.object[tempKey]; // tempParamConfig = FC.config.displayListSettings.additionalInfoParams[tempKey]; if (tempParamConfig.toFixed || tempParamConfig.toFixed === 0) { if (parsedData !== Math.floor(parsedData)) { parsedData = (parsedData as number).toFixed(tempParamConfig.toFixed); } } // tempVisualKey = tempKey; if (tempParamConfig.visualName) { tempVisualKey = tempParamConfig.visualName; } result += tempVisualKey + ": " + parsedData; } } result += " }"; } } if (data.children && data.children.length > 0) { let childPrefix:string = "- " + prefix; let childrenCount:number = data.children.length; for (let childIndex:number = 0; childIndex < childrenCount; childIndex++) { result += "\n" + this.parseUnderPointData(data.children[childIndex], childPrefix); } } } return result; } private groupLogUnderPointData(data:IObjectUnderPointVO, prefix:string = "∟"):void { if (data && data.object) { //console.log(data.object); //console.dir(data.object); console.log(prefix, data.object); if (data.children && data.children.length > 0) { // console.group(" children"); let childrenCount:number = data.children.length; for (let childIndex:number = 0; childIndex < childrenCount; childIndex++) { this.groupLogUnderPointData(data.children[childIndex], " " + prefix); } // console.groupEnd(); } } } private checkUnderPointDataEqual(data1:IObjectUnderPointVO, data2:IObjectUnderPointVO):boolean { let result:boolean = true; // If one of the data objects exists and other doesn't if (!!data1 != !!data2) { result = false; // If 2 data objects are available } else if (data1 && data2) { if (data1.object != data2.object) { result = false; // If one of data has children and other doesn't have } else if (!!data1.children != !!data2.children) { result = false; // If there are children arrays in the both data objects } else if (data1.children && data2.children) { // If length of the children lists are not equal, then data objects are not equal too if (data1.children.length != data2.children.length) { result = false; } else { let childrenCount:number = data1.children.length; for (let childIndex:number = 0; childIndex < childrenCount; childIndex++) { // If one of the children are not equeal, than stop checking and break the loop if (!this.checkUnderPointDataEqual(data1.children[childIndex], data2.children[childIndex])) { result = false; break; } } } } } return result; } private parseUnderPointDataToSingleList(data:IObjectUnderPointVO, list:any[]):void { if (data && data.object) { list.push(data.object); if (data.children && data.children.length > 0) { let childrenCount:number = data.children.length; for (let childIndex:number = 0; childIndex < childrenCount; childIndex++) { this.parseUnderPointDataToSingleList(data.children[childIndex], list); } } } } get isAdditionalInfoEnabled():boolean { return this._isAdditionalInfoEnabled; } set isAdditionalInfoEnabled(value:boolean) { if (value == this._isAdditionalInfoEnabled) { return; } this._isAdditionalInfoEnabled = value; this.commitData(); } get isMoveHelperEnabled():boolean { return this._isMoveHelperEnabled; } set isMoveHelperEnabled(value:boolean) { if (value == this._isMoveHelperEnabled) { return; } this._isMoveHelperEnabled = value; this.commitData(); } protected commitData():void { super.commitData(); if (!this.visible) { this.isAdditionalInfoEnabled = false; this.isMoveHelperEnabled = false; } if (this.additionalInfoBtn) { if (this.isAdditionalInfoEnabled) { this.additionalInfoBtn.label = FC.config.localization.additionalInfoBtnPressedLabel; } else { this.additionalInfoBtn.label = FC.config.localization.additionalInfoBtnNormalLabel; } } if (this.moveHelperBtn) { if (this.isMoveHelperEnabled) { this.moveHelperBtn.label = FC.config.localization.moveHelperBtnPressedLabel; // Select an object (if index is -1, it means that selection is reset) if (this.moveObjectIndex < -1 || this.moveObjectIndex >= this.lastAllObjectsUnderPointList.length) { this.moveObjectIndex = this.lastAllObjectsUnderPointList.length - 1; } // If there is an object, select it if (this.lastAllObjectsUnderPointList[this.moveObjectIndex]) { this.moveObjectWrapper.object = this.lastAllObjectsUnderPointList[this.moveObjectIndex]; } else { this.moveObjectWrapper.object = null; } } else { this.moveHelperBtn.label = FC.config.localization.moveHelperBtnNormalLabel; // Reset selection this.moveObjectWrapper.object = null; this.moveObjectIndex = -1; } // Update the under point view if a new move object was chosen if (this.prevMoveObject !== this.moveObjectWrapper.object) { this.forceUpdateUnderPointView = true; } this.prevMoveObject = this.moveObjectWrapper.object; } } }
the_stack
import { Address, ConditionalTransferTypes, EventNames, EventPayloads, GraphReceipt, IConnextClient, NodeResponses, PrivateKey, PublicParams, SignedTransferStatus, } from "@connext/types"; import { getChainId, getRandomPrivateKey, getTestGraphReceiptToSign, getTestVerifyingContract, signGraphReceiptMessage, } from "@connext/utils"; import { providers, constants, utils } from "ethers"; import { createClient, ETH_AMOUNT_SM, ethProviderUrl, expect, fundChannel, getTestLoggers, TOKEN_AMOUNT, } from "../util"; const { AddressZero } = constants; const { hexlify, randomBytes } = utils; const name = "Graph Signed Transfers"; const { timeElapsed } = getTestLoggers(name); describe(name, () => { let chainId: number; let clientA: IConnextClient; let clientB: IConnextClient; let privateKeyA: PrivateKey; let privateKeyB: PrivateKey; let provider: providers.JsonRpcProvider; let receipt: GraphReceipt; let start: number; let tokenAddress: Address; let verifyingContract: Address; before(async () => { start = Date.now(); provider = new providers.JsonRpcProvider(ethProviderUrl, await getChainId(ethProviderUrl)); const currBlock = await provider.getBlockNumber(); // the node uses a `TIMEOUT_BUFFER` on recipient of 100 blocks // so make sure the current block const TIMEOUT_BUFFER = 100; if (currBlock > TIMEOUT_BUFFER) { // no adjustment needed, return return; } for (let index = currBlock; index <= TIMEOUT_BUFFER + 1; index++) { await provider.send("evm_mine", []); } timeElapsed("beforeEach complete", start); }); beforeEach(async () => { privateKeyA = getRandomPrivateKey(); clientA = await createClient({ signer: privateKeyA, id: "A" }); privateKeyB = getRandomPrivateKey(); clientB = await createClient({ signer: privateKeyB, id: "B" }); tokenAddress = clientA.config.contractAddresses[clientA.chainId].Token!; receipt = getTestGraphReceiptToSign(); chainId = (await clientA.ethProvider.getNetwork()).chainId; verifyingContract = getTestVerifyingContract(); }); afterEach(async () => { await clientA.off(); await clientB.off(); }); it("clientA signed transfers eth to clientB through node, clientB is online", async () => { const transfer = { amount: ETH_AMOUNT_SM, assetId: AddressZero }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); const transferPromise = clientB.waitFor(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, 10_000); await clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, recipient: clientB.publicIdentifier, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer); const installed = await transferPromise; expect(installed).deep.contain({ amount: transfer.amount, appIdentityHash: installed.appIdentityHash, assetId: transfer.assetId, type: ConditionalTransferTypes.GraphTransfer, paymentId, sender: clientA.publicIdentifier, transferMeta: { signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, }, meta: { foo: "bar", recipient: clientB.publicIdentifier, sender: clientA.publicIdentifier, paymentId, senderAssetId: transfer.assetId, }, } as EventPayloads.GraphTransferCreated); const { [clientA.signerAddress]: clientAPostTransferBal, [clientA.nodeSignerAddress]: nodePostTransferBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostTransferBal).to.eq(0); const signature = await signGraphReceiptMessage( receipt, chainId, verifyingContract, privateKeyB, ); const unlockedPromise = clientA.waitFor(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, 10_000); const uninstalledPromise = clientA.waitFor(EventNames.UNINSTALL_EVENT, 10_000); await clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, responseCID: receipt.responseCID, signature, } as PublicParams.ResolveGraphTransfer); const eventData = await unlockedPromise; await uninstalledPromise; expect(eventData).to.deep.contain({ amount: transfer.amount, assetId: transfer.assetId, type: ConditionalTransferTypes.GraphTransfer, paymentId, sender: clientA.publicIdentifier, transferMeta: { responseCID: receipt.responseCID, signature, }, meta: { foo: "bar", recipient: clientB.publicIdentifier, sender: clientA.publicIdentifier, senderAssetId: transfer.assetId, paymentId, }, } as EventPayloads.GraphTransferUnlocked); const { [clientA.signerAddress]: clientAPostReclaimBal, [clientA.nodeSignerAddress]: nodePostReclaimBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostReclaimBal).to.eq(0); expect(nodePostReclaimBal).to.eq(nodePostTransferBal.add(transfer.amount)); const { [clientB.signerAddress]: clientBPostTransferBal } = await clientB.getFreeBalance( transfer.assetId, ); expect(clientBPostTransferBal).to.eq(transfer.amount); }); it("clientA signed transfers tokens to clientB through node", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); const promises = await Promise.all([ clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, recipient: clientB.publicIdentifier, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer), new Promise(async (res) => { clientB.once(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, res); }), ]); const [, installed] = promises; expect(installed).deep.contain({ amount: transfer.amount, assetId: transfer.assetId, type: ConditionalTransferTypes.GraphTransfer, paymentId, transferMeta: { signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, }, meta: { foo: "bar", recipient: clientB.publicIdentifier, sender: clientA.publicIdentifier, senderAssetId: transfer.assetId, paymentId, }, } as Partial<EventPayloads.GraphTransferCreated>); const { [clientA.signerAddress]: clientAPostTransferBal, [clientA.nodeSignerAddress]: nodePostTransferBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostTransferBal).to.eq(0); const signature = await signGraphReceiptMessage( receipt, chainId, verifyingContract, privateKeyB, ); await new Promise(async (res) => { clientA.on(EventNames.UNINSTALL_EVENT, async (data) => { const { [clientA.signerAddress]: clientAPostReclaimBal, [clientA.nodeSignerAddress]: nodePostReclaimBal, } = await clientA.getFreeBalance(transfer.assetId); expect(clientAPostReclaimBal).to.eq(0); expect(nodePostReclaimBal).to.eq(nodePostTransferBal.add(transfer.amount)); res(); }); await clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, responseCID: receipt.responseCID, signature, } as PublicParams.ResolveGraphTransfer); const { [clientB.signerAddress]: clientBPostTransferBal } = await clientB.getFreeBalance( transfer.assetId, ); expect(clientBPostTransferBal).to.eq(transfer.amount); }); }); it("gets a pending signed transfer by lock hash", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); await clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, recipient: clientB.publicIdentifier, assetId: transfer.assetId, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer); const retrievedTransfer = await clientB.getGraphTransfer(paymentId); expect(retrievedTransfer).to.deep.equal({ amount: transfer.amount.toString(), assetId: transfer.assetId, paymentId, senderIdentifier: clientA.publicIdentifier, receiverIdentifier: clientB.publicIdentifier, status: SignedTransferStatus.PENDING, meta: { foo: "bar", sender: clientA.publicIdentifier, paymentId, senderAssetId: transfer.assetId, }, } as NodeResponses.GetSignedTransfer); }); it("gets a completed signed transfer by lock hash", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); const receiverInstall = clientB.waitFor(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, 10_000); await clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, recipient: clientB.publicIdentifier, signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer); await receiverInstall; // disconnect so that it cant be unlocked await clientA.off(); const signature = await signGraphReceiptMessage( receipt, chainId, verifyingContract, privateKeyB, ); // wait for transfer to be picked up by receiver await new Promise(async (resolve, reject) => { clientB.once( EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, resolve, (data) => !!data.paymentId && data.paymentId === paymentId, ); clientB.once( EventNames.CONDITIONAL_TRANSFER_FAILED_EVENT, reject, (data) => !!data.paymentId && data.paymentId === paymentId, ); await clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, responseCID: receipt.responseCID, signature, }); }); const retrievedTransfer = await clientB.getGraphTransfer(paymentId); expect(retrievedTransfer).to.deep.equal({ amount: transfer.amount.toString(), assetId: transfer.assetId, paymentId, senderIdentifier: clientA.publicIdentifier, receiverIdentifier: clientB.publicIdentifier, status: SignedTransferStatus.COMPLETED, meta: { foo: "bar", sender: clientA.publicIdentifier, paymentId, senderAssetId: transfer.assetId, }, } as NodeResponses.GetSignedTransfer); }); it("cannot resolve a signed transfer if signature is wrong", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); const receiverInstalled = clientB.waitFor( EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, 10_000, ); await clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, signerAddress: clientB.signerAddress, chainId, recipient: clientB.publicIdentifier, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer); await receiverInstalled; const badSig = hexlify(randomBytes(65)); await expect( clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, responseCID: receipt.responseCID, signature: badSig, } as PublicParams.ResolveGraphTransfer), ).to.eventually.be.rejectedWith(/invalid signature/); }); it("if sender uninstalls, node should force uninstall receiver first", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); const [transferRes, receiverRes] = await Promise.all([ clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, recipient: clientB.publicIdentifier, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer), new Promise((res, rej) => { clientB.once(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, res); clientA.once(EventNames.REJECT_INSTALL_EVENT, rej); }), ]); clientA.uninstallApp((transferRes as any).appIdentityHash); const winner = await Promise.race([ new Promise<EventPayloads.Uninstall>((res) => { clientA.once( EventNames.UNINSTALL_EVENT, res, (data) => data.appIdentityHash === (transferRes as any).appIdentityHash, ); }), new Promise<EventPayloads.Uninstall>((res) => { clientB.once(EventNames.UNINSTALL_EVENT, res); }), ]); expect(winner.appIdentityHash).to.be.eq( (receiverRes as EventPayloads.SignedTransferCreated).appIdentityHash, ); }); it("sender cannot uninstall before receiver", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); const [transferRes] = await Promise.all([ clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, recipient: clientB.publicIdentifier, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer), new Promise((res, rej) => { clientB.once(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, res); clientA.once(EventNames.REJECT_INSTALL_EVENT, rej); }), ]); // disconnect so receiver cannot uninstall await clientB.off(); await clientB.off(); await expect(clientA.uninstallApp((transferRes as any).appIdentityHash)).to.eventually.be .rejected; }); it("sender cannot uninstall unfinalized app when receiver is finalized", async () => { const transfer = { amount: TOKEN_AMOUNT, assetId: tokenAddress }; await fundChannel(clientA, transfer.amount, transfer.assetId); const paymentId = hexlify(randomBytes(32)); const signature = await signGraphReceiptMessage( receipt, chainId, verifyingContract, privateKeyB, ); const [transferRes] = await Promise.all([ clientA.conditionalTransfer({ amount: transfer.amount, conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, signerAddress: clientB.signerAddress, chainId, verifyingContract, requestCID: receipt.requestCID, subgraphDeploymentID: receipt.subgraphDeploymentID, assetId: transfer.assetId, recipient: clientB.publicIdentifier, meta: { foo: "bar", sender: clientA.publicIdentifier }, } as PublicParams.GraphTransfer), new Promise((res, rej) => { clientB.once(EventNames.CONDITIONAL_TRANSFER_CREATED_EVENT, res); clientA.once(EventNames.REJECT_INSTALL_EVENT, rej); }), ]); // disconnect so sender cannot unlock await clientA.off(); await Promise.all([ new Promise((res) => { clientB.once(EventNames.CONDITIONAL_TRANSFER_UNLOCKED_EVENT, res); }), clientB.resolveCondition({ conditionType: ConditionalTransferTypes.GraphTransfer, paymentId, responseCID: receipt.responseCID, signature, } as PublicParams.ResolveGraphTransfer), ]); clientA.messaging.connect(); await expect(clientA.uninstallApp((transferRes as any).appIdentityHash)).to.eventually.be .rejected; }); });
the_stack
import { DefaultWebGL2BufferFragment, DefaultWebGLBufferFragment } from '../context/chunks'; import Context from '../context/context'; import IterableStringMap from '../core/iterable'; import FlatGeometry from '../geometry/flat-geometry'; import Geometry from '../geometry/geometry'; export enum BufferFloatType { FLOAT = 0, HALF_FLOAT, } export class Buffer { texture: WebGLTexture; buffer: WebGLFramebuffer; BW: number; BH: number; index: number; static type: BufferFloatType = BufferFloatType.HALF_FLOAT; static getFloatType(gl: WebGLRenderingContext | WebGL2RenderingContext): number | null { let extension: any; if (Context.isWebGl2(gl)) { extension = gl.getExtension('EXT_color_buffer_float'); if (extension) { return gl.FLOAT; } } extension = gl.getExtension('OES_texture_float'); if (extension) { return gl.FLOAT; } return null; } static getHalfFloatType(gl: WebGLRenderingContext | WebGL2RenderingContext): number | null { let extension: any; if (Context.isWebGl2(gl)) { extension = gl.getExtension('EXT_color_buffer_half_float') || gl.getExtension('EXT_color_buffer_float'); if (extension) { return (gl as WebGL2RenderingContext).HALF_FLOAT; } } extension = gl.getExtension('OES_texture_half_float'); if (extension) { return extension.HALF_FLOAT_OES || null; } return null; } static getInternalFormat(gl: WebGLRenderingContext | WebGL2RenderingContext): number { return (Context.isWebGl2(gl) ? (gl as WebGL2RenderingContext).RGBA16F : gl.RGBA); } static getType(gl: WebGLRenderingContext | WebGL2RenderingContext): number { let type: number; if (Buffer.type === BufferFloatType.HALF_FLOAT) { type = Buffer.getHalfFloatType(gl); if (type) { return type; } else { Buffer.type = BufferFloatType.FLOAT; return Buffer.getType(gl); } } else { type = Buffer.getFloatType(gl); if (type) { return type; } else { Buffer.type = BufferFloatType.HALF_FLOAT; return Buffer.getType(gl); } } } static getTexture(gl: WebGLRenderingContext | WebGL2RenderingContext, BW: number, BH: number, index: number): WebGLTexture { const internalFormat = Buffer.getInternalFormat(gl); const format = gl.RGBA; const type = Buffer.getType(gl); const texture = gl.createTexture(); gl.activeTexture(gl.TEXTURE0 + index); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, BW, BH, 0, format, type, null); const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status !== gl.FRAMEBUFFER_COMPLETE) { if (Buffer.type === BufferFloatType.FLOAT) { Buffer.type = BufferFloatType.HALF_FLOAT; } else { Buffer.type = BufferFloatType.FLOAT; } return Buffer.getTexture(gl, BW, BH, index); } // console.log('getTexture', 'internalFormat', internalFormat === (gl as WebGL2RenderingContext).RGBA16F, 'format', format === gl.RGBA, 'type', type === (gl as WebGL2RenderingContext).HALF_FLOAT, 'status', status === gl.FRAMEBUFFER_COMPLETE); return texture; } constructor(gl: WebGLRenderingContext | WebGL2RenderingContext, BW: number, BH: number, index: number) { const buffer = gl.createFramebuffer(); const texture = Buffer.getTexture(gl, BW, BH, index); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); this.texture = texture; this.buffer = buffer; this.BW = BW; this.BH = BH; this.index = index; } resize(gl: WebGLRenderingContext | WebGL2RenderingContext, BW: number, BH: number) { if (BW !== this.BW || BH !== this.BH) { const buffer = this.buffer; const texture = this.texture; const index = this.index; gl.bindFramebuffer(gl.FRAMEBUFFER, buffer); const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); const minW = Math.min(BW, this.BW); const minH = Math.min(BH, this.BH); let pixels: Float32Array; let type = Buffer.getType(gl); if (status === gl.FRAMEBUFFER_COMPLETE) { pixels = new Float32Array(minW * minH * 4); gl.readPixels(0, 0, minW, minH, gl.RGBA, type, pixels); } gl.bindFramebuffer(gl.FRAMEBUFFER, null); const newIndex = index + 1; // temporary index const newTexture = Buffer.getTexture(gl, BW, BH, newIndex); type = Buffer.getType(gl); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); if (pixels) { gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, minW, minH, gl.RGBA, type, pixels); } const newBuffer = gl.createFramebuffer(); /* if (!newBuffer) { Logger.error('Failed to create the frame buffer object'); return null; } */ gl.bindFramebuffer(gl.FRAMEBUFFER, null); gl.deleteTexture(texture); gl.activeTexture(gl.TEXTURE0 + index); gl.bindTexture(gl.TEXTURE_2D, newTexture); this.index = index; this.texture = newTexture; this.buffer = newBuffer; this.BW = BW; this.BH = BH; // console.log('resize', newBuffer); } } } export class IOBuffer { program: WebGLProgram; geometry: Geometry; input: Buffer; output: Buffer; index: number; key: string; vertexString: string; fragmentString: string; BW: number; BH: number; isValid: boolean = false; constructor(index: number, key: string, vertexString: string, fragmentString: string) { this.index = index; this.key = key; this.vertexString = vertexString; this.fragmentString = fragmentString; this.geometry = new FlatGeometry(); } create(gl: WebGLRenderingContext | WebGL2RenderingContext, BW: number, BH: number) { // BW = BH = 1024; const vertexShader = Context.createShader(gl, this.vertexString, gl.VERTEX_SHADER); let fragmentShader = Context.createShader(gl, this.fragmentString, gl.FRAGMENT_SHADER, 1); if (!fragmentShader) { fragmentShader = Context.createShader(gl, Context.isWebGl2(gl) ? DefaultWebGL2BufferFragment : DefaultWebGLBufferFragment, gl.FRAGMENT_SHADER); this.isValid = false; } else { this.isValid = true; } const program = Context.createProgram(gl, [vertexShader, fragmentShader]); if (!program) { this.isValid = false; gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); return; } this.geometry.create(gl, program); gl.deleteShader(vertexShader); gl.deleteShader(fragmentShader); const input = new Buffer(gl, BW, BH, this.index + 0); const output = new Buffer(gl, BW, BH, this.index + 2); this.program = program; this.input = input; this.output = output; // console.log(geometry.position.length / 3, geometry.size); // console.log(gl.getProgramInfoLog(program)); // Context.lastError = gl.getProgramInfoLog(program); // Logger.warn(`Error in program linking: ${Context.lastError}`); } render(gl: WebGLRenderingContext | WebGL2RenderingContext, BW: number, BH: number) { // BW = BH = 1024; gl.useProgram(this.program); // gl.activeTexture(gl.TEXTURE0); // gl.bindTexture(gl.TEXTURE_2D, this.input.texture); gl.bindFramebuffer(gl.FRAMEBUFFER, this.output.buffer); // gl.bindTexture(gl.TEXTURE_2D, this.output.texture); // console.log(this.output.texture); // console.log('binding', gl.getParameter(gl.FRAMEBUFFER_BINDING)); // gl.enable(gl.DEPTH_TEST); // Enable depth testing // gl.depthFunc(gl.LEQUAL); // Near things obscure far things gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.output.texture, 0); const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (status === gl.FRAMEBUFFER_COMPLETE) { // Clear the canvas before we start drawing on it. gl.clearColor(0, 0, 0, 1); // black gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } // this.geometry.createAttributes_(gl, this.program); // this.geometry.bindAttributes_(gl, this.program); gl.viewport(0, 0, BW, BH); gl.drawArrays(gl.TRIANGLES, 0, this.geometry.size); // console.log(this.geometry.size); // gl.bindFramebuffer(gl.FRAMEBUFFER, null); // console.log(BW, BH); // console.log(gl.getProgramInfoLog(this.program)); // swap const input = this.input; // const output = this.output; this.input = this.output; this.output = input; // console.log('swap'); } resize(gl: WebGLRenderingContext | WebGL2RenderingContext, BW: number, BH: number) { // BW = BH = 1024; gl.useProgram(this.program); gl.viewport(0, 0, BW, BH); this.input.resize(gl, BW, BH); this.output.resize(gl, BW, BH); } destroy(gl: WebGLRenderingContext | WebGL2RenderingContext) { gl.deleteProgram(this.program); this.program = null; this.input = null; this.output = null; } } export default class Buffers extends IterableStringMap<IOBuffer> { get count(): number { return Object.keys(this.values).length * 4; } static getBuffers(gl: WebGLRenderingContext | WebGL2RenderingContext, fragmentString: string, vertexString: string): Buffers { const buffers: Buffers = new Buffers(); let count = 0; if (fragmentString) { if (Context.isWebGl2(gl)) { fragmentString = fragmentString.replace(/^\#version\s*300\s*es\s*\n/, ''); } const regexp = /(?:^\s*)((?:#if|#elif)(?:\s*)(defined\s*\(\s*BUFFER_)(\d+)(?:\s*\))|(?:#ifdef)(?:\s*BUFFER_)(\d+)(?:\s*))/gm; let matches; while ((matches = regexp.exec(fragmentString)) !== null) { const i = matches[3] || matches[4]; const key = 'u_buffer' + i; const bufferFragmentString = Context.isWebGl2(gl) ? `#version 300 es #define BUFFER_${i} ${fragmentString}` : `#define BUFFER_${i} ${fragmentString}`; const buffer = new IOBuffer(count, key, vertexString, bufferFragmentString); buffer.create(gl, gl.drawingBufferWidth, gl.drawingBufferHeight); if (buffer.program) { buffers.set(key, buffer); } else { throw (`buffer error ${key}`); } count += 4; } } return buffers; } }
the_stack
import { ApplicationRef, Component, Directive, HostBinding, Inject, Injectable, Input, ModuleWithProviders, NgModule, Optional } from '@angular/core'; import { MenuCheckboxDirective, MenuDirective, MenuItemDirective, MenuRadioDirective, MenuSeparatorDirective } from './menu.component'; import { detectChangesNextFrame, OpenExternalDirective, ZonelessChangeDetector } from './utils'; import { ViewDirective } from './dui-view.directive'; import { CdCounterComponent } from './cd-counter.component'; import { DuiResponsiveDirective } from './dui-responsive.directive'; import { CommonModule, DOCUMENT } from '@angular/common'; import { Electron } from '../../core/utils'; import { ActivationEnd, Event as RouterEvent, NavigationEnd, Router } from '@angular/router'; import { WindowRegistry } from '../window/window-state'; import { ELECTRON_WINDOW, IN_DIALOG } from './token'; import { AsyncRenderPipe, HumanFileSizePipe, ObjectURLPipe } from './pipes'; import { ReactiveChangeDetectionModule } from './reactivate-change-detection'; import { arrayRemoveItem } from '@deepkit/core'; export * from './reactivate-change-detection'; export * from './cd-counter.component'; export * from './dui-view.directive'; export * from './dui-responsive.directive'; export * from './utils'; export * from './menu.component'; export * from './pipes'; if ('undefined' !== typeof window && 'undefined' === typeof (window as any)['global']) { (window as any).global = window; } @Directive() export class BaseComponent { @Input() disabled?: boolean; @HostBinding('class.disabled') get isDisabled() { return this.disabled === true; } } @Component({ selector: 'ui-component', template: ` {{name}} disabled={{isDisabled}} `, styles: [` :host { display: inline-block; } :host.disabled { border: 1px solid red; } `], host: { '[class.is-textarea]': 'name === "textarea"', } }) export class UiComponentComponent extends BaseComponent { @Input() name: string = ''; } export class OverlayStackItem { constructor(public host: HTMLElement, protected stack: OverlayStackItem[], public release: () => void) { } getAllAfter(): OverlayStackItem[] { const result: OverlayStackItem[] = []; let flip = false; for (let i = 0; i < this.stack.length; i++) { if (flip) result.push(this.stack[i]); if (this.stack[i] === this) flip = true; } return result; } getPrevious(): OverlayStackItem | undefined { const before = this.getAllBefore(); return before.length ? before[before.length - 1] : undefined; } isLast(): boolean { return this.getAllAfter().length === 0; } getAllBefore(): OverlayStackItem[] { const result: OverlayStackItem[] = []; for (let i = 0; i < this.stack.length; i++) { if (this.stack[i] === this) return result; result.push(this.stack[i]); } return result; } } export class OverlayStack { public stack: OverlayStackItem[] = []; public register(host: HTMLElement): OverlayStackItem { const item = new OverlayStackItem(host, this.stack, () => { const before = item.getPrevious(); if (before) before.host.focus(); arrayRemoveItem(this.stack, item); }); this.stack.push(item); return item; } } @Injectable() export class DuiApp { protected darkMode?: boolean = false; protected platform: 'web' | 'darwin' | 'linux' | 'win32' = 'darwin'; constructor( protected app: ApplicationRef, protected windowRegistry: WindowRegistry, @Optional() protected router?: Router ) { ZonelessChangeDetector.app = app; if ('undefined' !== typeof window) { (window as any)['DuiApp'] = this; } } start() { if (Electron.isAvailable()) { document.body.classList.add('electron'); const remote = Electron.getRemote(); this.setPlatform(remote.process.platform); } else { this.setPlatform('web'); } let overwrittenDarkMode = localStorage.getItem('duiApp/darkMode'); if (overwrittenDarkMode) { this.setDarkMode(JSON.parse(overwrittenDarkMode)); } else { this.setDarkMode(); } const mm = window.matchMedia('(prefers-color-scheme: dark)'); const setTheme = () => { if (localStorage.getItem('duiApp/darkMode') === null) { this.setAutoDarkMode(); this.app.tick(); } }; if (mm.addEventListener) { mm.addEventListener('change', setTheme); } else { //ios mm.addListener(setTheme); } if ('undefined' !== typeof document) { document.addEventListener('click', () => detectChangesNextFrame()); document.addEventListener('focus', () => detectChangesNextFrame()); document.addEventListener('blur', () => detectChangesNextFrame()); document.addEventListener('keydown', () => detectChangesNextFrame()); document.addEventListener('keyup', () => detectChangesNextFrame()); document.addEventListener('keypress', () => detectChangesNextFrame()); document.addEventListener('mousedown', () => detectChangesNextFrame()); } //necessary to render all router-outlet once the router changes if (this.router) { this.router.events.subscribe((event: RouterEvent) => { if (event instanceof NavigationEnd || event instanceof ActivationEnd) { detectChangesNextFrame(); } }); } } setPlatform(platform: 'web' | 'darwin' | 'linux' | 'win32') { this.platform = platform; //deprecate these document.body.classList.remove('platform-linux'); document.body.classList.remove('platform-darwin'); document.body.classList.remove('platform-win32'); document.body.classList.remove('platform-native'); document.body.classList.remove('platform-web'); document.body.classList.remove('dui-platform-linux'); document.body.classList.remove('dui-platform-darwin'); document.body.classList.remove('dui-platform-win32'); document.body.classList.remove('dui-platform-native'); document.body.classList.remove('dui-platform-web'); if (this.platform !== 'web') { document.body.classList.add('platform-native'); //todo: deprecate document.body.classList.add('dui-platform-native'); } document.body.classList.add('platform-' + platform);//todo: deprecate document.body.classList.add('dui-platform-' + platform); } getPlatform(): string { return this.platform; } isDarkMode(): boolean { return this.darkMode === true; } setAutoDarkMode(): void { this.setDarkMode(); } get theme(): 'auto' | 'light' | 'dark' { if (this.isDarkModeOverwritten()) { return this.isDarkMode() ? 'dark' : 'light'; } return 'auto'; } set theme(theme: 'auto' | 'light' | 'dark') { if (theme === 'auto') { this.setAutoDarkMode(); return; } this.setDarkMode(theme === 'dark'); } isDarkModeOverwritten(): boolean { return localStorage.getItem('duiApp/darkMode') !== null; } setGlobalDarkMode(darkMode: boolean): void { if (Electron.isAvailable()) { const remote = Electron.getRemote(); for (const win of remote.BrowserWindow.getAllWindows()) { win.webContents.executeJavaScript(`DuiApp.setDarkMode(${darkMode})`); } } } getVibrancy(): 'ultra-dark' | 'light' { return this.darkMode ? 'ultra-dark' : 'light'; } setDarkMode(darkMode?: boolean) { if (darkMode === undefined) { this.darkMode = this.isPreferDarkColorSchema(); localStorage.removeItem('duiApp/darkMode'); } else { localStorage.setItem('duiApp/darkMode', JSON.stringify(darkMode)); this.darkMode = darkMode; } for (const win of this.windowRegistry.getAllElectronWindows()) { win.setVibrancy(this.getVibrancy()); } //todo: deprecate these document.body.classList.remove('dark'); document.body.classList.remove('light'); document.body.classList.add(this.darkMode ? 'dark' : 'light'); document.body.classList.remove('dui-theme-dark'); document.body.classList.remove('dui-theme-light'); document.body.classList.add(this.darkMode ? 'dui-theme-dark' : 'dui-theme-light'); window.dispatchEvent(new Event('theme-changed')); } protected isPreferDarkColorSchema() { return window.matchMedia('(prefers-color-scheme: dark)').matches; } } @NgModule({ declarations: [ UiComponentComponent, MenuDirective, MenuSeparatorDirective, MenuRadioDirective, MenuCheckboxDirective, MenuItemDirective, OpenExternalDirective, ViewDirective, CdCounterComponent, DuiResponsiveDirective, AsyncRenderPipe, ObjectURLPipe, HumanFileSizePipe, ], exports: [ UiComponentComponent, MenuDirective, MenuSeparatorDirective, MenuRadioDirective, MenuCheckboxDirective, MenuItemDirective, OpenExternalDirective, ViewDirective, CdCounterComponent, DuiResponsiveDirective, AsyncRenderPipe, ObjectURLPipe, HumanFileSizePipe, ], providers: [OverlayStack], imports: [ CommonModule, ReactiveChangeDetectionModule, ] }) export class DuiAppModule { constructor(app: DuiApp, @Inject(DOCUMENT) @Optional() document: Document) { app.start(); if (document && Electron.isAvailable()) { document.addEventListener('click', (event: MouseEvent) => { if (event.target) { const target = event.target as HTMLElement; if (target.tagName.toLowerCase() === 'a') { event.preventDefault(); event.stopPropagation(); Electron.getRemote().shell.openExternal((target as any).href); } } }); } } static forRoot(): ModuleWithProviders<DuiAppModule> { return { ngModule: DuiAppModule, providers: [ DuiApp, { provide: IN_DIALOG, useValue: false }, { provide: ELECTRON_WINDOW, useValue: Electron.isAvailable() ? Electron.getRemote().BrowserWindow.getAllWindows()[0] : undefined }, ] }; } }
the_stack
import * as Immutable from 'immutable'; import * as shortid from 'shortid'; import { RequestForApplicationNotifications, RequestForApplicationNotificationsStep, } from '../notifications/duck'; import { Targets } from '../urlrouter/constants'; import { InstallContext } from './types'; /** * ------------- * - PERSISTED - * ------------- */ // Constants export const CREATE_APPLICATION = 'browserX/applications/CREATE_APPLICATION'; export type CREATE_APPLICATION = 'browserX/applications/CREATE_APPLICATION'; export const DROP_APPLICATION = 'browserX/applications/DROP_APPLICATION'; export type DROP_APPLICATION = 'browserX/applications/DROP_APPLICATION'; export const RESET_APPLICATION = 'browserX/applications/RESET_APPLICATION'; export type RESET_APPLICATION = 'browserX/applications/RESET_APPLICATION'; export const SET_ACTIVE_TAB = 'browserX/applications/SET_ACTIVE_TAB'; export type SET_ACTIVE_TAB = 'browserX/applications/SET_ACTIVE_TAB'; export const ZOOM_IN = 'browserX/applications/ZOOM_IN'; export type ZOOM_IN = 'browserX/applications/ZOOM_IN'; export const ZOOM_OUT = 'browserX/applications/ZOOM_OUT'; export type ZOOM_OUT = 'browserX/applications/ZOOM_OUT'; export const RESET_ZOOM = 'browserX/applications/RESET_ZOOM'; export type RESET_ZOOM = 'browserX/applications/RESET_ZOOM'; export const UPDATE_ICON = 'browserX/applications/UPDATE_ICON'; export type UPDATE_ICON = 'browserX/applications/UPDATE_ICON'; export const SET_CONFIG_DATA = 'browserX/applications/SET_CONFIG_DATA'; export type SET_CONFIG_DATA = 'browserX/applications/SET_CONFIG_DATA'; export const INSTALL_APPLICATION = 'browserX/applications/INSTALL_APPLICATION'; export type INSTALL_APPLICATION = 'browserX/applications/INSTALL_APPLICATION'; export const UNINSTALL_APPLICATION = 'browserX/applications/UNINSTALL_APPLICATION'; export type UNINSTALL_APPLICATION = 'browserX/applications/UNINSTALL_APPLICATION'; export const REMOTE_UPDATE_INSTALLED_APPLICATIONS = 'browserX/applications/REMOTE_UPDATE_INSTALLED_APPLICATIONS'; export type REMOTE_UPDATE_INSTALLED_APPLICATIONS = 'browserX/applications/REMOTE_UPDATE_INSTALLED_APPLICATIONS'; export const DISPATCH_URL = 'browserX/applications/DISPATCH_URL'; export type DISPATCH_URL = 'browserX/applications/DISPATCH_URL'; export const TOGGLE_NOTIFICATIONS = 'browserX/applications/TOGGLE_NOTIFICATIONS'; export type TOGGLE_NOTIFICATIONS = 'browserX/applications/TOGGLE_NOTIFICATIONS'; export const DISABLE_NOTIFICATIONS = 'browserX/applications/DISABLE_NOTIFICATIONS'; export type DISABLE_NOTIFICATIONS = 'browserX/applications/DISABLE_NOTIFICATIONS'; export const ENABLE_NOTIFICATIONS = 'browserX/applications/ENABLE_NOTIFICATIONS'; export type ENABLE_NOTIFICATIONS = 'browserX/applications/ENABLE_NOTIFICATIONS'; export const ASK_ENABLE_NOTIFICATIONS = 'browserX/notification-center/ASK_ENABLE_NOTIFICATIONS'; export type ASK_ENABLE_NOTIFICATIONS = 'browserX/notification-center/ASK_ENABLE_NOTIFICATIONS'; export const SET_HOME_TAB_AS_ACTIVE = 'browserX/applications/SET_HOME_TAB_AS_ACTIVE'; export type SET_HOME_TAB_AS_ACTIVE = 'browserX/applications/SET_HOME_TAB_AS_ACTIVE'; export const CREATE_NEW_EMPTY_TAB = 'browserX/applications/CREATE_NEW_EMPTY_TAB'; export type CREATE_NEW_EMPTY_TAB = 'browserX/applications/CREATE_NEW_EMPTY_TAB'; export const CREATE_NEW_TAB = 'browserX/applications/CREATE_NEW_TAB'; export type CREATE_NEW_TAB = 'browserX/applications/CREATE_NEW_TAB'; export const CHANGE_SELECTED_APP = 'browserX/applications/CHANGE_SELECTED_APP'; export type CHANGE_SELECTED_APP = 'browserX/applications/CHANGE_SELECTED_APP'; export const NAVIGATE_TO_TAB = 'browserX/applications/NAVIGATE_TO_TAB'; export type NAVIGATE_TO_TAB = 'browserX/applications/NAVIGATE_TO_TAB'; export const NAVIGATE_TO_APPLICATION_TAB = 'browserX/applications/NAVIGATE_TO_APPLICATION_TAB'; export type NAVIGATE_TO_APPLICATION_TAB = 'browserX/applications/NAVIGATE_TO_APPLICATION_TAB'; export const NAVIGATE_TO_APPLICATION_TAB_AUTO = 'browserX/applications/NAVIGATE_TO_APPLICATION_TAB_AUTO'; export type NAVIGATE_TO_APPLICATION_TAB_AUTO = 'browserX/applications/NAVIGATE_TO_APPLICATION_TAB_AUTO'; export type ApplicationConfigData = { identityId?: string, subdomain?: string, customURL?: string }; export type ChangeSelectedAppVia = 'keyboard_shortcut_ctrl_num' | 'keyboard_shortcut_ctrl_alt_arrow' | 'mouse_click' | 'settings-configure-account' | 'app-installation' | 'app-reset' | 'close-tab' | null; // Action Types export type CreateApplicationAction = { type: CREATE_APPLICATION, applicationId: string; manifestURL: string, installContext?: InstallContext, doNotNavigateTo: boolean, }; export type DropApplicationAction = { type: DROP_APPLICATION, applicationId: string, }; export type ResetApplicationAction = { type: RESET_APPLICATION, applicationId: string, via: string, }; export type SetActiveTabAction = { type: SET_ACTIVE_TAB, applicationId: string, tabId: string, silent: boolean, }; export type ZoomInAction = { type: ZOOM_IN, applicationId: string, }; export type ZoomOutAction = { type: ZOOM_OUT, applicationId: string, }; export type ResetZoomAction = { type: RESET_ZOOM, applicationId: string, }; export type UpdateIconAction = { type: UPDATE_ICON, applicationId: string, imageURL: string, }; export type SetConfigDataAction = { type: SET_CONFIG_DATA, applicationId: string, configData: ApplicationConfigData, }; export type InstallApplicationAction = { type: INSTALL_APPLICATION, manifestURL: string, configData?: ApplicationConfigData, navigate?: boolean, optOutFlow?: boolean, installContext?: InstallContext, andCreateTabWithURL?: string, }; export type UninstallApplicationAction = { type: UNINSTALL_APPLICATION, applicationId: string, }; export type RemoteUpdateInstalledApplicationsAction = { type: REMOTE_UPDATE_INSTALLED_APPLICATIONS, }; export type DispatchURLAction = { type: DISPATCH_URL, url: string, origin?: { tabId?: string, applicationId?: string }, options?: { target: Targets }, }; export type ToggleNotificationsAction = { type: TOGGLE_NOTIFICATIONS, applicationId: string, }; export type DisableNotificationsAction = { type: DISABLE_NOTIFICATIONS, applicationId: string, }; export type EnableNotificationsAction = { type: ENABLE_NOTIFICATIONS, applicationId: string, }; export type AskEnableNotificationsAction = { type: ASK_ENABLE_NOTIFICATIONS, applicationId: string, tabId: string, notificationId: string, props: any, step: RequestForApplicationNotificationsStep, }; export type SetHomeTabAsActiveAction = { type: SET_HOME_TAB_AS_ACTIVE, applicationId: string, }; export type CreateNewEmptyTabAction = { type: CREATE_NEW_EMPTY_TAB, applicationId: string, home: boolean, }; export type CreateNewTabAction = { type: CREATE_NEW_TAB, applicationId: string, url: string, detach: boolean, home: boolean, navigateToApplication: boolean, }; export type ChangeSelectedAppAction = { type: CHANGE_SELECTED_APP, applicationId: string, via: ChangeSelectedAppVia, markAsActiveTab: boolean, }; export type NavigateToTabAction = { type: NAVIGATE_TO_TAB, applicationId: string, tabId: string, silent: boolean, }; export type NavigateToApplicationTabAction = { type: NAVIGATE_TO_APPLICATION_TAB, applicationId: string, tabId: string, silent: boolean, via: ChangeSelectedAppVia, }; export type NavigateToApplicationTabAutoAction = { type: NAVIGATE_TO_APPLICATION_TAB_AUTO, tabId: string, silent: boolean, via: ChangeSelectedAppVia, }; export type ZoomActions = ZoomInAction | ZoomOutAction | ResetZoomAction; export type ApplicationActions = CreateApplicationAction | DropApplicationAction | ResetApplicationAction | SetActiveTabAction | ZoomInAction | ZoomOutAction | ResetZoomAction | UpdateIconAction | SetConfigDataAction | InstallApplicationAction | UninstallApplicationAction | ToggleNotificationsAction | DisableNotificationsAction | EnableNotificationsAction | AskEnableNotificationsAction; // Action Creators export const createApplication = ( manifestURL: string, installContext?: InstallContext, doNotNavigateTo = false, ): CreateApplicationAction => { const applicationId = shortid.generate(); return { type: CREATE_APPLICATION, applicationId, manifestURL, installContext, doNotNavigateTo, }; }; export const dropApplication = (applicationId: string): DropApplicationAction => ({ type: DROP_APPLICATION, applicationId, }); export const uninstallApplication = (applicationId: string): UninstallApplicationAction => ({ type: UNINSTALL_APPLICATION, applicationId, }); export const resetApplication = (applicationId: string, via: string): ResetApplicationAction => ({ type: RESET_APPLICATION, applicationId, via, }); export const setActiveTab = (applicationId: string, tabId: string, silent: boolean = false): SetActiveTabAction => ({ type: SET_ACTIVE_TAB, applicationId, tabId, silent, }); export const zoomIn = (applicationId: string): ZoomInAction => ({ type: ZOOM_IN, applicationId, }); export const zoomOut = (applicationId: string): ZoomOutAction => ({ type: ZOOM_OUT, applicationId, }); export const resetZoom = (applicationId: string): ResetZoomAction => ({ type: RESET_ZOOM, applicationId, }); export const updateApplicationIcon = (applicationId: string, imageURL: string): UpdateIconAction => ({ type: UPDATE_ICON, applicationId, imageURL, }); export const setConfigData = (applicationId: string, configData: ApplicationConfigData): SetConfigDataAction => ({ type: SET_CONFIG_DATA, applicationId, configData, }); export const setHomeTabAsActive = (applicationId: string): SetHomeTabAsActiveAction => ({ type: SET_HOME_TAB_AS_ACTIVE, applicationId, }); export const createNewEmptyTab = (applicationId: string, home: boolean = false): CreateNewEmptyTabAction => ({ type: CREATE_NEW_EMPTY_TAB, applicationId, home, }); type CreateNewTabOptions = { home?: boolean, detach?: boolean, /** * When true, we'll navigate to the application * directly after creating the tab. */ navigateToApplication?: boolean, }; export const createNewTab = (applicationId: string, url: string, options: CreateNewTabOptions = {}): CreateNewTabAction => { const { home = false, detach = false, navigateToApplication = false, } = options; return { type: CREATE_NEW_TAB, applicationId, url, detach, home, navigateToApplication, }; }; export const changeSelectedApp = (applicationId: string, via: ChangeSelectedAppVia = null, markAsActiveTab: boolean = true): ChangeSelectedAppAction => ({ type: CHANGE_SELECTED_APP, applicationId, via, markAsActiveTab, }); export const navigateToTab = (applicationId: string, tabId: string, silent: boolean = false): NavigateToTabAction => ({ type: NAVIGATE_TO_TAB, applicationId, tabId, silent, }); export const navigateToApplicationTab = (applicationId: string, tabId: string, via: ChangeSelectedAppVia = null, silent: boolean = false): NavigateToApplicationTabAction => ({ type: NAVIGATE_TO_APPLICATION_TAB, applicationId, tabId, silent, via, }); export const navigateToApplicationTabAutomatically = (tabId: string, via: ChangeSelectedAppVia = null, silent: boolean = false): NavigateToApplicationTabAutoAction => ({ type: NAVIGATE_TO_APPLICATION_TAB_AUTO, tabId, silent, via, }); interface InstallApplicationOptions { configData?: ApplicationConfigData, /** * Will make Station navigate to the application after installation. */ navigate?: boolean, /** * Will instruct to create a new tab with this URL to the * installed application. */ andCreateTabWithURL?: string, optOutFlow?: boolean, installContext?: InstallContext, } export const installApplication = ( manifestURL: string, options: InstallApplicationOptions = {} ): InstallApplicationAction => ({ type: INSTALL_APPLICATION, manifestURL, configData: options.configData, navigate: options.navigate, optOutFlow: options.optOutFlow, installContext: options.installContext, andCreateTabWithURL: options.andCreateTabWithURL, }); export const remoteUpdateInstalledApplications = (): RemoteUpdateInstalledApplicationsAction => ({ type: REMOTE_UPDATE_INSTALLED_APPLICATIONS, }); export const dispatchUrl = (url: string, origin?: { tabId?: string, applicationId?: string }, options?: { target: Targets }): DispatchURLAction => ({ type: DISPATCH_URL, url, origin, options, }); export const toggleNotifications = (applicationId: string): ToggleNotificationsAction => ({ type: TOGGLE_NOTIFICATIONS, applicationId, }); export const disableNotifications = (applicationId: string): DisableNotificationsAction => ({ type: DISABLE_NOTIFICATIONS, applicationId, }); export const enableNotifications = (applicationId: string): EnableNotificationsAction => ({ type: ENABLE_NOTIFICATIONS, applicationId, }); export const askEnableNotifications = ({ applicationId, tabId, notificationId, props, step }: RequestForApplicationNotifications): AskEnableNotificationsAction => ({ type: ASK_ENABLE_NOTIFICATIONS, applicationId, tabId, notificationId, props, step, }); // Reducer export default function applications(state: Immutable.Map<string, any> = Immutable.Map(), action: ApplicationActions) { switch (action.type) { case CREATE_APPLICATION: { const { applicationId, manifestURL, installContext } = action; return state.set(applicationId, Immutable.Map({ applicationId, manifestURL, installContext: installContext ? Immutable.Map(installContext) : undefined, })); } case SET_CONFIG_DATA: { const { applicationId, configData: { identityId, subdomain, customURL } } = action; let newState = state; if (identityId) { newState = state.setIn([applicationId, 'identityId'], identityId); } if (subdomain) { newState = state.setIn([applicationId, 'subdomain'], subdomain); } if (customURL) { newState = state.setIn([applicationId, 'customURL'], customURL); } return newState; } case DROP_APPLICATION: { const { applicationId } = action; return state.remove(applicationId); } case SET_ACTIVE_TAB: { const { applicationId, tabId } = action; if (!state.has(applicationId)) return state; return state.setIn([applicationId, 'activeTab'], tabId); } case ZOOM_IN: { const { applicationId } = action; if (!state.has(applicationId)) return state; return state.updateIn([applicationId, 'zoomLevel'], 0, zoomLevel => zoomLevel + 0.5); } case ZOOM_OUT: { const { applicationId } = action; if (!state.has(applicationId)) return state; return state.updateIn([applicationId, 'zoomLevel'], 0, zoomLevel => zoomLevel - 0.5); } case RESET_ZOOM: { const { applicationId } = action; return state.setIn([applicationId, 'zoomLevel'], 0); } case UPDATE_ICON: { const { applicationId, imageURL } = action; if (!state.has(applicationId)) return state; return state.setIn([applicationId, 'iconURL'], imageURL); } case DISABLE_NOTIFICATIONS: { const { applicationId } = action; return state.setIn([applicationId, 'notificationsEnabled'], false); } case ENABLE_NOTIFICATIONS: { const { applicationId } = action; return state.setIn([applicationId, 'notificationsEnabled'], true); } case ASK_ENABLE_NOTIFICATIONS: { const { applicationId, tabId, notificationId, props, step } = action; if (step === RequestForApplicationNotificationsStep.FINISH) { return state.deleteIn([applicationId, 'askEnableNotification']); } return state.setIn([applicationId, 'askEnableNotification'], Immutable.fromJS({ applicationId, tabId, notificationId, props, step })); } default: return state; } }
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const Trial: msRest.CompositeMapper = { serializedName: "Trial", type: { name: "Composite", className: "Trial", modelProperties: { status: { readOnly: true, serializedName: "status", type: { name: "String" } }, availableHosts: { readOnly: true, serializedName: "availableHosts", type: { name: "Number" } } } } }; export const Quota: msRest.CompositeMapper = { serializedName: "Quota", type: { name: "Composite", className: "Quota", modelProperties: { hostsRemaining: { readOnly: true, serializedName: "hostsRemaining", type: { name: "Dictionary", value: { type: { name: "Number" } } } }, quotaEnabled: { readOnly: true, serializedName: "quotaEnabled", type: { name: "String" } } } } }; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } } } } }; export const TrackedResource: msRest.CompositeMapper = { serializedName: "TrackedResource", type: { name: "Composite", className: "TrackedResource", modelProperties: { ...Resource.type.modelProperties, location: { serializedName: "location", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const ErrorAdditionalInfo: msRest.CompositeMapper = { serializedName: "ErrorAdditionalInfo", type: { name: "Composite", className: "ErrorAdditionalInfo", modelProperties: { type: { readOnly: true, serializedName: "type", type: { name: "String" } }, info: { readOnly: true, serializedName: "info", type: { name: "Object" } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { code: { readOnly: true, serializedName: "code", type: { name: "String" } }, message: { readOnly: true, serializedName: "message", type: { name: "String" } }, target: { readOnly: true, serializedName: "target", type: { name: "String" } }, details: { readOnly: true, serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorResponse" } } } }, additionalInfo: { readOnly: true, serializedName: "additionalInfo", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorAdditionalInfo" } } } } } } }; export const OperationDisplay: msRest.CompositeMapper = { serializedName: "Operation_display", type: { name: "Composite", className: "OperationDisplay", modelProperties: { provider: { readOnly: true, serializedName: "provider", type: { name: "String" } }, resource: { readOnly: true, serializedName: "resource", type: { name: "String" } }, operation: { readOnly: true, serializedName: "operation", type: { name: "String" } }, description: { readOnly: true, serializedName: "description", type: { name: "String" } } } } }; export const Operation: msRest.CompositeMapper = { serializedName: "Operation", type: { name: "Composite", className: "Operation", modelProperties: { name: { readOnly: true, serializedName: "name", type: { name: "String" } }, display: { readOnly: true, serializedName: "display", type: { name: "Composite", className: "OperationDisplay" } } } } }; export const ExpressRouteAuthorization: msRest.CompositeMapper = { serializedName: "ExpressRouteAuthorization", type: { name: "Composite", className: "ExpressRouteAuthorization", modelProperties: { ...Resource.type.modelProperties, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, expressRouteAuthorizationId: { readOnly: true, serializedName: "properties.expressRouteAuthorizationId", type: { name: "String" } }, expressRouteAuthorizationKey: { readOnly: true, serializedName: "properties.expressRouteAuthorizationKey", type: { name: "String" } } } } }; export const Circuit: msRest.CompositeMapper = { serializedName: "Circuit", type: { name: "Composite", className: "Circuit", modelProperties: { primarySubnet: { readOnly: true, serializedName: "primarySubnet", type: { name: "String" } }, secondarySubnet: { readOnly: true, serializedName: "secondarySubnet", type: { name: "String" } }, expressRouteID: { readOnly: true, serializedName: "expressRouteID", type: { name: "String" } }, expressRoutePrivatePeeringID: { readOnly: true, serializedName: "expressRoutePrivatePeeringID", type: { name: "String" } } } } }; export const Endpoints: msRest.CompositeMapper = { serializedName: "Endpoints", type: { name: "Composite", className: "Endpoints", modelProperties: { nsxtManager: { readOnly: true, serializedName: "nsxtManager", type: { name: "String" } }, vcsa: { readOnly: true, serializedName: "vcsa", type: { name: "String" } }, hcxCloudManager: { readOnly: true, serializedName: "hcxCloudManager", type: { name: "String" } } } } }; export const IdentitySource: msRest.CompositeMapper = { serializedName: "IdentitySource", type: { name: "Composite", className: "IdentitySource", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, alias: { serializedName: "alias", type: { name: "String" } }, domain: { serializedName: "domain", type: { name: "String" } }, baseUserDN: { serializedName: "baseUserDN", type: { name: "String" } }, baseGroupDN: { serializedName: "baseGroupDN", type: { name: "String" } }, primaryServer: { serializedName: "primaryServer", type: { name: "String" } }, secondaryServer: { serializedName: "secondaryServer", type: { name: "String" } }, ssl: { serializedName: "ssl", type: { name: "String" } }, username: { serializedName: "username", type: { name: "String" } }, password: { serializedName: "password", type: { name: "String" } } } } }; export const Sku: msRest.CompositeMapper = { serializedName: "Sku", type: { name: "Composite", className: "Sku", modelProperties: { name: { required: true, serializedName: "name", type: { name: "String" } } } } }; export const PrivateCloud: msRest.CompositeMapper = { serializedName: "PrivateCloud", type: { name: "Composite", className: "PrivateCloud", modelProperties: { ...TrackedResource.type.modelProperties, sku: { required: true, serializedName: "sku", type: { name: "Composite", className: "Sku" } }, managementCluster: { serializedName: "properties.managementCluster", type: { name: "Composite", className: "ManagementCluster" } }, internet: { serializedName: "properties.internet", type: { name: "String" } }, identitySources: { serializedName: "properties.identitySources", type: { name: "Sequence", element: { type: { name: "Composite", className: "IdentitySource" } } } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, circuit: { serializedName: "properties.circuit", type: { name: "Composite", className: "Circuit" } }, endpoints: { readOnly: true, serializedName: "properties.endpoints", type: { name: "Composite", className: "Endpoints" } }, networkBlock: { required: true, serializedName: "properties.networkBlock", type: { name: "String" } }, managementNetwork: { readOnly: true, serializedName: "properties.managementNetwork", type: { name: "String" } }, provisioningNetwork: { readOnly: true, serializedName: "properties.provisioningNetwork", type: { name: "String" } }, vmotionNetwork: { readOnly: true, serializedName: "properties.vmotionNetwork", type: { name: "String" } }, vcenterPassword: { serializedName: "properties.vcenterPassword", type: { name: "String" } }, nsxtPassword: { serializedName: "properties.nsxtPassword", type: { name: "String" } }, vcenterCertificateThumbprint: { readOnly: true, serializedName: "properties.vcenterCertificateThumbprint", type: { name: "String" } }, nsxtCertificateThumbprint: { readOnly: true, serializedName: "properties.nsxtCertificateThumbprint", type: { name: "String" } } } } }; export const ClusterUpdateProperties: msRest.CompositeMapper = { serializedName: "ClusterUpdateProperties", type: { name: "Composite", className: "ClusterUpdateProperties", modelProperties: { clusterSize: { serializedName: "clusterSize", type: { name: "Number" } } } } }; export const ManagementCluster: msRest.CompositeMapper = { serializedName: "ManagementCluster", type: { name: "Composite", className: "ManagementCluster", modelProperties: { ...ClusterUpdateProperties.type.modelProperties, clusterId: { readOnly: true, serializedName: "clusterId", type: { name: "Number" } }, hosts: { readOnly: true, serializedName: "hosts", type: { name: "Sequence", element: { type: { name: "String" } } } } } } }; export const PrivateCloudUpdate: msRest.CompositeMapper = { serializedName: "PrivateCloudUpdate", type: { name: "Composite", className: "PrivateCloudUpdate", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, managementCluster: { serializedName: "properties.managementCluster", type: { name: "Composite", className: "ManagementCluster" } }, internet: { serializedName: "properties.internet", type: { name: "String" } }, identitySources: { serializedName: "properties.identitySources", type: { name: "Sequence", element: { type: { name: "Composite", className: "IdentitySource" } } } } } } }; export const Cluster: msRest.CompositeMapper = { serializedName: "Cluster", type: { name: "Composite", className: "Cluster", modelProperties: { ...Resource.type.modelProperties, sku: { required: true, serializedName: "sku", type: { name: "Composite", className: "Sku" } }, clusterSize: { serializedName: "properties.clusterSize", type: { name: "Number" } }, clusterId: { readOnly: true, serializedName: "properties.clusterId", type: { name: "Number" } }, hosts: { readOnly: true, serializedName: "properties.hosts", type: { name: "Sequence", element: { type: { name: "String" } } } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } } } } }; export const ClusterUpdate: msRest.CompositeMapper = { serializedName: "ClusterUpdate", type: { name: "Composite", className: "ClusterUpdate", modelProperties: { clusterSize: { serializedName: "properties.clusterSize", type: { name: "Number" } } } } }; export const AdminCredentials: msRest.CompositeMapper = { serializedName: "AdminCredentials", type: { name: "Composite", className: "AdminCredentials", modelProperties: { nsxtUsername: { readOnly: true, serializedName: "nsxtUsername", type: { name: "String" } }, nsxtPassword: { readOnly: true, serializedName: "nsxtPassword", type: { name: "String" } }, vcenterUsername: { readOnly: true, serializedName: "vcenterUsername", type: { name: "String" } }, vcenterPassword: { readOnly: true, serializedName: "vcenterPassword", type: { name: "String" } } } } }; export const HcxEnterpriseSite: msRest.CompositeMapper = { serializedName: "HcxEnterpriseSite", type: { name: "Composite", className: "HcxEnterpriseSite", modelProperties: { ...Resource.type.modelProperties, activationKey: { readOnly: true, serializedName: "properties.activationKey", type: { name: "String" } }, status: { readOnly: true, serializedName: "properties.status", type: { name: "String" } } } } }; export const OperationList: msRest.CompositeMapper = { serializedName: "OperationList", type: { name: "Composite", className: "OperationList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const PrivateCloudList: msRest.CompositeMapper = { serializedName: "PrivateCloudList", type: { name: "Composite", className: "PrivateCloudList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PrivateCloud" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const ClusterList: msRest.CompositeMapper = { serializedName: "ClusterList", type: { name: "Composite", className: "ClusterList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Cluster" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const HcxEnterpriseSiteList: msRest.CompositeMapper = { serializedName: "HcxEnterpriseSiteList", type: { name: "Composite", className: "HcxEnterpriseSiteList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "HcxEnterpriseSite" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } }; export const ExpressRouteAuthorizationList: msRest.CompositeMapper = { serializedName: "ExpressRouteAuthorizationList", type: { name: "Composite", className: "ExpressRouteAuthorizationList", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "ExpressRouteAuthorization" } } } }, nextLink: { readOnly: true, serializedName: "nextLink", type: { name: "String" } } } } };
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Redis Enterprise Database. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleEnterpriseCluster = new azure.redis.EnterpriseCluster("exampleEnterpriseCluster", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * skuName: "Enterprise_E20-4", * }); * const exampleEnterpriseDatabase = new azure.redis.EnterpriseDatabase("exampleEnterpriseDatabase", { * resourceGroupName: exampleResourceGroup.name, * clusterId: exampleEnterpriseCluster.id, * }); * ``` * * ## Import * * Redis Enterprise Databases can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:redis/enterpriseDatabase:EnterpriseDatabase example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Cache/redisEnterprise/cluster1/databases/database1 * ``` */ export class EnterpriseDatabase extends pulumi.CustomResource { /** * Get an existing EnterpriseDatabase resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: EnterpriseDatabaseState, opts?: pulumi.CustomResourceOptions): EnterpriseDatabase { return new EnterpriseDatabase(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:redis/enterpriseDatabase:EnterpriseDatabase'; /** * Returns true if the given object is an instance of EnterpriseDatabase. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is EnterpriseDatabase { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === EnterpriseDatabase.__pulumiType; } /** * Specifies whether redis clients can connect using TLS-encrypted or plaintext redis protocols. Default is TLS-encrypted. Possible values are `Encrypted` and `Plaintext`. Defaults to `Encrypted`. Changing this forces a new Redis Enterprise Database to be created. */ public readonly clientProtocol!: pulumi.Output<string | undefined>; /** * The resource id of the Redis Enterprise Cluster to deploy this Redis Enterprise Database. Changing this forces a new Redis Enterprise Database to be created. */ public readonly clusterId!: pulumi.Output<string>; /** * Clustering policy - default is OSSCluster. Specified at create time. Possible values are `EnterpriseCluster` and `OSSCluster`. Defaults to `OSSCluster`. Changing this forces a new Redis Enterprise Database to be created. */ public readonly clusteringPolicy!: pulumi.Output<string | undefined>; /** * Redis eviction policy - default is VolatileLRU. Possible values are `AllKeysLFU`, `AllKeysLRU`, `AllKeysRandom`, `VolatileLRU`, `VolatileLFU`, `VolatileTTL`, `VolatileRandom` and `NoEviction`. Defaults to `VolatileLRU`. Changing this forces a new Redis Enterprise Database to be created. */ public readonly evictionPolicy!: pulumi.Output<string | undefined>; /** * A `module` block as defined below. */ public readonly modules!: pulumi.Output<outputs.redis.EnterpriseDatabaseModule[] | undefined>; /** * The name which should be used for this Redis Enterprise Database. Currently the acceptable value for this argument is `default`. Defaults to `default`. Changing this forces a new Redis Enterprise Database to be created. */ public readonly name!: pulumi.Output<string>; /** * TCP port of the database endpoint. Specified at create time. Defaults to an available port. Changing this forces a new Redis Enterprise Database to be created. */ public readonly port!: pulumi.Output<number | undefined>; /** * The Primary Access Key for the Redis Enterprise Database Instance. */ public /*out*/ readonly primaryAccessKey!: pulumi.Output<string>; /** * The name of the Resource Group where the Redis Enterprise Database should exist. Changing this forces a new Redis Enterprise Database to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The Secondary Access Key for the Redis Enterprise Database Instance. */ public /*out*/ readonly secondaryAccessKey!: pulumi.Output<string>; /** * Create a EnterpriseDatabase resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: EnterpriseDatabaseArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: EnterpriseDatabaseArgs | EnterpriseDatabaseState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as EnterpriseDatabaseState | undefined; inputs["clientProtocol"] = state ? state.clientProtocol : undefined; inputs["clusterId"] = state ? state.clusterId : undefined; inputs["clusteringPolicy"] = state ? state.clusteringPolicy : undefined; inputs["evictionPolicy"] = state ? state.evictionPolicy : undefined; inputs["modules"] = state ? state.modules : undefined; inputs["name"] = state ? state.name : undefined; inputs["port"] = state ? state.port : undefined; inputs["primaryAccessKey"] = state ? state.primaryAccessKey : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["secondaryAccessKey"] = state ? state.secondaryAccessKey : undefined; } else { const args = argsOrState as EnterpriseDatabaseArgs | undefined; if ((!args || args.clusterId === undefined) && !opts.urn) { throw new Error("Missing required property 'clusterId'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } inputs["clientProtocol"] = args ? args.clientProtocol : undefined; inputs["clusterId"] = args ? args.clusterId : undefined; inputs["clusteringPolicy"] = args ? args.clusteringPolicy : undefined; inputs["evictionPolicy"] = args ? args.evictionPolicy : undefined; inputs["modules"] = args ? args.modules : undefined; inputs["name"] = args ? args.name : undefined; inputs["port"] = args ? args.port : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["primaryAccessKey"] = undefined /*out*/; inputs["secondaryAccessKey"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(EnterpriseDatabase.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering EnterpriseDatabase resources. */ export interface EnterpriseDatabaseState { /** * Specifies whether redis clients can connect using TLS-encrypted or plaintext redis protocols. Default is TLS-encrypted. Possible values are `Encrypted` and `Plaintext`. Defaults to `Encrypted`. Changing this forces a new Redis Enterprise Database to be created. */ clientProtocol?: pulumi.Input<string>; /** * The resource id of the Redis Enterprise Cluster to deploy this Redis Enterprise Database. Changing this forces a new Redis Enterprise Database to be created. */ clusterId?: pulumi.Input<string>; /** * Clustering policy - default is OSSCluster. Specified at create time. Possible values are `EnterpriseCluster` and `OSSCluster`. Defaults to `OSSCluster`. Changing this forces a new Redis Enterprise Database to be created. */ clusteringPolicy?: pulumi.Input<string>; /** * Redis eviction policy - default is VolatileLRU. Possible values are `AllKeysLFU`, `AllKeysLRU`, `AllKeysRandom`, `VolatileLRU`, `VolatileLFU`, `VolatileTTL`, `VolatileRandom` and `NoEviction`. Defaults to `VolatileLRU`. Changing this forces a new Redis Enterprise Database to be created. */ evictionPolicy?: pulumi.Input<string>; /** * A `module` block as defined below. */ modules?: pulumi.Input<pulumi.Input<inputs.redis.EnterpriseDatabaseModule>[]>; /** * The name which should be used for this Redis Enterprise Database. Currently the acceptable value for this argument is `default`. Defaults to `default`. Changing this forces a new Redis Enterprise Database to be created. */ name?: pulumi.Input<string>; /** * TCP port of the database endpoint. Specified at create time. Defaults to an available port. Changing this forces a new Redis Enterprise Database to be created. */ port?: pulumi.Input<number>; /** * The Primary Access Key for the Redis Enterprise Database Instance. */ primaryAccessKey?: pulumi.Input<string>; /** * The name of the Resource Group where the Redis Enterprise Database should exist. Changing this forces a new Redis Enterprise Database to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The Secondary Access Key for the Redis Enterprise Database Instance. */ secondaryAccessKey?: pulumi.Input<string>; } /** * The set of arguments for constructing a EnterpriseDatabase resource. */ export interface EnterpriseDatabaseArgs { /** * Specifies whether redis clients can connect using TLS-encrypted or plaintext redis protocols. Default is TLS-encrypted. Possible values are `Encrypted` and `Plaintext`. Defaults to `Encrypted`. Changing this forces a new Redis Enterprise Database to be created. */ clientProtocol?: pulumi.Input<string>; /** * The resource id of the Redis Enterprise Cluster to deploy this Redis Enterprise Database. Changing this forces a new Redis Enterprise Database to be created. */ clusterId: pulumi.Input<string>; /** * Clustering policy - default is OSSCluster. Specified at create time. Possible values are `EnterpriseCluster` and `OSSCluster`. Defaults to `OSSCluster`. Changing this forces a new Redis Enterprise Database to be created. */ clusteringPolicy?: pulumi.Input<string>; /** * Redis eviction policy - default is VolatileLRU. Possible values are `AllKeysLFU`, `AllKeysLRU`, `AllKeysRandom`, `VolatileLRU`, `VolatileLFU`, `VolatileTTL`, `VolatileRandom` and `NoEviction`. Defaults to `VolatileLRU`. Changing this forces a new Redis Enterprise Database to be created. */ evictionPolicy?: pulumi.Input<string>; /** * A `module` block as defined below. */ modules?: pulumi.Input<pulumi.Input<inputs.redis.EnterpriseDatabaseModule>[]>; /** * The name which should be used for this Redis Enterprise Database. Currently the acceptable value for this argument is `default`. Defaults to `default`. Changing this forces a new Redis Enterprise Database to be created. */ name?: pulumi.Input<string>; /** * TCP port of the database endpoint. Specified at create time. Defaults to an available port. Changing this forces a new Redis Enterprise Database to be created. */ port?: pulumi.Input<number>; /** * The name of the Resource Group where the Redis Enterprise Database should exist. Changing this forces a new Redis Enterprise Database to be created. */ resourceGroupName: pulumi.Input<string>; }
the_stack